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