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