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