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