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