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