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