]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/playlist/playlist_model.cpp
Revert "qt4: rebuild tree on updateTreeItem"
[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     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( currentItem == item )
761     {
762         currentItem = NULL;
763         emit currentChanged( QModelIndex() );
764     }
765
766     if( item->parentItem ) item->parentItem->removeChild( item );
767     else delete item;
768
769     if(item == rootItem)
770     {
771         rootItem = NULL;
772         reset();
773     }
774 }
775
776 /* This function must be entered WITH the playlist lock */
777 void PLModel::updateChildren( PLItem *root )
778 {
779     playlist_item_t *p_node = playlist_ItemGetById( p_playlist, root->i_id );
780     updateChildren( p_node, root );
781 }
782
783 /* This function must be entered WITH the playlist lock */
784 void PLModel::updateChildren( playlist_item_t *p_node, PLItem *root )
785 {
786     playlist_item_t *p_item = playlist_CurrentPlayingItem(p_playlist);
787     for( int i = 0; i < p_node->i_children ; i++ )
788     {
789         if( p_node->pp_children[i]->i_flags & PLAYLIST_DBL_FLAG ) continue;
790         PLItem *newItem =  new PLItem( p_node->pp_children[i], root );
791         root->appendChild( newItem );
792         if( p_item && newItem->p_input == p_item->p_input )
793         {
794             currentItem = newItem;
795             emit currentChanged( index( currentItem, 0 ) );
796         }
797         if( p_node->pp_children[i]->i_children != -1 )
798             updateChildren( p_node->pp_children[i], newItem );
799     }
800 }
801
802 /* Function doesn't need playlist-lock, as we don't touch playlist_item_t stuff here*/
803 void PLModel::updateTreeItem( PLItem *item )
804 {
805     if( !item ) return;
806     emit dataChanged( index( item, 0 ) , index( item, columnCount( QModelIndex() ) ) );
807 }
808
809 /************************* Actions ******************************/
810
811 /**
812  * Deletion, here we have to do a ugly slow hack as we retrieve the full
813  * list of indexes to delete at once: when we delete a node and all of
814  * its children, we need to update the list.
815  * Todo: investigate whethere we can use ranges to be sure to delete all items?
816  */
817 void PLModel::doDelete( QModelIndexList selected )
818 {
819     for( int i = selected.size() -1 ; i >= 0; i-- )
820     {
821         QModelIndex index = selected[i];
822         if( index.column() != 0 ) continue;
823         PLItem *item = getItem( index );
824         if( item )
825         {
826             if( item->children.size() )
827                 recurseDelete( item->children, &selected );
828             doDeleteItem( item, &selected );
829         }
830         if( i > selected.size() ) i = selected.size();
831     }
832 }
833
834 void PLModel::recurseDelete( QList<PLItem*> children, QModelIndexList *fullList )
835 {
836     for( int i = children.size() - 1; i >= 0 ; i-- )
837     {
838         PLItem *item = children[i];
839         if( item->children.size() )
840             recurseDelete( item->children, fullList );
841         doDeleteItem( item, fullList );
842     }
843 }
844
845 void PLModel::doDeleteItem( PLItem *item, QModelIndexList *fullList )
846 {
847     QModelIndex deleteIndex = index( item, 0 );
848     fullList->removeAll( deleteIndex );
849
850     PL_LOCK;
851     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, item->i_id );
852     if( !p_item )
853     {
854         PL_UNLOCK;
855         return;
856     }
857     if( p_item->i_children == -1 )
858         playlist_DeleteFromInput( p_playlist, p_item->p_input, pl_Locked );
859     else
860         playlist_NodeDelete( p_playlist, p_item, true, false );
861     PL_UNLOCK;
862     /* And finally, remove it from the tree */
863     int itemIndex = item->parentItem->children.indexOf( item );
864     beginRemoveRows( index( item->parentItem, 0), itemIndex, itemIndex );
865     removeItem( item );
866     endRemoveRows();
867 }
868
869 /******* Volume III: Sorting and searching ********/
870 void PLModel::sort( int column, Qt::SortOrder order )
871 {
872     sort( rootItem->i_id, column, order );
873 }
874
875 void PLModel::sort( int i_root_id, int column, Qt::SortOrder order )
876 {
877     int meta = columnToMeta( column );
878     if( meta == COLUMN_END ) return;
879
880     PLItem *item = findById( rootItem, i_root_id );
881     if( !item ) return;
882     QModelIndex qIndex = index( item, 0 );
883     int count = item->children.size();
884     if( count )
885     {
886         beginRemoveRows( qIndex, 0, count - 1 );
887         item->removeChildren();
888         endRemoveRows( );
889     }
890
891     PL_LOCK;
892     {
893         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
894                                                         i_root_id );
895         if( p_root )
896         {
897             playlist_RecursiveNodeSort( p_playlist, p_root,
898                                         i_column_sorting( meta ),
899                                         order == Qt::AscendingOrder ?
900                                             ORDER_NORMAL : ORDER_REVERSE );
901         }
902     }
903     if( count )
904     {
905         beginInsertRows( qIndex, 0, count - 1 );
906         updateChildren( item );
907         endInsertRows( );
908     }
909     PL_UNLOCK;
910 }
911
912 void PLModel::search( const QString& search_text )
913 {
914     /** \todo Fire the search with a small delay ? */
915     PL_LOCK;
916     {
917         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
918                                                         rootItem->i_id );
919         assert( p_root );
920         const char *psz_name = search_text.toUtf8().data();
921         playlist_LiveSearchUpdate( p_playlist , p_root, psz_name );
922     }
923     PL_UNLOCK;
924     rebuild();
925 }
926
927 /*********** Popup *********/
928 void PLModel::popup( QModelIndex & index, QPoint &point, QModelIndexList list )
929 {
930     int i_id = index.isValid() ? itemId( index ) : rootItem->i_id;
931
932     PL_LOCK;
933     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, i_id );
934     if( !p_item )
935     {
936         PL_UNLOCK; return;
937     }
938     i_popup_item = index.isValid() ? p_item->i_id : -1;
939     i_popup_parent = index.isValid() ?
940         ( p_item->p_parent ? p_item->p_parent->i_id : -1 ) :
941         ( p_item->i_id );
942     i_popup_column = index.column();
943     /* check whether we are in tree view */
944     bool tree = false;
945     playlist_item_t *p_up = p_item;
946     while( p_up )
947     {
948         if ( p_up == p_playlist->p_root_category ) tree = true;
949         p_up = p_up->p_parent;
950     }
951     PL_UNLOCK;
952
953     current_selection = list;
954     QMenu *menu = new QMenu;
955     if( i_popup_item > -1 )
956     {
957         menu->addAction( qtr(I_POP_PLAY), this, SLOT( popupPlay() ) );
958         menu->addAction( qtr(I_POP_DEL), this, SLOT( popupDel() ) );
959         menu->addSeparator();
960         menu->addAction( qtr(I_POP_STREAM), this, SLOT( popupStream() ) );
961         menu->addAction( qtr(I_POP_SAVE), this, SLOT( popupSave() ) );
962         menu->addSeparator();
963         menu->addAction( qtr(I_POP_INFO), this, SLOT( popupInfo() ) );
964         menu->addSeparator();
965         QMenu *sort_menu = menu->addMenu( qtr( "Sort by ") +
966             qfu( psz_column_title( columnToMeta( index.column() ) ) ) );
967         sort_menu->addAction( qtr( "Ascending" ),
968             this, SLOT( popupSortAsc() ) );
969         sort_menu->addAction( qtr( "Descending" ),
970             this, SLOT( popupSortDesc() ) );
971     }
972     if( tree )
973         menu->addAction( qtr(I_POP_ADD), this, SLOT( popupAddNode() ) );
974     if( i_popup_item > -1 )
975     {
976         menu->addSeparator();
977         menu->addAction( qtr( I_POP_EXPLORE ), this, SLOT( popupExplore() ) );
978     }
979     menu->popup( point );
980 }
981
982 void PLModel::popupDel()
983 {
984     doDelete( current_selection );
985 }
986
987 void PLModel::popupPlay()
988 {
989     PL_LOCK;
990     {
991         playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
992                                                         i_popup_item );
993         activateItem( p_item );
994     }
995     PL_UNLOCK;
996 }
997
998 void PLModel::popupInfo()
999 {
1000     PL_LOCK;
1001     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1002                                                     i_popup_item );
1003     if( p_item )
1004     {
1005         input_item_t* p_input = p_item->p_input;
1006         vlc_gc_incref( p_input );
1007         PL_UNLOCK;
1008         MediaInfoDialog *mid = new MediaInfoDialog( p_intf, p_input );
1009         vlc_gc_decref( p_input );
1010         mid->setParent( PlaylistDialog::getInstance( p_intf ),
1011                         Qt::Dialog );
1012         mid->show();
1013     } else
1014         PL_UNLOCK;
1015 }
1016
1017 void PLModel::popupStream()
1018 {
1019     QStringList mrls = selectedURIs();
1020     if( !mrls.isEmpty() )
1021         THEDP->streamingDialog( NULL, mrls[0], false );
1022
1023 }
1024
1025 void PLModel::popupSave()
1026 {
1027     QStringList mrls = selectedURIs();
1028     if( !mrls.isEmpty() )
1029         THEDP->streamingDialog( NULL, mrls[0] );
1030 }
1031
1032 #include <QUrl>
1033 #include <QFileInfo>
1034 #include <QDesktopServices>
1035 void PLModel::popupExplore()
1036 {
1037     PL_LOCK;
1038     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1039                                                     i_popup_item );
1040     if( p_item )
1041     {
1042        input_item_t *p_input = p_item->p_input;
1043        char *psz_meta = input_item_GetURI( p_input );
1044        PL_UNLOCK;
1045        if( psz_meta )
1046        {
1047            const char *psz_access;
1048            const char *psz_demux;
1049            char  *psz_path;
1050            input_SplitMRL( &psz_access, &psz_demux, &psz_path, psz_meta );
1051
1052            if( EMPTY_STR( psz_access ) ||
1053                !strncasecmp( psz_access, "file", 4 ) ||
1054                !strncasecmp( psz_access, "dire", 4 ) )
1055            {
1056                QFileInfo info( qfu( psz_meta ) );
1057                QDesktopServices::openUrl(
1058                                QUrl::fromLocalFile( info.absolutePath() ) );
1059            }
1060            free( psz_meta );
1061        }
1062     }
1063     else
1064         PL_UNLOCK;
1065 }
1066
1067 #include <QInputDialog>
1068 void PLModel::popupAddNode()
1069 {
1070     bool ok;
1071     QString name = QInputDialog::getText( PlaylistDialog::getInstance( p_intf ),
1072         qtr( I_POP_ADD ), qtr( "Enter name for new node:" ),
1073         QLineEdit::Normal, QString(), &ok);
1074     if( !ok || name.isEmpty() ) return;
1075     PL_LOCK;
1076     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1077                                                     i_popup_parent );
1078     if( p_item )
1079     {
1080         playlist_NodeCreate( p_playlist, qtu( name ), p_item, 0, NULL );
1081     }
1082     PL_UNLOCK;
1083 }
1084
1085 void PLModel::popupSortAsc()
1086 {
1087     sort( i_popup_parent, i_popup_column, Qt::AscendingOrder );
1088 }
1089
1090 void PLModel::popupSortDesc()
1091 {
1092     sort( i_popup_parent, i_popup_column, Qt::DescendingOrder );
1093 }
1094 /**********************************************************************
1095  * Playlist callbacks
1096  **********************************************************************/
1097
1098 static int ItemDeleted( vlc_object_t *p_this, const char *psz_variable,
1099                         vlc_value_t oval, vlc_value_t nval, void *param )
1100 {
1101     PLModel *p_model = (PLModel *) param;
1102     PLEvent *event = new PLEvent( ItemDelete_Type, nval.i_int );
1103     QApplication::postEvent( p_model, event );
1104     return VLC_SUCCESS;
1105 }
1106
1107 static int ItemAppended( vlc_object_t *p_this, const char *psz_variable,
1108                          vlc_value_t oval, vlc_value_t nval, void *param )
1109 {
1110     PLModel *p_model = (PLModel *) param;
1111     const playlist_add_t *p_add = (playlist_add_t *)nval.p_address;
1112     PLEvent *event = new PLEvent( p_add );
1113     QApplication::postEvent( p_model, event );
1114     return VLC_SUCCESS;
1115 }
1116