]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/interface_widgets.cpp
dc405d625966be37335f88e11c3aaf366d257a08
[vlc] / modules / gui / qt4 / components / interface_widgets.cpp
1 /*****************************************************************************
2  * interface_widgets.cpp : Custom widgets for the main interface
3  ****************************************************************************
4  * Copyright (C) 2006-2010 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Clément Stenac <zorglub@videolan.org>
8  *          Jean-Baptiste Kempf <jb@videolan.org>
9  *          Rafaël Carré <funman@videolanorg>
10  *          Ilkka Ollakka <ileoo@videolan.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * ( at your option ) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include "components/interface_widgets.hpp"
32
33 #include "menus.hpp"             /* Popup menu on bgWidget */
34
35 #include <vlc_vout.h>
36
37 #include <QLabel>
38 #include <QToolButton>
39 #include <QPalette>
40 #include <QResizeEvent>
41 #include <QDate>
42 #include <QMenu>
43 #include <QWidgetAction>
44 #include <QDesktopWidget>
45 #include <QPainter>
46 #include <QTimer>
47 #include <QSlider>
48
49 #ifdef Q_WS_X11
50 # include <X11/Xlib.h>
51 # include <qx11info_x11.h>
52 static void videoSync( void )
53 {
54     /* Make sure the X server has processed all requests.
55      * This protects other threads using distinct connections from getting
56      * the video widget window in an inconsistent states. */
57     XSync( QX11Info::display(), False );
58 }
59 #else
60 # define videoSync() (void)0
61 #endif
62
63 #include <math.h>
64 #include <assert.h>
65
66 class ReparentableWidget : public QWidget
67 {
68 private:
69     VideoWidget *owner;
70 public:
71     ReparentableWidget( VideoWidget *owner ) : owner( owner )
72     {
73     }
74
75 protected:
76     void keyPressEvent( QKeyEvent *e )
77     {
78         emit owner->keyPressed( e );
79     }
80 };
81
82 /**********************************************************************
83  * Video Widget. A simple frame on which video is drawn
84  * This class handles resize issues
85  **********************************************************************/
86
87 VideoWidget::VideoWidget( intf_thread_t *_p_i )
88     : QFrame( NULL )
89       , p_intf( _p_i )
90       , reparentable( NULL )
91 {
92     /* Set the policy to expand in both directions */
93     // setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
94
95     layout = new QHBoxLayout( this );
96     layout->setContentsMargins( 0, 0, 0, 0 );
97     setLayout( layout );
98 }
99
100 VideoWidget::~VideoWidget()
101 {
102     /* Ensure we are not leaking the video output. This would crash. */
103     assert( reparentable == NULL );
104 }
105
106 /**
107  * Request the video to avoid the conflicts
108  **/
109 WId VideoWidget::request( int *pi_x, int *pi_y,
110                           unsigned int *pi_width, unsigned int *pi_height,
111                           bool b_keep_size )
112 {
113     msg_Dbg( p_intf, "Video was requested %i, %i", *pi_x, *pi_y );
114
115     if( reparentable != NULL )
116     {
117         msg_Dbg( p_intf, "embedded video already in use" );
118         return NULL;
119     }
120     if( b_keep_size )
121     {
122         *pi_width  = size().width();
123         *pi_height = size().height();
124     }
125
126     /* The Qt4 UI needs a fixed a widget ("this"), so that the parent layout is
127      * not messed up when we the video is reparented. Hence, we create an extra
128      * reparentable widget, that will be within the VideoWidget in windowed
129      * mode, and within the root window (NULL parent) in full-screen mode.
130      */
131     reparentable = new ReparentableWidget( this );
132     QLayout *innerLayout = new QHBoxLayout( reparentable );
133     innerLayout->setContentsMargins( 0, 0, 0, 0 );
134
135     /* The owner of the video window needs a stable handle (WinId). Reparenting
136      * in Qt4-X11 changes the WinId of the widget, so we need to create another
137      * dummy widget that stays within the reparentable widget. */
138     QWidget *stable = new QWidget();
139     QPalette plt = palette();
140     plt.setColor( QPalette::Window, Qt::black );
141     stable->setPalette( plt );
142     stable->setAutoFillBackground(true);
143     /* Indicates that the widget wants to draw directly onto the screen.
144        Widgets with this attribute set do not participate in composition
145        management */
146     stable->setAttribute( Qt::WA_PaintOnScreen, true );
147
148     innerLayout->addWidget( stable );
149
150     layout->addWidget( reparentable );
151
152 #ifdef Q_WS_X11
153     /* HACK: Only one X11 client can subscribe to mouse button press events.
154      * VLC currently handles those in the video display.
155      * Force Qt4 to unsubscribe from mouse press and release events. */
156     Display *dpy = QX11Info::display();
157     Window w = stable->winId();
158     XWindowAttributes attr;
159
160     XGetWindowAttributes( dpy, w, &attr );
161     attr.your_event_mask &= ~(ButtonPressMask|ButtonReleaseMask);
162     XSelectInput( dpy, w, attr.your_event_mask );
163 #endif
164     videoSync();
165 #ifndef NDEBUG
166     msg_Dbg( p_intf, "embedded video ready (handle %p)",
167              (void *)stable->winId() );
168 #endif
169     return stable->winId();
170 }
171
172 /* Set the Widget to the correct Size */
173 /* Function has to be called by the parent
174    Parent has to care about resizing itself */
175 void VideoWidget::SetSizing( unsigned int w, unsigned int h )
176 {
177     if (reparentable->windowState() & Qt::WindowFullScreen )
178         return;
179     msg_Dbg( p_intf, "Video is resizing to: %i %i", w, h );
180     videoSize.setWidth( w );
181     videoSize.setHeight( h );
182     if( !isVisible() ) show();
183     updateGeometry(); // Needed for deinterlace
184     videoSync();
185 }
186
187 void VideoWidget::SetFullScreen( bool b_fs )
188 {
189     const Qt::WindowStates curstate = reparentable->windowState();
190     Qt::WindowStates newstate = curstate;
191     Qt::WindowFlags  newflags = reparentable->windowFlags();
192
193
194     if( b_fs )
195     {
196         newstate |= Qt::WindowFullScreen;
197         newflags |= Qt::WindowStaysOnTopHint;
198     }
199     else
200     {
201         newstate &= ~Qt::WindowFullScreen;
202         newflags &= ~Qt::WindowStaysOnTopHint;
203     }
204     if( newstate == curstate )
205         return; /* no changes needed */
206
207     if( b_fs )
208     {   /* Go full-screen */
209         int numscreen = var_InheritInteger( p_intf, "qt-fullscreen-screennumber" );
210         /* if user hasn't defined screennumber, or screennumber that is bigger
211          * than current number of screens, take screennumber where current interface
212          * is
213          */
214         if( numscreen == -1 || numscreen > QApplication::desktop()->numScreens() )
215             numscreen = QApplication::desktop()->screenNumber( p_intf->p_sys->p_mi );
216
217         QRect screenres = QApplication::desktop()->screenGeometry( numscreen );
218
219         reparentable->setParent( NULL, newflags );
220         reparentable->setWindowState( newstate );
221         /* To be sure window is on proper-screen in xinerama */
222         if( !screenres.contains( reparentable->pos() ) )
223         {
224             msg_Dbg( p_intf, "Moving video to correct screen");
225             reparentable->move( QPoint( screenres.x(), screenres.y() ) );
226         }
227         reparentable->show();
228     }
229     else
230     {   /* Go windowed */
231         reparentable->setWindowFlags( newflags );
232         reparentable->setWindowState( newstate );
233         layout->addWidget( reparentable );
234     }
235     videoSync();
236 }
237
238 void VideoWidget::release( void )
239 {
240     msg_Dbg( p_intf, "Video is not needed anymore" );
241     //layout->removeWidget( reparentable );
242
243 #ifdef WIN32
244     /* Come back to default thumbnail for Windows 7 taskbar */
245     LPTASKBARLIST3 p_taskbl;
246
247     CoInitialize( 0 );
248
249     if( S_OK == CoCreateInstance( &clsid_ITaskbarList,
250                 NULL, CLSCTX_INPROC_SERVER,
251                 &IID_ITaskbarList3,
252                 (void **)&p_taskbl) )
253     {
254         p_taskbl->vt->HrInit(p_taskbl);
255
256         HWND hroot = GetAncestor(reparentable->winId(),GA_ROOT);
257
258         if (S_OK != p_taskbl->vt->SetThumbnailClip(p_taskbl, hroot, NULL))
259             msg_Err(p_intf, "SetThumbNailClip failed");
260         msg_Err(p_intf, "Releasing taskbar | root handle = %08x", hroot);
261         p_taskbl->vt->Release(p_taskbl);
262     }
263     CoUninitialize();
264
265 #endif
266
267     delete reparentable;
268     reparentable = NULL;
269     videoSize = QSize();
270     updateGeometry();
271     hide();
272 }
273
274
275 QSize VideoWidget::sizeHint() const
276 {
277     return videoSize;
278 }
279
280 /**********************************************************************
281  * Background Widget. Show a simple image background. Currently,
282  * it's album art if present or cone.
283  **********************************************************************/
284 #define ICON_SIZE 128
285 #define MAX_BG_SIZE 400
286 #define MIN_BG_SIZE 128
287 #define MARGIN 5
288
289 BackgroundWidget::BackgroundWidget( intf_thread_t *_p_i )
290                  :QWidget( NULL ), p_intf( _p_i )
291 {
292     /* We should use that one to take the more size it can */
293     //setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding);
294
295     /* A dark background */
296     setAutoFillBackground( true );
297     QPalette plt = palette();
298     plt.setColor( QPalette::Active, QPalette::Window , Qt::black );
299     plt.setColor( QPalette::Inactive, QPalette::Window , Qt::black );
300     setPalette( plt );
301
302     /* A cone in the middle */
303     label = new QLabel;
304     label->setMargin( MARGIN );
305     label->setAlignment( Qt::AlignCenter );
306
307     /* Init the cone art */
308     updateArt( "" );
309
310     /* Grid, because of the visual selector */
311     QGridLayout *backgroundLayout = new QGridLayout( this );
312     backgroundLayout->setMargin( 0 );
313     backgroundLayout->addWidget( label, 0, 1 );
314     backgroundLayout->setColumnStretch( 0, 1 );
315     backgroundLayout->setColumnStretch( 2, 1 );
316
317     CONNECT( THEMIM->getIM(), artChanged( QString ),
318              this, updateArt( const QString& ) );
319
320     /* Start Hidden */
321     label->hide();
322 }
323
324 void BackgroundWidget::resizeEvent( QResizeEvent * event )
325 {
326     if( event->size().height() <= MIN_BG_SIZE + MARGIN * 2 + 2 )
327         label->hide();
328     else
329         label->show();
330 }
331
332 void BackgroundWidget::updateArt( const QString& url )
333 {
334     if( url.isEmpty() )
335     {
336         /* Xmas joke */
337         if( QDate::currentDate().dayOfYear() >= 354 )
338             label->setPixmap( QPixmap( ":/logo/vlc128-christmas.png" ) );
339         else
340             label->setPixmap( QPixmap( ":/logo/vlc128.png" ) );
341     }
342     else
343     {
344         QPixmap pixmap( url );
345         if( pixmap.width() > label->maximumWidth() ||
346             pixmap.height() > label->maximumHeight() )
347         {
348             pixmap = pixmap.scaled( label->maximumWidth(),
349                           label->maximumHeight(), Qt::KeepAspectRatio );
350         }
351
352         label->setPixmap( pixmap );
353     }
354 }
355
356 void BackgroundWidget::contextMenuEvent( QContextMenuEvent *event )
357 {
358     QVLCMenu::PopupMenu( p_intf, true );
359     event->accept();
360 }
361
362 #if 0
363 #include <QPushButton>
364 #include <QHBoxLayout>
365
366 /**********************************************************************
367  * Visualization selector panel
368  **********************************************************************/
369 VisualSelector::VisualSelector( intf_thread_t *_p_i ) :
370                                 QFrame( NULL ), p_intf( _p_i )
371 {
372     QHBoxLayout *layout = new QHBoxLayout( this );
373     layout->setMargin( 0 );
374     QPushButton *prevButton = new QPushButton( "Prev" );
375     QPushButton *nextButton = new QPushButton( "Next" );
376     layout->addWidget( prevButton );
377     layout->addWidget( nextButton );
378
379     layout->addStretch( 10 );
380     layout->addWidget( new QLabel( qtr( "Current visualization" ) ) );
381
382     current = new QLabel( qtr( "None" ) );
383     layout->addWidget( current );
384
385     BUTTONACT( prevButton, prev() );
386     BUTTONACT( nextButton, next() );
387
388     setLayout( layout );
389     setMaximumHeight( 35 );
390 }
391
392 VisualSelector::~VisualSelector()
393 {}
394
395 void VisualSelector::prev()
396 {
397     char *psz_new = aout_VisualPrev( p_intf );
398     if( psz_new )
399     {
400         current->setText( qfu( psz_new ) );
401         free( psz_new );
402     }
403 }
404
405 void VisualSelector::next()
406 {
407     char *psz_new = aout_VisualNext( p_intf );
408     if( psz_new )
409     {
410         current->setText( qfu( psz_new ) );
411         free( psz_new );
412     }
413 }
414 #endif
415
416 SpeedLabel::SpeedLabel( intf_thread_t *_p_intf, QWidget *parent )
417            : QLabel( parent ), p_intf( _p_intf )
418 {
419     setToolTip( qtr( "Current playback speed.\nClick to adjust" ) );
420
421     /* Create the Speed Control Widget */
422     speedControl = new SpeedControlWidget( p_intf, this );
423     speedControlMenu = new QMenu( this );
424
425     QWidgetAction *widgetAction = new QWidgetAction( speedControl );
426     widgetAction->setDefaultWidget( speedControl );
427     speedControlMenu->addAction( widgetAction );
428
429     /* Change the SpeedRate in the Status Bar */
430     CONNECT( THEMIM->getIM(), rateChanged( float ), this, setRate( float ) );
431
432     DCONNECT( THEMIM, inputChanged( input_thread_t * ),
433               speedControl, activateOnState() );
434     setRate( var_InheritFloat( p_intf, "rate" ) );
435 }
436
437 SpeedLabel::~SpeedLabel()
438 {
439     delete speedControl;
440     delete speedControlMenu;
441 }
442
443 /****************************************************************************
444  * Small right-click menu for rate control
445  ****************************************************************************/
446
447 void SpeedLabel::showSpeedMenu( QPoint pos )
448 {
449     speedControlMenu->exec( QCursor::pos() - pos
450                           + QPoint( 0, height() ) );
451 }
452
453 void SpeedLabel::setRate( float rate )
454 {
455     QString str;
456     str.setNum( rate, 'f', 2 );
457     str.append( "x" );
458     setText( str );
459     setToolTip( str );
460     speedControl->updateControls( rate );
461 }
462
463 /**********************************************************************
464  * Speed control widget
465  **********************************************************************/
466 SpeedControlWidget::SpeedControlWidget( intf_thread_t *_p_i, QWidget *_parent )
467                     : QFrame( _parent ), p_intf( _p_i )
468 {
469     QSizePolicy sizePolicy( QSizePolicy::Maximum, QSizePolicy::Fixed );
470     sizePolicy.setHorizontalStretch( 0 );
471     sizePolicy.setVerticalStretch( 0 );
472
473     speedSlider = new QSlider( this );
474     speedSlider->setSizePolicy( sizePolicy );
475     speedSlider->setMaximumSize( QSize( 80, 200 ) );
476     speedSlider->setOrientation( Qt::Vertical );
477     speedSlider->setTickPosition( QSlider::TicksRight );
478
479     speedSlider->setRange( -34, 34 );
480     speedSlider->setSingleStep( 1 );
481     speedSlider->setPageStep( 1 );
482     speedSlider->setTickInterval( 17 );
483
484     CONNECT( speedSlider, valueChanged( int ), this, updateRate( int ) );
485
486     QToolButton *normalSpeedButton = new QToolButton( this );
487     normalSpeedButton->setMaximumSize( QSize( 26, 20 ) );
488     normalSpeedButton->setAutoRaise( true );
489     normalSpeedButton->setText( "1x" );
490     normalSpeedButton->setToolTip( qtr( "Revert to normal play speed" ) );
491
492     CONNECT( normalSpeedButton, clicked(), this, resetRate() );
493
494     QVBoxLayout *speedControlLayout = new QVBoxLayout( this );
495     speedControlLayout->setContentsMargins( 4, 4, 4, 4 );
496     speedControlLayout->setSpacing( 4 );
497     speedControlLayout->addWidget( speedSlider );
498     speedControlLayout->addWidget( normalSpeedButton );
499
500     activateOnState();
501 }
502
503 void SpeedControlWidget::activateOnState()
504 {
505     speedSlider->setEnabled( THEMIM->getIM()->hasInput() );
506 }
507
508 void SpeedControlWidget::updateControls( float rate )
509 {
510     if( speedSlider->isSliderDown() )
511     {
512         //We don't want to change anything if the user is using the slider
513         return;
514     }
515
516     double value = 17 * log( rate ) / log( 2 );
517     int sliderValue = (int) ( ( value > 0 ) ? value + .5 : value - .5 );
518
519     if( sliderValue < speedSlider->minimum() )
520     {
521         sliderValue = speedSlider->minimum();
522     }
523     else if( sliderValue > speedSlider->maximum() )
524     {
525         sliderValue = speedSlider->maximum();
526     }
527
528     speedSlider->setValue( sliderValue );
529 }
530
531 void SpeedControlWidget::updateRate( int sliderValue )
532 {
533     double speed = pow( 2, (double)sliderValue / 17 );
534     int rate = INPUT_RATE_DEFAULT / speed;
535
536     THEMIM->getIM()->setRate(rate);
537 }
538
539 void SpeedControlWidget::resetRate()
540 {
541     THEMIM->getIM()->setRate( INPUT_RATE_DEFAULT );
542 }
543
544 CoverArtLabel::CoverArtLabel( QWidget *parent, intf_thread_t *_p_i )
545               : QLabel( parent ), p_intf( _p_i )
546 {
547     setContextMenuPolicy( Qt::ActionsContextMenu );
548     CONNECT( this, updateRequested(), this, askForUpdate() );
549
550     setMinimumHeight( 128 );
551     setMinimumWidth( 128 );
552     setMaximumHeight( 128 );
553     setMaximumWidth( 128 );
554     setScaledContents( false );
555     setAlignment( Qt::AlignCenter );
556
557     QList< QAction* > artActions = actions();
558     QAction *action = new QAction( qtr( "Download cover art" ), this );
559     CONNECT( action, triggered(), this, askForUpdate() );
560     addAction( action );
561
562     showArtUpdate( "" );
563 }
564
565 CoverArtLabel::~CoverArtLabel()
566 {
567     QList< QAction* > artActions = actions();
568     foreach( QAction *act, artActions )
569         removeAction( act );
570 }
571
572 void CoverArtLabel::showArtUpdate( const QString& url )
573 {
574     QPixmap pix;
575     if( !url.isEmpty() && pix.load( url ) )
576     {
577         pix = pix.scaled( maximumWidth(), maximumHeight(),
578                           Qt::KeepAspectRatioByExpanding );
579     }
580     else
581     {
582         pix = QPixmap( ":/noart.png" );
583     }
584     setPixmap( pix );
585 }
586
587 void CoverArtLabel::askForUpdate()
588 {
589     THEMIM->getIM()->requestArtUpdate();
590 }
591
592 TimeLabel::TimeLabel( intf_thread_t *_p_intf  )
593     : QLabel(), p_intf( _p_intf ), bufTimer( new QTimer(this) ),
594       buffering( false ), showBuffering(false), bufVal( -1 )
595 {
596     b_remainingTime = false;
597     setText( " --:--/--:-- " );
598     setAlignment( Qt::AlignRight | Qt::AlignVCenter );
599     setToolTip( qtr( "Toggle between elapsed and remaining time" ) );
600     bufTimer->setSingleShot( true );
601
602     CONNECT( THEMIM->getIM(), positionUpdated( float, int64_t, int ),
603               this, setDisplayPosition( float, int64_t, int ) );
604     CONNECT( THEMIM->getIM(), cachingChanged( float ),
605               this, updateBuffering( float ) );
606     CONNECT( bufTimer, timeout(), this, updateBuffering() );
607 }
608
609 void TimeLabel::setDisplayPosition( float pos, int64_t t, int length )
610 {
611     showBuffering = false;
612     bufTimer->stop();
613
614     if( pos == -1.f )
615     {
616         setText( " --:--/--:-- " );
617         return;
618     }
619
620     int time = t / 1000000;
621
622     secstotimestr( psz_length, length );
623     secstotimestr( psz_time, ( b_remainingTime && length ) ? length - time
624                                                            : time );
625
626     QString timestr;
627     timestr.sprintf( " %s%s/%s ", (b_remainingTime && length) ? "-" : "",
628                      psz_time, ( !length && time ) ? "--:--" : psz_length );
629
630     setText( timestr );
631
632     cachedLength = length;
633 }
634
635 void TimeLabel::setDisplayPosition( float pos )
636 {
637     if( pos == -1.f || cachedLength == 0 )
638     {
639         setText( " --:--/--:-- " );
640         return;
641     }
642
643     int time = pos * cachedLength;
644     secstotimestr( psz_time,
645                    ( b_remainingTime && cachedLength ?
646                    cachedLength - time : time ) );
647     QString timestr;
648     timestr.sprintf( " %s%s/%s ", (b_remainingTime && cachedLength) ? "-" : "",
649                      psz_time, ( !cachedLength && time ) ? "--:--" : psz_length );
650
651     setText( timestr );
652 }
653
654
655 void TimeLabel::toggleTimeDisplay()
656 {
657     b_remainingTime = !b_remainingTime;
658 }
659
660
661 void TimeLabel::updateBuffering( float _buffered )
662 {
663     bufVal = _buffered;
664     if( !buffering || bufVal == 0 )
665     {
666         showBuffering = false;
667         buffering = true;
668         bufTimer->start(200);
669     }
670     else if( bufVal == 1 )
671     {
672         showBuffering = buffering = false;
673         bufTimer->stop();
674     }
675     update();
676 }
677
678 void TimeLabel::updateBuffering()
679 {
680     showBuffering = true;
681     update();
682 }
683
684 void TimeLabel::paintEvent( QPaintEvent* event )
685 {
686     if( showBuffering )
687     {
688         QRect r( rect() );
689         r.setLeft( r.width() * bufVal );
690         QPainter p( this );
691         p.setOpacity( 0.4 );
692         p.fillRect( r, palette().color( QPalette::Highlight ) );
693     }
694     QLabel::paintEvent( event );
695 }