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