]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/playlist/standardpanel.cpp
Qt4: make sure Item can be scrolled to visible even in treeview
[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     browseInto( index.parent() );
163     currentView->scrollTo( index );
164 }
165
166 void StandardPLPanel::handleRootChange()
167 {
168     browseInto();
169 }
170
171 void StandardPLPanel::popupPlView( const QPoint &point )
172 {
173     QModelIndex index = currentView->indexAt( point );
174     QPoint globalPoint = currentView->viewport()->mapToGlobal( point );
175     QItemSelectionModel *selection = currentView->selectionModel();
176     QModelIndexList list = selection->selectedIndexes();
177
178     if( !model->popup( index, globalPoint, list ) )
179         QVLCMenu::PopupMenu( p_intf, true );
180 }
181
182 void StandardPLPanel::popupSelectColumn( QPoint pos )
183 {
184     QMenu menu;
185     assert( treeView );
186
187     /* We do not offer the option to hide index 0 column, or
188     * QTreeView will behave weird */
189     int i, j;
190     for( i = 1 << 1, j = 1; i < COLUMN_END; i <<= 1, j++ )
191     {
192         QAction* option = menu.addAction(
193             qfu( psz_column_title( i ) ) );
194         option->setCheckable( true );
195         option->setChecked( !treeView->isColumnHidden( j ) );
196         selectColumnsSigMapper->setMapping( option, j );
197         CONNECT( option, triggered(), selectColumnsSigMapper, map() );
198     }
199     menu.exec( QCursor::pos() );
200 }
201
202 void StandardPLPanel::toggleColumnShown( int i )
203 {
204     treeView->setColumnHidden( i, !treeView->isColumnHidden( i ) );
205 }
206
207 /* Search in the playlist */
208 void StandardPLPanel::search( const QString& searchText )
209 {
210     bool flat = currentView == iconView || currentView == listView;
211     model->search( searchText,
212                    flat ? currentView->rootIndex() : QModelIndex(),
213                    !flat );
214 }
215
216 /* Set the root of the new Playlist */
217 /* This activated by the selector selection */
218 void StandardPLPanel::setRoot( playlist_item_t *p_item )
219 {
220     model->rebuild( p_item );
221 }
222
223 void StandardPLPanel::browseInto( const QModelIndex &index )
224 {
225     if( currentView == iconView || currentView == listView )
226     {
227         currentRootIndexId = model->itemId( index );;
228         currentView->setRootIndex( index );
229     }
230
231     locationBar->setIndex( index );
232     searchEdit->clear();
233 }
234
235 void StandardPLPanel::browseInto( )
236 {
237     browseInto( currentRootIndexId != -1 && currentView != treeView ?
238                 model->index( currentRootIndexId, 0 ) :
239                 QModelIndex() );
240 }
241
242 void StandardPLPanel::wheelEvent( QWheelEvent *e )
243 {
244     // Accept this event in order to prevent unwanted volume up/down changes
245     e->accept();
246 }
247
248 bool StandardPLPanel::eventFilter ( QObject * watched, QEvent * event )
249 {
250     if (event->type() == QEvent::KeyPress)
251     {
252         QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
253         if( keyEvent->key() == Qt::Key_Delete ||
254             keyEvent->key() == Qt::Key_Backspace )
255         {
256             deleteSelection();
257             return true;
258         }
259     }
260     return false;
261 }
262
263 void StandardPLPanel::deleteSelection()
264 {
265     QItemSelectionModel *selection = currentView->selectionModel();
266     QModelIndexList list = selection->selectedIndexes();
267     model->doDelete( list );
268 }
269
270 void StandardPLPanel::createIconView()
271 {
272     iconView = new PlIconView( model, this );
273     iconView->setContextMenuPolicy( Qt::CustomContextMenu );
274     CONNECT( iconView, customContextMenuRequested( const QPoint & ),
275              this, popupPlView( const QPoint & ) );
276     CONNECT( iconView, activated( const QModelIndex & ),
277              this, activate( const QModelIndex & ) );
278     iconView->installEventFilter( this );
279     viewStack->addWidget( iconView );
280 }
281
282 void StandardPLPanel::createListView()
283 {
284     listView = new PlListView( model, this );
285     listView->setContextMenuPolicy( Qt::CustomContextMenu );
286     CONNECT( listView, customContextMenuRequested( const QPoint & ),
287              this, popupPlView( const QPoint & ) );
288     CONNECT( listView, activated( const QModelIndex & ),
289              this, activate( const QModelIndex & ) );
290     listView->installEventFilter( this );
291     viewStack->addWidget( listView );
292 }
293
294
295 void StandardPLPanel::createTreeView()
296 {
297     /* Create and configure the QTreeView */
298     treeView = new PlTreeView;
299
300     treeView->setIconSize( QSize( 20, 20 ) );
301     treeView->setAlternatingRowColors( true );
302     treeView->setAnimated( true );
303     treeView->setUniformRowHeights( true );
304     treeView->setSortingEnabled( true );
305     treeView->header()->setSortIndicator( -1 , Qt::AscendingOrder );
306     treeView->header()->setSortIndicatorShown( true );
307     treeView->header()->setClickable( true );
308     treeView->header()->setContextMenuPolicy( Qt::CustomContextMenu );
309
310     treeView->setSelectionBehavior( QAbstractItemView::SelectRows );
311     treeView->setSelectionMode( QAbstractItemView::ExtendedSelection );
312     treeView->setDragEnabled( true );
313     treeView->setAcceptDrops( true );
314     treeView->setDropIndicatorShown( true );
315     treeView->setContextMenuPolicy( Qt::CustomContextMenu );
316
317     /* setModel after setSortingEnabled(true), or the model will sort immediately! */
318     treeView->setModel( model );
319
320     getSettings()->beginGroup("Playlist");
321
322     if( getSettings()->contains( "headerStateV2" ) )
323     {
324         treeView->header()->restoreState(
325                 getSettings()->value( "headerStateV2" ).toByteArray() );
326     }
327     else
328     {
329         for( int m = 1, c = 0; m != COLUMN_END; m <<= 1, c++ )
330         {
331             treeView->setColumnHidden( c, !( m & COLUMN_DEFAULT ) );
332             if( m == COLUMN_TITLE ) treeView->header()->resizeSection( c, 200 );
333             else if( m == COLUMN_DURATION ) treeView->header()->resizeSection( c, 80 );
334         }
335     }
336
337     getSettings()->endGroup();
338
339     /* Connections for the TreeView */
340     CONNECT( treeView, activated( const QModelIndex& ),
341              this, activate( const QModelIndex& ) );
342     CONNECT( treeView->header(), customContextMenuRequested( const QPoint & ),
343              this, popupSelectColumn( QPoint ) );
344     CONNECT( treeView, customContextMenuRequested( const QPoint & ),
345              this, popupPlView( const QPoint & ) );
346     treeView->installEventFilter( this );
347
348     /* SignalMapper for columns */
349     selectColumnsSigMapper = new QSignalMapper( this );
350     CONNECT( selectColumnsSigMapper, mapped( int ),
351              this, toggleColumnShown( int ) );
352
353     /* Finish the layout */
354     viewStack->addWidget( treeView );
355 }
356
357 void StandardPLPanel::showView( int i_view )
358 {
359     switch( i_view )
360     {
361     case TREE_VIEW:
362     {
363         if( treeView == NULL )
364             createTreeView();
365         currentView = treeView;
366         break;
367     }
368     case ICON_VIEW:
369     {
370         if( iconView == NULL )
371             createIconView();
372         currentView = iconView;
373         break;
374     }
375     case LIST_VIEW:
376     {
377         if( listView == NULL )
378             createListView();
379         currentView = listView;
380         break;
381     }
382     default: return;
383     }
384
385     viewStack->setCurrentWidget( currentView );
386     viewActions[i_view]->setChecked( true );
387     browseInto();
388     gotoPlayingItem();
389 }
390
391 void StandardPLPanel::cycleViews()
392 {
393     if( currentView == iconView )
394         showView( TREE_VIEW );
395     else if( currentView == treeView )
396         showView( LIST_VIEW );
397     else if( currentView == listView )
398         showView( ICON_VIEW );
399     else
400         assert( 0 );
401 }
402
403 void StandardPLPanel::activate( const QModelIndex &index )
404 {
405     if( !index.data( PLModel::IsLeafNodeRole ).toBool() )
406     {
407         if( currentView != treeView )
408             browseInto( index );
409     }
410     else
411     {
412         playlist_Lock( THEPL );
413         playlist_item_t *p_item = playlist_ItemGetById( THEPL, model->itemId( index ) );
414         p_item->i_flags |= PLAYLIST_SUBITEM_STOP_FLAG;
415         lastActivatedId = p_item->p_input->i_id;
416         playlist_Unlock( THEPL );
417         model->activateItem( index );
418     }
419 }
420
421 void StandardPLPanel::browseInto( input_item_t *p_input )
422 {
423
424     if( p_input->i_id != lastActivatedId ) return;
425
426     playlist_Lock( THEPL );
427
428     playlist_item_t *p_item = playlist_ItemGetByInput( THEPL, p_input );
429     if( !p_item )
430     {
431         playlist_Unlock( THEPL );
432         return;
433     }
434
435     QModelIndex index = model->index( p_item->i_id, 0 );
436
437     playlist_Unlock( THEPL );
438
439     if( currentView == treeView )
440         treeView->setExpanded( index, true );
441     else
442         browseInto( index );
443
444     lastActivatedId = -1;
445
446
447 }
448
449 LocationBar::LocationBar( PLModel *m )
450 {
451     model = m;
452     mapper = new QSignalMapper( this );
453     CONNECT( mapper, mapped( int ), this, invoke( int ) );
454
455     btnMore = new LocationButton( "...", false, true, this );
456     menuMore = new QMenu( this );
457     btnMore->setMenu( menuMore );
458 }
459
460 void LocationBar::setIndex( const QModelIndex &index )
461 {
462     qDeleteAll( buttons );
463     buttons.clear();
464     qDeleteAll( actions );
465     actions.clear();
466
467     QModelIndex i = index;
468     bool first = true;
469
470     while( true )
471     {
472         PLItem *item = model->getItem( i );
473
474         char *fb_name = input_item_GetTitleFbName( item->inputItem() );
475         QString text = qfu(fb_name);
476         free(fb_name);
477
478         QAbstractButton *btn = new LocationButton( text, first, !first, this );
479         btn->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Fixed );
480         buttons.append( btn );
481
482         QAction *action = new QAction( text, this );
483         actions.append( action );
484         CONNECT( btn, clicked(), action, trigger() );
485
486         mapper->setMapping( action, item->id() );
487         CONNECT( action, triggered(), mapper, map() );
488
489         first = false;
490
491         if( i.isValid() ) i = i.parent();
492         else break;
493     }
494
495     QString prefix;
496     for( int a = actions.count() - 1; a >= 0 ; a-- )
497     {
498         actions[a]->setText( prefix + actions[a]->text() );
499         prefix += QString("  ");
500     }
501
502     if( isVisible() ) layOut( size() );
503 }
504
505 void LocationBar::setRootIndex()
506 {
507     setIndex( QModelIndex() );
508 }
509
510 void LocationBar::invoke( int i_id )
511 {
512     QModelIndex index = model->index( i_id, 0 );
513     emit invoked ( index );
514 }
515
516 void LocationBar::layOut( const QSize& size )
517 {
518     menuMore->clear();
519     widths.clear();
520
521     int count = buttons.count();
522     int totalWidth = 0;
523     for( int i = 0; i < count; i++ )
524     {
525         int w = buttons[i]->sizeHint().width();
526         widths.append( w );
527         totalWidth += w;
528         if( totalWidth > size.width() ) break;
529     }
530
531     int x = 0;
532     int shown = widths.count();
533
534     if( totalWidth > size.width() && count > 1 )
535     {
536         QSize sz = btnMore->sizeHint();
537         btnMore->setGeometry( 0, 0, sz.width(), size.height() );
538         btnMore->show();
539         x = sz.width();
540         totalWidth += x;
541     }
542     else
543     {
544         btnMore->hide();
545     }
546     for( int i = count - 1; i >= 0; i-- )
547     {
548         if( totalWidth <= size.width() || i == 0)
549         {
550             buttons[i]->setGeometry( x, 0, qMin( size.width() - x, widths[i] ), size.height() );
551             buttons[i]->show();
552             x += widths[i];
553             totalWidth -= widths[i];
554         }
555         else
556         {
557             menuMore->addAction( actions[i] );
558             buttons[i]->hide();
559             if( i < shown ) totalWidth -= widths[i];
560         }
561     }
562 }
563
564 void LocationBar::resizeEvent ( QResizeEvent * event )
565 {
566     layOut( event->size() );
567 }
568
569 QSize LocationBar::sizeHint() const
570 {
571     return btnMore->sizeHint();
572 }
573
574 LocationButton::LocationButton( const QString &text, bool bold,
575                                 bool arrow, QWidget * parent )
576   : b_arrow( arrow ), QPushButton( parent )
577 {
578     QFont font;
579     font.setBold( bold );
580     setFont( font );
581     setText( text );
582 }
583
584 #define PADDING 4
585
586 void LocationButton::paintEvent ( QPaintEvent * event )
587 {
588     QStyleOptionButton option;
589     option.initFrom( this );
590     option.state |= QStyle::State_Enabled;
591     QPainter p( this );
592
593     if( underMouse() )
594     {
595         p.save();
596         p.setRenderHint( QPainter::Antialiasing, true );
597         QColor c = palette().color( QPalette::Highlight );
598         p.setPen( c );
599         p.setBrush( c.lighter( 150 ) );
600         p.setOpacity( 0.2 );
601         p.drawRoundedRect( option.rect.adjusted( 0, 2, 0, -2 ), 5, 5 );
602         p.restore();
603     }
604
605     QRect r = option.rect.adjusted( PADDING, 0, -PADDING - (b_arrow ? 10 : 0), 0 );
606
607     QString str( text() );
608     /* This check is absurd, but either it is not done properly inside elidedText(),
609        or boundingRect() is wrong */
610     if( r.width() < fontMetrics().boundingRect( text() ).width() )
611         str = fontMetrics().elidedText( text(), Qt::ElideRight, r.width() );
612     p.drawText( r, Qt::AlignVCenter | Qt::AlignLeft, str );
613
614     if( b_arrow )
615     {
616         option.rect.setWidth( 10 );
617         option.rect.moveRight( rect().right() );
618         style()->drawPrimitive( QStyle::PE_IndicatorArrowRight, &option, &p );
619     }
620 }
621
622 QSize LocationButton::sizeHint() const
623 {
624     QSize s( fontMetrics().boundingRect( text() ).size() );
625     /* Add two pixels to width: font metrics are buggy, if you pass text through elidation
626        with exactly the width of its bounding rect, sometimes it still elides */
627     s.setWidth( s.width() + ( 2 * PADDING ) + ( b_arrow ? 10 : 0 ) + 2 );
628     s.setHeight( s.height() + 2 * PADDING );
629     return s;
630 }
631
632 #undef PADDING