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