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