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