]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/interface_widgets.cpp
Fixed preparsing/art fetching locking.
[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
45 #ifdef Q_WS_X11
46 # include <X11/Xlib.h>
47 # include <qx11info_x11.h>
48 #endif
49
50 #include <math.h>
51
52 /**********************************************************************
53  * Video Widget. A simple frame on which video is drawn
54  * This class handles resize issues
55  **********************************************************************/
56
57 VideoWidget::VideoWidget( intf_thread_t *_p_i ) : QFrame( NULL ), p_intf( _p_i )
58 {
59     /* Init */
60     p_vout = NULL;
61     videoSize.rwidth() = -1;
62     videoSize.rheight() = -1;
63
64     hide();
65
66     /* Set the policy to expand in both directions */
67 //    setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
68
69     /* Black background is more coherent for a Video Widget */
70     QPalette plt =  palette();
71     plt.setColor( QPalette::Window, Qt::black );
72     setPalette( plt );
73     setAutoFillBackground(true);
74
75     /* Indicates that the widget wants to draw directly onto the screen.
76        Widgets with this attribute set do not participate in composition
77        management */
78     setAttribute( Qt::WA_PaintOnScreen, true );
79
80     /* The core can ask through a callback to show the video. */
81     connect( this, SIGNAL(askVideoWidgetToShow( unsigned int, unsigned int)),
82              this, SLOT(SetSizing(unsigned int, unsigned int )),
83              Qt::BlockingQueuedConnection );
84 }
85
86 void VideoWidget::paintEvent(QPaintEvent *ev)
87 {
88     QFrame::paintEvent(ev);
89 #ifdef Q_WS_X11
90     XFlush( QX11Info::display() );
91 #endif
92 }
93
94 VideoWidget::~VideoWidget()
95 {
96     /* Ensure we are not leaking the video output. This would crash. */
97     assert( !p_vout );
98 }
99
100 /**
101  * Request the video to avoid the conflicts
102  **/
103 void *VideoWidget::request( vout_thread_t *p_nvout, int *pi_x, int *pi_y,
104                             unsigned int *pi_width, unsigned int *pi_height )
105 {
106     msg_Dbg( p_intf, "Video was requested %i, %i", *pi_x, *pi_y );
107     emit askVideoWidgetToShow( *pi_width, *pi_height );
108     if( p_vout )
109     {
110         msg_Dbg( p_intf, "embedded video already in use" );
111         return NULL;
112     }
113     p_vout = p_nvout;
114 #ifndef NDEBUG
115     msg_Dbg( p_intf, "embedded video ready (handle %p)", winId() );
116 #endif
117     return ( void* )winId();
118 }
119
120 /* Set the Widget to the correct Size */
121 /* Function has to be called by the parent
122    Parent has to care about resizing himself*/
123 void VideoWidget::SetSizing( unsigned int w, unsigned int h )
124 {
125     msg_Dbg( p_intf, "Video is resizing to: %i %i", w, h );
126     videoSize.rwidth() = w;
127     videoSize.rheight() = h;
128     if( isHidden() ) show();
129     updateGeometry(); // Needed for deinterlace
130 }
131
132 void VideoWidget::release( void )
133 {
134     msg_Dbg( p_intf, "Video is not needed anymore" );
135     p_vout = NULL;
136     videoSize.rwidth() = 0;
137     videoSize.rheight() = 0;
138     updateGeometry();
139     hide();
140 }
141
142 QSize VideoWidget::sizeHint() const
143 {
144     return videoSize;
145 }
146
147 /**********************************************************************
148  * Background Widget. Show a simple image background. Currently,
149  * it's album art if present or cone.
150  **********************************************************************/
151 #define ICON_SIZE 128
152 #define MAX_BG_SIZE 400
153 #define MIN_BG_SIZE 128
154
155 BackgroundWidget::BackgroundWidget( intf_thread_t *_p_i )
156                  :QWidget( NULL ), p_intf( _p_i )
157 {
158     /* We should use that one to take the more size it can */
159     setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding);
160
161     /* A dark background */
162     setAutoFillBackground( true );
163     plt = palette();
164     plt.setColor( QPalette::Active, QPalette::Window , Qt::black );
165     plt.setColor( QPalette::Inactive, QPalette::Window , Qt::black );
166     setPalette( plt );
167
168     /* A cone in the middle */
169     label = new QLabel;
170     label->setMargin( 5 );
171     label->setMaximumHeight( MAX_BG_SIZE );
172     label->setMaximumWidth( MAX_BG_SIZE );
173     label->setMinimumHeight( MIN_BG_SIZE );
174     label->setMinimumWidth( MIN_BG_SIZE );
175     if( QDate::currentDate().dayOfYear() >= 354 )
176         label->setPixmap( QPixmap( ":/vlc128-christmas.png" ) );
177     else
178         label->setPixmap( QPixmap( ":/vlc128.png" ) );
179
180     QGridLayout *backgroundLayout = new QGridLayout( this );
181     backgroundLayout->addWidget( label, 0, 1 );
182     backgroundLayout->setColumnStretch( 0, 1 );
183     backgroundLayout->setColumnStretch( 2, 1 );
184
185     CONNECT( THEMIM->getIM(), artChanged( input_item_t* ),
186              this, updateArt( input_item_t* ) );
187 }
188
189 BackgroundWidget::~BackgroundWidget()
190 {}
191
192 void BackgroundWidget::resizeEvent( QResizeEvent * event )
193 {
194     if( event->size().height() <= MIN_BG_SIZE )
195         label->hide();
196     else
197         label->show();
198 }
199
200 void BackgroundWidget::updateArt( input_item_t *p_item )
201 {
202     QString url;
203     if( p_item )
204     {
205         char *psz_art = input_item_GetArtURL( p_item );
206         url = psz_art;
207         free( psz_art );
208     }
209
210     if( url.isEmpty() )
211     {
212         if( QDate::currentDate().dayOfYear() >= 354 )
213             label->setPixmap( QPixmap( ":/vlc128-christmas.png" ) );
214         else
215             label->setPixmap( QPixmap( ":/vlc128.png" ) );
216     }
217     else
218     {
219         url = url.replace( "file://", QString("" ) );
220         /* Taglib seems to define a attachment://, It won't work yet */
221         url = url.replace( "attachment://", QString("" ) );
222         label->setPixmap( QPixmap( url ) );
223     }
224 }
225
226 void BackgroundWidget::contextMenuEvent( QContextMenuEvent *event )
227 {
228     QVLCMenu::PopupMenu( p_intf, true );
229 }
230
231 #if 0
232 #include <QPushButton>
233 #include <QHBoxLayout>
234
235 /**********************************************************************
236  * Visualization selector panel
237  **********************************************************************/
238 VisualSelector::VisualSelector( intf_thread_t *_p_i ) :
239                                 QFrame( NULL ), p_intf( _p_i )
240 {
241     QHBoxLayout *layout = new QHBoxLayout( this );
242     layout->setMargin( 0 );
243     QPushButton *prevButton = new QPushButton( "Prev" );
244     QPushButton *nextButton = new QPushButton( "Next" );
245     layout->addWidget( prevButton );
246     layout->addWidget( nextButton );
247
248     layout->addStretch( 10 );
249     layout->addWidget( new QLabel( qtr( "Current visualization" ) ) );
250
251     current = new QLabel( qtr( "None" ) );
252     layout->addWidget( current );
253
254     BUTTONACT( prevButton, prev() );
255     BUTTONACT( nextButton, next() );
256
257     setLayout( layout );
258     setMaximumHeight( 35 );
259 }
260
261 VisualSelector::~VisualSelector()
262 {}
263
264 void VisualSelector::prev()
265 {
266     char *psz_new = aout_VisualPrev( p_intf );
267     if( psz_new )
268     {
269         current->setText( qfu( psz_new ) );
270         free( psz_new );
271     }
272 }
273
274 void VisualSelector::next()
275 {
276     char *psz_new = aout_VisualNext( p_intf );
277     if( psz_new )
278     {
279         current->setText( qfu( psz_new ) );
280         free( psz_new );
281     }
282 }
283 #endif
284
285 SpeedLabel::SpeedLabel( intf_thread_t *_p_intf, const QString text )
286            : QLabel( text ), p_intf( _p_intf )
287 {
288     setToolTip( qtr( "Current playback speed.\nRight click to adjust" ) );
289     setContextMenuPolicy ( Qt::CustomContextMenu );
290
291     /* Create the Speed Control Widget */
292     speedControl = new SpeedControlWidget( p_intf, this );
293     speedControlMenu = new QMenu( this );
294
295     QWidgetAction *widgetAction = new QWidgetAction( speedControl );
296     widgetAction->setDefaultWidget( speedControl );
297     speedControlMenu->addAction( widgetAction );
298
299     /* Speed Label behaviour:
300        - right click gives the vertical speed slider */
301     CONNECT( this, customContextMenuRequested( QPoint ),
302              this, showSpeedMenu( QPoint ) );
303
304     /* Change the SpeedRate in the Status Bar */
305     CONNECT( THEMIM->getIM(), rateChanged( int ), this, setRate( int ) );
306
307     CONNECT( THEMIM, inputChanged( input_thread_t * ),
308              speedControl, activateOnState() );
309 }
310
311 /****************************************************************************
312  * Small right-click menu for rate control
313  ****************************************************************************/
314 void SpeedLabel::showSpeedMenu( QPoint pos )
315 {
316     speedControlMenu->exec( QCursor::pos() - pos
317                           + QPoint( 0, height() ) );
318 }
319
320 void SpeedLabel::setRate( int rate )
321 {
322     QString str;
323     str.setNum( ( 1000 / (double)rate ), 'f', 2 );
324     str.append( "x" );
325     setText( str );
326     setToolTip( str );
327     speedControl->updateControls( rate );
328 }
329
330 /**********************************************************************
331  * Speed control widget
332  **********************************************************************/
333 SpeedControlWidget::SpeedControlWidget( intf_thread_t *_p_i, QWidget *_parent )
334                     : QFrame( _parent ), p_intf( _p_i )
335 {
336     QSizePolicy sizePolicy( QSizePolicy::Maximum, QSizePolicy::Fixed );
337     sizePolicy.setHorizontalStretch( 0 );
338     sizePolicy.setVerticalStretch( 0 );
339
340     speedSlider = new QSlider;
341     speedSlider->setSizePolicy( sizePolicy );
342     speedSlider->setMaximumSize( QSize( 80, 200 ) );
343     speedSlider->setOrientation( Qt::Vertical );
344     speedSlider->setTickPosition( QSlider::TicksRight );
345
346     speedSlider->setRange( -34, 34 );
347     speedSlider->setSingleStep( 1 );
348     speedSlider->setPageStep( 1 );
349     speedSlider->setTickInterval( 17 );
350
351     CONNECT( speedSlider, valueChanged( int ), this, updateRate( int ) );
352
353     QToolButton *normalSpeedButton = new QToolButton( this );
354     normalSpeedButton->setMaximumSize( QSize( 26, 20 ) );
355     normalSpeedButton->setAutoRaise( true );
356     normalSpeedButton->setText( "1x" );
357     normalSpeedButton->setToolTip( qtr( "Revert to normal play speed" ) );
358
359     CONNECT( normalSpeedButton, clicked(), this, resetRate() );
360
361     QVBoxLayout *speedControlLayout = new QVBoxLayout( this );
362     speedControlLayout->setLayoutMargins( 4, 4, 4, 4, 4 );
363     speedControlLayout->setSpacing( 4 );
364     speedControlLayout->addWidget( speedSlider );
365     speedControlLayout->addWidget( normalSpeedButton );
366
367     activateOnState();
368 }
369
370 void SpeedControlWidget::activateOnState()
371 {
372     speedSlider->setEnabled( THEMIM->getIM()->hasInput() );
373 }
374
375 void SpeedControlWidget::updateControls( int rate )
376 {
377     if( speedSlider->isSliderDown() )
378     {
379         //We don't want to change anything if the user is using the slider
380         return;
381     }
382
383     double value = 17 * log( (double)INPUT_RATE_DEFAULT / rate ) / log( 2 );
384     int sliderValue = (int) ( ( value > 0 ) ? value + .5 : value - .5 );
385
386     if( sliderValue < speedSlider->minimum() )
387     {
388         sliderValue = speedSlider->minimum();
389     }
390     else if( sliderValue > speedSlider->maximum() )
391     {
392         sliderValue = speedSlider->maximum();
393     }
394
395     //Block signals to avoid feedback loop
396     speedSlider->blockSignals( true );
397     speedSlider->setValue( sliderValue );
398     speedSlider->blockSignals( false );
399 }
400
401 void SpeedControlWidget::updateRate( int sliderValue )
402 {
403     double speed = pow( 2, (double)sliderValue / 17 );
404     int rate = INPUT_RATE_DEFAULT / speed;
405
406     THEMIM->getIM()->setRate(rate);
407 }
408
409 void SpeedControlWidget::resetRate()
410 {
411     THEMIM->getIM()->setRate( INPUT_RATE_DEFAULT );
412 }
413
414 static int downloadCoverCallback( vlc_object_t *p_this,
415                                   char const *psz_var,
416                                   vlc_value_t oldvar, vlc_value_t newvar,
417                                   void *data )
418 {
419     if( !strcmp( psz_var, "item-change" ) )
420     {
421         CoverArtLabel *art = static_cast< CoverArtLabel* >( data );
422         if( art )
423             art->requestUpdate();
424     }
425     return VLC_SUCCESS;
426 }
427
428 CoverArtLabel::CoverArtLabel( QWidget *parent,
429                               vlc_object_t *_p_this,
430                               input_item_t *_p_input )
431         : QLabel( parent ), p_this( _p_this), p_input( _p_input ), prevArt()
432 {
433     setContextMenuPolicy( Qt::ActionsContextMenu );
434     CONNECT( this, updateRequested(), this, doUpdate() );
435
436     playlist_t *p_playlist = pl_Hold( p_this );
437     var_AddCallback( p_playlist, "item-change",
438                      downloadCoverCallback, this );
439     pl_Release( p_this );
440
441     setMinimumHeight( 128 );
442     setMinimumWidth( 128 );
443     setMaximumHeight( 128 );
444     setMaximumWidth( 128 );
445     setScaledContents( true );
446
447     doUpdate();
448 }
449
450 CoverArtLabel::~CoverArtLabel()
451 {
452     playlist_t *p_playlist = pl_Hold( p_this );
453     var_DelCallback( p_playlist, "item-change", downloadCoverCallback, this );
454     pl_Release( p_this );
455
456     if( p_input )
457         vlc_gc_decref( p_input );
458 };
459
460 void CoverArtLabel::downloadCover()
461 {
462     if( p_input )
463     {
464         playlist_t *p_playlist = pl_Hold( p_this );
465         playlist_AskForArtEnqueue( p_playlist, p_input, pl_Unlocked );
466         pl_Release( p_this );
467     }
468 }
469
470 void CoverArtLabel::doUpdate()
471 {
472     if( !p_input )
473     {
474         setPixmap( QPixmap( ":/noart.png" ) );
475         QList< QAction* > artActions = actions();
476         if( !artActions.isEmpty() )
477             foreach( QAction *act, artActions )
478                 removeAction( act );
479         prevArt = "";
480     }
481     else
482     {
483         char *psz_meta = input_item_GetArtURL( p_input );
484         if( psz_meta && !strncmp( psz_meta, "file://", 7 ) )
485         {
486             QString artUrl = qfu( psz_meta ).replace( "file://", "" );
487             if( artUrl != prevArt )
488             {
489                 QPixmap pix;
490                 if( pix.load( artUrl ) )
491                     setPixmap( pix );
492                 else
493                 {
494                     msg_Dbg( p_this, "Qt could not load image '%s'",
495                              qtu( artUrl ) );
496                     setPixmap( QPixmap( ":/noart.png" ) );
497                 }
498             }
499             QList< QAction* > artActions = actions();
500             if( !artActions.isEmpty() )
501             {
502                 foreach( QAction *act, artActions )
503                     removeAction( act );
504             }
505             prevArt = artUrl;
506         }
507         else
508         {
509             if( prevArt != "" )
510                 setPixmap( QPixmap( ":/noart.png" ) );
511             prevArt = "";
512             QList< QAction* > artActions = actions();
513             if( artActions.isEmpty() )
514             {
515                 QAction *action = new QAction( qtr( "Download cover art" ),
516                                                this );
517                 addAction( action );
518                 CONNECT( action, triggered(),
519                          this, downloadCover() );
520             }
521         }
522         free( psz_meta );
523     }
524 }
525
526 TimeLabel::TimeLabel( intf_thread_t *_p_intf  ) :QLabel(), p_intf( _p_intf )
527 {
528    b_remainingTime = false;
529    setText( " --:--/--:-- " );
530    setAlignment( Qt::AlignRight | Qt::AlignVCenter );
531    setToolTip( qtr( "Toggle between elapsed and remaining time" ) );
532
533
534    CONNECT( THEMIM->getIM(), cachingChanged( float ),
535             this, setCaching( float ) );
536    CONNECT( THEMIM->getIM(), positionUpdated( float, int, int ),
537              this, setDisplayPosition( float, int, int ) );
538 }
539
540 void TimeLabel::setDisplayPosition( float pos, int time, int length )
541 {
542     char psz_length[MSTRTIME_MAX_SIZE], psz_time[MSTRTIME_MAX_SIZE];
543     secstotimestr( psz_length, length );
544     secstotimestr( psz_time, ( b_remainingTime && length ) ? length - time
545                                                            : time );
546
547     QString timestr;
548     timestr.sprintf( "%s/%s", psz_time,
549                             ( !length && time ) ? "--:--" : psz_length );
550
551     /* Add a minus to remaining time*/
552     if( b_remainingTime && length ) setText( " -"+timestr+" " );
553     else setText( " "+timestr+" " );
554 }
555
556 void TimeLabel::toggleTimeDisplay()
557 {
558     b_remainingTime = !b_remainingTime;
559 }
560
561 void TimeLabel::setCaching( float f_cache )
562 {
563     setText( "Buffering" );
564 }
565
566