]> git.sesse.net Git - vlc/blob - modules/gui/qt4/main_interface.cpp
qt4: special icon made by Geoffrey Roussel alias akem/meka is displayed in the last...
[vlc] / modules / gui / qt4 / main_interface.cpp
1 /*****************************************************************************
2  * main_interface.cpp : Main interface
3  ****************************************************************************
4  * Copyright (C) 2006-2007 the VideoLAN team
5  * $Id$
6  *
7  * Authors: ClĂ©ment Stenac <zorglub@videolan.org>
8  *          Jean-Baptiste Kempf <jb@videolan.org>
9  *          Ilkka Ollakka <ileoo@videolan.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 #include "qt4.hpp"
27 #include "main_interface.hpp"
28 #include "input_manager.hpp"
29 #include "util/qvlcframe.hpp"
30 #include "util/customwidgets.hpp"
31 #include "dialogs_provider.hpp"
32 #include "components/interface_widgets.hpp"
33 #include "components/playlist/playlist.hpp"
34 #include "dialogs/extended.hpp"
35 #include "dialogs/playlist.hpp"
36 #include "menus.hpp"
37
38 #include <QMenuBar>
39 #include <QCloseEvent>
40 #include <QPushButton>
41 #include <QStatusBar>
42 #include <QKeyEvent>
43 #include <QUrl>
44 #include <QSystemTrayIcon>
45 #include <QSize>
46 #include <QMenu>
47 #include <QLabel>
48 #include <QSlider>
49 #include <QWidgetAction>
50 #include <QDockWidget>
51 #include <QToolBar>
52 #include <QGroupBox>
53 #include <QDate>
54
55 #include <assert.h>
56 #include <vlc_keys.h>
57 #include <vlc_vout.h>
58
59 #define SET_WIDTH(i,j) i->widgetSize.setWidth(j)
60 #define SET_HEIGHT(i,j) i->widgetSize.setHeight(j)
61 #define SET_WH( i,j,k) i->widgetSize.setWidth(j); i->widgetSize.setHeight(k);
62
63 #define DS(i) i.width(),i.height()
64
65 /* Callback prototypes */
66 static int PopupMenuCB( vlc_object_t *p_this, const char *psz_variable,
67                         vlc_value_t old_val, vlc_value_t new_val, void *param );
68 static int IntfShowCB( vlc_object_t *p_this, const char *psz_variable,
69                        vlc_value_t old_val, vlc_value_t new_val, void *param );
70 static int InteractCallback( vlc_object_t *, const char *, vlc_value_t,
71                              vlc_value_t, void *);
72 /* Video handling */
73 static void *DoRequest( intf_thread_t *p_intf, vout_thread_t *p_vout,
74                         int *pi1, int *pi2, unsigned int*pi3,unsigned int*pi4)
75 {
76     return p_intf->p_sys->p_mi->requestVideo( p_vout, pi1, pi2, pi3, pi4 );
77 }
78 static void DoRelease( intf_thread_t *p_intf, void *p_win )
79 {
80     return p_intf->p_sys->p_mi->releaseVideo( p_win );
81 }
82 static int DoControl( intf_thread_t *p_intf, void *p_win, int i_q, va_list a )
83 {
84     return p_intf->p_sys->p_mi->controlVideo( p_win, i_q, a );
85 }
86
87 MainInterface::MainInterface( intf_thread_t *_p_intf ) : QVLCMW( _p_intf )
88 {
89     /* Variables initialisation */
90     // need_components_update = false;
91     bgWidget = NULL; videoWidget = NULL; playlistWidget = NULL;
92     videoIsActive = false;
93     input_name = "";
94
95     /* Ask for privacy */
96     privacy();
97
98     /**
99      *  Configuration and settings
100      **/
101     settings = new QSettings( "vlc", "vlc-qt-interface" );
102     settings->beginGroup( "MainWindow" );
103
104     /* Main settings */
105     setFocusPolicy( Qt::StrongFocus );
106     setAcceptDrops( true );
107     setWindowIcon( QApplication::windowIcon() );
108     setWindowOpacity( config_GetFloat( p_intf, "qt-opacity" ) );
109
110     /* Set The Video In emebedded Mode or not */
111     videoEmbeddedFlag = false;
112     if( config_GetInt( p_intf, "embedded-video" ) ) videoEmbeddedFlag = true;
113
114     /* Are we in the enhanced always-video mode or not ? */
115     alwaysVideoFlag = false;
116     if( videoEmbeddedFlag && config_GetInt( p_intf, "qt-always-video" ) )
117         alwaysVideoFlag = true;
118
119     /* Set the other interface settings */
120     //TODO: I don't like that code
121     visualSelectorEnabled = settings->value( "visual-selector", false ).toBool();
122     notificationEnabled = config_GetInt( p_intf, "qt-notification" )
123                           ? true : false;
124
125     /**************************
126      *  UI and Widgets design
127      **************************/
128     setVLCWindowsTitle();
129     handleMainUi( settings );
130
131     /* Create a Dock to get the playlist */
132     dockPL = new QDockWidget( qtr( "Playlist" ), this );
133     dockPL->setSizePolicy( QSizePolicy::Preferred,
134                            QSizePolicy::Expanding );
135     dockPL->setFeatures( QDockWidget::AllDockWidgetFeatures );
136     dockPL->setAllowedAreas( Qt::LeftDockWidgetArea
137                            | Qt::RightDockWidgetArea
138                            | Qt::BottomDockWidgetArea );
139     dockPL->hide();
140
141     /************
142      * Menu Bar
143      ************/
144     QVLCMenu::createMenuBar( this, p_intf, visualSelectorEnabled );
145
146     /****************
147      *  Status Bar  *
148      ****************/
149     /* Widgets Creation*/
150     b_remainingTime = false;
151     timeLabel = new TimeLabel;
152     nameLabel = new QLabel;
153     nameLabel->setTextInteractionFlags( Qt::TextSelectableByMouse
154                                       | Qt::TextSelectableByKeyboard );
155     speedLabel = new QLabel( "1.00x" );
156     speedLabel->setContextMenuPolicy ( Qt::CustomContextMenu );
157
158     /* Styling those labels */
159     timeLabel->setFrameStyle( QFrame::Sunken | QFrame::Panel );
160     speedLabel->setFrameStyle( QFrame::Sunken | QFrame::Panel );
161     nameLabel->setFrameStyle( QFrame::Sunken | QFrame::StyledPanel);
162
163     /* and adding those */
164     statusBar()->addWidget( nameLabel, 8 );
165     statusBar()->addPermanentWidget( speedLabel, 0 );
166     statusBar()->addPermanentWidget( timeLabel, 2 );
167
168     /* timeLabel behaviour:
169        - double clicking opens the goto time dialog
170        - right-clicking and clicking just toggle between remaining and
171          elapsed time.*/
172     CONNECT( timeLabel, timeLabelClicked(), this, toggleTimeDisplay() );
173     CONNECT( timeLabel, timeLabelDoubleClicked(), THEDP, gotoTimeDialog() );
174     CONNECT( timeLabel, timeLabelDoubleClicked(), this, toggleTimeDisplay() );
175
176     /* Speed Label behaviour:
177        - right click gives the vertical speed slider */
178     CONNECT( speedLabel, customContextMenuRequested( QPoint ),
179              this, showSpeedMenu( QPoint ) );
180
181     /**********************
182      * Systray Management *
183      **********************/
184     sysTray = NULL;
185     bool b_createSystray = false;
186     bool b_systrayAvailable = QSystemTrayIcon::isSystemTrayAvailable();
187     if( config_GetInt( p_intf, "qt-start-minimized") )
188     {
189         if( b_systrayAvailable ){
190             b_createSystray = true;
191             hide(); //FIXME BUG HERE
192         }
193         else msg_Warn( p_intf, "You can't minize if you haven't a system "
194                 "tray bar" );
195     }
196     if( config_GetInt( p_intf, "qt-system-tray") )
197         b_createSystray = true;
198
199     if( b_systrayAvailable && b_createSystray )
200             createSystray();
201
202     if( config_GetInt( p_intf, "qt-minimal-view" ) )
203         toggleMinimalView();
204
205     /********************
206      * Input Manager    *
207      ********************/
208     MainInputManager::getInstance( p_intf );
209
210     /********************
211      * Various CONNECTs *
212      ********************/
213     /* Connect the input manager to the GUI elements it manages */
214
215     /* It is also connected to the control->slider, see the ControlsWidget */
216     CONNECT( THEMIM->getIM(), positionUpdated( float, int, int ),
217              this, setDisplayPosition( float, int, int ) );
218     /* Change the SpeedRate in the Status */
219     CONNECT( THEMIM->getIM(), rateChanged( int ), this, setRate( int ) );
220
221     /**
222      * Connects on nameChanged()
223      * Those connects are not merged because different options can trigger
224      * them down.
225      */
226     /* Naming in the controller statusbar */
227     CONNECT( THEMIM->getIM(), nameChanged( QString ), this,
228              setName( QString ) );
229     /* and in the systray */
230     if( sysTray )
231     {
232         CONNECT( THEMIM->getIM(), nameChanged( QString ), this,
233                  updateSystrayTooltipName( QString ) );
234     }
235     /* and in the title of the controller */
236     if( config_GetInt( p_intf, "qt-name-in-title" ) )
237     {
238         CONNECT( THEMIM->getIM(), nameChanged( QString ), this,
239              setVLCWindowsTitle( QString ) );
240     }
241
242     /**
243      * CONNECTS on PLAY_STATUS
244      **/
245     /* Status on the main controller */
246     CONNECT( THEMIM->getIM(), statusChanged( int ), this, setStatus( int ) );
247     /* and in the systray */
248     if( sysTray )
249     {
250         CONNECT( THEMIM->getIM(), statusChanged( int ), this,
251                  updateSystrayTooltipStatus( int ) );
252     }
253
254     /** OnTimeOut **/
255     // TODO
256     ON_TIMEOUT( updateOnTimer() );
257     //ON_TIMEOUT( debug() );
258
259     /**
260      * Callbacks
261      **/
262     var_Create( p_intf, "interaction", VLC_VAR_ADDRESS );
263     var_AddCallback( p_intf, "interaction", InteractCallback, this );
264     p_intf->b_interaction = VLC_TRUE;
265
266     /* Register callback for the intf-popupmenu variable */
267     playlist_t *p_playlist = (playlist_t *)vlc_object_find( p_intf,
268                                         VLC_OBJECT_PLAYLIST, FIND_ANYWHERE );
269     if( p_playlist != NULL )
270     {
271         var_AddCallback( p_playlist, "intf-popupmenu", PopupMenuCB, p_intf );
272         var_AddCallback( p_playlist, "intf-show", IntfShowCB, p_intf );
273         vlc_object_release( p_playlist );
274     }
275
276     /* VideoWidget connect mess to avoid different threads speaking to each other */
277     CONNECT( this, askReleaseVideo( void * ), this, releaseVideoSlot( void * ) );
278     CONNECT( this, askVideoToResize( unsigned int, unsigned int ),
279              videoWidget, SetSizing( unsigned int, unsigned int ) );
280     CONNECT( this, askUpdate(), this, doComponentsUpdate() );
281
282     CONNECT( dockPL, topLevelChanged( bool ), this, doComponentsUpdate() );
283     CONNECT( controls, advancedControlsToggled( bool ),
284              this, doComponentsUpdate() );
285
286     move( settings->value( "pos", QPoint( 0, 0 ) ).toPoint() );
287
288     resize( settings->value( "size", QSize( 350, 60 ) ).toSize() );
289     updateGeometry();
290
291     settings->endGroup();
292 }
293
294 MainInterface::~MainInterface()
295 {
296     if( playlistWidget ) playlistWidget->savingSettings( settings );
297     if( ExtendedDialog::exists() )
298         ExtendedDialog::getInstance( p_intf )->savingSettings();
299
300     settings->beginGroup( "MainWindow" );
301     settings->setValue( "playlist-floats", dockPL->isFloating() );
302     settings->setValue( "adv-controls",
303                         getControlsVisibilityStatus() & CONTROLS_ADVANCED );
304     settings->setValue( "pos", pos() );
305     settings->setValue( "size", size() );
306
307     settings->endGroup();
308     delete settings;
309
310     /* Unregister callback for the intf-popupmenu variable */
311     playlist_t *p_playlist = (playlist_t *)vlc_object_find( p_intf,
312                                         VLC_OBJECT_PLAYLIST, FIND_ANYWHERE );
313     if( p_playlist != NULL )
314     {
315         var_DelCallback( p_playlist, "intf-popupmenu", PopupMenuCB, p_intf );
316         var_DelCallback( p_playlist, "intf-show", IntfShowCB, p_intf );
317         vlc_object_release( p_playlist );
318     }
319
320     p_intf->b_interaction = VLC_FALSE;
321     var_DelCallback( p_intf, "interaction", InteractCallback, this );
322
323     p_intf->pf_request_window = NULL;
324     p_intf->pf_release_window = NULL;
325     p_intf->pf_control_window = NULL;
326 }
327
328 /*****************************
329  *   Main UI handling        *
330  *****************************/
331
332 /**
333  * Give the decorations of the Main Window a correct Name.
334  * If nothing is given, set it to VLC...
335  **/
336 void MainInterface::setVLCWindowsTitle( QString aTitle )
337 {
338     if( aTitle.isEmpty() )
339     {
340         setWindowTitle( qtr( "VLC media player" ) );
341     }
342     else
343     {
344         setWindowTitle( aTitle + " - " + qtr( "VLC media player" ) );
345     }
346 }
347
348 void MainInterface::handleMainUi( QSettings *settings )
349 {
350     /* Create the main Widget and the mainLayout */
351     QWidget *main = new QWidget;
352     setCentralWidget( main );
353     mainLayout = new QVBoxLayout( main );
354
355     /* Margins, spacing */
356     main->setContentsMargins( 0, 0, 0, 0 );
357    // main->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Maximum );
358     mainLayout->setMargin( 0 );
359
360     /* Create the CONTROLS Widget */
361     /* bool b_shiny = config_GetInt( p_intf, "qt-blingbling" ); */
362     controls = new ControlsWidget( p_intf, this,
363                    settings->value( "adv-controls", false ).toBool(),
364                    config_GetInt( p_intf, "qt-blingbling" ) );
365
366     /* Add the controls Widget to the main Widget */
367     mainLayout->insertWidget( 0, controls );
368
369     /* Create the Speed Control Widget */
370     speedControl = new SpeedControlWidget( p_intf );
371     speedControlMenu = new QMenu( this );
372
373     QWidgetAction *widgetAction = new QWidgetAction( speedControl );
374     widgetAction->setDefaultWidget( speedControl );
375     speedControlMenu->addAction( widgetAction );
376
377     /* Visualisation */
378     /* Disabled for now, they SUCK */
379     #if 0
380     visualSelector = new VisualSelector( p_intf );
381     mainLayout->insertWidget( 0, visualSelector );
382     visualSelector->hide();
383     #endif
384
385     /* And video Outputs */
386     if( alwaysVideoFlag )
387     {
388         bgWidget = new BackgroundWidget( p_intf );
389         bgWidget->widgetSize = settings->value( "backgroundSize",
390                                            QSize( 300, 200 ) ).toSize();
391         bgWidget->resize( bgWidget->widgetSize );
392         bgWidget->updateGeometry();
393         mainLayout->insertWidget( 0, bgWidget );
394         CONNECT( this, askBgWidgetToToggle(), bgWidget, toggle() );
395     }
396
397     if( videoEmbeddedFlag )
398     {
399         videoWidget = new VideoWidget( p_intf );
400         //videoWidget->widgetSize = QSize( 16, 16 );
401         //videoWidget->hide();
402         //videoWidget->resize( videoWidget->widgetSize );
403         mainLayout->insertWidget( 0, videoWidget );
404
405         p_intf->pf_request_window  = ::DoRequest;
406         p_intf->pf_release_window  = ::DoRelease;
407         p_intf->pf_control_window  = ::DoControl;
408     }
409
410     /* Finish the sizing */
411     updateGeometry();
412 }
413
414 inline void MainInterface::privacy()
415 {
416     /**
417      * Ask for the network policy on FIRST STARTUP
418      **/
419     if( config_GetInt( p_intf, "privacy-ask") )
420     {
421         QList<ConfigControl *> controls;
422         if( privacyDialog( controls ) == QDialog::Accepted )
423         {
424             QList<ConfigControl *>::Iterator i;
425             for(  i = controls.begin() ; i != controls.end() ; i++ )
426             {
427                 ConfigControl *c = qobject_cast<ConfigControl *>(*i);
428                 c->doApply( p_intf );
429             }
430
431             config_PutInt( p_intf,  "privacy-ask" , 0 );
432             config_SaveConfigFile( p_intf, NULL );
433         }
434     }
435 }
436
437 int MainInterface::privacyDialog( QList<ConfigControl *> controls )
438 {
439     QDialog *privacy = new QDialog( this );
440
441     privacy->setWindowTitle( qtr( "Privacy and Network policies" ) );
442
443     QGridLayout *gLayout = new QGridLayout( privacy );
444
445     QGroupBox *blabla = new QGroupBox( qtr( "Privacy and Network Warning" ) );
446     QGridLayout *blablaLayout = new QGridLayout( blabla );
447     QLabel *text = new QLabel( qtr(
448         "<p>The <i>VideoLAN Team</i> doesn't like when an application goes "
449         "online without authorisation.</p>\n "
450         "<p><i>VLC media player</i> can request limited information on "
451         "Internet, espically to get CD Covers and songs metadata or to know "
452         "if updates are available.</p>\n"
453         "<p><i>VLC media player</i> <b>DOES NOT</b> send or collect <b>ANY</b> "
454         "information, even anonymously about your "
455         "usage.</p>\n"
456         "<p>Therefore please check the following options, the default being "
457         "almost no access on the web.</p>\n") );
458     text->setWordWrap( true );
459     text->setTextFormat( Qt::RichText );
460
461     blablaLayout->addWidget( text, 0, 0 ) ;
462
463     QGroupBox *options = new QGroupBox;
464     QGridLayout *optionsLayout = new QGridLayout( options );
465
466     gLayout->addWidget( blabla, 0, 0, 1, 3 );
467     gLayout->addWidget( options, 1, 0, 1, 3 );
468     module_config_t *p_config;
469     ConfigControl *control;
470     int line = 0;
471
472 #define CONFIG_GENERIC( option, type )                            \
473     p_config =  config_FindConfig( VLC_OBJECT(p_intf), option );  \
474     if( p_config )                                                \
475     {                                                             \
476         control =  new type ## ConfigControl( VLC_OBJECT(p_intf), \
477                 p_config, options, false, optionsLayout, line );  \
478         controls.append( control );                               \
479     }
480
481 #define CONFIG_GENERIC_NOBOOL( option, type )                     \
482     p_config =  config_FindConfig( VLC_OBJECT(p_intf), option );  \
483     if( p_config )                                                \
484     {                                                             \
485         control =  new type ## ConfigControl( VLC_OBJECT(p_intf), \
486                 p_config, options, optionsLayout, line );  \
487         controls.append( control );                               \
488     }
489
490     CONFIG_GENERIC( "album-art", IntegerList ); line++;
491     CONFIG_GENERIC_NOBOOL( "fetch-meta", Bool ); line++;
492     CONFIG_GENERIC_NOBOOL( "qt-updates-notif", Bool );
493
494     QPushButton *ok = new QPushButton( qtr( "Ok" ) );
495
496     gLayout->addWidget( ok, 2, 2 );
497
498     CONNECT( ok, clicked(), privacy, accept() );
499     return privacy->exec();
500 }
501
502 //FIXME remove me at the end...
503 void MainInterface::debug()
504 {
505     msg_Dbg( p_intf, "size: %i - %i", controls->size().height(), controls->size().width() );
506     msg_Dbg( p_intf, "sizeHint: %i - %i", controls->sizeHint().height(), controls->sizeHint().width() );
507 }
508
509 /**********************************************************************
510  * Handling of sizing of the components
511  **********************************************************************/
512
513 /* This function is probably wrong, but we don't have many many choices...
514    Since we can't know from the playlist Widget if we are inside a dock or not,
515    because the playlist Widget can be called by THEDP, as a separate windows for
516    the skins.
517    Maybe the other solution is to redefine the sizeHint() of the playlist and
518    ask _parent->isFloating()...
519    If you think this would be better, please FIXME it...
520 */
521 QSize MainInterface::sizeHint() const
522 {
523     int nwidth = controls->sizeHint().width();
524     int nheight = controls->sizeHint().height();
525                 + menuBar()->size().height()
526                 + statusBar()->size().height();
527
528     msg_Dbg( p_intf, "1 %i %i", nheight, nwidth );
529     if( VISIBLE( bgWidget ) )
530     {
531         nheight += bgWidget->size().height();
532         nwidth  = bgWidget->size().width();
533     }
534     else if( videoIsActive )
535     {
536         nheight += videoWidget->size().height();
537         nwidth  = videoWidget->size().width();
538         msg_Dbg( p_intf, "2 %i %i", nheight, nwidth );
539     }
540     if( !dockPL->isFloating() && dockPL->widget() )
541     {
542         nheight += dockPL->size().height();
543         nwidth = MAX( nwidth, dockPL->size().width() );
544         msg_Dbg( p_intf, "3 %i %i", nheight, nwidth );
545     }
546     msg_Dbg( p_intf, "4 %i %i", nheight, nwidth );
547     return QSize( nwidth, nheight );
548 }
549
550 #if 0
551 /* FIXME This is dead code and need to be removed AT THE END */
552 void MainInterface::resizeEvent( QResizeEvent *e )
553 {
554     if( videoWidget )
555         videoWidget->widgetSize.setWidth( e->size().width() - addSize.width() );
556     if( videoWidget && videoIsActive && videoWidget->widgetSize.height() > 1 )
557     {
558         SET_WH( videoWidget, e->size().width() - addSize.width(),
559                              e->size().height()  - addSize.height() );
560         videoWidget->updateGeometry();
561     }
562     if( VISIBLE( playlistWidget ) )
563     {
564 //        SET_WH( playlistWidget , e->size().width() - addSize.width(),
565               //                   e->size().height() - addSize.height() );
566         playlistWidget->updateGeometry();
567     }
568 }
569 #endif
570
571 /****************************************************************************
572  * Small right-click menu for rate control
573  ****************************************************************************/
574 void MainInterface::showSpeedMenu( QPoint pos )
575 {
576     speedControlMenu->exec( QCursor::pos() - pos
577                           + QPoint( 0, speedLabel->height() ) );
578 }
579
580 /****************************************************************************
581  * Video Handling
582  ****************************************************************************/
583 class SetVideoOnTopQtEvent : public QEvent
584 {
585 public:
586     SetVideoOnTopQtEvent( bool _onTop ) :
587       QEvent( (QEvent::Type)SetVideoOnTopEvent_Type ), onTop( _onTop)
588     {}
589
590     bool OnTop() const
591     {
592         return onTop;
593     }
594
595 private:
596     bool onTop;
597 };
598
599 /* function called from ::DoRequest in order to show a nice VideoWidget
600     at the good size */
601 void *MainInterface::requestVideo( vout_thread_t *p_nvout, int *pi_x,
602                                    int *pi_y, unsigned int *pi_width,
603                                    unsigned int *pi_height )
604 {
605     bool bgWasVisible = false;
606
607     /* Request the videoWidget */
608     void *ret = videoWidget->request( p_nvout,pi_x, pi_y, pi_width, pi_height );
609     if( ret ) /* The videoWidget is available */
610     {
611         /* Did we have a bg ? Hide it! */
612         if( VISIBLE( bgWidget) )
613         {
614             bgWasVisible = true;
615             emit askBgWidgetToToggle();
616         }
617
618         /*if( THEMIM->getIM()->hasVideo() || !bgWasVisible )
619         {
620             videoWidget->widgetSize = QSize( *pi_width, *pi_height );
621         }
622         else /* Background widget available, use its size */
623         /*{
624             /* Ok, our visualizations are bad, so don't do this for the moment
625              * use the requested size anyway */
626             // videoWidget->widgetSize = bgWidget->widgeTSize;
627           /*  videoWidget->widgetSize = QSize( *pi_width, *pi_height );
628         }*/
629
630         videoIsActive = true;
631
632         emit askVideoToResize( *pi_width, *pi_height );
633         emit askUpdate();
634     }
635     return ret;
636 }
637
638 void MainInterface::releaseVideo( void *p_win )
639 {
640     emit askReleaseVideo( p_win );
641 }
642
643 void MainInterface::releaseVideoSlot( void *p_win )
644 {
645     videoWidget->release( p_win );
646     videoWidget->hide();
647
648     if( bgWidget )// WORONG
649         bgWidget->show();
650
651     videoIsActive = false;
652     emit askUpdate();
653 }
654
655 int MainInterface::controlVideo( void *p_window, int i_query, va_list args )
656 {
657     int i_ret = VLC_EGENERIC;
658     switch( i_query )
659     {
660         case VOUT_GET_SIZE:
661         {
662             unsigned int *pi_width  = va_arg( args, unsigned int * );
663             unsigned int *pi_height = va_arg( args, unsigned int * );
664             *pi_width = videoWidget->widgetSize.width();
665             *pi_height = videoWidget->widgetSize.height();
666             i_ret = VLC_SUCCESS;
667             break;
668         }
669         case VOUT_SET_SIZE:
670         {
671             unsigned int i_width  = va_arg( args, unsigned int );
672             unsigned int i_height = va_arg( args, unsigned int );
673             emit askVideoToResize( i_width, i_height );
674             emit askUpdate();
675             updateGeometry();
676             i_ret = VLC_SUCCESS;
677             break;
678         }
679         case VOUT_SET_STAY_ON_TOP:
680         {
681             int i_arg = va_arg( args, int );
682             QApplication::postEvent( this, new SetVideoOnTopQtEvent( i_arg ) );
683             i_ret = VLC_SUCCESS;
684             break;
685         }
686         default:
687             msg_Warn( p_intf, "unsupported control query" );
688             break;
689     }
690     return i_ret;
691 }
692
693 /*****************************************************************************
694  * Playlist, Visualisation and Menus handling
695  *****************************************************************************/
696 /**
697  * Toggle the playlist widget or dialog
698  **/
699 void MainInterface::togglePlaylist()
700 {
701     /* CREATION
702     If no playlist exist, then create one and attach it to the DockPL*/
703     if( !playlistWidget )
704     {
705         playlistWidget = new PlaylistWidget( p_intf, settings );
706
707         /* Add it to the parent DockWidget */
708         dockPL->setWidget( playlistWidget );
709
710         /* Add the dock to the main Interface */
711         addDockWidget( Qt::BottomDockWidgetArea, dockPL );
712
713         /* Make the playlist floating is requested. Default is not. */
714         //FIXME
715         if( settings->value( "playlist-floats", false ).toBool() );
716         {
717             msg_Dbg( p_intf, "we don't want the playlist inside");
718             dockPL->setFloating( true );
719         }
720         dockPL->show();
721     }
722     else
723     {
724     /* toggle the visibility of the playlist */
725        TOGGLEV( dockPL );
726        //resize(sizeHint());
727     }
728 #if 0
729     doComponentsUpdate();
730 #endif
731     updateGeometry();
732 }
733
734 /* Function called from the menu to undock the playlist */
735 void MainInterface::undockPlaylist()
736 {
737     dockPL->setFloating( true );
738     updateGeometry();
739 }
740
741 void MainInterface::toggleMinimalView()
742 {
743     TOGGLEV( menuBar() );
744     TOGGLEV( controls );
745     TOGGLEV( statusBar() );
746     updateGeometry();
747 }
748
749 /* Video widget cannot do this synchronously as it runs in another thread */
750 /* Well, could it, actually ? Probably dangerous ... */
751 void MainInterface::doComponentsUpdate()
752 {
753     msg_Dbg( p_intf, "Updating the geometry" );
754     updateGeometry();
755     resize( sizeHint() );
756 }
757
758 /* toggling advanced controls buttons */
759 void MainInterface::toggleAdvanced()
760 {
761     controls->toggleAdvanced();
762 }
763
764 /* Get the visibility status of the controls (hidden or not, advanced or not) */
765 int MainInterface::getControlsVisibilityStatus()
766 {
767     return( (controls->isVisible() ? CONTROLS_VISIBLE : CONTROLS_HIDDEN )
768                 + CONTROLS_ADVANCED * controls->b_advancedVisible );
769 }
770
771 #if 0
772 void MainInterface::visual()
773 {
774     if( !VISIBLE( visualSelector) )
775     {
776         visualSelector->show();
777         if( !THEMIM->getIM()->hasVideo() )
778         {
779             /* Show the background widget */
780         }
781         visualSelectorEnabled = true;
782     }
783     else
784     {
785         /* Stop any currently running visualization */
786         visualSelector->hide();
787         visualSelectorEnabled = false;
788     }
789     doComponentsUpdate();
790 }
791 #endif
792
793 /************************************************************************
794  * Other stuff
795  ************************************************************************/
796 void MainInterface::setDisplayPosition( float pos, int time, int length )
797 {
798     char psz_length[MSTRTIME_MAX_SIZE], psz_time[MSTRTIME_MAX_SIZE];
799     secstotimestr( psz_length, length );
800     secstotimestr( psz_time, ( b_remainingTime && length ) ? length - time
801                                                            : time );
802
803     QString title;
804     title.sprintf( "%s/%s", psz_time,
805                             ( !length && time ) ? "--:--" : psz_length );
806
807     /* Add a minus to remaining time*/
808     if( b_remainingTime && length ) timeLabel->setText( " -"+title+" " );
809     else timeLabel->setText( " "+title+" " );
810 }
811
812 void MainInterface::toggleTimeDisplay()
813 {
814     b_remainingTime = !b_remainingTime;
815 }
816
817 void MainInterface::setName( QString name )
818 {
819     input_name = name; /* store it for the QSystray use */
820     /* Display it in the status bar, but also as a Tooltip in case it doesn't
821        fit in the label */
822     nameLabel->setText( " " + name + " " );
823     nameLabel->setToolTip( " " + name +" " );
824 }
825
826 void MainInterface::setStatus( int status )
827 {
828     /* Forward the status to the controls to toggle Play/Pause */
829     controls->setStatus( status );
830     /* And in the systray for the menu */
831     if( sysTray )
832         QVLCMenu::updateSystrayMenu( this, p_intf );
833 }
834
835 void MainInterface::setRate( int rate )
836 {
837     QString str;
838     str.setNum( ( 1000 / (double)rate ), 'f', 2 );
839     str.append( "x" );
840     speedLabel->setText( str );
841     speedControl->updateControls( rate );
842 }
843
844 void MainInterface::updateOnTimer()
845 {
846     if( intf_ShouldDie( p_intf ) )
847     {
848         QApplication::closeAllWindows();
849         QApplication::quit();
850     }
851 #if 0
852     if( need_components_update )
853     {
854         doComponentsUpdate();
855         need_components_update = false;
856     }
857 #endif
858
859     controls->updateOnTimer();
860 }
861
862 /*****************************************************************************
863  * Systray Icon and Systray Menu
864  *****************************************************************************/
865
866 /**
867  * Create a SystemTray icon and a menu that would go with it.
868  * Connects to a click handler on the icon.
869  **/
870 void MainInterface::createSystray()
871 {
872     QIcon iconVLC;
873     if( QDate::currentDate().dayOfYear() >= 354 )
874         iconVLC =  QIcon( QPixmap( ":/vlc128-christmas.png" ) );
875     else
876         iconVLC =  QIcon( QPixmap( ":/vlc128.png" ) );
877     sysTray = new QSystemTrayIcon( iconVLC, this );
878     sysTray->setToolTip( qtr( "VLC media player" ));
879
880     systrayMenu = new QMenu( qtr( "VLC media player" ), this );
881     systrayMenu->setIcon( iconVLC );
882
883     QVLCMenu::updateSystrayMenu( this, p_intf, true );
884     sysTray->show();
885
886     CONNECT( sysTray, activated( QSystemTrayIcon::ActivationReason ),
887             this, handleSystrayClick( QSystemTrayIcon::ActivationReason ) );
888 }
889
890 /**
891  * Updates the Systray Icon's menu and toggle the main interface
892  */
893 void MainInterface::toggleUpdateSystrayMenu()
894 {
895     /* If hidden, show it */
896     if( isHidden() )
897     {
898         show();
899         activateWindow();
900     }
901     else if( isMinimized() )
902     {
903         /* Minimized */
904         showNormal();
905         activateWindow();
906     }
907     else
908     {
909         /* Visible */
910 #ifdef WIN32
911         /* check if any visible window is above vlc in the z-order,
912          * but ignore the ones always on top */
913         WINDOWINFO wi;
914         HWND hwnd;
915         wi.cbSize = sizeof( WINDOWINFO );
916         for( hwnd = GetNextWindow( internalWinId(), GW_HWNDPREV );
917                 hwnd && !IsWindowVisible( hwnd );
918                 hwnd = GetNextWindow( hwnd, GW_HWNDPREV ) );
919         if( !hwnd || !GetWindowInfo( hwnd, &wi ) ||
920                 (wi.dwExStyle&WS_EX_TOPMOST) )
921 #else
922         if( isActiveWindow() )
923 #endif
924         {
925             hide();
926         }
927         else
928         {
929             activateWindow();
930         }
931     }
932     QVLCMenu::updateSystrayMenu( this, p_intf );
933 }
934
935 void MainInterface::handleSystrayClick(
936                                     QSystemTrayIcon::ActivationReason reason )
937 {
938     switch( reason )
939     {
940         case QSystemTrayIcon::Trigger:
941             toggleUpdateSystrayMenu();
942             break;
943         case QSystemTrayIcon::MiddleClick:
944             sysTray->showMessage( qtr( "VLC media player" ),
945                     qtr( "Control menu for the player" ),
946                     QSystemTrayIcon::Information, 3000 );
947             break;
948     }
949 }
950
951 /**
952  * Updates the name of the systray Icon tooltip.
953  * Doesn't check if the systray exists, check before you call it.
954  **/
955 void MainInterface::updateSystrayTooltipName( QString name )
956 {
957     if( name.isEmpty() )
958     {
959         sysTray->setToolTip( qtr( "VLC media player" ) );
960     }
961     else
962     {
963         sysTray->setToolTip( name );
964         if( notificationEnabled && ( isHidden() || isMinimized() ) )
965         {
966             sysTray->showMessage( qtr( "VLC media player" ), name,
967                     QSystemTrayIcon::NoIcon, 3000 );
968         }
969     }
970 }
971
972 /**
973  * Updates the status of the systray Icon tooltip.
974  * Doesn't check if the systray exists, check before you call it.
975  **/
976 void MainInterface::updateSystrayTooltipStatus( int i_status )
977 {
978     switch( i_status )
979     {
980         case  0:
981         case  END_S:
982             {
983                 sysTray->setToolTip( qtr( "VLC media player" ) );
984                 break;
985             }
986         case PLAYING_S:
987             {
988                 sysTray->setToolTip( input_name );
989                 break;
990             }
991         case PAUSE_S:
992             {
993                 sysTray->setToolTip( input_name + " - "
994                         + qtr( "Paused") );
995                 break;
996             }
997     }
998 }
999
1000 /************************************************************************
1001  * D&D Events
1002  ************************************************************************/
1003 void MainInterface::dropEvent(QDropEvent *event)
1004 {
1005      const QMimeData *mimeData = event->mimeData();
1006
1007      /* D&D of a subtitles file, add it on the fly */
1008      if( mimeData->urls().size() == 1 )
1009      {
1010         if( THEMIM->getIM()->hasInput() )
1011         {
1012             if( input_AddSubtitles( THEMIM->getInput(),
1013                                     qtu( mimeData->urls()[0].toString() ),
1014                                     VLC_TRUE ) )
1015             {
1016                 event->acceptProposedAction();
1017                 return;
1018             }
1019         }
1020      }
1021      bool first = true;
1022      foreach( QUrl url, mimeData->urls() ) {
1023         QString s = url.toString();
1024         if( s.length() > 0 ) {
1025             playlist_Add( THEPL, qtu(s), NULL,
1026                           PLAYLIST_APPEND | (first ? PLAYLIST_GO:0),
1027                           PLAYLIST_END, VLC_TRUE, VLC_FALSE );
1028             first = false;
1029         }
1030      }
1031      event->acceptProposedAction();
1032 }
1033 void MainInterface::dragEnterEvent(QDragEnterEvent *event)
1034 {
1035      event->acceptProposedAction();
1036 }
1037 void MainInterface::dragMoveEvent(QDragMoveEvent *event)
1038 {
1039      event->acceptProposedAction();
1040 }
1041 void MainInterface::dragLeaveEvent(QDragLeaveEvent *event)
1042 {
1043      event->accept();
1044 }
1045
1046 /************************************************************************
1047  * Events stuff
1048  ************************************************************************/
1049 void MainInterface::customEvent( QEvent *event )
1050 {
1051 #if 0
1052     if( event->type() == PLDockEvent_Type )
1053     {
1054         PlaylistDialog::killInstance();
1055         playlistEmbeddedFlag = true;
1056         menuBar()->clear();
1057         QVLCMenu::createMenuBar(this, p_intf, true, visualSelectorEnabled);
1058         togglePlaylist();
1059     }
1060 #endif
1061     /*else */
1062     if ( event->type() == SetVideoOnTopEvent_Type )
1063     {
1064         SetVideoOnTopQtEvent* p_event = (SetVideoOnTopQtEvent*)event;
1065         if( p_event->OnTop() )
1066             setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
1067         else
1068             setWindowFlags(windowFlags() & ~Qt::WindowStaysOnTopHint);
1069         show(); /* necessary to apply window flags?? */
1070     }
1071 }
1072
1073 void MainInterface::keyPressEvent( QKeyEvent *e )
1074 {
1075     if( ( e->modifiers() &  Qt::ControlModifier ) && ( e->key() & Qt::Key_H )
1076           && menuBar()->isHidden() )
1077     {
1078         toggleMinimalView();
1079         e->accept();
1080     }
1081
1082     int i_vlck = qtEventToVLCKey( e );
1083     if( i_vlck > 0 )
1084     {
1085         var_SetInteger( p_intf->p_libvlc, "key-pressed", i_vlck );
1086         e->accept();
1087     }
1088     else
1089         e->ignore();
1090 }
1091
1092 void MainInterface::wheelEvent( QWheelEvent *e )
1093 {
1094     int i_vlckey = qtWheelEventToVLCKey( e );
1095     var_SetInteger( p_intf->p_libvlc, "key-pressed", i_vlckey );
1096     e->accept();
1097 }
1098
1099 void MainInterface::closeEvent( QCloseEvent *e )
1100 {
1101     hide();
1102     vlc_object_kill( p_intf );
1103     QApplication::closeAllWindows();
1104     QApplication::quit();
1105 }
1106
1107 /*****************************************************************************
1108  * Callbacks
1109  *****************************************************************************/
1110 static int InteractCallback( vlc_object_t *p_this,
1111                              const char *psz_var, vlc_value_t old_val,
1112                              vlc_value_t new_val, void *param )
1113 {
1114     intf_dialog_args_t *p_arg = new intf_dialog_args_t;
1115     p_arg->p_dialog = (interaction_dialog_t *)(new_val.p_address);
1116     DialogEvent *event = new DialogEvent( INTF_DIALOG_INTERACTION, 0, p_arg );
1117     QApplication::postEvent( THEDP, static_cast<QEvent*>(event) );
1118     return VLC_SUCCESS;
1119 }
1120
1121 /*****************************************************************************
1122  * PopupMenuCB: callback triggered by the intf-popupmenu playlist variable.
1123  *  We don't show the menu directly here because we don't want the
1124  *  caller to block for a too long time.
1125  *****************************************************************************/
1126 static int PopupMenuCB( vlc_object_t *p_this, const char *psz_variable,
1127                         vlc_value_t old_val, vlc_value_t new_val, void *param )
1128 {
1129     intf_thread_t *p_intf = (intf_thread_t *)param;
1130
1131     if( p_intf->pf_show_dialog )
1132     {
1133         p_intf->pf_show_dialog( p_intf, INTF_DIALOG_POPUPMENU,
1134                                 new_val.b_bool, 0 );
1135     }
1136
1137     return VLC_SUCCESS;
1138 }
1139
1140 /*****************************************************************************
1141  * IntfShowCB: callback triggered by the intf-show playlist variable.
1142  *****************************************************************************/
1143 static int IntfShowCB( vlc_object_t *p_this, const char *psz_variable,
1144                        vlc_value_t old_val, vlc_value_t new_val, void *param )
1145 {
1146     intf_thread_t *p_intf = (intf_thread_t *)param;
1147     //p_intf->p_sys->b_intf_show = VLC_TRUE;
1148
1149     return VLC_SUCCESS;
1150 }