]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/interface_widgets.cpp
756630b603d228be8c08884d60edf26c75eec159
[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::resizeEvent( QResizeEvent * event )
295 {
296     updateArt( "" );
297     QWidget::resizeEvent( event );
298 }
299
300 void BackgroundWidget::updateArt( const QString& url )
301 {
302     if ( !url.isEmpty() )
303     {
304         pixmapUrl = url;
305     }
306     else
307     {   /* Xmas joke */
308         if( QDate::currentDate().dayOfYear() >= 354 )
309             pixmapUrl = QString( ":/logo/vlc128-christmas.png" );
310         else
311             pixmapUrl = QString( ":/logo/vlc128.png" );
312     }
313 }
314
315 void BackgroundWidget::paintEvent( QPaintEvent *e )
316 {
317     int i_maxwidth, i_maxheight;
318     QPixmap pixmap = QPixmap( pixmapUrl );
319     QPainter painter(this);
320     QBitmap pMask;
321     float f_alpha = 1.0;
322
323     i_maxwidth = std::min( maximumWidth(), width() ) - MARGIN * 2;
324     i_maxheight = std::min( maximumHeight(), height() ) - MARGIN * 2;
325
326     if ( height() > MARGIN * 2 )
327     {
328         /* Scale down the pixmap if the widget is too small */
329         if( pixmap.width() > i_maxwidth || pixmap.height() > i_maxheight )
330         {
331             pixmap = pixmap.scaled( i_maxwidth, i_maxheight,
332                             Qt::KeepAspectRatio, Qt::SmoothTransformation );
333         }
334         else
335         if ( b_expandPixmap &&
336              pixmap.width() < width() && pixmap.height() < height() )
337         {
338             /* Scale up the pixmap to fill widget's size */
339             f_alpha = ( (float) pixmap.height() / (float) height() );
340             pixmap = pixmap.scaled(
341                     width() - MARGIN * 2,
342                     height() - MARGIN * 2,
343                     Qt::KeepAspectRatio,
344                     ( f_alpha < .2 )? /* Don't waste cpu when not visible */
345                         Qt::SmoothTransformation:
346                         Qt::FastTransformation
347                     );
348             /* Non agressive alpha compositing when sizing up */
349             pMask = QBitmap( pixmap.width(), pixmap.height() );
350             pMask.fill( QColor::fromRgbF( 1.0, 1.0, 1.0, f_alpha ) );
351             pixmap.setMask( pMask );
352         }
353
354         painter.drawPixmap(
355                 MARGIN + ( i_maxwidth - pixmap.width() ) /2,
356                 MARGIN + ( i_maxheight - pixmap.height() ) /2,
357                 pixmap);
358     }
359     QWidget::paintEvent( e );
360 }
361
362 void BackgroundWidget::contextMenuEvent( QContextMenuEvent *event )
363 {
364     QVLCMenu::PopupMenu( p_intf, true );
365     event->accept();
366 }
367
368 #if 0
369 #include <QPushButton>
370 #include <QHBoxLayout>
371
372 /**********************************************************************
373  * Visualization selector panel
374  **********************************************************************/
375 VisualSelector::VisualSelector( intf_thread_t *_p_i ) :
376                                 QFrame( NULL ), p_intf( _p_i )
377 {
378     QHBoxLayout *layout = new QHBoxLayout( this );
379     layout->setMargin( 0 );
380     QPushButton *prevButton = new QPushButton( "Prev" );
381     QPushButton *nextButton = new QPushButton( "Next" );
382     layout->addWidget( prevButton );
383     layout->addWidget( nextButton );
384
385     layout->addStretch( 10 );
386     layout->addWidget( new QLabel( qtr( "Current visualization" ) ) );
387
388     current = new QLabel( qtr( "None" ) );
389     layout->addWidget( current );
390
391     BUTTONACT( prevButton, prev() );
392     BUTTONACT( nextButton, next() );
393
394     setLayout( layout );
395     setMaximumHeight( 35 );
396 }
397
398 VisualSelector::~VisualSelector()
399 {}
400
401 void VisualSelector::prev()
402 {
403     char *psz_new = aout_VisualPrev( p_intf );
404     if( psz_new )
405     {
406         current->setText( qfu( psz_new ) );
407         free( psz_new );
408     }
409 }
410
411 void VisualSelector::next()
412 {
413     char *psz_new = aout_VisualNext( p_intf );
414     if( psz_new )
415     {
416         current->setText( qfu( psz_new ) );
417         free( psz_new );
418     }
419 }
420 #endif
421
422 SpeedLabel::SpeedLabel( intf_thread_t *_p_intf, QWidget *parent )
423            : QLabel( parent ), p_intf( _p_intf )
424 {
425     setToolTip( qtr( "Current playback speed.\nClick to adjust" ) );
426
427     /* Create the Speed Control Widget */
428     speedControl = new SpeedControlWidget( p_intf, this );
429     speedControlMenu = new QMenu( this );
430
431     QWidgetAction *widgetAction = new QWidgetAction( speedControl );
432     widgetAction->setDefaultWidget( speedControl );
433     speedControlMenu->addAction( widgetAction );
434
435     /* Change the SpeedRate in the Status Bar */
436     CONNECT( THEMIM->getIM(), rateChanged( float ), this, setRate( float ) );
437
438     DCONNECT( THEMIM, inputChanged( input_thread_t * ),
439               speedControl, activateOnState() );
440     setRate( var_InheritFloat( p_intf, "rate" ) );
441 }
442
443 SpeedLabel::~SpeedLabel()
444 {
445     delete speedControl;
446     delete speedControlMenu;
447 }
448
449 /****************************************************************************
450  * Small right-click menu for rate control
451  ****************************************************************************/
452
453 void SpeedLabel::showSpeedMenu( QPoint pos )
454 {
455     speedControlMenu->exec( QCursor::pos() - pos
456                           + QPoint( 0, height() ) );
457 }
458
459 void SpeedLabel::setRate( float rate )
460 {
461     QString str;
462     str.setNum( rate, 'f', 2 );
463     str.append( "x" );
464     setText( str );
465     setToolTip( str );
466     speedControl->updateControls( rate );
467 }
468
469 /**********************************************************************
470  * Speed control widget
471  **********************************************************************/
472 SpeedControlWidget::SpeedControlWidget( intf_thread_t *_p_i, QWidget *_parent )
473                     : QFrame( _parent ), p_intf( _p_i )
474 {
475     QSizePolicy sizePolicy( QSizePolicy::Maximum, QSizePolicy::Fixed );
476     sizePolicy.setHorizontalStretch( 0 );
477     sizePolicy.setVerticalStretch( 0 );
478
479     speedSlider = new QSlider( this );
480     speedSlider->setSizePolicy( sizePolicy );
481     speedSlider->setMaximumSize( QSize( 80, 200 ) );
482     speedSlider->setOrientation( Qt::Vertical );
483     speedSlider->setTickPosition( QSlider::TicksRight );
484
485     speedSlider->setRange( -34, 34 );
486     speedSlider->setSingleStep( 1 );
487     speedSlider->setPageStep( 1 );
488     speedSlider->setTickInterval( 17 );
489
490     CONNECT( speedSlider, valueChanged( int ), this, updateRate( int ) );
491
492     QToolButton *normalSpeedButton = new QToolButton( this );
493     normalSpeedButton->setMaximumSize( QSize( 26, 20 ) );
494     normalSpeedButton->setAutoRaise( true );
495     normalSpeedButton->setText( "1x" );
496     normalSpeedButton->setToolTip( qtr( "Revert to normal play speed" ) );
497
498     CONNECT( normalSpeedButton, clicked(), this, resetRate() );
499
500     QVBoxLayout *speedControlLayout = new QVBoxLayout( this );
501     speedControlLayout->setContentsMargins( 4, 4, 4, 4 );
502     speedControlLayout->setSpacing( 4 );
503     speedControlLayout->addWidget( speedSlider );
504     speedControlLayout->addWidget( normalSpeedButton );
505
506     activateOnState();
507 }
508
509 void SpeedControlWidget::activateOnState()
510 {
511     speedSlider->setEnabled( THEMIM->getIM()->hasInput() );
512 }
513
514 void SpeedControlWidget::updateControls( float rate )
515 {
516     if( speedSlider->isSliderDown() )
517     {
518         //We don't want to change anything if the user is using the slider
519         return;
520     }
521
522     double value = 17 * log( rate ) / log( 2 );
523     int sliderValue = (int) ( ( value > 0 ) ? value + .5 : value - .5 );
524
525     if( sliderValue < speedSlider->minimum() )
526     {
527         sliderValue = speedSlider->minimum();
528     }
529     else if( sliderValue > speedSlider->maximum() )
530     {
531         sliderValue = speedSlider->maximum();
532     }
533
534     speedSlider->setValue( sliderValue );
535 }
536
537 void SpeedControlWidget::updateRate( int sliderValue )
538 {
539     double speed = pow( 2, (double)sliderValue / 17 );
540     int rate = INPUT_RATE_DEFAULT / speed;
541
542     THEMIM->getIM()->setRate(rate);
543 }
544
545 void SpeedControlWidget::resetRate()
546 {
547     THEMIM->getIM()->setRate( INPUT_RATE_DEFAULT );
548 }
549
550 CoverArtLabel::CoverArtLabel( QWidget *parent, intf_thread_t *_p_i )
551               : QLabel( parent ), p_intf( _p_i )
552 {
553     setContextMenuPolicy( Qt::ActionsContextMenu );
554     CONNECT( this, updateRequested(), this, askForUpdate() );
555
556     setMinimumHeight( 128 );
557     setMinimumWidth( 128 );
558     setMaximumHeight( 128 );
559     setMaximumWidth( 128 );
560     setScaledContents( false );
561     setAlignment( Qt::AlignCenter );
562
563     QList< QAction* > artActions = actions();
564     QAction *action = new QAction( qtr( "Download cover art" ), this );
565     CONNECT( action, triggered(), this, askForUpdate() );
566     addAction( action );
567
568     showArtUpdate( "" );
569 }
570
571 CoverArtLabel::~CoverArtLabel()
572 {
573     QList< QAction* > artActions = actions();
574     foreach( QAction *act, artActions )
575         removeAction( act );
576 }
577
578 void CoverArtLabel::showArtUpdate( const QString& url )
579 {
580     QPixmap pix;
581     if( !url.isEmpty() && pix.load( url ) )
582     {
583         pix = pix.scaled( maximumWidth(), maximumHeight(),
584                           Qt::KeepAspectRatioByExpanding );
585     }
586     else
587     {
588         pix = QPixmap( ":/noart.png" );
589     }
590     setPixmap( pix );
591 }
592
593 void CoverArtLabel::askForUpdate()
594 {
595     THEMIM->getIM()->requestArtUpdate();
596 }
597
598 TimeLabel::TimeLabel( intf_thread_t *_p_intf  )
599     : QLabel(), p_intf( _p_intf ), bufTimer( new QTimer(this) ),
600       buffering( false ), showBuffering(false), bufVal( -1 )
601 {
602     b_remainingTime = false;
603     setText( " --:--/--:-- " );
604     setAlignment( Qt::AlignRight | Qt::AlignVCenter );
605     setToolTip( qtr( "Toggle between elapsed and remaining time" ) );
606     bufTimer->setSingleShot( true );
607
608     CONNECT( THEMIM->getIM(), positionUpdated( float, int64_t, int ),
609               this, setDisplayPosition( float, int64_t, int ) );
610     CONNECT( THEMIM->getIM(), cachingChanged( float ),
611               this, updateBuffering( float ) );
612     CONNECT( bufTimer, timeout(), this, updateBuffering() );
613 }
614
615 void TimeLabel::setDisplayPosition( float pos, int64_t t, int length )
616 {
617     showBuffering = false;
618     bufTimer->stop();
619
620     if( pos == -1.f )
621     {
622         setText( " --:--/--:-- " );
623         return;
624     }
625
626     int time = t / 1000000;
627
628     secstotimestr( psz_length, length );
629     secstotimestr( psz_time, ( b_remainingTime && length ) ? length - time
630                                                            : time );
631
632     QString timestr;
633     timestr.sprintf( " %s%s/%s ", (b_remainingTime && length) ? "-" : "",
634                      psz_time, ( !length && time ) ? "--:--" : psz_length );
635
636     setText( timestr );
637
638     cachedLength = length;
639 }
640
641 void TimeLabel::setDisplayPosition( float pos )
642 {
643     if( pos == -1.f || cachedLength == 0 )
644     {
645         setText( " --:--/--:-- " );
646         return;
647     }
648
649     int time = pos * cachedLength;
650     secstotimestr( psz_time,
651                    ( b_remainingTime && cachedLength ?
652                    cachedLength - time : time ) );
653     QString timestr;
654     timestr.sprintf( " %s%s/%s ", (b_remainingTime && cachedLength) ? "-" : "",
655                      psz_time, ( !cachedLength && time ) ? "--:--" : psz_length );
656
657     setText( timestr );
658 }
659
660
661 void TimeLabel::toggleTimeDisplay()
662 {
663     b_remainingTime = !b_remainingTime;
664 }
665
666
667 void TimeLabel::updateBuffering( float _buffered )
668 {
669     bufVal = _buffered;
670     if( !buffering || bufVal == 0 )
671     {
672         showBuffering = false;
673         buffering = true;
674         bufTimer->start(200);
675     }
676     else if( bufVal == 1 )
677     {
678         showBuffering = buffering = false;
679         bufTimer->stop();
680     }
681     update();
682 }
683
684 void TimeLabel::updateBuffering()
685 {
686     showBuffering = true;
687     update();
688 }
689
690 void TimeLabel::paintEvent( QPaintEvent* event )
691 {
692     if( showBuffering )
693     {
694         QRect r( rect() );
695         r.setLeft( r.width() * bufVal );
696         QPainter p( this );
697         p.setOpacity( 0.4 );
698         p.fillRect( r, palette().color( QPalette::Highlight ) );
699     }
700     QLabel::paintEvent( event );
701 }