]> git.sesse.net Git - vlc/blob - modules/gui/qt4/util/input_slider.cpp
fd2f24ea89394c07e39e2247e6c3675fadbc725e
[vlc] / modules / gui / qt4 / util / input_slider.cpp
1 /*****************************************************************************
2  * input_slider.cpp : VolumeSlider and SeekSlider
3  ****************************************************************************
4  * Copyright (C) 2006-2011 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Clément Stenac <zorglub@videolan.org>
8  *          Jean-Baptiste Kempf <jb@videolan.org>
9  *          Ludovic Fauvet <etix@videolan.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include "qt4.hpp"
31
32 #include "util/input_slider.hpp"
33 #include "adapters/seekpoints.hpp"
34
35 #include <QPaintEvent>
36 #include <QPainter>
37 #include <QBitmap>
38 #include <QStyleOptionSlider>
39 #include <QLinearGradient>
40 #include <QTimer>
41 #include <QRadialGradient>
42 #include <QLinearGradient>
43 #include <QSize>
44 #include <QPalette>
45 #include <QColor>
46 #include <QPoint>
47 #include <QPropertyAnimation>
48 #include <QApplication>
49
50 #define MINIMUM 0
51 #define MAXIMUM 1000
52 #define CHAPTERSSPOTSIZE 3
53 #define FADEDURATION 300
54 #define FADEOUTDELAY 2000
55
56 SeekSlider::SeekSlider( Qt::Orientation q, QWidget *_parent, bool _static )
57           : QSlider( q, _parent ), b_classic( _static )
58 {
59     isSliding = false;
60     isJumping = false;
61     f_buffering = 1.0;
62     mHandleOpacity = 1.0;
63     chapters = NULL;
64     mHandleLength = -1;
65     b_seekable = true;
66     alternativeStyle = NULL;
67
68     // prepare some static colors
69     QPalette p = palette();
70     QColor background = p.color( QPalette::Active, QPalette::Window );
71     tickpointForeground = p.color( QPalette::Active, QPalette::WindowText );
72     tickpointForeground.setHsv( tickpointForeground.hue(),
73             ( background.saturation() + tickpointForeground.saturation() ) / 2,
74             ( background.value() + tickpointForeground.value() ) / 2 );
75
76     // set the background color and gradient
77     QColor backgroundBase( p.window().color() );
78     backgroundGradient.setColorAt( 0.0, backgroundBase.darker( 140 ) );
79     backgroundGradient.setColorAt( 1.0, backgroundBase );
80
81     // set the foreground color and gradient
82     QColor foregroundBase( 50, 156, 255 );
83     foregroundGradient.setColorAt( 0.0,  foregroundBase );
84     foregroundGradient.setColorAt( 1.0,  foregroundBase.darker( 140 ) );
85
86     // prepare the handle's gradient
87     handleGradient.setColorAt( 0.0, p.window().color().lighter( 120 ) );
88     handleGradient.setColorAt( 0.9, p.window().color().darker( 120 ) );
89
90     // prepare the handle's shadow gradient
91     QColor shadowBase = p.shadow().color();
92     if( shadowBase.lightness() > 100 )
93         shadowBase = QColor( 60, 60, 60 ); // Palette's shadow is too bright
94     shadowDark = shadowBase.darker( 150 );
95     shadowLight = shadowBase.lighter( 180 );
96     shadowLight.setAlpha( 50 );
97
98     /* Timer used to fire intermediate updatePos() when sliding */
99     seekLimitTimer = new QTimer( this );
100     seekLimitTimer->setSingleShot( true );
101
102     /* Tooltip bubble */
103     mTimeTooltip = new TimeTooltip( this );
104     mTimeTooltip->setMouseTracking( true );
105
106     /* Properties */
107     setRange( MINIMUM, MAXIMUM );
108     setSingleStep( 2 );
109     setPageStep( 10 );
110     setMouseTracking( true );
111     setTracking( true );
112     setFocusPolicy( Qt::NoFocus );
113
114     /* Use the new/classic style */
115     setMinimumHeight( 18 );
116     if( !b_classic )
117     {
118         alternativeStyle = new SeekStyle;
119         setStyle( alternativeStyle );
120     }
121
122     /* Init to 0 */
123     setPosition( -1.0, 0, 0 );
124     secstotimestr( psz_length, 0 );
125
126     animHandle = new QPropertyAnimation( this, "handleOpacity", this );
127     animHandle->setDuration( FADEDURATION );
128     animHandle->setStartValue( 0.0 );
129     animHandle->setEndValue( 1.0 );
130
131     hideHandleTimer = new QTimer( this );
132     hideHandleTimer->setSingleShot( true );
133     hideHandleTimer->setInterval( FADEOUTDELAY );
134
135     CONNECT( this, sliderMoved( int ), this, startSeekTimer() );
136     CONNECT( seekLimitTimer, timeout(), this, updatePos() );
137     CONNECT( hideHandleTimer, timeout(), this, hideHandle() );
138     mTimeTooltip->installEventFilter( this );
139 }
140
141 SeekSlider::~SeekSlider()
142 {
143     delete chapters;
144     if ( alternativeStyle )
145         delete alternativeStyle;
146 }
147
148 /***
149  * \brief Sets the chapters seekpoints adapter
150  *
151  * \params SeekPoints initilized with current intf thread
152 ***/
153 void SeekSlider::setChapters( SeekPoints *chapters_ )
154 {
155     delete chapters;
156     chapters = chapters_;
157     chapters->setParent( this );
158 }
159
160 /***
161  * \brief Main public method, superseeding setValue. Disabling the slider when neeeded
162  *
163  * \param pos Position, between 0 and 1. -1 disables the slider
164  * \param time Elapsed time. Unused
165  * \param legnth Duration time.
166  ***/
167 void SeekSlider::setPosition( float pos, int64_t time, int length )
168 {
169     VLC_UNUSED(time);
170     if( pos == -1.0 )
171     {
172         setEnabled( false );
173         mTimeTooltip->hide();
174         isSliding = false;
175     }
176     else
177         setEnabled( b_seekable );
178
179     if( !isSliding )
180         setValue( (int)( pos * 1000.0 ) );
181
182     inputLength = length;
183 }
184
185 void SeekSlider::startSeekTimer()
186 {
187     /* Only fire one update, when sliding, every 150ms */
188     if( isSliding && !seekLimitTimer->isActive() )
189         seekLimitTimer->start( 150 );
190 }
191
192 void SeekSlider::updatePos()
193 {
194     float f_pos = (float)( value() ) / 1000.0;
195     emit sliderDragged( f_pos ); /* Send new position to VLC's core */
196 }
197
198 void SeekSlider::updateBuffering( float f_buffering_ )
199 {
200     f_buffering = f_buffering_;
201     repaint();
202 }
203
204 void SeekSlider::processReleasedButton()
205 {
206     if ( !isSliding && !isJumping ) return;
207     isSliding = false;
208     bool b_seekPending = seekLimitTimer->isActive();
209     seekLimitTimer->stop(); /* We're not sliding anymore: only last seek on release */
210     if ( isJumping )
211     {
212         isJumping = false;
213         return;
214     }
215     if( b_seekPending && isEnabled() )
216         updatePos();
217 }
218
219 void SeekSlider::mouseReleaseEvent( QMouseEvent *event )
220 {
221     if ( event->button() != Qt::LeftButton && event->button() != Qt::MidButton )
222     {
223         QSlider::mouseReleaseEvent( event );
224         return;
225     }
226     event->accept();
227     processReleasedButton();
228 }
229
230 void SeekSlider::mousePressEvent( QMouseEvent* event )
231 {
232     /* Right-click */
233     if ( !isEnabled() ||
234          ( event->button() != Qt::LeftButton && event->button() != Qt::MidButton )
235        )
236     {
237         QSlider::mousePressEvent( event );
238         return;
239     }
240
241     isJumping = false;
242     /* handle chapter clicks */
243     int i_width = size().width();
244     if ( chapters && inputLength && i_width)
245     {
246         if ( orientation() == Qt::Horizontal ) /* TODO: vertical */
247         {
248              /* only on chapters zone */
249             if ( event->y() < CHAPTERSSPOTSIZE ||
250                  event->y() > ( size().height() - CHAPTERSSPOTSIZE ) )
251             {
252                 QList<SeekPoint> points = chapters->getPoints();
253                 int i_selected = -1;
254                 bool b_startsnonzero = false; /* as we always starts at 1 */
255                 if ( points.count() > 0 ) /* do we need an extra offset ? */
256                     b_startsnonzero = ( points.at(0).time > 0 );
257                 int i_min_diff = i_width + 1;
258                 for( int i = 0 ; i < points.count() ; i++ )
259                 {
260                     int x = points.at(i).time / 1000000.0 / inputLength * i_width;
261                     int diff_x = abs( x - event->x() );
262                     if ( diff_x < i_min_diff )
263                     {
264                         i_min_diff = diff_x;
265                         i_selected = i + ( ( b_startsnonzero )? 1 : 0 );
266                     } else break;
267                 }
268                 if ( i_selected && i_min_diff < 4 ) // max 4px around mark
269                 {
270                     chapters->jumpTo( i_selected );
271                     event->accept();
272                     isJumping = true;
273                     return;
274                 }
275             }
276         }
277     }
278
279     isSliding = true ;
280
281     setValue( QStyle::sliderValueFromPosition( MINIMUM, MAXIMUM, event->x() - handleLength() / 2, width() - handleLength(), false ) );
282     emit sliderMoved( value() );
283     event->accept();
284 }
285
286 void SeekSlider::mouseMoveEvent( QMouseEvent *event )
287 {
288     if ( ! ( event->buttons() & ( Qt::LeftButton | Qt::MidButton ) ) )
289     {
290         /* Handle button release when mouserelease has been hijacked by popup */
291         processReleasedButton();
292     }
293
294     if ( !isEnabled() ) return event->accept();
295
296     if( isSliding )
297     {
298         setValue( QStyle::sliderValueFromPosition( MINIMUM, MAXIMUM, event->x() - handleLength() / 2, width() - handleLength(), false) );
299         emit sliderMoved( value() );
300     }
301
302     /* Tooltip */
303     if ( inputLength > 0 )
304     {
305         int margin = handleLength() / 2;
306         int posX = qMax( rect().left() + margin, qMin( rect().right() - margin, event->x() ) );
307
308         QString chapterLabel;
309
310         if ( orientation() == Qt::Horizontal ) /* TODO: vertical */
311         {
312                 QList<SeekPoint> points = chapters->getPoints();
313                 int i_selected = -1;
314                 bool b_startsnonzero = false;
315                 if ( points.count() > 0 )
316                     b_startsnonzero = ( points.at(0).time > 0 );
317                 for( int i = 0 ; i < points.count() ; i++ )
318                 {
319                     int x = points.at(i).time / 1000000.0 / inputLength * size().width();
320                     if ( event->x() >= x )
321                         i_selected = i + ( ( b_startsnonzero )? 1 : 0 );
322                 }
323                 if ( i_selected >= 0 && i_selected < points.size() )
324                     chapterLabel = points.at( i_selected ).name;
325         }
326
327         QPoint target( event->globalX() - ( event->x() - posX ),
328                   QWidget::mapToGlobal( QPoint( 0, 0 ) ).y() );
329         if( likely( size().width() > handleLength() ) ) {
330             secstotimestr( psz_length, ( ( posX - margin ) * inputLength ) / ( size().width() - handleLength() ) );
331             mTimeTooltip->setTip( target, psz_length, chapterLabel );
332         }
333     }
334     event->accept();
335 }
336
337 void SeekSlider::wheelEvent( QWheelEvent *event )
338 {
339     /* Don't do anything if we are for somehow reason sliding */
340     if( !isSliding && isEnabled() )
341     {
342         setValue( value() + event->delta() / 12 ); /* 12 = 8 * 15 / 10
343          Since delta is in 1/8 of ° and mouse have steps of 15 °
344          and that our slider is in 0.1% and we want one step to be a 1%
345          increment of position */
346         emit sliderDragged( value() / 1000.0 );
347     }
348     event->accept();
349 }
350
351 void SeekSlider::enterEvent( QEvent * )
352 {
353     /* Cancel the fade-out timer */
354     hideHandleTimer->stop();
355     /* Only start the fade-in if needed */
356     if( isEnabled() && animHandle->direction() != QAbstractAnimation::Forward )
357     {
358         /* If pause is called while not running Qt will complain */
359         if( animHandle->state() == QAbstractAnimation::Running )
360             animHandle->pause();
361         animHandle->setDirection( QAbstractAnimation::Forward );
362         animHandle->start();
363     }
364     /* Don't show the tooltip if the slider is disabled or a menu is open */
365     if( isEnabled() && inputLength > 0 && !qApp->activePopupWidget() )
366         mTimeTooltip->show();
367 }
368
369 void SeekSlider::leaveEvent( QEvent * )
370 {
371     hideHandleTimer->start();
372     /* Hide the tooltip
373        - if the mouse leave the slider rect (Note: it can still be
374          over the tooltip!)
375        - if another window is on the way of the cursor */
376     if( !rect().contains( mapFromGlobal( QCursor::pos() ) ) ||
377       ( !isActiveWindow() && !mTimeTooltip->isActiveWindow() ) )
378     {
379         mTimeTooltip->hide();
380     }
381 }
382
383 void SeekSlider::paintEvent( QPaintEvent *ev )
384 {
385     if ( alternativeStyle )
386     {
387         SeekStyle::SeekStyleOption option;
388         option.initFrom( this );
389         option.buffering = f_buffering;
390         option.length = inputLength;
391         option.animate = ( animHandle->state() == QAbstractAnimation::Running
392                            || hideHandleTimer->isActive() );
393         option.animationopacity = mHandleOpacity;
394         option.sliderPosition = sliderPosition();
395         option.sliderValue = value();
396         option.maximum = maximum();
397         option.minimum = minimum();
398         foreach( const SeekPoint &point, chapters->getPoints() )
399             option.points << point.time;
400         QPainter painter( this );
401         style()->drawComplexControl( QStyle::CC_Slider, &option, &painter, this );
402     }
403     else
404         QSlider::paintEvent( ev );
405 }
406
407 void SeekSlider::hideEvent( QHideEvent * )
408 {
409     mTimeTooltip->hide();
410 }
411
412 bool SeekSlider::eventFilter( QObject *obj, QEvent *event )
413 {
414     if( obj == mTimeTooltip )
415     {
416         if( event->type() == QEvent::Leave ||
417             event->type() == QEvent::MouseMove )
418         {
419             QMouseEvent *e = static_cast<QMouseEvent*>( event );
420             if( !rect().contains( mapFromGlobal( e->globalPos() ) ) )
421                 mTimeTooltip->hide();
422         }
423         return false;
424     }
425     else
426         return QSlider::eventFilter( obj, event );
427 }
428
429 QSize SeekSlider::sizeHint() const
430 {
431     if ( b_classic )
432         return QSlider::sizeHint();
433     return ( orientation() == Qt::Horizontal ) ? QSize( 100, 18 )
434                                                : QSize( 18, 100 );
435 }
436
437 qreal SeekSlider::handleOpacity() const
438 {
439     return mHandleOpacity;
440 }
441
442 void SeekSlider::setHandleOpacity(qreal opacity)
443 {
444     mHandleOpacity = opacity;
445     /* Request a new paintevent */
446     update();
447 }
448
449 inline int SeekSlider::handleLength()
450 {
451     if ( mHandleLength > 0 )
452         return mHandleLength;
453
454     /* Ask for the length of the handle to the underlying style */
455     QStyleOptionSlider option;
456     initStyleOption( &option );
457     mHandleLength = style()->pixelMetric( QStyle::PM_SliderLength, &option );
458     return mHandleLength;
459 }
460
461 void SeekSlider::hideHandle()
462 {
463     /* If pause is called while not running Qt will complain */
464     if( animHandle->state() == QAbstractAnimation::Running )
465         animHandle->pause();
466     /* Play the animation backward */
467     animHandle->setDirection( QAbstractAnimation::Backward );
468     animHandle->start();
469 }
470
471
472 /* This work is derived from Amarok's work under GPLv2+
473     - Mark Kretschmann
474     - Gábor Lehel
475    */
476 #define WLENGTH   80 // px
477 #define WHEIGHT   22  // px
478 #define SOUNDMIN  0   // %
479
480 SoundSlider::SoundSlider( QWidget *_parent, float _i_step,
481                           char *psz_colors, int max )
482                         : QAbstractSlider( _parent )
483 {
484     f_step = (float)(_i_step * 10000)
485            / (float)((max - SOUNDMIN) * AOUT_VOLUME_DEFAULT);
486     setRange( SOUNDMIN, max);
487     setMouseTracking( true );
488     isSliding = false;
489     b_mouseOutside = true;
490     b_isMuted = false;
491
492     pixOutside = QPixmap( ":/toolbar/volslide-outside" );
493
494     const QPixmap temp( ":/toolbar/volslide-inside" );
495     const QBitmap mask( temp.createHeuristicMask() );
496
497     setFixedSize( pixOutside.size() );
498
499     pixGradient = QPixmap( mask.size() );
500     pixGradient2 = QPixmap( mask.size() );
501
502     /* Gradient building from the preferences */
503     QLinearGradient gradient( paddingL, 2, WLENGTH + paddingL , 2 );
504     QLinearGradient gradient2( paddingL, 2, WLENGTH + paddingL , 2 );
505
506     QStringList colorList = qfu( psz_colors ).split( ";" );
507     free( psz_colors );
508
509     /* Fill with 255 if the list is too short */
510     if( colorList.count() < 12 )
511         for( int i = colorList.count(); i < 12; i++)
512             colorList.append( "255" );
513
514     background = palette().color( QPalette::Active, QPalette::Window );
515     foreground = palette().color( QPalette::Active, QPalette::WindowText );
516     foreground.setHsv( foreground.hue(),
517                     ( background.saturation() + foreground.saturation() ) / 2,
518                     ( background.value() + foreground.value() ) / 2 );
519
520     textfont.setPixelSize( 9 );
521     textrect.setRect( 0, 0, 34, 15 );
522
523     /* Regular colors */
524 #define c(i) colorList.at(i).toInt()
525 #define add_color(gradient, range, c1, c2, c3) \
526     gradient.setColorAt( range, QColor( c(c1), c(c2), c(c3) ) );
527
528     /* Desaturated colors */
529 #define desaturate(c) c->setHsvF( c->hueF(), 0.2 , 0.5, 1.0 )
530 #define add_desaturated_color(gradient, range, c1, c2, c3) \
531     foo = new QColor( c(c1), c(c2), c(c3) );\
532     desaturate( foo ); gradient.setColorAt( range, *foo );\
533     delete foo;
534
535     /* combine the two helpers */
536 #define add_colors( gradient1, gradient2, range, c1, c2, c3 )\
537     add_color( gradient1, range, c1, c2, c3 ); \
538     add_desaturated_color( gradient2, range, c1, c2, c3 );
539
540     float f_mid_point = ( 100.0 / maximum() );
541     QColor * foo;
542     add_colors( gradient, gradient2, 0.0, 0, 1, 2 );
543     add_colors( gradient, gradient2, f_mid_point - 0.05, 3, 4, 5 );
544     add_colors( gradient, gradient2, f_mid_point + 0.05, 6, 7, 8 );
545     add_colors( gradient, gradient2, 1.0, 9, 10, 11 );
546
547     painter.begin( &pixGradient );
548     painter.setPen( Qt::NoPen );
549     painter.setBrush( gradient );
550     painter.drawRect( pixGradient.rect() );
551     painter.end();
552
553     painter.begin( &pixGradient2 );
554     painter.setPen( Qt::NoPen );
555     painter.setBrush( gradient2 );
556     painter.drawRect( pixGradient2.rect() );
557     painter.end();
558
559     pixGradient.setMask( mask );
560     pixGradient2.setMask( mask );
561 }
562
563 void SoundSlider::wheelEvent( QWheelEvent *event )
564 {
565     int newvalue = value() + event->delta() / ( 8 * 15 ) * f_step;
566     setValue( __MIN( __MAX( minimum(), newvalue ), maximum() ) );
567
568     emit sliderReleased();
569     emit sliderMoved( value() );
570 }
571
572 void SoundSlider::mousePressEvent( QMouseEvent *event )
573 {
574     if( event->button() != Qt::RightButton )
575     {
576         /* We enter the sliding mode */
577         isSliding = true;
578         i_oldvalue = value();
579         emit sliderPressed();
580         changeValue( event->x() - paddingL );
581         emit sliderMoved( value() );
582     }
583 }
584
585 void SoundSlider::processReleasedButton()
586 {
587     if( !b_mouseOutside && value() != i_oldvalue )
588     {
589         emit sliderReleased();
590         setValue( value() );
591         emit sliderMoved( value() );
592     }
593     isSliding = false;
594     b_mouseOutside = false;
595 }
596
597 void SoundSlider::mouseReleaseEvent( QMouseEvent *event )
598 {
599     if( event->button() != Qt::RightButton )
600         processReleasedButton();
601 }
602
603 void SoundSlider::mouseMoveEvent( QMouseEvent *event )
604 {
605     /* handle mouserelease hijacking */
606     if ( isSliding && ( event->buttons() & ~Qt::RightButton ) == Qt::NoButton )
607         processReleasedButton();
608
609     if( isSliding )
610     {
611         QRect rect( paddingL - 15,    -1,
612                     WLENGTH + 15 * 2 , WHEIGHT + 5 );
613         if( !rect.contains( event->pos() ) )
614         { /* We are outside */
615             if ( !b_mouseOutside )
616                 setValue( i_oldvalue );
617             b_mouseOutside = true;
618         }
619         else
620         { /* We are inside */
621             b_mouseOutside = false;
622             changeValue( event->x() - paddingL );
623             emit sliderMoved( value() );
624         }
625     }
626     else
627     {
628         int i = ( ( event->x() - paddingL ) * maximum() + 40 ) / WLENGTH;
629         i = __MIN( __MAX( 0, i ), maximum() );
630         setToolTip( QString("%1  %" ).arg( i ) );
631     }
632 }
633
634 void SoundSlider::changeValue( int x )
635 {
636     setValue( (x * maximum() + 40 ) / WLENGTH );
637 }
638
639 void SoundSlider::setMuted( bool m )
640 {
641     b_isMuted = m;
642     update();
643 }
644
645 void SoundSlider::paintEvent( QPaintEvent *e )
646 {
647     QPixmap *paintGradient;
648     if (b_isMuted)
649         paintGradient = &this->pixGradient2;
650     else
651         paintGradient = &this->pixGradient;
652
653     painter.begin( this );
654
655     const int offset = int( ( WLENGTH * value() + 100 ) / maximum() ) + paddingL;
656
657     const QRectF boundsG( 0, 0, offset , paintGradient->height() );
658     painter.drawPixmap( boundsG, *paintGradient, boundsG );
659
660     const QRectF boundsO( 0, 0, pixOutside.width(), pixOutside.height() );
661     painter.drawPixmap( boundsO, pixOutside, boundsO );
662
663     painter.setPen( foreground );
664     painter.setFont( textfont );
665     painter.drawText( textrect, Qt::AlignRight | Qt::AlignVCenter,
666                       QString::number( value() ) + '%' );
667
668     painter.end();
669     e->accept();
670 }