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