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