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