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