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