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