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