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