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