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