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