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