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