]> git.sesse.net Git - vlc/blob - modules/gui/qt4/dialogs/plugins.cpp
Qt: ExtensionListModel: don't specialize
[vlc] / modules / gui / qt4 / dialogs / plugins.cpp
1 /*****************************************************************************
2  * plugins.cpp : Plug-ins and extensions listing
3  ****************************************************************************
4  * Copyright (C) 2008-2010 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Jean-Baptiste Kempf <jb (at) videolan.org>
8  *          Jean-Philippe AndrĂ© <jpeg (at) 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 "plugins.hpp"
30
31 #include "util/searchlineedit.hpp"
32 #include "extensions_manager.hpp"
33
34 #include <assert.h>
35
36 #include <vlc_modules.h>
37
38 #include <QTreeWidget>
39 #include <QStringList>
40 #include <QTabWidget>
41 #include <QHeaderView>
42 #include <QDialogButtonBox>
43 #include <QLineEdit>
44 #include <QLabel>
45 #include <QVBoxLayout>
46 #include <QComboBox>
47 #include <QHBoxLayout>
48 #include <QVBoxLayout>
49 #include <QSpacerItem>
50 #include <QListView>
51 #include <QPainter>
52 #include <QStyleOptionViewItem>
53 #include <QKeyEvent>
54 #include <QPushButton>
55 #include <QPixmap>
56
57 static QPixmap *loadPixmapFromData( char *, int size );
58
59
60 PluginDialog::PluginDialog( intf_thread_t *_p_intf ) : QVLCFrame( _p_intf )
61 {
62     setWindowTitle( qtr( "Plugins and extensions" ) );
63     setWindowRole( "vlc-plugins" );
64
65     QVBoxLayout *layout = new QVBoxLayout( this );
66     tabs = new QTabWidget( this );
67     tabs->addTab( extensionTab = new ExtensionTab( p_intf ),
68                   qtr( "Extensions" ) );
69     tabs->addTab( pluginTab = new PluginTab( p_intf ),
70                   qtr( "Plugins" ) );
71     layout->addWidget( tabs );
72
73     QDialogButtonBox *box = new QDialogButtonBox;
74     QPushButton *okButton = new QPushButton( qtr( "&Close" ), this );
75     box->addButton( okButton, QDialogButtonBox::RejectRole );
76     layout->addWidget( box );
77     BUTTONACT( okButton, close() );
78     restoreWidgetPosition( "PluginsDialog", QSize( 435, 280 ) );
79 }
80
81 PluginDialog::~PluginDialog()
82 {
83     saveWidgetPosition( "PluginsDialog" );
84 }
85
86 /* Plugins tab */
87
88 PluginTab::PluginTab( intf_thread_t *p_intf_ )
89         : QVLCFrame( p_intf_ )
90 {
91     QGridLayout *layout = new QGridLayout( this );
92
93     /* Main Tree for modules */
94     treePlugins = new QTreeWidget;
95     layout->addWidget( treePlugins, 0, 0, 1, -1 );
96
97     /* Users cannot move the columns around but we need to sort */
98 #if QT_VERSION >= 0x050000
99     treePlugins->header()->setSectionsMovable( false );
100 #else
101     treePlugins->header()->setMovable( false );
102 #endif
103     treePlugins->header()->setSortIndicatorShown( true );
104     //    treePlugins->header()->setResizeMode( QHeaderView::ResizeToContents );
105     treePlugins->setAlternatingRowColors( true );
106     treePlugins->setColumnWidth( 0, 200 );
107
108     QStringList headerNames;
109     headerNames << qtr("Name") << qtr("Capability" ) << qtr( "Score" );
110     treePlugins->setHeaderLabels( headerNames );
111
112     FillTree();
113
114     /* Set capability column to the correct Size*/
115     treePlugins->resizeColumnToContents( 1 );
116     treePlugins->header()->restoreState(
117             getSettings()->value( "Plugins/Header-State" ).toByteArray() );
118
119     treePlugins->setSortingEnabled( true );
120     treePlugins->sortByColumn( 1, Qt::AscendingOrder );
121
122     QLabel *label = new QLabel( qtr("&Search:"), this );
123     edit = new SearchLineEdit( this );
124     label->setBuddy( edit );
125
126     layout->addWidget( label, 1, 0 );
127     layout->addWidget( edit, 1, 1, 1, 1 );
128     CONNECT( edit, textChanged( const QString& ),
129             this, search( const QString& ) );
130
131     setMinimumSize( 500, 300 );
132     restoreWidgetPosition( "Plugins", QSize( 540, 400 ) );
133 }
134
135 inline void PluginTab::FillTree()
136 {
137     size_t count;
138     module_t **p_list = module_list_get( &count );
139
140     for( unsigned int i = 0; i < count; i++ )
141     {
142         module_t *p_module = p_list[i];
143
144         QStringList qs_item;
145         qs_item << qfu( module_get_name( p_module, true ) )
146                 << qfu( module_get_capability( p_module ) )
147                 << QString::number( module_get_score( p_module ) );
148 #ifndef DEBUG
149         if( qs_item.at(1).isEmpty() ) continue;
150 #endif
151
152         QTreeWidgetItem *item = new PluginTreeItem( qs_item );
153         treePlugins->addTopLevelItem( item );
154     }
155     module_list_free( p_list );
156 }
157
158 void PluginTab::search( const QString& qs )
159 {
160     QList<QTreeWidgetItem *> items = treePlugins->findItems( qs, Qt::MatchContains );
161     items += treePlugins->findItems( qs, Qt::MatchContains, 1 );
162
163     QTreeWidgetItem *item = NULL;
164     for( int i = 0; i < treePlugins->topLevelItemCount(); i++ )
165     {
166         item = treePlugins->topLevelItem( i );
167         item->setHidden( !items.contains( item ) );
168     }
169 }
170
171 PluginTab::~PluginTab()
172 {
173     saveWidgetPosition( "Plugins" );
174     getSettings()->setValue( "Plugins/Header-State",
175                              treePlugins->header()->saveState() );
176 }
177
178 void PluginTab::keyPressEvent( QKeyEvent *keyEvent )
179 {
180     if( keyEvent->key() == Qt::Key_Return ||
181         keyEvent->key() == Qt::Key_Enter )
182         keyEvent->accept();
183     else
184         keyEvent->ignore();
185 }
186
187 bool PluginTreeItem::operator< ( const QTreeWidgetItem & other ) const
188 {
189     int col = treeWidget()->sortColumn();
190     if( col == PluginTab::SCORE )
191         return text( col ).toInt() < other.text( col ).toInt();
192     else if ( col == PluginTab::CAPABILITY )
193     {
194         if ( text( PluginTab::CAPABILITY ) == other.text( PluginTab::CAPABILITY ) )
195             return text( PluginTab::NAME ) < other.text( PluginTab::NAME );
196         else
197             return text( PluginTab::CAPABILITY ) < other.text( PluginTab::CAPABILITY );
198     }
199     return text( col ) < other.text( col );
200 }
201
202 /* Extensions tab */
203 ExtensionTab::ExtensionTab( intf_thread_t *p_intf_ )
204         : QVLCFrame( p_intf_ )
205 {
206     // Layout
207     QVBoxLayout *layout = new QVBoxLayout( this );
208
209     QLabel *notice = new QLabel( qtr("Get more extensions from")
210             + QString( " <a href=\"http://addons.videolan.org/\">"
211                        "addons.videolan.org</a>." ) );
212     notice->setOpenExternalLinks( true );
213     layout->addWidget( notice );
214
215     // ListView
216     extList = new QListView( this );
217     CONNECT( extList, activated( const QModelIndex& ),
218              this, moreInformation() );
219     layout->addWidget( extList );
220
221     // List item delegate
222     ExtensionItemDelegate *itemDelegate = new ExtensionItemDelegate( extList );
223     extList->setItemDelegate( itemDelegate );
224
225     // Extension list look & feeling
226     extList->setAlternatingRowColors( true );
227     extList->setSelectionMode( QAbstractItemView::SingleSelection );
228
229     // Model
230     ExtensionListModel *model = new ExtensionListModel( extList, p_intf );
231     extList->setModel( model );
232
233     // Buttons' layout
234     QDialogButtonBox *buttonsBox = new QDialogButtonBox;
235
236     // More information button
237     butMoreInfo = new QPushButton( QIcon( ":/menu/info" ),
238                                    qtr( "More information..." ),
239                                    this );
240     CONNECT( butMoreInfo, clicked(), this, moreInformation() );
241     buttonsBox->addButton( butMoreInfo, QDialogButtonBox::ActionRole );
242
243     // Reload button
244     ExtensionsManager *EM = ExtensionsManager::getInstance( p_intf );
245     QPushButton *reload = new QPushButton( QIcon( ":/update" ),
246                                            qtr( "Reload extensions" ),
247                                            this );
248     CONNECT( reload, clicked(), EM, reloadExtensions() );
249     CONNECT( reload, clicked(), this, updateButtons() );
250     CONNECT( extList->selectionModel(),
251              selectionChanged( const QItemSelection &, const QItemSelection & ),
252              this,
253              updateButtons() );
254     buttonsBox->addButton( reload, QDialogButtonBox::ResetRole );
255
256     layout->addWidget( buttonsBox );
257     updateButtons();
258 }
259
260 ExtensionTab::~ExtensionTab()
261 {
262 }
263
264 void ExtensionTab::updateButtons()
265 {
266     butMoreInfo->setEnabled( extList->selectionModel()->hasSelection() );
267 }
268
269 // Do not close on ESC or ENTER
270 void ExtensionTab::keyPressEvent( QKeyEvent *keyEvent )
271 {
272     if( keyEvent->key() == Qt::Key_Return ||
273         keyEvent->key() == Qt::Key_Enter )
274         keyEvent->accept();
275     else
276         keyEvent->ignore();
277 }
278
279 // Show more information
280 void ExtensionTab::moreInformation()
281 {
282     QModelIndex index = extList->selectionModel()->selectedIndexes().first();
283
284     if( !index.isValid() )
285         return;
286
287     ExtensionInfoDialog dlg( index, p_intf, this );
288     dlg.exec();
289 }
290
291 /* Safe copy of the extension_t struct */
292 ExtensionListModel::ExtensionCopy::ExtensionCopy( extension_t *p_ext )
293 {
294     name = qfu( p_ext->psz_name );
295     description = qfu( p_ext->psz_description );
296     shortdesc = qfu( p_ext->psz_shortdescription );
297     if( description.isEmpty() )
298         description = shortdesc;
299     if( shortdesc.isEmpty() && !description.isEmpty() )
300         shortdesc = description;
301     title = qfu( p_ext->psz_title );
302     author = qfu( p_ext->psz_author );
303     version = qfu( p_ext->psz_version );
304     url = qfu( p_ext->psz_url );
305     icon = loadPixmapFromData( p_ext->p_icondata, p_ext->i_icondata_size );
306 }
307
308 ExtensionListModel::ExtensionCopy::~ExtensionCopy()
309 {
310     delete icon;
311 }
312
313 QVariant ExtensionListModel::ExtensionCopy::data( int role ) const
314 {
315     switch( role )
316     {
317     case Qt::DisplayRole:
318         return title;
319     case Qt::DecorationRole:
320         if ( !icon ) return QPixmap( ":/logo/vlc48.png" );
321         return *icon;
322     case DescriptionRole:
323         return shortdesc;
324     case VersionRole:
325         return version;
326     case AuthorRole:
327         return author;
328     case LinkRole:
329         return url;
330     case NameRole:
331         return name;
332     default:
333         return QVariant();
334     }
335 }
336
337 /* Extensions list model for the QListView */
338
339 ExtensionListModel::ExtensionListModel( QObject *parent, intf_thread_t *intf )
340         : QAbstractListModel( parent ), p_intf( intf )
341 {
342     // Connect to ExtensionsManager::extensionsUpdated()
343     ExtensionsManager* EM = ExtensionsManager::getInstance( p_intf );
344     CONNECT( EM, extensionsUpdated(), this, updateList() );
345
346     // Load extensions now if not already loaded
347     EM->loadExtensions();
348 }
349
350 ExtensionListModel::~ExtensionListModel()
351 {
352     // Clear extensions list
353     while( !extensions.isEmpty() )
354         delete extensions.takeLast();
355 }
356
357 void ExtensionListModel::updateList()
358 {
359     ExtensionCopy *ext;
360
361     // Clear extensions list
362     while( !extensions.isEmpty() )
363     {
364         ext = extensions.takeLast();
365         delete ext;
366     }
367
368     // Find new extensions
369     ExtensionsManager *EM = ExtensionsManager::getInstance( p_intf );
370     extensions_manager_t *p_mgr = EM->getManager();
371     if( !p_mgr )
372         return;
373
374     vlc_mutex_lock( &p_mgr->lock );
375     extension_t *p_ext;
376     FOREACH_ARRAY( p_ext, p_mgr->extensions )
377     {
378         ext = new ExtensionCopy( p_ext );
379         extensions.append( ext );
380     }
381     FOREACH_END()
382     vlc_mutex_unlock( &p_mgr->lock );
383     vlc_object_release( p_mgr );
384
385     emit dataChanged( index( 0 ), index( rowCount() - 1 ) );
386 }
387
388 int ExtensionListModel::rowCount( const QModelIndex& ) const
389 {
390     int count = 0;
391     ExtensionsManager *EM = ExtensionsManager::getInstance( p_intf );
392     extensions_manager_t *p_mgr = EM->getManager();
393     if( !p_mgr )
394         return 0;
395
396     vlc_mutex_lock( &p_mgr->lock );
397     count = p_mgr->extensions.i_size;
398     vlc_mutex_unlock( &p_mgr->lock );
399     vlc_object_release( p_mgr );
400
401     return count;
402 }
403
404 QVariant ExtensionListModel::data( const QModelIndex& index, int role ) const
405 {
406     if( !index.isValid() )
407         return QVariant();
408
409     ExtensionCopy * extension =
410             static_cast<ExtensionCopy *>(index.internalPointer());
411
412     return extension->data( role );
413 }
414
415 QModelIndex ExtensionListModel::index( int row, int column,
416                                        const QModelIndex& ) const
417 {
418     if( column != 0 )
419         return QModelIndex();
420     if( row < 0 || row >= extensions.count() )
421         return QModelIndex();
422
423     return createIndex( row, 0, extensions.at( row ) );
424 }
425
426
427 /* Extension List Widget Item */
428 ExtensionItemDelegate::ExtensionItemDelegate( QObject *parent )
429         : QStyledItemDelegate( parent )
430 {
431     margins = QMargins( 4, 4, 4, 4 );
432 }
433
434 ExtensionItemDelegate::~ExtensionItemDelegate()
435 {
436 }
437
438 void ExtensionItemDelegate::paint( QPainter *painter,
439                                    const QStyleOptionViewItem &option,
440                                    const QModelIndex &index ) const
441 {
442     QStyleOptionViewItemV4 opt = option;
443     initStyleOption( &opt, index );
444
445     // Draw background
446     if ( opt.state & QStyle::State_Selected )
447         painter->fillRect( opt.rect, opt.palette.highlight() );
448
449     // Icon
450     QPixmap icon = index.data( Qt::DecorationRole ).value<QPixmap>();
451     if( !icon.isNull() )
452     {
453         painter->drawPixmap( opt.rect.left() + margins.left(),
454                              opt.rect.top() + margins.top(),
455                              icon.scaled( opt.decorationSize,
456                                           Qt::KeepAspectRatio,
457                                           Qt::SmoothTransformation )
458         );
459     }
460
461     painter->save();
462     painter->setRenderHint( QPainter::TextAntialiasing );
463
464     if ( opt.state & QStyle::State_Selected )
465         painter->setPen( opt.palette.highlightedText().color() );
466
467     QFont font( option.font );
468     font.setBold( true );
469     painter->setFont( font );
470     QRect textrect( opt.rect );
471     textrect.adjust( 2 * margins.left() + margins.right() + opt.decorationSize.width(),
472                      margins.top(),
473                      - margins.right(),
474                      - margins.bottom() - opt.fontMetrics.height() );
475
476     painter->drawText( textrect, Qt::AlignLeft,
477                        index.data( Qt::DisplayRole ).toString() );
478
479     font.setBold( false );
480     painter->setFont( font );
481     painter->drawText( textrect.translated( 0, option.fontMetrics.height() ),
482                        Qt::AlignLeft,
483                        index.data( ExtensionListModel::DescriptionRole ).toString() );
484
485     painter->restore();
486 }
487
488 QSize ExtensionItemDelegate::sizeHint( const QStyleOptionViewItem &option,
489                                        const QModelIndex &index ) const
490 {
491     if ( index.isValid() )
492     {
493         return QSize( 200, 2 * option.fontMetrics.height()
494                       + margins.top() + margins.bottom() );
495     }
496     else
497         return QSize();
498 }
499
500 void ExtensionItemDelegate::initStyleOption( QStyleOptionViewItem *option,
501                                              const QModelIndex &index ) const
502 {
503     QStyledItemDelegate::initStyleOption( option, index );
504     option->decorationSize = QSize( option->rect.height(), option->rect.height() );
505     option->decorationSize -= QSize( margins.left() + margins.right(),
506                                      margins.top() + margins.bottom() );
507 }
508
509 /* "More information" dialog */
510
511 ExtensionInfoDialog::ExtensionInfoDialog( const QModelIndex &index,
512                                           intf_thread_t *p_intf,
513                                           QWidget *parent )
514        : QVLCDialog( parent, p_intf )
515 {
516     // Let's be a modal dialog
517     setWindowModality( Qt::WindowModal );
518
519     // Window title
520     setWindowTitle( qtr( "About" ) + " " + index.data(Qt::DisplayRole).toString() );
521
522     // Layout
523     QGridLayout *layout = new QGridLayout( this );
524
525     // Icon
526     QLabel *icon = new QLabel( this );
527     QPixmap pix = index.data(Qt::DecorationRole).value<QPixmap>();
528     Q_ASSERT( !pix.isNull() );
529     icon->setPixmap( pix );
530     icon->setAlignment( Qt::AlignCenter );
531     icon->setFixedSize( 48, 48 );
532     layout->addWidget( icon, 1, 0, 2, 1 );
533
534     // Title
535     QLabel *label = new QLabel( index.data(Qt::DisplayRole).toString(), this );
536     QFont font = label->font();
537     font.setBold( true );
538     font.setPointSizeF( font.pointSizeF() * 1.3f );
539     label->setFont( font );
540     layout->addWidget( label, 0, 0, 1, -1 );
541
542     // Version
543     label = new QLabel( "<b>" + qtr( "Version" ) + ":</b>", this );
544     layout->addWidget( label, 1, 1, 1, 1, Qt::AlignBottom );
545     label = new QLabel( index.data(ExtensionListModel::VersionRole).toString(), this );
546     layout->addWidget( label, 1, 2, 1, 2, Qt::AlignBottom );
547
548     // Author
549     label = new QLabel( "<b>" + qtr( "Author" ) + ":</b>", this );
550     layout->addWidget( label, 2, 1, 1, 1, Qt::AlignTop );
551     label = new QLabel( index.data(ExtensionListModel::AuthorRole).toString(), this );
552     layout->addWidget( label, 2, 2, 1, 2, Qt::AlignTop );
553
554
555     // Description
556     label = new QLabel( this );
557     label->setText( index.data(ExtensionListModel::DescriptionRole).toString() );
558     label->setWordWrap( true );
559     label->setOpenExternalLinks( true );
560     layout->addWidget( label, 4, 0, 1, -1 );
561
562     // URL
563     label = new QLabel( "<b>" + qtr( "Website" ) + ":</b>", this );
564     layout->addWidget( label, 5, 0, 1, 2 );
565     label = new QLabel( QString("<a href=\"%1\">%2</a>")
566                         .arg( index.data(ExtensionListModel::LinkRole).toString() )
567                         .arg( index.data(ExtensionListModel::LinkRole).toString() )
568                         , this );
569     label->setOpenExternalLinks( true );
570     layout->addWidget( label, 5, 2, 1, -1 );
571
572     // Script file
573     label = new QLabel( "<b>" + qtr( "File" ) + ":</b>", this );
574     layout->addWidget( label, 6, 0, 1, 2 );
575     QLineEdit *line =
576             new QLineEdit( index.data(ExtensionListModel::NameRole).toString(), this );
577     line->setReadOnly( true );
578     layout->addWidget( line, 6, 2, 1, -1 );
579
580     // Close button
581     QDialogButtonBox *group = new QDialogButtonBox( this );
582     QPushButton *closeButton = new QPushButton( qtr( "&Close" ) );
583     group->addButton( closeButton, QDialogButtonBox::RejectRole );
584     BUTTONACT( closeButton, close() );
585
586     layout->addWidget( group, 7, 0, 1, -1 );
587
588     // Fix layout
589     layout->setColumnStretch( 2, 1 );
590     layout->setRowStretch( 4, 1 );
591     setMinimumSize( 450, 350 );
592 }
593
594 static QPixmap *loadPixmapFromData( char *data, int size )
595 {
596     if( !data || size <= 0 )
597         return NULL;
598     QPixmap *pixmap = new QPixmap();
599     if( !pixmap->loadFromData( (const uchar*) data, (uint) size ) )
600     {
601         delete pixmap;
602         return NULL;
603     }
604     return pixmap;
605 }