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