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