]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/playlist/playlist_model.cpp
Qt: add popupAddToPlaylist
[vlc] / modules / gui / qt4 / components / playlist / playlist_model.cpp
1 /*****************************************************************************
2  * playlist_model.cpp : Manage playlist model
3  ****************************************************************************
4  * Copyright (C) 2006-2011 the VideoLAN team
5  * $Id$
6  *
7  * Authors: ClĂ©ment Stenac <zorglub@videolan.org>
8  *          Ilkka Ollakkka <ileoo (at) videolan dot org>
9  *          Jakob Leben <jleben@videolan.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include "qt4.hpp"
31 #include "components/playlist/playlist_model.hpp"
32 #include "dialogs_provider.hpp"                         /* THEDP */
33 #include "input_manager.hpp"                            /* THEMIM */
34 #include "dialogs/mediainfo.hpp"                        /* MediaInfo Dialog */
35 #include "dialogs/playlist.hpp"                         /* Playlist Dialog */
36
37 #include <vlc_intf_strings.h>                           /* I_DIR */
38
39 #include "pixmaps/types/type_unknown.xpm"
40 #include "sorting.h"
41
42 #include <assert.h>
43 #include <QIcon>
44 #include <QFont>
45 #include <QMenu>
46 #include <QUrl>
47 #include <QFileInfo>
48 #include <QDesktopServices>
49 #include <QInputDialog>
50 #include <QSignalMapper>
51
52 #define I_NEW_DIR \
53     I_DIR_OR_FOLDER( N_("Create Directory"), N_( "Create Folder" ) )
54 #define I_NEW_DIR_NAME \
55     I_DIR_OR_FOLDER( N_( "Enter name for new directory:" ), \
56                      N_( "Enter name for new folder:" ) )
57
58 QIcon PLModel::icons[ITEM_TYPE_NUMBER];
59
60 /*************************************************************************
61  * Playlist model implementation
62  *************************************************************************/
63
64 PLModel::PLModel( playlist_t *_p_playlist,  /* THEPL */
65                   intf_thread_t *_p_intf,   /* main Qt p_intf */
66                   playlist_item_t * p_root,
67                   QObject *parent )         /* Basic Qt parent */
68                   : VLCModel( _p_intf, parent )
69 {
70     p_playlist        = _p_playlist;
71     i_cached_id       = -1;
72     i_cached_input_id = -1;
73     i_popup_item      = i_popup_parent = -1;
74     sortingMenu       = NULL;
75
76     rootItem          = NULL; /* PLItem rootItem, will be set in rebuild( ) */
77
78     /* Icons initialization */
79 #define ADD_ICON(type, x) icons[ITEM_TYPE_##type] = QIcon( x )
80     ADD_ICON( UNKNOWN , type_unknown_xpm );
81     ADD_ICON( FILE, ":/type/file" );
82     ADD_ICON( DIRECTORY, ":/type/directory" );
83     ADD_ICON( DISC, ":/type/disc" );
84     ADD_ICON( CDDA, ":/type/cdda" );
85     ADD_ICON( CARD, ":/type/capture-card" );
86     ADD_ICON( NET, ":/type/net" );
87     ADD_ICON( PLAYLIST, ":/type/playlist" );
88     ADD_ICON( NODE, ":/type/node" );
89 #undef ADD_ICON
90
91     rebuild( p_root );
92     DCONNECT( THEMIM->getIM(), metaChanged( input_item_t *),
93               this, processInputItemUpdate( input_item_t *) );
94     DCONNECT( THEMIM, inputChanged( input_thread_t * ),
95               this, processInputItemUpdate( input_thread_t* ) );
96     CONNECT( THEMIM, playlistItemAppended( int, int ),
97              this, processItemAppend( int, int ) );
98     CONNECT( THEMIM, playlistItemRemoved( int ),
99              this, processItemRemoval( int ) );
100 }
101
102 PLModel::~PLModel()
103 {
104     delete rootItem;
105     delete sortingMenu;
106 }
107
108 Qt::DropActions PLModel::supportedDropActions() const
109 {
110     return Qt::CopyAction | Qt::MoveAction;
111 }
112
113 Qt::ItemFlags PLModel::flags( const QModelIndex &index ) const
114 {
115     Qt::ItemFlags flags = QAbstractItemModel::flags( index );
116
117     const PLItem *item = index.isValid() ? getItem( index ) : rootItem;
118
119     if( canEdit() )
120     {
121         PL_LOCK;
122         playlist_item_t *plItem =
123             playlist_ItemGetById( p_playlist, item->i_id );
124
125         if ( plItem && ( plItem->i_children > -1 ) )
126             flags |= Qt::ItemIsDropEnabled;
127
128         PL_UNLOCK;
129
130     }
131     flags |= Qt::ItemIsDragEnabled;
132
133     return flags;
134 }
135
136 QStringList PLModel::mimeTypes() const
137 {
138     QStringList types;
139     types << "vlc/qt-input-items";
140     return types;
141 }
142
143 bool modelIndexLessThen( const QModelIndex &i1, const QModelIndex &i2 )
144 {
145     if( !i1.isValid() || !i2.isValid() ) return false;
146     PLItem *item1 = static_cast<PLItem*>( i1.internalPointer() );
147     PLItem *item2 = static_cast<PLItem*>( i2.internalPointer() );
148     if( item1->parent() == item2->parent() ) return i1.row() < i2.row();
149     else return *item1 < *item2;
150 }
151
152 QMimeData *PLModel::mimeData( const QModelIndexList &indexes ) const
153 {
154     PlMimeData *plMimeData = new PlMimeData();
155     QModelIndexList list;
156
157     foreach( const QModelIndex &index, indexes ) {
158         if( index.isValid() && index.column() == 0 )
159             list.append(index);
160     }
161
162     qSort(list.begin(), list.end(), modelIndexLessThen);
163
164     PLItem *item = NULL;
165     foreach( const QModelIndex &index, list ) {
166         if( item )
167         {
168             PLItem *testee = getItem( index );
169             while( testee->parent() )
170             {
171                 if( testee->parent() == item ||
172                     testee->parent() == item->parent() ) break;
173                 testee = testee->parent();
174             }
175             if( testee->parent() == item ) continue;
176             item = getItem( index );
177         }
178         else
179             item = getItem( index );
180
181         plMimeData->appendItem( item->inputItem() );
182     }
183
184     return plMimeData;
185 }
186
187 /* Drop operation */
188 bool PLModel::dropMimeData( const QMimeData *data, Qt::DropAction action,
189         int row, int, const QModelIndex &parent )
190 {
191     bool copy = action == Qt::CopyAction;
192     if( !copy && action != Qt::MoveAction )
193         return true;
194
195     const PlMimeData *plMimeData = qobject_cast<const PlMimeData*>( data );
196     if( plMimeData )
197     {
198         if( copy )
199             dropAppendCopy( plMimeData, getItem( parent ), row );
200         else
201             dropMove( plMimeData, getItem( parent ), row );
202     }
203     return true;
204 }
205
206 void PLModel::dropAppendCopy( const PlMimeData *plMimeData, PLItem *target, int pos )
207 {
208     PL_LOCK;
209
210     playlist_item_t *p_parent =
211         playlist_ItemGetByInput( p_playlist, target->inputItem() );
212     if( !p_parent ) return;
213
214     if( pos == -1 ) pos = PLAYLIST_END;
215
216     QList<input_item_t*> inputItems = plMimeData->inputItems();
217
218     foreach( input_item_t* p_input, inputItems )
219     {
220         playlist_item_t *p_item = playlist_ItemGetByInput( p_playlist, p_input );
221         if( !p_item ) continue;
222         pos = playlist_NodeAddCopy( p_playlist, p_item, p_parent, pos );
223     }
224
225     PL_UNLOCK;
226 }
227
228 void PLModel::dropMove( const PlMimeData * plMimeData, PLItem *target, int row )
229 {
230     QList<input_item_t*> inputItems = plMimeData->inputItems();
231     QList<PLItem*> model_items;
232     playlist_item_t *pp_items[inputItems.size()];
233
234     PL_LOCK;
235
236     playlist_item_t *p_parent =
237         playlist_ItemGetByInput( p_playlist, target->inputItem() );
238
239     if( !p_parent || row > p_parent->i_children )
240     {
241         PL_UNLOCK; return;
242     }
243
244     int new_pos = row == -1 ? p_parent->i_children : row;
245     int model_pos = new_pos;
246     int i = 0;
247
248     foreach( input_item_t *p_input, inputItems )
249     {
250         playlist_item_t *p_item = playlist_ItemGetByInput( p_playlist, p_input );
251         if( !p_item ) continue;
252
253         PLItem *item = findByInput( rootItem, p_input->i_id );
254         if( !item ) continue;
255
256         /* Better not try to move a node into itself.
257            Abort the whole operation in that case,
258            because it is ambiguous. */
259         PLItem *climber = target;
260         while( climber )
261         {
262             if( climber == item )
263             {
264                 PL_UNLOCK; return;
265             }
266             climber = climber->parent();
267         }
268
269         if( item->parent() == target &&
270             target->children.indexOf( item ) < new_pos )
271             model_pos--;
272
273         model_items.append( item );
274         pp_items[i] = p_item;
275         i++;
276     }
277
278     if( model_items.isEmpty() )
279     {
280         PL_UNLOCK; return;
281     }
282
283     playlist_TreeMoveMany( p_playlist, i, pp_items, p_parent, new_pos );
284
285     PL_UNLOCK;
286
287     foreach( PLItem *item, model_items )
288         takeItem( item );
289
290     insertChildren( target, model_items, model_pos );
291 }
292
293 /* remove item with its id */
294 void PLModel::removeItem( int i_id )
295 {
296     PLItem *item = findById( rootItem, i_id );
297     removeItem( item );
298 }
299
300 void PLModel::activateItem( const QModelIndex &index )
301 {
302     assert( index.isValid() );
303     const PLItem *item = getItem( index );
304     assert( item );
305     PL_LOCK;
306     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, item->i_id );
307     activateItem( p_item );
308     PL_UNLOCK;
309 }
310
311 /* Must be entered with lock */
312 void PLModel::activateItem( playlist_item_t *p_item )
313 {
314     if( !p_item ) return;
315     playlist_item_t *p_parent = p_item;
316     while( p_parent )
317     {
318         if( p_parent->i_id == rootItem->id() ) break;
319         p_parent = p_parent->p_parent;
320     }
321     if( p_parent )
322         playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, pl_Locked,
323                 p_parent, p_item );
324 }
325
326 /****************** Base model mandatory implementations *****************/
327 QVariant PLModel::data( const QModelIndex &index, const int role ) const
328 {
329     if( !index.isValid() ) return QVariant();
330     const PLItem *item = getItem( index );
331     if( role == Qt::DisplayRole )
332     {
333         int metadata = columnToMeta( index.column() );
334         if( metadata == COLUMN_END ) return QVariant();
335
336         QString returninfo;
337         if( metadata == COLUMN_NUMBER )
338             returninfo = QString::number( index.row() + 1 );
339         else if( metadata == COLUMN_COVER )
340         {
341             QString artUrl;
342             artUrl = InputManager::decodeArtURL( item->inputItem() );
343             if( artUrl.isEmpty() )
344             {
345                 for( int i = 0; i < item->childCount(); i++ )
346                 {
347                     artUrl = InputManager::decodeArtURL( item->child( i )->inputItem() );
348                     if( !artUrl.isEmpty() )
349                         break;
350                 }
351             }
352             return QVariant( artUrl );
353         }
354         else
355         {
356             char *psz = psz_column_meta( item->inputItem(), metadata );
357             returninfo = qfu( psz );
358             free( psz );
359         }
360         return QVariant( returninfo );
361     }
362     else if( role == Qt::DecorationRole && index.column() == 0  )
363     {
364         /* Used to segfault here because i_type wasn't always initialized */
365         return QVariant( PLModel::icons[item->inputItem()->i_type] );
366     }
367     else if( role == Qt::FontRole )
368     {
369         QFont f;
370         f.setPointSize( f.pointSize() - 1 );
371         if( isCurrent( index ) )
372             f.setBold( true );
373         return QVariant( f );
374     }
375     else if( role == Qt::BackgroundRole && isCurrent( index ) )
376     {
377         return QVariant( QBrush( Qt::gray ) );
378     }
379     else if( role == IsCurrentRole ) return QVariant( isCurrent( index ) );
380     else if( role == IsLeafNodeRole )
381     {
382         QVariant isLeaf;
383         PL_LOCK;
384         playlist_item_t *plItem =
385             playlist_ItemGetById( p_playlist, item->i_id );
386
387         if( plItem )
388             isLeaf = plItem->i_children == -1;
389
390         PL_UNLOCK;
391         return isLeaf;
392     }
393     else if( role == IsCurrentsParentNodeRole )
394     {
395         return QVariant( isParent( index, currentIndex() ) );
396     }
397     return QVariant();
398 }
399
400 /* Seek from current index toward the top and see if index is one of parent nodes */
401 bool PLModel::isParent( const QModelIndex &index, const QModelIndex &current ) const
402 {
403     if( !index.isValid() )
404         return false;
405
406     if( index == current )
407         return true;
408
409     if( !current.isValid() || !current.parent().isValid() )
410         return false;
411
412     return isParent( index, current.parent() );
413 }
414
415 bool PLModel::isCurrent( const QModelIndex &index ) const
416 {
417     return getItem( index )->inputItem() == THEMIM->currentInputItem();
418 }
419
420 int PLModel::itemId( const QModelIndex &index ) const
421 {
422     return getItem( index )->id();
423 }
424
425 QVariant PLModel::headerData( int section, Qt::Orientation orientation,
426                               int role ) const
427 {
428     if (orientation != Qt::Horizontal || role != Qt::DisplayRole)
429         return QVariant();
430
431     int meta_col = columnToMeta( section );
432
433     if( meta_col == COLUMN_END ) return QVariant();
434
435     return QVariant( qfu( psz_column_title( meta_col ) ) );
436 }
437
438 QModelIndex PLModel::index( const int row, const int column, const QModelIndex &parent )
439                   const
440 {
441     PLItem *parentItem = parent.isValid() ? getItem( parent ) : rootItem;
442
443     PLItem *childItem = parentItem->child( row );
444     if( childItem )
445         return createIndex( row, column, childItem );
446     else
447         return QModelIndex();
448 }
449
450 QModelIndex PLModel::index( const int i_id, const int c )
451 {
452     return index( findById( rootItem, i_id ), c );
453 }
454
455 /* Return the index of a given item */
456 QModelIndex PLModel::index( PLItem *item, int column ) const
457 {
458     if( !item ) return QModelIndex();
459     const PLItem *parent = item->parent();
460     if( parent )
461         return createIndex( parent->children.lastIndexOf( item ),
462                             column, item );
463     return QModelIndex();
464 }
465
466 QModelIndex PLModel::currentIndex() const
467 {
468     input_thread_t *p_input_thread = THEMIM->getInput();
469     if( !p_input_thread ) return QModelIndex();
470     PLItem *item = findByInput( rootItem, input_GetItem( p_input_thread )->i_id );
471     return index( item, 0 );
472 }
473
474 QModelIndex PLModel::parent( const QModelIndex &index ) const
475 {
476     if( !index.isValid() ) return QModelIndex();
477
478     PLItem *childItem = getItem( index );
479     if( !childItem )
480     {
481         msg_Err( p_playlist, "NULL CHILD" );
482         return QModelIndex();
483     }
484
485     PLItem *parentItem = childItem->parent();
486     if( !parentItem || parentItem == rootItem ) return QModelIndex();
487     if( !parentItem->parent() )
488     {
489         msg_Err( p_playlist, "No parent parent, trying row 0 " );
490         msg_Err( p_playlist, "----- PLEASE REPORT THIS ------" );
491         return createIndex( 0, 0, parentItem );
492     }
493     return createIndex(parentItem->row(), 0, parentItem);
494 }
495
496 int PLModel::columnCount( const QModelIndex &) const
497 {
498     return columnFromMeta( COLUMN_END );
499 }
500
501 int PLModel::rowCount( const QModelIndex &parent ) const
502 {
503     const PLItem *parentItem = parent.isValid() ? getItem( parent ) : rootItem;
504     return parentItem->childCount();
505 }
506
507 QStringList PLModel::selectedURIs()
508 {
509     QStringList lst;
510     for( int i = 0; i < current_selection.size(); i++ )
511     {
512         const PLItem *item = getItem( current_selection[i] );
513         if( item )
514         {
515             PL_LOCK;
516             playlist_item_t *p_item = playlist_ItemGetById( p_playlist, item->i_id );
517             if( p_item )
518             {
519                 char *psz = input_item_GetURI( p_item->p_input );
520                 if( psz )
521                 {
522                     lst.append( qfu(psz) );
523                     free( psz );
524                 }
525             }
526             PL_UNLOCK;
527         }
528     }
529     return lst;
530 }
531
532 /************************* Lookups *****************************/
533 PLItem *PLModel::findById( PLItem *root, int i_id ) const
534 {
535     return findInner( root, i_id, false );
536 }
537
538 PLItem *PLModel::findByInput( PLItem *root, int i_id ) const
539 {
540     PLItem *result = findInner( root, i_id, true );
541     return result;
542 }
543
544 PLItem * PLModel::findInner( PLItem *root, int i_id, bool b_input ) const
545 {
546     if( !root ) return NULL;
547
548     if( !b_input && root->id() == i_id )
549         return root;
550
551     else if( b_input && root->inputItem()->i_id == i_id )
552         return root;
553
554     QList<PLItem *>::iterator it = root->children.begin();
555     while ( it != root->children.end() )
556     {
557         if( !b_input && (*it)->id() == i_id )
558             return (*it);
559
560         else if( b_input && (*it)->inputItem()->i_id == i_id )
561             return (*it);
562
563         if( (*it)->childCount() )
564         {
565             PLItem *childFound = findInner( (*it), i_id, b_input );
566             if( childFound )
567                 return childFound;
568         }
569         ++it;
570     }
571     return NULL;
572 }
573
574 bool PLModel::canEdit() const
575 {
576     return (
577             rootItem != NULL &&
578             (
579              rootItem->inputItem() == p_playlist->p_playing->p_input ||
580              ( p_playlist->p_media_library &&
581               rootItem->inputItem() == p_playlist->p_media_library->p_input )
582             )
583            );
584 }
585
586 /************************* Updates handling *****************************/
587
588 /**** Events processing ****/
589 void PLModel::processInputItemUpdate( input_thread_t *p_input )
590 {
591     if( !p_input ) return;
592     if( p_input && !( p_input->b_dead || !vlc_object_alive( p_input ) ) )
593     {
594         PLItem *item = findByInput( rootItem, input_GetItem( p_input )->i_id );
595         if( item ) emit currentChanged( index( item, 0 ) );
596     }
597     processInputItemUpdate( input_GetItem( p_input ) );
598 }
599
600 void PLModel::processInputItemUpdate( input_item_t *p_item )
601 {
602     if( !p_item ||  p_item->i_id <= 0 ) return;
603     PLItem *item = findByInput( rootItem, p_item->i_id );
604     if( item )
605         updateTreeItem( item );
606 }
607
608 void PLModel::processItemRemoval( int i_id )
609 {
610     if( i_id <= 0 ) return;
611     removeItem( i_id );
612 }
613
614 void PLModel::processItemAppend( int i_item, int i_parent )
615 {
616     playlist_item_t *p_item = NULL;
617     PLItem *newItem = NULL;
618     int pos;
619
620     /* Find the Parent */
621     PLItem *nodeParentItem = findById( rootItem, i_parent );
622     if( !nodeParentItem ) return;
623
624     /* Search for an already matching children */
625     foreach( const PLItem *existing, nodeParentItem->children )
626         if( existing->i_id == i_item ) return;
627
628     /* Find the child */
629     PL_LOCK;
630     p_item = playlist_ItemGetById( p_playlist, i_item );
631     if( !p_item || p_item->i_flags & PLAYLIST_DBL_FLAG )
632     {
633         PL_UNLOCK; return;
634     }
635
636     for( pos = 0; pos < p_item->p_parent->i_children; pos++ )
637         if( p_item->p_parent->pp_children[pos] == p_item ) break;
638
639     newItem = new PLItem( p_item, nodeParentItem );
640     PL_UNLOCK;
641
642     /* We insert the newItem (children) inside the parent */
643     beginInsertRows( index( nodeParentItem, 0 ), pos, pos );
644     nodeParentItem->insertChild( newItem, pos );
645     endInsertRows();
646
647     if( newItem->inputItem() == THEMIM->currentInputItem() )
648         emit currentChanged( index( newItem, 0 ) );
649 }
650
651 void PLModel::rebuild( playlist_item_t *p_root )
652 {
653     /* Invalidate cache */
654     i_cached_id = i_cached_input_id = -1;
655
656     if( rootItem ) rootItem->removeChildren();
657
658     PL_LOCK;
659     if( p_root ) // Can be NULL
660     {
661         delete rootItem;
662         rootItem = new PLItem( p_root );
663     }
664     assert( rootItem );
665     /* Recreate from root */
666     updateChildren( rootItem );
667     PL_UNLOCK;
668
669     /* And signal the view */
670     reset();
671
672     if( p_root ) emit rootChanged();
673 }
674
675 void PLModel::takeItem( PLItem *item )
676 {
677     assert( item );
678     PLItem *parent = item->parent();
679     assert( parent );
680     int i_index = parent->children.indexOf( item );
681
682     beginRemoveRows( index( parent, 0 ), i_index, i_index );
683     parent->takeChildAt( i_index );
684     endRemoveRows();
685 }
686
687 void PLModel::insertChildren( PLItem *node, QList<PLItem*>& items, int i_pos )
688 {
689     assert( node );
690     int count = items.size();
691     if( !count ) return;
692     printf( "Here I am\n");
693     beginInsertRows( index( node, 0 ), i_pos, i_pos + count - 1 );
694     for( int i = 0; i < count; i++ )
695     {
696         node->children.insert( i_pos + i, items[i] );
697         items[i]->parentItem = node;
698     }
699     endInsertRows();
700 }
701
702 void PLModel::removeItem( PLItem *item )
703 {
704     if( !item ) return;
705
706     i_cached_id = -1;
707     i_cached_input_id = -1;
708
709     if( item->parent() ) {
710         int i = item->parent()->children.indexOf( item );
711         beginRemoveRows( index( item->parent(), 0), i, i );
712         item->parent()->children.removeAt(i);
713         delete item;
714         endRemoveRows();
715     }
716     else delete item;
717
718     if(item == rootItem)
719     {
720         rootItem = NULL;
721         rebuild( p_playlist->p_playing );
722     }
723 }
724
725 /* This function must be entered WITH the playlist lock */
726 void PLModel::updateChildren( PLItem *root )
727 {
728     playlist_item_t *p_node = playlist_ItemGetById( p_playlist, root->id() );
729     updateChildren( p_node, root );
730 }
731
732 /* This function must be entered WITH the playlist lock */
733 void PLModel::updateChildren( playlist_item_t *p_node, PLItem *root )
734 {
735     for( int i = 0; i < p_node->i_children ; i++ )
736     {
737         if( p_node->pp_children[i]->i_flags & PLAYLIST_DBL_FLAG ) continue;
738         PLItem *newItem =  new PLItem( p_node->pp_children[i], root );
739         root->appendChild( newItem );
740         if( p_node->pp_children[i]->i_children != -1 )
741             updateChildren( p_node->pp_children[i], newItem );
742     }
743 }
744
745 /* Function doesn't need playlist-lock, as we don't touch playlist_item_t stuff here*/
746 void PLModel::updateTreeItem( PLItem *item )
747 {
748     if( !item ) return;
749     emit dataChanged( index( item, 0 ) , index( item, columnCount( QModelIndex() ) ) );
750 }
751
752 /************************* Actions ******************************/
753
754 /**
755  * Deletion, don't delete items childrens if item is going to be
756  * delete allready, so we remove childrens from selection-list.
757  */
758 void PLModel::doDelete( QModelIndexList selected )
759 {
760     if( !canEdit() ) return;
761
762     while( !selected.isEmpty() )
763     {
764         QModelIndex index = selected[0];
765         selected.removeAt( 0 );
766
767         if( index.column() != 0 ) continue;
768
769         PLItem *item = getItem( index );
770         if( item->childCount() )
771             recurseDelete( item->children, &selected );
772
773         PL_LOCK;
774         playlist_DeleteFromInput( p_playlist, item->inputItem(), pl_Locked );
775         PL_UNLOCK;
776
777         removeItem( item );
778     }
779 }
780
781 void PLModel::recurseDelete( QList<PLItem*> children, QModelIndexList *fullList )
782 {
783     for( int i = children.size() - 1; i >= 0 ; i-- )
784     {
785         PLItem *item = children[i];
786         if( item->childCount() )
787             recurseDelete( item->children, fullList );
788         fullList->removeAll( index( item, 0 ) );
789     }
790 }
791
792 /******* Volume III: Sorting and searching ********/
793 void PLModel::sort( const int column, Qt::SortOrder order )
794 {
795     sort( rootItem->id(), column, order );
796 }
797
798 void PLModel::sort( const int i_root_id, const int column, Qt::SortOrder order )
799 {
800     msg_Dbg( p_intf, "Sorting by column %i, order %i", column, order );
801
802     int meta = columnToMeta( column );
803     if( meta == COLUMN_END ) return;
804
805     PLItem *item = findById( rootItem, i_root_id );
806     if( !item ) return;
807     QModelIndex qIndex = index( item, 0 );
808     int count = item->childCount();
809     if( count )
810     {
811         beginRemoveRows( qIndex, 0, count - 1 );
812         item->removeChildren();
813         endRemoveRows( );
814     }
815
816     PL_LOCK;
817     {
818         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
819                                                         i_root_id );
820         if( p_root )
821         {
822             playlist_RecursiveNodeSort( p_playlist, p_root,
823                                         i_column_sorting( meta ),
824                                         order == Qt::AscendingOrder ?
825                                             ORDER_NORMAL : ORDER_REVERSE );
826         }
827     }
828
829     i_cached_id = i_cached_input_id = -1;
830
831     if( count )
832     {
833         beginInsertRows( qIndex, 0, count - 1 );
834         updateChildren( item );
835         endInsertRows( );
836     }
837     PL_UNLOCK;
838     /* if we have popup item, try to make sure that you keep that item visible */
839     if( i_popup_item > -1 )
840     {
841         PLItem *popupitem = findById( rootItem, i_popup_item );
842         if( popupitem ) emit currentChanged( index( popupitem, 0 ) );
843         /* reset i_popup_item as we don't show it as selected anymore anyway */
844         i_popup_item = -1;
845     }
846     else if( currentIndex().isValid() ) emit currentChanged( currentIndex() );
847 }
848
849 void PLModel::search( const QString& search_text, const QModelIndex & idx, bool b_recursive )
850 {
851     /** \todo Fire the search with a small delay ? */
852     PL_LOCK;
853     {
854         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
855                                                         itemId( idx ) );
856         assert( p_root );
857         const char *psz_name = qtu( search_text );
858         playlist_LiveSearchUpdate( p_playlist , p_root, psz_name, b_recursive );
859
860         if( idx.isValid() )
861         {
862             PLItem *searchRoot = getItem( idx );
863
864             beginRemoveRows( idx, 0, searchRoot->childCount() - 1 );
865             searchRoot->removeChildren();
866             endRemoveRows( );
867
868             beginInsertRows( idx, 0, searchRoot->childCount() - 1 );
869             updateChildren( searchRoot ); // The PL_LOCK is needed here
870             endInsertRows();
871
872             PL_UNLOCK;
873             return;
874         }
875     }
876     PL_UNLOCK;
877     rebuild();
878 }
879
880 /*********** Popup *********/
881 bool PLModel::popup( const QModelIndex & index, const QPoint &point, const QModelIndexList &list )
882 {
883     int i_id = index.isValid() ? itemId( index ) : rootItem->id();
884
885     PL_LOCK;
886     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, i_id );
887     if( !p_item )
888     {
889         PL_UNLOCK;
890         return false;
891     }
892
893     input_item_t *p_input = p_item->p_input;
894     vlc_gc_incref( p_input );
895
896     i_popup_item = index.isValid() ? p_item->i_id : -1;
897     i_popup_parent = index.isValid() ?
898         ( p_item->p_parent ? p_item->p_parent->i_id : -1 ) :
899         ( rootItem->id() );
900     i_popup_column = index.column();
901
902     bool tree = ( rootItem && rootItem->id() != p_playlist->p_playing->i_id ) ||
903                 var_InheritBool( p_intf, "playlist-tree" );
904
905     PL_UNLOCK;
906
907     current_selection = list;
908
909     QMenu menu;
910     if( i_popup_item > -1 )
911     {
912         menu.addAction( QIcon( ":/menu/play" ), qtr(I_POP_PLAY), this, SLOT( popupPlay() ) );
913         menu.addAction( QIcon( ":/menu/stream" ),
914                         qtr(I_POP_STREAM), this, SLOT( popupStream() ) );
915         menu.addAction( qtr(I_POP_SAVE), this, SLOT( popupSave() ) );
916         menu.addAction( QIcon( ":/menu/info" ), qtr(I_POP_INFO), this, SLOT( popupInfo() ) );
917         if( p_input->psz_uri && !strncasecmp( p_input->psz_uri, "file://", 7 ) )
918         {
919             menu.addAction( QIcon( ":/type/folder-grey" ),
920                             qtr( I_POP_EXPLORE ), this, SLOT( popupExplore() ) );
921         }
922         menu.addSeparator();
923     }
924     vlc_gc_decref( p_input );
925
926     if( canEdit() )
927     {
928         QIcon addIcon( ":/buttons/playlist/playlist_add" );
929         menu.addSeparator();
930         if( tree ) menu.addAction( addIcon, qtr(I_POP_NEWFOLDER), this, SLOT( popupAddNode() ) );
931         if( rootItem->id() == THEPL->p_playing->i_id )
932         {
933             menu.addAction( addIcon, qtr(I_PL_ADDF), THEDP, SLOT( simplePLAppendDialog()) );
934             menu.addAction( addIcon, qtr(I_PL_ADDDIR), THEDP, SLOT( PLAppendDir()) );
935             menu.addAction( addIcon, qtr(I_OP_ADVOP), THEDP, SLOT( PLAppendDialog()) );
936         }
937         else if( THEPL->p_media_library &&
938                     rootItem->id() == THEPL->p_media_library->i_id )
939         {
940             menu.addAction( addIcon, qtr(I_PL_ADDF), THEDP, SLOT( simpleMLAppendDialog()) );
941             menu.addAction( addIcon, qtr(I_PL_ADDDIR), THEDP, SLOT( MLAppendDir() ) );
942             menu.addAction( addIcon, qtr(I_OP_ADVOP), THEDP, SLOT( MLAppendDialog() ) );
943         }
944     }
945     if( i_popup_item > -1 )
946     {
947         if( rootItem->id() != THEPL->p_playing->i_id )
948             menu.addAction( qtr( "Add to playlist"), this, SLOT( popupAddToPlaylist() ) );
949         menu.addAction( QIcon( ":/buttons/playlist/playlist_remove" ),
950                         qtr(I_POP_DEL), this, SLOT( popupDel() ) );
951         menu.addSeparator();
952         if( !sortingMenu )
953         {
954             sortingMenu = new QMenu( qtr( "Sort by" ) );
955             sortingMapper = new QSignalMapper( this );
956             for( int i = 1, j = 1; i < COLUMN_END; i <<= 1, j++ )
957             {
958                 if( i == COLUMN_NUMBER ) continue;
959                 QMenu *m = sortingMenu->addMenu( qfu( psz_column_title( i ) ) );
960                 QAction *asc = m->addAction( qtr("Ascending") );
961                 QAction *desc = m->addAction( qtr("Descending") );
962                 sortingMapper->setMapping( asc, j );
963                 sortingMapper->setMapping( desc, -j );
964                 CONNECT( asc, triggered(), sortingMapper, map() );
965                 CONNECT( desc, triggered(), sortingMapper, map() );
966             }
967             CONNECT( sortingMapper, mapped( int ), this, popupSort( int ) );
968         }
969         menu.addMenu( sortingMenu );
970     }
971
972     if( !menu.isEmpty() )
973     {
974         menu.exec( point ); return true;
975     }
976     else return false;
977 }
978
979 void PLModel::popupDel()
980 {
981     doDelete( current_selection );
982 }
983
984 void PLModel::popupPlay()
985 {
986     PL_LOCK;
987     {
988         playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
989                                                         i_popup_item );
990         activateItem( p_item );
991     }
992     PL_UNLOCK;
993 }
994
995 void PLModel::popupAddToPlaylist()
996 {
997     playlist_Lock( THEPL );
998
999     foreach( QModelIndex currentIndex, current_selection )
1000     {
1001         playlist_item_t *p_item = playlist_ItemGetById( THEPL, getId( currentIndex ) );
1002         if( !p_item ) continue;
1003
1004         playlist_NodeAddCopy( THEPL, p_item,
1005                               THEPL->p_playing,
1006                               PLAYLIST_END );
1007     }
1008     playlist_Unlock( THEPL );
1009 }
1010
1011 void PLModel::popupInfo()
1012 {
1013     PL_LOCK;
1014     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1015                                                     i_popup_item );
1016     if( p_item )
1017     {
1018         input_item_t* p_input = p_item->p_input;
1019         vlc_gc_incref( p_input );
1020         PL_UNLOCK;
1021         MediaInfoDialog *mid = new MediaInfoDialog( p_intf, p_input );
1022         vlc_gc_decref( p_input );
1023         mid->setParent( PlaylistDialog::getInstance( p_intf ),
1024                         Qt::Dialog );
1025         mid->show();
1026     } else
1027         PL_UNLOCK;
1028 }
1029
1030 void PLModel::popupStream()
1031 {
1032     QStringList mrls = selectedURIs();
1033     if( !mrls.isEmpty() )
1034         THEDP->streamingDialog( NULL, mrls[0], false );
1035 }
1036
1037 void PLModel::popupSave()
1038 {
1039     QStringList mrls = selectedURIs();
1040     if( !mrls.isEmpty() )
1041         THEDP->streamingDialog( NULL, mrls[0] );
1042 }
1043
1044 void PLModel::popupExplore()
1045 {
1046     PL_LOCK;
1047     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, i_popup_item );
1048     if( p_item )
1049     {
1050         input_item_t *p_input = p_item->p_input;
1051         char *psz_meta = input_item_GetURI( p_input );
1052         PL_UNLOCK;
1053         if( psz_meta )
1054         {
1055             const char *psz_access;
1056             const char *psz_demux;
1057             char  *psz_path;
1058             input_SplitMRL( &psz_access, &psz_demux, &psz_path, psz_meta );
1059
1060             if( !EMPTY_STR( psz_access ) && (
1061                    !strncasecmp( psz_access, "file", 4 ) ||
1062                    !strncasecmp( psz_access, "dire", 4 ) ))
1063             {
1064 #if defined( WIN32 ) || defined( __OS2__ )
1065                 /* Qt openURL doesn't know to open files that starts with a / or \ */
1066                 if( psz_path[0] == '/' || psz_path[0] == '\\'  )
1067                     psz_path++;
1068 #endif
1069
1070                 QFileInfo info( qfu( decode_URI( psz_path ) ) );
1071                 QDesktopServices::openUrl(
1072                         QUrl::fromLocalFile( info.absolutePath() ) );
1073             }
1074             free( psz_meta );
1075         }
1076     }
1077     else
1078         PL_UNLOCK;
1079 }
1080
1081 void PLModel::popupAddNode()
1082 {
1083     bool ok;
1084     QString name = QInputDialog::getText( PlaylistDialog::getInstance( p_intf ),
1085         qtr( I_NEW_DIR ), qtr( I_NEW_DIR_NAME ),
1086         QLineEdit::Normal, QString(), &ok);
1087     if( !ok || name.isEmpty() ) return;
1088
1089     PL_LOCK;
1090     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1091                                                     i_popup_parent );
1092     if( p_item )
1093         playlist_NodeCreate( p_playlist, qtu( name ), p_item, PLAYLIST_END, 0, NULL );
1094     PL_UNLOCK;
1095 }
1096
1097 void PLModel::popupSort( int column )
1098 {
1099     sort( i_popup_parent,
1100           column > 0 ? column - 1 : -column - 1,
1101           column > 0 ? Qt::AscendingOrder : Qt::DescendingOrder );
1102 }
1103
1104 /******************* Drag and Drop helper class ******************/
1105 PlMimeData::~PlMimeData()
1106 {
1107     foreach( input_item_t *p_item, _inputItems )
1108         vlc_gc_decref( p_item );
1109 }
1110
1111 void PlMimeData::appendItem( input_item_t *p_item )
1112 {
1113     vlc_gc_incref( p_item );
1114     _inputItems.append( p_item );
1115 }
1116
1117 QList<input_item_t*> PlMimeData::inputItems() const
1118 {
1119     return _inputItems;
1120 }
1121
1122 QStringList PlMimeData::formats () const
1123 {
1124     QStringList fmts;
1125     fmts << "vlc/qt-input-items";
1126     return fmts;
1127 }