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