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