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