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