]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/playlist/selector.cpp
Qt: selector, prevent some podcast crashes
[vlc] / modules / gui / qt4 / components / playlist / selector.cpp
1 /*****************************************************************************
2  * selector.cpp : Playlist source selector
3  ****************************************************************************
4  * Copyright (C) 2006-2009 the VideoLAN team
5  * $Id$
6  *
7  * Authors: ClĂ©ment Stenac <zorglub@videolan.org>
8  *          Jean-Baptiste Kempf
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 "qt4.hpp"
30 #include "components/playlist/selector.hpp"
31 #include "playlist_model.hpp"                /* plMimeData */
32 #include "input_manager.hpp"                 /* MainInputManager, for podcast */
33
34 #include <QApplication>
35 #include <QInputDialog>
36 #include <QMessageBox>
37 #include <QMimeData>
38 #include <QDragMoveEvent>
39 #include <QTreeWidgetItem>
40 #include <QHBoxLayout>
41 #include <QPainter>
42 #include <QPalette>
43 #include <QScrollBar>
44 #include <assert.h>
45
46 #include <vlc_playlist.h>
47 #include <vlc_services_discovery.h>
48
49 void SelectorActionButton::paintEvent( QPaintEvent *event )
50 {
51     QPainter p( this );
52     QColor color = palette().color( QPalette::HighlightedText );
53     color.setAlpha( 80 );
54     if( underMouse() )
55         p.fillRect( rect(), color );
56     p.setPen( color );
57     int frame = style()->pixelMetric( QStyle::PM_DefaultFrameWidth, 0, this );
58     p.drawLine( rect().topLeft() + QPoint( 0, frame ),
59                 rect().bottomLeft() - QPoint( 0, frame ) );
60     QFramelessButton::paintEvent( event );
61 }
62
63 PLSelItem::PLSelItem ( QTreeWidgetItem *i, const QString& text )
64     : qitem(i), lblAction( NULL)
65 {
66     layout = new QHBoxLayout( this );
67     layout->setContentsMargins(0,0,0,0);
68     layout->addSpacing( 3 );
69
70     lbl = new QElidingLabel( text );
71     layout->addWidget(lbl, 1);
72
73     int height = qMax( 22, fontMetrics().height() + 8 );
74     setMinimumHeight( height );
75 }
76
77 void PLSelItem::addAction( ItemAction act, const QString& tooltip )
78 {
79     if( lblAction ) return; //might change later
80
81     QIcon icon;
82
83     switch( act )
84     {
85     case ADD_ACTION:
86         icon = QIcon( ":/buttons/playlist/playlist_add" ); break;
87     case RM_ACTION:
88         icon = QIcon( ":/buttons/playlist/playlist_remove" ); break;
89     default:
90         return;
91     }
92
93     lblAction = new SelectorActionButton();
94     lblAction->setIcon( icon );
95     lblAction->setMinimumWidth( lblAction->sizeHint().width() + 6 );
96
97     if( !tooltip.isEmpty() ) lblAction->setToolTip( tooltip );
98
99     layout->addWidget( lblAction, 0 );
100     lblAction->hide();
101
102     CONNECT( lblAction, clicked(), this, triggerAction() );
103 }
104
105
106 PLSelector::PLSelector( QWidget *p, intf_thread_t *_p_intf )
107            : QTreeWidget( p ), p_intf(_p_intf)
108 {
109     /* Properties */
110     setFrameStyle( QFrame::NoFrame );
111     setAttribute( Qt::WA_MacShowFocusRect, false );
112     viewport()->setAutoFillBackground( false );
113     setIconSize( QSize( 24,24 ) );
114     setIndentation( 12 );
115     setHeaderHidden( true );
116     setRootIsDecorated( true );
117     setAlternatingRowColors( false );
118
119     /* drops */
120     viewport()->setAcceptDrops(true);
121     setDropIndicatorShown(true);
122     invisibleRootItem()->setFlags( invisibleRootItem()->flags() & ~Qt::ItemIsDropEnabled );
123
124 #ifdef Q_WS_MAC
125     setAutoFillBackground( true );
126     QPalette palette;
127     palette.setColor( QPalette::Window, QColor(209,215,226) );
128     setPalette( palette );
129 #endif
130     setMinimumHeight( 120 );
131
132     /* Podcasts */
133     podcastsParent = NULL;
134     podcastsParentId = -1;
135
136     /* Podcast connects */
137     CONNECT( THEMIM, playlistItemAppended( int, int ),
138              this, plItemAdded( int, int ) );
139     CONNECT( THEMIM, playlistItemRemoved( int ),
140              this, plItemRemoved( int ) );
141     DCONNECT( THEMIM->getIM(), metaChanged( input_item_t *),
142               this, inputItemUpdate( input_item_t * ) );
143
144     createItems();
145
146     /* Expand at least to show level 2 */
147     for ( int i = 0; i < topLevelItemCount(); i++ )
148         expandItem( topLevelItem( i ) );
149
150     /***
151      * We need to react to both clicks and activation (enter-key) here.
152      * We use curItem to avoid rebuilding twice.
153      * See QStyle::SH_ItemView_ActivateItemOnSingleClick
154      ***/
155     curItem = NULL;
156     CONNECT( this, itemActivated( QTreeWidgetItem *, int ),
157              this, setSource( QTreeWidgetItem *) );
158     CONNECT( this, itemClicked( QTreeWidgetItem *, int ),
159              this, setSource( QTreeWidgetItem *) );
160 }
161
162 PLSelector::~PLSelector()
163 {
164     if( podcastsParent )
165     {
166         int c = podcastsParent->childCount();
167         for( int i = 0; i < c; i++ )
168         {
169             QTreeWidgetItem *item = podcastsParent->child(i);
170             input_item_t *p_input = item->data( 0, IN_ITEM_ROLE ).value<input_item_t*>();
171             vlc_gc_decref( p_input );
172         }
173     }
174 }
175
176 PLSelItem * putSDData( PLSelItem* item, const char* name, const char* longname )
177 {
178     item->treeItem()->setData( 0, NAME_ROLE, qfu( name ) );
179     item->treeItem()->setData( 0, LONGNAME_ROLE, qfu( longname ) );
180     return item;
181 }
182
183 PLSelItem * putPLData( PLSelItem* item, playlist_item_t* plItem )
184 {
185     item->treeItem()->setData( 0, PL_ITEM_ROLE, QVariant::fromValue( plItem ) );
186 /*    item->setData( 0, PL_ITEM_ID_ROLE, plItem->i_id );
187     item->setData( 0, IN_ITEM_ROLE, QVariant::fromValue( (void*) plItem->p_input ) ); );*/
188     return item;
189 }
190
191 void PLSelector::createItems()
192 {
193     /* PL */
194     PLSelItem *pl = putPLData( addItem( PL_ITEM_TYPE, N_("Playlist"), true ),
195                               THEPL->p_playing );
196     pl->treeItem()->setData( 0, SPECIAL_ROLE, QVariant( IS_PL ) );
197     setCurrentItem( pl->treeItem() );
198
199     /* ML */
200     PLSelItem *ml = putPLData( addItem( PL_ITEM_TYPE, N_("Media Library"), true ),
201                               THEPL->p_media_library );
202     ml->treeItem()->setData( 0, SPECIAL_ROLE, QVariant( IS_ML ) );
203
204 #ifdef MEDIA_LIBRARY
205     /* SQL ML */
206     addItem( SQL_ML_TYPE, "SQL Media Library" )->treeItem();
207 #endif
208
209     /* SD nodes */
210     QTreeWidgetItem *mycomp = addItem( CATEGORY_TYPE, N_("My Computer") )->treeItem();
211     QTreeWidgetItem *devices = addItem( CATEGORY_TYPE, N_("Devices") )->treeItem();
212     QTreeWidgetItem *lan = addItem( CATEGORY_TYPE, N_("Local Network") )->treeItem();
213     QTreeWidgetItem *internet = addItem( CATEGORY_TYPE, N_("Internet") )->treeItem();
214
215 #define NOT_SELECTABLE(w) w->setFlags( w->flags() ^ Qt::ItemIsSelectable );
216     NOT_SELECTABLE( mycomp );
217     NOT_SELECTABLE( devices );
218     NOT_SELECTABLE( lan );
219     NOT_SELECTABLE( internet );
220 #undef NOT_SELECTABLE
221
222     /* SD subnodes */
223     char **ppsz_longnames;
224     int *p_categories;
225     char **ppsz_names = vlc_sd_GetNames( THEPL, &ppsz_longnames, &p_categories );
226     if( !ppsz_names )
227         return;
228
229     char **ppsz_name = ppsz_names, **ppsz_longname = ppsz_longnames;
230     int *p_category = p_categories;
231     for( ; *ppsz_name; ppsz_name++, ppsz_longname++, p_category++ )
232     {
233         //msg_Dbg( p_intf, "Adding a SD item: %s", *ppsz_longname );
234
235         PLSelItem *selItem;
236         switch( *p_category )
237         {
238         case SD_CAT_INTERNET:
239             {
240             selItem = addItem( SD_TYPE, *ppsz_longname, false, internet );
241             if( !strncmp( *ppsz_name, "podcast", 7 ) )
242             {
243                 selItem->treeItem()->setData( 0, SPECIAL_ROLE, QVariant( IS_PODCAST ) );
244                 selItem->addAction( ADD_ACTION, qtr( "Subscribe to a podcast" ) );
245                 CONNECT( selItem, action( PLSelItem* ), this, podcastAdd( PLSelItem* ) );
246                 podcastsParent = selItem->treeItem();
247             }
248             }
249             break;
250         case SD_CAT_DEVICES:
251             selItem = addItem( SD_TYPE, *ppsz_longname, false, devices );
252             break;
253         case SD_CAT_LAN:
254             selItem = addItem( SD_TYPE, *ppsz_longname, false, lan );
255             break;
256         case SD_CAT_MYCOMPUTER:
257             selItem = addItem( SD_TYPE, *ppsz_longname, false, mycomp );
258             break;
259         default:
260             selItem = addItem( SD_TYPE, *ppsz_longname );
261         }
262
263         putSDData( selItem, *ppsz_name, *ppsz_longname );
264         free( *ppsz_name );
265         free( *ppsz_longname );
266     }
267     free( ppsz_names );
268     free( ppsz_longnames );
269     free( p_categories );
270
271     if( mycomp->childCount() == 0 ) delete mycomp;
272     if( devices->childCount() == 0 ) delete devices;
273     if( lan->childCount() == 0 ) delete lan;
274     if( internet->childCount() == 0 ) delete internet;
275 }
276
277 void PLSelector::setSource( QTreeWidgetItem *item )
278 {
279     if( !item || item == curItem )
280         return;
281
282     bool b_ok;
283     int i_type = item->data( 0, TYPE_ROLE ).toInt( &b_ok );
284     if( !b_ok || i_type == CATEGORY_TYPE )
285         return;
286
287     bool sd_loaded;
288     if( i_type == SD_TYPE )
289     {
290         QString qs = item->data( 0, NAME_ROLE ).toString();
291         sd_loaded = playlist_IsServicesDiscoveryLoaded( THEPL, qtu( qs ) );
292         if( !sd_loaded )
293         {
294             if ( playlist_ServicesDiscoveryAdd( THEPL, qtu( qs ) ) != VLC_SUCCESS )
295                 return ;
296
297             services_discovery_descriptor_t *p_test = new services_discovery_descriptor_t;
298             int i_ret = playlist_ServicesDiscoveryControl( THEPL, qtu( qs ), SD_CMD_DESCRIPTOR, p_test );
299             if( i_ret == VLC_SUCCESS && p_test->i_capabilities & SD_CAP_SEARCH )
300                 item->setData( 0, CAP_SEARCH_ROLE, true );
301         }
302     }
303 #ifdef MEDIA_LIBRARY
304     else if( i_type == SQL_ML_TYPE )
305     {
306         emit categoryActivated( NULL, true );
307         curItem = item;
308         return;
309     }
310 #endif
311
312     curItem = item;
313
314     /* */
315     playlist_Lock( THEPL );
316     playlist_item_t *pl_item = NULL;
317
318     /* Special case for podcast */
319     // FIXME: simplify
320     if( i_type == SD_TYPE )
321     {
322         /* Find the right item for the SD */
323         pl_item = playlist_ChildSearchName( THEPL->p_root,
324                       qtu( item->data(0, LONGNAME_ROLE ).toString() ) );
325
326         /* Podcasts */
327         if( item->data( 0, SPECIAL_ROLE ).toInt() == IS_PODCAST )
328         {
329             if( pl_item && !sd_loaded )
330             {
331                 podcastsParentId = pl_item->i_id;
332                 for( int i=0; i < pl_item->i_children; i++ )
333                     addPodcastItem( pl_item->pp_children[i] );
334             }
335             pl_item = NULL; //to prevent activating it
336         }
337     }
338     else
339         pl_item = item->data( 0, PL_ITEM_ROLE ).value<playlist_item_t*>();
340
341     playlist_Unlock( THEPL );
342
343     /* */
344     if( pl_item )
345         emit categoryActivated( pl_item, false );
346 }
347
348 PLSelItem * PLSelector::addItem (
349     SelectorItemType type, const char* str, bool drop,
350     QTreeWidgetItem* parentItem )
351 {
352   QTreeWidgetItem *item = parentItem ?
353       new QTreeWidgetItem( parentItem ) : new QTreeWidgetItem( this );
354
355   PLSelItem *selItem = new PLSelItem( item, qtr( str ) );
356   setItemWidget( item, 0, selItem );
357   item->setData( 0, TYPE_ROLE, (int)type );
358   if( !drop ) item->setFlags( item->flags() & ~Qt::ItemIsDropEnabled );
359
360   return selItem;
361 }
362
363 PLSelItem *PLSelector::addPodcastItem( playlist_item_t *p_item )
364 {
365     vlc_gc_incref( p_item->p_input );
366
367     char *psz_name = input_item_GetName( p_item->p_input );
368     PLSelItem *item = addItem( PL_ITEM_TYPE,  psz_name, false, podcastsParent );
369     free( psz_name );
370
371     item->addAction( RM_ACTION, qtr( "Remove this podcast subscription" ) );
372     item->treeItem()->setData( 0, PL_ITEM_ROLE, QVariant::fromValue( p_item ) );
373     item->treeItem()->setData( 0, PL_ITEM_ID_ROLE, QVariant(p_item->i_id) );
374     item->treeItem()->setData( 0, IN_ITEM_ROLE, QVariant::fromValue( p_item->p_input ) );
375     CONNECT( item, action( PLSelItem* ), this, podcastRemove( PLSelItem* ) );
376     return item;
377 }
378
379 QStringList PLSelector::mimeTypes() const
380 {
381     QStringList types;
382     types << "vlc/qt-input-items";
383     return types;
384 }
385
386 bool PLSelector::dropMimeData ( QTreeWidgetItem * parent, int,
387     const QMimeData * data, Qt::DropAction )
388 {
389     if( !parent ) return false;
390
391     QVariant type = parent->data( 0, TYPE_ROLE );
392     if( type == QVariant() ) return false;
393
394     int i_truth = parent->data( 0, SPECIAL_ROLE ).toInt();
395     if( i_truth != IS_PL && i_truth != IS_ML ) return false;
396
397     bool to_pl = ( i_truth == IS_PL );
398
399     const PlMimeData *plMimeData = qobject_cast<const PlMimeData*>( data );
400     if( !plMimeData ) return false;
401
402     QList<input_item_t*> inputItems = plMimeData->inputItems();
403
404     playlist_Lock( THEPL );
405
406     foreach( input_item_t *p_input, inputItems )
407     {
408         playlist_item_t *p_item = playlist_ItemGetByInput( THEPL, p_input );
409         if( !p_item ) continue;
410
411         playlist_NodeAddCopy( THEPL, p_item,
412                               to_pl ? THEPL->p_playing : THEPL->p_media_library,
413                               PLAYLIST_END );
414     }
415
416     playlist_Unlock( THEPL );
417
418     return true;
419 }
420
421 void PLSelector::dragMoveEvent ( QDragMoveEvent * event )
422 {
423     event->setDropAction( Qt::CopyAction );
424     QAbstractItemView::dragMoveEvent( event );
425 }
426
427 void PLSelector::plItemAdded( int item, int parent )
428 {
429     if( parent != podcastsParentId || podcastsParent == NULL ) return;
430
431     playlist_Lock( THEPL );
432
433     playlist_item_t *p_item = playlist_ItemGetById( THEPL, item );
434     if( !p_item ) {
435         playlist_Unlock( THEPL );
436         return;
437     }
438
439     int c = podcastsParent->childCount();
440     for( int i = 0; i < c; i++ )
441     {
442         QTreeWidgetItem *podItem = podcastsParent->child(i);
443         if( podItem->data( 0, PL_ITEM_ID_ROLE ).toInt() == item )
444         {
445           //msg_Dbg( p_intf, "Podcast already in: (%d) %s", item, p_item->p_input->psz_uri);
446           playlist_Unlock( THEPL );
447           return;
448         }
449     }
450
451     //msg_Dbg( p_intf, "Adding podcast: (%d) %s", item, p_item->p_input->psz_uri );
452     addPodcastItem( p_item );
453
454     playlist_Unlock( THEPL );
455
456     podcastsParent->setExpanded( true );
457 }
458
459 void PLSelector::plItemRemoved( int id )
460 {
461     if( !podcastsParent ) return;
462
463     int c = podcastsParent->childCount();
464     for( int i = 0; i < c; i++ )
465     {
466         QTreeWidgetItem *item = podcastsParent->child(i);
467         if( item->data( 0, PL_ITEM_ID_ROLE ).toInt() == id )
468         {
469             input_item_t *p_input = item->data( 0, IN_ITEM_ROLE ).value<input_item_t*>();
470             //msg_Dbg( p_intf, "Removing podcast: (%d) %s", id, p_input->psz_uri );
471             vlc_gc_decref( p_input );
472             delete item;
473             return;
474         }
475     }
476 }
477
478 void PLSelector::inputItemUpdate( input_item_t *arg )
479 {
480     if( podcastsParent == NULL )
481         return;
482
483     int c = podcastsParent->childCount();
484     for( int i = 0; i < c; i++ )
485     {
486         QTreeWidgetItem *item = podcastsParent->child(i);
487         input_item_t *p_input = item->data( 0, IN_ITEM_ROLE ).value<input_item_t*>();
488         if( p_input == arg )
489         {
490             PLSelItem *si = itemWidget( item );
491             char *psz_name = input_item_GetName( p_input );
492             si->setText( qfu( psz_name ) );
493             free( psz_name );
494             return;
495         }
496     }
497 }
498
499 void PLSelector::podcastAdd( PLSelItem * )
500 {
501     assert( podcastsParent );
502
503     bool ok;
504     QString url = QInputDialog::getText( this, qtr( "Subscribe" ),
505                                          qtr( "Enter URL of the podcast to subscribe to:" ),
506                                          QLineEdit::Normal, QString(), &ok );
507     if( !ok || url.isEmpty() ) return;
508
509     setSource( podcastsParent ); //to load the SD in case it's not loaded
510
511     vlc_object_t *p_obj = (vlc_object_t*) vlc_object_find_name( p_intf->p_libvlc, "podcast" );
512     if( !p_obj ) return;
513
514     QString request("ADD:");
515     request += url.trimmed();
516     var_SetString( p_obj, "podcast-request", qtu( request ) );
517     vlc_object_release( p_obj );
518 }
519
520 void PLSelector::podcastRemove( PLSelItem* item )
521 {
522     QString question ( qtr( "Do you really want to unsubscribe from %1?" ) );
523     question = question.arg( item->text() );
524     QMessageBox::StandardButton res =
525         QMessageBox::question( this, qtr( "Unsubscribe" ), question,
526                                QMessageBox::Yes | QMessageBox::No,
527                                QMessageBox::No );
528     if( res == QMessageBox::No ) return;
529
530     input_item_t *input = item->treeItem()->data( 0, IN_ITEM_ROLE ).value<input_item_t*>();
531     if( !input ) return;
532
533     vlc_object_t *p_obj = (vlc_object_t*) vlc_object_find_name(
534         p_intf->p_libvlc, "podcast" );
535     if( !p_obj ) return;
536
537     QString request("RM:");
538     char *psz_uri = input_item_GetURI( input );
539     request += qfu( psz_uri );
540     var_SetString( p_obj, "podcast-request", qtu( request ) );
541     vlc_object_release( p_obj );
542     free( psz_uri );
543 }
544
545 PLSelItem * PLSelector::itemWidget( QTreeWidgetItem *item )
546 {
547     return ( static_cast<PLSelItem*>( QTreeWidget::itemWidget( item, 0 ) ) );
548 }
549
550 void PLSelector::drawBranches ( QPainter * painter, const QRect & rect, const QModelIndex & index ) const
551 {
552     if( !model()->hasChildren( index ) ) return;
553     QStyleOption option;
554     option.initFrom( this );
555     option.rect = rect.adjusted( rect.width() - indentation(), 0, 0, 0 );
556     style()->drawPrimitive( isExpanded( index ) ?
557                             QStyle::PE_IndicatorArrowDown :
558                             QStyle::PE_IndicatorArrowRight, &option, painter );
559 }
560
561 void PLSelector::getCurrentItemInfos( int* type, bool* can_delay_search, QString *string)
562 {
563     *type = currentItem()->data( 0, TYPE_ROLE ).toInt();
564     *string = currentItem()->data( 0, NAME_ROLE ).toString();
565     *can_delay_search = currentItem()->data( 0, CAP_SEARCH_ROLE ).toBool();
566 }
567
568 int PLSelector::getCurrentItemCategory()
569 {
570     return currentItem()->data( 0, SPECIAL_ROLE ).toInt();
571 }
572
573 void PLSelector::wheelEvent( QWheelEvent *e )
574 {
575     if( verticalScrollBar()->isVisible() && (
576         (verticalScrollBar()->value() != verticalScrollBar()->minimum() && e->delta() >= 0 ) ||
577         (verticalScrollBar()->value() != verticalScrollBar()->maximum() && e->delta() < 0 )
578         ) )
579         QApplication::sendEvent(verticalScrollBar(), e);
580
581     // Accept this event in order to prevent unwanted volume up/down changes
582     e->accept();
583 }