]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/playlist/playlist_model.cpp
qt4: don't crash when sd is selected in playlist and unloaded from menu
[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     removeItem( i_id );
657 }
658
659 void PLModel::processItemAppend( const playlist_add_t *p_add )
660 {
661     playlist_item_t *p_item = NULL;
662     PLItem *newItem = NULL;
663
664     PLItem *nodeItem = findById( rootItem, p_add->i_node );
665     if( !nodeItem ) return;
666
667     foreach( PLItem *existing, nodeItem->children )
668       if( existing->i_id == p_add->i_item ) return;
669
670     PL_LOCK;
671     p_item = playlist_ItemGetById( p_playlist, p_add->i_item );
672     if( !p_item || p_item->i_flags & PLAYLIST_DBL_FLAG ) goto end;
673
674     newItem = new PLItem( p_item, nodeItem );
675     PL_UNLOCK;
676
677     beginInsertRows( index( nodeItem, 0 ), nodeItem->childCount(), nodeItem->childCount() );
678     nodeItem->appendChild( newItem );
679     endInsertRows();
680     updateTreeItem( newItem );
681     return;
682 end:
683     PL_UNLOCK;
684     return;
685 }
686
687
688 void PLModel::rebuild()
689 {
690     rebuild( NULL, false );
691 }
692
693 void PLModel::rebuild( playlist_item_t *p_root, bool b_first )
694 {
695     playlist_item_t* p_item;
696     /* Remove callbacks before locking to avoid deadlocks
697        The first time the callbacks are not present so
698        don't try to delete them */
699     if( !b_first )
700         delCallbacks();
701
702     /* Invalidate cache */
703     i_cached_id = i_cached_input_id = -1;
704
705     if( rootItem ) rootItem->removeChildren();
706
707     PL_LOCK;
708     if( p_root )
709     {
710         delete rootItem;
711         rootItem = new PLItem( p_root );
712     }
713     assert( rootItem );
714     /* Recreate from root */
715     updateChildren( rootItem );
716     if( (p_item = playlist_CurrentPlayingItem(p_playlist)) )
717         currentItem = findByInput( rootItem, p_item->p_input->i_id );
718     else
719         currentItem = NULL;
720     PL_UNLOCK;
721
722     /* And signal the view */
723     reset();
724
725     emit currentChanged( index( currentItem, 0 ) );
726
727     addCallbacks();
728 }
729
730 void PLModel::takeItem( PLItem *item )
731 {
732     assert( item );
733     PLItem *parent = item->parentItem;
734     assert( parent );
735     int i_index = parent->children.indexOf( item );
736
737     beginRemoveRows( index( parent, 0 ), i_index, i_index );
738     parent->takeChildAt( i_index );
739     endRemoveRows();
740 }
741
742 void PLModel::insertChildren( PLItem *node, QList<PLItem*>& items, int i_pos )
743 {
744     assert( node );
745     int count = items.size();
746     if( !count ) return;
747     beginInsertRows( index( node, 0 ), i_pos, i_pos + count - 1 );
748     for( int i = 0; i < count; i++ )
749     {
750         node->children.insert( i_pos + i, items[i] );
751         items[i]->parentItem = node;
752     }
753     endInsertRows();
754 }
755
756 void PLModel::removeItem( PLItem *item )
757 {
758     if( !item ) return;
759
760     if( item->i_id == i_cached_id ) i_cached_id = -1;
761     i_cached_input_id = -1;
762
763     if( currentItem == item || rootItem == item)
764     {
765         currentItem = NULL;
766         emit currentChanged( QModelIndex() );
767     }
768
769     if(item == rootItem)
770         rootItem = NULL;
771
772     if( item->parentItem ) {
773         int i = item->parentItem->children.indexOf( item );
774         beginRemoveRows( index( item->parentItem, 0), i, i );
775         item->parentItem->children.removeAt(i);
776         delete item;
777         endRemoveRows();
778     }
779     else delete item;
780
781 }
782
783 /* This function must be entered WITH the playlist lock */
784 void PLModel::updateChildren( PLItem *root )
785 {
786     playlist_item_t *p_node = playlist_ItemGetById( p_playlist, root->i_id );
787     updateChildren( p_node, root );
788 }
789
790 /* This function must be entered WITH the playlist lock */
791 void PLModel::updateChildren( playlist_item_t *p_node, PLItem *root )
792 {
793     playlist_item_t *p_item = playlist_CurrentPlayingItem(p_playlist);
794     for( int i = 0; i < p_node->i_children ; i++ )
795     {
796         if( p_node->pp_children[i]->i_flags & PLAYLIST_DBL_FLAG ) continue;
797         PLItem *newItem =  new PLItem( p_node->pp_children[i], root );
798         root->appendChild( newItem );
799         if( p_item && newItem->p_input == p_item->p_input )
800         {
801             currentItem = newItem;
802             emit currentChanged( index( currentItem, 0 ) );
803         }
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, here we have to do a ugly slow hack as we retrieve the full
820  * list of indexes to delete at once: when we delete a node and all of
821  * its children, we need to update the list.
822  * Todo: investigate whethere we can use ranges to be sure to delete all items?
823  */
824 void PLModel::doDelete( QModelIndexList selected )
825 {
826     for( int i = selected.size() -1 ; i >= 0; i-- )
827     {
828         QModelIndex index = selected[i];
829         if( index.column() != 0 ) continue;
830         PLItem *item = getItem( index );
831         if( item )
832         {
833             if( item->children.size() )
834                 recurseDelete( item->children, &selected );
835             doDeleteItem( item, &selected );
836         }
837         if( i > selected.size() ) i = selected.size();
838     }
839 }
840
841 void PLModel::recurseDelete( QList<PLItem*> children, QModelIndexList *fullList )
842 {
843     for( int i = children.size() - 1; i >= 0 ; i-- )
844     {
845         PLItem *item = children[i];
846         if( item->children.size() )
847             recurseDelete( item->children, fullList );
848         doDeleteItem( item, fullList );
849     }
850 }
851
852 void PLModel::doDeleteItem( PLItem *item, QModelIndexList *fullList )
853 {
854     QModelIndex deleteIndex = index( item, 0 );
855     fullList->removeAll( deleteIndex );
856
857     PL_LOCK;
858     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, item->i_id );
859     if( !p_item )
860     {
861         PL_UNLOCK;
862         return;
863     }
864     if( p_item->i_children == -1 )
865         playlist_DeleteFromInput( p_playlist, p_item->p_input, pl_Locked );
866     else
867         playlist_NodeDelete( p_playlist, p_item, true, false );
868     PL_UNLOCK;
869
870     /* And finally, remove it from the tree */
871     removeItem( item );
872 }
873
874 /******* Volume III: Sorting and searching ********/
875 void PLModel::sort( int column, Qt::SortOrder order )
876 {
877     sort( rootItem->i_id, column, order );
878 }
879
880 void PLModel::sort( int i_root_id, int column, Qt::SortOrder order )
881 {
882     int meta = columnToMeta( column );
883     if( meta == COLUMN_END ) return;
884
885     PLItem *item = findById( rootItem, i_root_id );
886     if( !item ) return;
887     QModelIndex qIndex = index( item, 0 );
888     int count = item->children.size();
889     if( count )
890     {
891         beginRemoveRows( qIndex, 0, count - 1 );
892         item->removeChildren();
893         endRemoveRows( );
894     }
895
896     PL_LOCK;
897     {
898         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
899                                                         i_root_id );
900         if( p_root )
901         {
902             playlist_RecursiveNodeSort( p_playlist, p_root,
903                                         i_column_sorting( meta ),
904                                         order == Qt::AscendingOrder ?
905                                             ORDER_NORMAL : ORDER_REVERSE );
906         }
907     }
908     if( count )
909     {
910         beginInsertRows( qIndex, 0, count - 1 );
911         updateChildren( item );
912         endInsertRows( );
913     }
914     PL_UNLOCK;
915 }
916
917 void PLModel::search( const QString& search_text )
918 {
919     /** \todo Fire the search with a small delay ? */
920     PL_LOCK;
921     {
922         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
923                                                         rootItem->i_id );
924         assert( p_root );
925         const char *psz_name = search_text.toUtf8().data();
926         playlist_LiveSearchUpdate( p_playlist , p_root, psz_name );
927     }
928     PL_UNLOCK;
929     rebuild();
930 }
931
932 /*********** Popup *********/
933 void PLModel::popup( QModelIndex & index, QPoint &point, QModelIndexList list )
934 {
935     int i_id = index.isValid() ? itemId( index ) : rootItem->i_id;
936
937     PL_LOCK;
938     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, i_id );
939     if( !p_item )
940     {
941         PL_UNLOCK; return;
942     }
943     i_popup_item = index.isValid() ? p_item->i_id : -1;
944     i_popup_parent = index.isValid() ?
945         ( p_item->p_parent ? p_item->p_parent->i_id : -1 ) :
946         ( p_item->i_id );
947     i_popup_column = index.column();
948     /* check whether we are in tree view */
949     bool tree = false;
950     playlist_item_t *p_up = p_item;
951     while( p_up )
952     {
953         if ( p_up == p_playlist->p_root_category ) tree = true;
954         p_up = p_up->p_parent;
955     }
956     PL_UNLOCK;
957
958     current_selection = list;
959     QMenu *menu = new QMenu;
960     if( i_popup_item > -1 )
961     {
962         menu->addAction( qtr(I_POP_PLAY), this, SLOT( popupPlay() ) );
963         menu->addAction( qtr(I_POP_DEL), this, SLOT( popupDel() ) );
964         menu->addSeparator();
965         menu->addAction( qtr(I_POP_STREAM), this, SLOT( popupStream() ) );
966         menu->addAction( qtr(I_POP_SAVE), this, SLOT( popupSave() ) );
967         menu->addSeparator();
968         menu->addAction( qtr(I_POP_INFO), this, SLOT( popupInfo() ) );
969         menu->addSeparator();
970         QMenu *sort_menu = menu->addMenu( qtr( "Sort by ") +
971             qfu( psz_column_title( columnToMeta( index.column() ) ) ) );
972         sort_menu->addAction( qtr( "Ascending" ),
973             this, SLOT( popupSortAsc() ) );
974         sort_menu->addAction( qtr( "Descending" ),
975             this, SLOT( popupSortDesc() ) );
976     }
977     if( tree )
978         menu->addAction( qtr(I_POP_ADD), this, SLOT( popupAddNode() ) );
979     if( i_popup_item > -1 )
980     {
981         menu->addSeparator();
982         menu->addAction( qtr( I_POP_EXPLORE ), this, SLOT( popupExplore() ) );
983     }
984     menu->popup( point );
985 }
986
987 void PLModel::popupDel()
988 {
989     doDelete( current_selection );
990 }
991
992 void PLModel::popupPlay()
993 {
994     PL_LOCK;
995     {
996         playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
997                                                         i_popup_item );
998         activateItem( p_item );
999     }
1000     PL_UNLOCK;
1001 }
1002
1003 void PLModel::popupInfo()
1004 {
1005     PL_LOCK;
1006     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1007                                                     i_popup_item );
1008     if( p_item )
1009     {
1010         input_item_t* p_input = p_item->p_input;
1011         vlc_gc_incref( p_input );
1012         PL_UNLOCK;
1013         MediaInfoDialog *mid = new MediaInfoDialog( p_intf, p_input );
1014         vlc_gc_decref( p_input );
1015         mid->setParent( PlaylistDialog::getInstance( p_intf ),
1016                         Qt::Dialog );
1017         mid->show();
1018     } else
1019         PL_UNLOCK;
1020 }
1021
1022 void PLModel::popupStream()
1023 {
1024     QStringList mrls = selectedURIs();
1025     if( !mrls.isEmpty() )
1026         THEDP->streamingDialog( NULL, mrls[0], false );
1027
1028 }
1029
1030 void PLModel::popupSave()
1031 {
1032     QStringList mrls = selectedURIs();
1033     if( !mrls.isEmpty() )
1034         THEDP->streamingDialog( NULL, mrls[0] );
1035 }
1036
1037 #include <QUrl>
1038 #include <QFileInfo>
1039 #include <QDesktopServices>
1040 void PLModel::popupExplore()
1041 {
1042     PL_LOCK;
1043     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1044                                                     i_popup_item );
1045     if( p_item )
1046     {
1047        input_item_t *p_input = p_item->p_input;
1048        char *psz_meta = input_item_GetURI( p_input );
1049        PL_UNLOCK;
1050        if( psz_meta )
1051        {
1052            const char *psz_access;
1053            const char *psz_demux;
1054            char  *psz_path;
1055            input_SplitMRL( &psz_access, &psz_demux, &psz_path, psz_meta );
1056
1057            if( EMPTY_STR( psz_access ) ||
1058                !strncasecmp( psz_access, "file", 4 ) ||
1059                !strncasecmp( psz_access, "dire", 4 ) )
1060            {
1061                QFileInfo info( qfu( psz_meta ) );
1062                QDesktopServices::openUrl(
1063                                QUrl::fromLocalFile( info.absolutePath() ) );
1064            }
1065            free( psz_meta );
1066        }
1067     }
1068     else
1069         PL_UNLOCK;
1070 }
1071
1072 #include <QInputDialog>
1073 void PLModel::popupAddNode()
1074 {
1075     bool ok;
1076     QString name = QInputDialog::getText( PlaylistDialog::getInstance( p_intf ),
1077         qtr( I_POP_ADD ), qtr( "Enter name for new node:" ),
1078         QLineEdit::Normal, QString(), &ok);
1079     if( !ok || name.isEmpty() ) return;
1080     PL_LOCK;
1081     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1082                                                     i_popup_parent );
1083     if( p_item )
1084     {
1085         playlist_NodeCreate( p_playlist, qtu( name ), p_item, 0, NULL );
1086     }
1087     PL_UNLOCK;
1088 }
1089
1090 void PLModel::popupSortAsc()
1091 {
1092     sort( i_popup_parent, i_popup_column, Qt::AscendingOrder );
1093 }
1094
1095 void PLModel::popupSortDesc()
1096 {
1097     sort( i_popup_parent, i_popup_column, Qt::DescendingOrder );
1098 }
1099 /**********************************************************************
1100  * Playlist callbacks
1101  **********************************************************************/
1102
1103 static int ItemDeleted( vlc_object_t *p_this, const char *psz_variable,
1104                         vlc_value_t oval, vlc_value_t nval, void *param )
1105 {
1106     PLModel *p_model = (PLModel *) param;
1107     PLEvent *event = new PLEvent( ItemDelete_Type, nval.i_int );
1108     QApplication::postEvent( p_model, event );
1109     return VLC_SUCCESS;
1110 }
1111
1112 static int ItemAppended( 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     const playlist_add_t *p_add = (playlist_add_t *)nval.p_address;
1117     PLEvent *event = new PLEvent( p_add );
1118     QApplication::postEvent( p_model, event );
1119     return VLC_SUCCESS;
1120 }
1121