]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/playlist/standardpanel.cpp
qt4: add tooltip to playlist viewchange-button
[vlc] / modules / gui / qt4 / components / playlist / standardpanel.cpp
1 /*****************************************************************************
2  * standardpanel.cpp : The "standard" playlist panel : just a treeview
3  ****************************************************************************
4  * Copyright (C) 2000-2009 VideoLAN
5  * $Id$
6  *
7  * Authors: ClĂ©ment Stenac <zorglub@videolan.org>
8  *          JB Kempf <jb@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include "dialogs_provider.hpp"
30
31 #include "components/playlist/playlist_model.hpp"
32 #include "components/playlist/standardpanel.hpp"
33 #include "components/playlist/icon_view.hpp"
34 #include "util/customwidgets.hpp"
35 #include "menus.hpp"
36
37 #include <vlc_intf_strings.h>
38
39 #include <QPushButton>
40 #include <QHeaderView>
41 #include <QKeyEvent>
42 #include <QModelIndexList>
43 #include <QLabel>
44 #include <QMenu>
45 #include <QSignalMapper>
46 #include <QWheelEvent>
47 #include <QToolButton>
48 #include <QFontMetrics>
49 #include <QPainter>
50 #include <QStackedLayout>
51
52 #include <assert.h>
53
54 #include "sorting.h"
55
56 static const QString viewNames[] = { qtr( "Detailed View" ),
57                                      qtr( "Icon View" ),
58                                      qtr( "List View" ) };
59
60 StandardPLPanel::StandardPLPanel( PlaylistWidget *_parent,
61                                   intf_thread_t *_p_intf,
62                                   playlist_t *p_playlist,
63                                   playlist_item_t *p_root ):
64                                   QWidget( _parent ), p_intf( _p_intf )
65 {
66     layout = new QGridLayout( this );
67     layout->setSpacing( 0 ); layout->setMargin( 0 );
68     setMinimumWidth( 300 );
69
70     iconView = NULL;
71     treeView = NULL;
72     listView = NULL;
73     viewStack = new QStackedLayout();
74     layout->addLayout( viewStack, 1, 0, 1, -1 );
75
76     model = new PLModel( p_playlist, p_intf, p_root, this );
77     currentRootId = -1;
78     currentRootIndexId = -1;
79     lastActivatedId = -1;
80
81     locationBar = new LocationBar( model );
82     locationBar->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Preferred );
83     layout->addWidget( locationBar, 0, 0 );
84     layout->setColumnStretch( 0, 5 );
85     CONNECT( locationBar, invoked( const QModelIndex & ),
86              this, browseInto( const QModelIndex & ) );
87
88     searchEdit = new SearchLineEdit( this );
89     searchEdit->setMaximumWidth( 250 );
90     searchEdit->setMinimumWidth( 80 );
91     layout->addWidget( searchEdit, 0, 2 );
92     CONNECT( searchEdit, textChanged( const QString& ),
93              this, search( const QString& ) );
94     layout->setColumnStretch( 2, 3 );
95
96     /* Button to switch views */
97     QToolButton *viewButton = new QToolButton( this );
98     viewButton->setIcon( style()->standardIcon( QStyle::SP_FileDialogDetailedView ) );
99     viewButton->setToolTip( qtr("Change playlistview"));
100     layout->addWidget( viewButton, 0, 1 );
101
102     /* View selection menu */
103     viewSelectionMapper = new QSignalMapper( this );
104     CONNECT( viewSelectionMapper, mapped( int ), this, showView( int ) );
105
106     QActionGroup *actionGroup = new QActionGroup( this );
107
108     for( int i = 0; i < VIEW_COUNT; i++ )
109     {
110         viewActions[i] = actionGroup->addAction( viewNames[i] );
111         viewActions[i]->setCheckable( true );
112         viewSelectionMapper->setMapping( viewActions[i], i );
113         CONNECT( viewActions[i], triggered(), viewSelectionMapper, map() );
114     }
115
116     BUTTONACT( viewButton, cycleViews() );
117     QMenu *viewMenu = new QMenu( this );
118     viewMenu->addActions( actionGroup->actions() );
119
120     viewButton->setMenu( viewMenu );
121
122     /* Saved Settings */
123     getSettings()->beginGroup("Playlist");
124
125     int i_viewMode = getSettings()->value( "view-mode", TREE_VIEW ).toInt();
126
127     getSettings()->endGroup();
128
129     showView( i_viewMode );
130
131     DCONNECT( THEMIM, leafBecameParent( input_item_t *),
132               this, browseInto( input_item_t * ) );
133
134     CONNECT( model, currentChanged( const QModelIndex& ),
135              this, handleExpansion( const QModelIndex& ) );
136     CONNECT( model, rootChanged(), this, handleRootChange() );
137 }
138
139 StandardPLPanel::~StandardPLPanel()
140 {
141     getSettings()->beginGroup("Playlist");
142     if( treeView )
143         getSettings()->setValue( "headerStateV2", treeView->header()->saveState() );
144     if( currentView == treeView )
145         getSettings()->setValue( "view-mode", TREE_VIEW );
146     else if( currentView == listView )
147         getSettings()->setValue( "view-mode", LIST_VIEW );
148     else if( currentView == iconView )
149         getSettings()->setValue( "view-mode", ICON_VIEW );
150     getSettings()->endGroup();
151 }
152
153 /* Unused anymore, but might be useful, like in right-click menu */
154 void StandardPLPanel::gotoPlayingItem()
155 {
156     currentView->scrollTo( model->currentIndex() );
157 }
158
159 void StandardPLPanel::handleExpansion( const QModelIndex& index )
160 {
161     assert( currentView );
162     currentView->scrollTo( index );
163 }
164
165 void StandardPLPanel::handleRootChange()
166 {
167     browseInto();
168 }
169
170 void StandardPLPanel::popupPlView( const QPoint &point )
171 {
172     QModelIndex index = currentView->indexAt( point );
173     QPoint globalPoint = currentView->viewport()->mapToGlobal( point );
174     QItemSelectionModel *selection = currentView->selectionModel();
175     QModelIndexList list = selection->selectedIndexes();
176
177     if( !model->popup( index, globalPoint, list ) )
178         QVLCMenu::PopupMenu( p_intf, true );
179 }
180
181 void StandardPLPanel::popupSelectColumn( QPoint pos )
182 {
183     QMenu menu;
184     assert( treeView );
185
186     /* We do not offer the option to hide index 0 column, or
187     * QTreeView will behave weird */
188     int i, j;
189     for( i = 1 << 1, j = 1; i < COLUMN_END; i <<= 1, j++ )
190     {
191         QAction* option = menu.addAction(
192             qfu( psz_column_title( i ) ) );
193         option->setCheckable( true );
194         option->setChecked( !treeView->isColumnHidden( j ) );
195         selectColumnsSigMapper->setMapping( option, j );
196         CONNECT( option, triggered(), selectColumnsSigMapper, map() );
197     }
198     menu.exec( QCursor::pos() );
199 }
200
201 void StandardPLPanel::toggleColumnShown( int i )
202 {
203     treeView->setColumnHidden( i, !treeView->isColumnHidden( i ) );
204 }
205
206 /* Search in the playlist */
207 void StandardPLPanel::search( const QString& searchText )
208 {
209     bool flat = currentView == iconView || currentView == listView;
210     model->search( searchText,
211                    flat ? currentView->rootIndex() : QModelIndex(),
212                    !flat );
213 }
214
215 /* Set the root of the new Playlist */
216 /* This activated by the selector selection */
217 void StandardPLPanel::setRoot( playlist_item_t *p_item )
218 {
219     model->rebuild( p_item );
220 }
221
222 void StandardPLPanel::browseInto( const QModelIndex &index )
223 {
224     if( currentView == iconView || currentView == listView )
225     {
226         currentRootIndexId = model->itemId( index );;
227         currentView->setRootIndex( index );
228     }
229
230     locationBar->setIndex( index );
231     searchEdit->clear();
232 }
233
234 void StandardPLPanel::browseInto( )
235 {
236     browseInto( currentRootIndexId != -1 && currentView != treeView ?
237                 model->index( currentRootIndexId, 0 ) :
238                 QModelIndex() );
239 }
240
241 void StandardPLPanel::wheelEvent( QWheelEvent *e )
242 {
243     // Accept this event in order to prevent unwanted volume up/down changes
244     e->accept();
245 }
246
247 bool StandardPLPanel::eventFilter ( QObject * watched, QEvent * event )
248 {
249     if (event->type() == QEvent::KeyPress)
250     {
251         QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
252         if( keyEvent->key() == Qt::Key_Delete ||
253             keyEvent->key() == Qt::Key_Backspace )
254         {
255             deleteSelection();
256             return true;
257         }
258     }
259     return false;
260 }
261
262 void StandardPLPanel::deleteSelection()
263 {
264     QItemSelectionModel *selection = currentView->selectionModel();
265     QModelIndexList list = selection->selectedIndexes();
266     model->doDelete( list );
267 }
268
269 void StandardPLPanel::createIconView()
270 {
271     iconView = new PlIconView( model, this );
272     iconView->setContextMenuPolicy( Qt::CustomContextMenu );
273     CONNECT( iconView, customContextMenuRequested( const QPoint & ),
274              this, popupPlView( const QPoint & ) );
275     CONNECT( iconView, activated( const QModelIndex & ),
276              this, activate( const QModelIndex & ) );
277     iconView->installEventFilter( this );
278     viewStack->addWidget( iconView );
279 }
280
281 void StandardPLPanel::createListView()
282 {
283     listView = new PlListView( model, this );
284     listView->setContextMenuPolicy( Qt::CustomContextMenu );
285     CONNECT( listView, customContextMenuRequested( const QPoint & ),
286              this, popupPlView( const QPoint & ) );
287     CONNECT( listView, activated( const QModelIndex & ),
288              this, activate( const QModelIndex & ) );
289     listView->installEventFilter( this );
290     viewStack->addWidget( listView );
291 }
292
293
294 void StandardPLPanel::createTreeView()
295 {
296     /* Create and configure the QTreeView */
297     treeView = new PlTreeView;
298
299     treeView->setIconSize( QSize( 20, 20 ) );
300     treeView->setAlternatingRowColors( true );
301     treeView->setAnimated( true );
302     treeView->setUniformRowHeights( true );
303     treeView->setSortingEnabled( true );
304     treeView->header()->setSortIndicator( -1 , Qt::AscendingOrder );
305     treeView->header()->setSortIndicatorShown( true );
306     treeView->header()->setClickable( true );
307     treeView->header()->setContextMenuPolicy( Qt::CustomContextMenu );
308
309     treeView->setSelectionBehavior( QAbstractItemView::SelectRows );
310     treeView->setSelectionMode( QAbstractItemView::ExtendedSelection );
311     treeView->setDragEnabled( true );
312     treeView->setAcceptDrops( true );
313     treeView->setDropIndicatorShown( true );
314     treeView->setContextMenuPolicy( Qt::CustomContextMenu );
315
316     /* setModel after setSortingEnabled(true), or the model will sort immediately! */
317     treeView->setModel( model );
318
319     getSettings()->beginGroup("Playlist");
320
321     if( getSettings()->contains( "headerStateV2" ) )
322     {
323         treeView->header()->restoreState(
324                 getSettings()->value( "headerStateV2" ).toByteArray() );
325     }
326     else
327     {
328         for( int m = 1, c = 0; m != COLUMN_END; m <<= 1, c++ )
329         {
330             treeView->setColumnHidden( c, !( m & COLUMN_DEFAULT ) );
331             if( m == COLUMN_TITLE ) treeView->header()->resizeSection( c, 200 );
332             else if( m == COLUMN_DURATION ) treeView->header()->resizeSection( c, 80 );
333         }
334     }
335
336     getSettings()->endGroup();
337
338     /* Connections for the TreeView */
339     CONNECT( treeView, activated( const QModelIndex& ),
340              this, activate( const QModelIndex& ) );
341     CONNECT( treeView->header(), customContextMenuRequested( const QPoint & ),
342              this, popupSelectColumn( QPoint ) );
343     CONNECT( treeView, customContextMenuRequested( const QPoint & ),
344              this, popupPlView( const QPoint & ) );
345     treeView->installEventFilter( this );
346
347     /* SignalMapper for columns */
348     selectColumnsSigMapper = new QSignalMapper( this );
349     CONNECT( selectColumnsSigMapper, mapped( int ),
350              this, toggleColumnShown( int ) );
351
352     /* Finish the layout */
353     viewStack->addWidget( treeView );
354 }
355
356 void StandardPLPanel::showView( int i_view )
357 {
358     switch( i_view )
359     {
360     case TREE_VIEW:
361     {
362         if( treeView == NULL )
363             createTreeView();
364         currentView = treeView;
365         break;
366     }
367     case ICON_VIEW:
368     {
369         if( iconView == NULL )
370             createIconView();
371         currentView = iconView;
372         break;
373     }
374     case LIST_VIEW:
375     {
376         if( listView == NULL )
377             createListView();
378         currentView = listView;
379         break;
380     }
381     default: return;
382     }
383
384     viewStack->setCurrentWidget( currentView );
385     viewActions[i_view]->setChecked( true );
386     browseInto();
387     gotoPlayingItem();
388 }
389
390 void StandardPLPanel::cycleViews()
391 {
392     if( currentView == iconView )
393         showView( TREE_VIEW );
394     else if( currentView == treeView )
395         showView( LIST_VIEW );
396     else if( currentView == listView )
397         showView( ICON_VIEW );
398     else
399         assert( 0 );
400 }
401
402 void StandardPLPanel::activate( const QModelIndex &index )
403 {
404     if( !index.data( PLModel::IsLeafNodeRole ).toBool() )
405     {
406         if( currentView != treeView )
407             browseInto( index );
408     }
409     else
410     {
411         playlist_Lock( THEPL );
412         playlist_item_t *p_item = playlist_ItemGetById( THEPL, model->itemId( index ) );
413         p_item->i_flags |= PLAYLIST_SUBITEM_STOP_FLAG;
414         lastActivatedId = p_item->p_input->i_id;
415         playlist_Unlock( THEPL );
416         model->activateItem( index );
417     }
418 }
419
420 void StandardPLPanel::browseInto( input_item_t *p_input )
421 {
422
423     if( p_input->i_id != lastActivatedId ) return;
424
425     playlist_Lock( THEPL );
426
427     playlist_item_t *p_item = playlist_ItemGetByInput( THEPL, p_input );
428     if( !p_item )
429     {
430         playlist_Unlock( THEPL );
431         return;
432     }
433
434     QModelIndex index = model->index( p_item->i_id, 0 );
435
436     playlist_Unlock( THEPL );
437
438     if( currentView == treeView )
439         treeView->setExpanded( index, true );
440     else
441         browseInto( index );
442
443     lastActivatedId = -1;
444
445
446 }
447
448 LocationBar::LocationBar( PLModel *m )
449 {
450     model = m;
451     mapper = new QSignalMapper( this );
452     CONNECT( mapper, mapped( int ), this, invoke( int ) );
453
454     btnMore = new LocationButton( "...", false, true, this );
455     menuMore = new QMenu( this );
456     btnMore->setMenu( menuMore );
457 }
458
459 void LocationBar::setIndex( const QModelIndex &index )
460 {
461     qDeleteAll( buttons );
462     buttons.clear();
463     qDeleteAll( actions );
464     actions.clear();
465
466     QModelIndex i = index;
467     bool first = true;
468
469     while( true )
470     {
471         PLItem *item = model->getItem( i );
472
473         char *fb_name = input_item_GetTitleFbName( item->inputItem() );
474         QString text = qfu(fb_name);
475         free(fb_name);
476
477         QAbstractButton *btn = new LocationButton( text, first, !first, this );
478         btn->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Fixed );
479         buttons.append( btn );
480
481         QAction *action = new QAction( text, this );
482         actions.append( action );
483         CONNECT( btn, clicked(), action, trigger() );
484
485         mapper->setMapping( action, item->id() );
486         CONNECT( action, triggered(), mapper, map() );
487
488         first = false;
489
490         if( i.isValid() ) i = i.parent();
491         else break;
492     }
493
494     QString prefix;
495     for( int a = actions.count() - 1; a >= 0 ; a-- )
496     {
497         actions[a]->setText( prefix + actions[a]->text() );
498         prefix += QString("  ");
499     }
500
501     if( isVisible() ) layOut( size() );
502 }
503
504 void LocationBar::setRootIndex()
505 {
506     setIndex( QModelIndex() );
507 }
508
509 void LocationBar::invoke( int i_id )
510 {
511     QModelIndex index = model->index( i_id, 0 );
512     emit invoked ( index );
513 }
514
515 void LocationBar::layOut( const QSize& size )
516 {
517     menuMore->clear();
518     widths.clear();
519
520     int count = buttons.count();
521     int totalWidth = 0;
522     for( int i = 0; i < count; i++ )
523     {
524         int w = buttons[i]->sizeHint().width();
525         widths.append( w );
526         totalWidth += w;
527         if( totalWidth > size.width() ) break;
528     }
529
530     int x = 0;
531     int shown = widths.count();
532
533     if( totalWidth > size.width() && count > 1 )
534     {
535         QSize sz = btnMore->sizeHint();
536         btnMore->setGeometry( 0, 0, sz.width(), size.height() );
537         btnMore->show();
538         x = sz.width();
539         totalWidth += x;
540     }
541     else
542     {
543         btnMore->hide();
544     }
545     for( int i = count - 1; i >= 0; i-- )
546     {
547         if( totalWidth <= size.width() || i == 0)
548         {
549             buttons[i]->setGeometry( x, 0, qMin( size.width() - x, widths[i] ), size.height() );
550             buttons[i]->show();
551             x += widths[i];
552             totalWidth -= widths[i];
553         }
554         else
555         {
556             menuMore->addAction( actions[i] );
557             buttons[i]->hide();
558             if( i < shown ) totalWidth -= widths[i];
559         }
560     }
561 }
562
563 void LocationBar::resizeEvent ( QResizeEvent * event )
564 {
565     layOut( event->size() );
566 }
567
568 QSize LocationBar::sizeHint() const
569 {
570     return btnMore->sizeHint();
571 }
572
573 LocationButton::LocationButton( const QString &text, bool bold,
574                                 bool arrow, QWidget * parent )
575   : b_arrow( arrow ), QPushButton( parent )
576 {
577     QFont font;
578     font.setBold( bold );
579     setFont( font );
580     setText( text );
581 }
582
583 #define PADDING 4
584
585 void LocationButton::paintEvent ( QPaintEvent * event )
586 {
587     QStyleOptionButton option;
588     option.initFrom( this );
589     option.state |= QStyle::State_Enabled;
590     QPainter p( this );
591
592     if( underMouse() )
593     {
594         p.save();
595         p.setRenderHint( QPainter::Antialiasing, true );
596         QColor c = palette().color( QPalette::Highlight );
597         p.setPen( c );
598         p.setBrush( c.lighter( 150 ) );
599         p.setOpacity( 0.2 );
600         p.drawRoundedRect( option.rect.adjusted( 0, 2, 0, -2 ), 5, 5 );
601         p.restore();
602     }
603
604     QRect r = option.rect.adjusted( PADDING, 0, -PADDING - (b_arrow ? 10 : 0), 0 );
605
606     QString str( text() );
607     /* This check is absurd, but either it is not done properly inside elidedText(),
608        or boundingRect() is wrong */
609     if( r.width() < fontMetrics().boundingRect( text() ).width() )
610         str = fontMetrics().elidedText( text(), Qt::ElideRight, r.width() );
611     p.drawText( r, Qt::AlignVCenter | Qt::AlignLeft, str );
612
613     if( b_arrow )
614     {
615         option.rect.setWidth( 10 );
616         option.rect.moveRight( rect().right() );
617         style()->drawPrimitive( QStyle::PE_IndicatorArrowRight, &option, &p );
618     }
619 }
620
621 QSize LocationButton::sizeHint() const
622 {
623     QSize s( fontMetrics().boundingRect( text() ).size() );
624     /* Add two pixels to width: font metrics are buggy, if you pass text through elidation
625        with exactly the width of its bounding rect, sometimes it still elides */
626     s.setWidth( s.width() + ( 2 * PADDING ) + ( b_arrow ? 10 : 0 ) + 2 );
627     s.setHeight( s.height() + 2 * PADDING );
628     return s;
629 }
630
631 #undef PADDING