]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/playlist/playlist_model.cpp
qt4: move item removal from PLItem to PLModel...
[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<int> ids;
259             while( !stream.atEnd() )
260             {
261                 int id;
262                 stream >> id;
263                 ids.append(id);
264             }
265             int count = ids.size();
266             playlist_item_t *items[count];
267             for( int i = 0; i < count; i++ )
268             {
269                 playlist_item_t *item = playlist_ItemGetById( p_playlist, ids[i] );
270                 if( !item )
271                 {
272                     PL_UNLOCK;
273                     return false;
274                 }
275                 items[i] = item;
276             }
277             playlist_TreeMoveMany( p_playlist, count, items, p_parent,
278                 (row == -1 ? p_parent->i_children : row) );
279         }
280
281         PL_UNLOCK;
282         /*TODO: That's not a good idea to rebuild the playlist */
283         rebuild();
284     }
285     return true;
286 }
287
288 /* remove item with its id */
289 void PLModel::removeItem( int i_id )
290 {
291     PLItem *item = FindById( rootItem, i_id );
292     RemoveItem( item );
293 }
294
295 /* callbacks and slots */
296 void PLModel::addCallbacks()
297 {
298     /* Some global changes happened -> Rebuild all */
299     var_AddCallback( p_playlist, "intf-change", PlaylistChanged, this );
300     /* We went to the next item
301     var_AddCallback( p_playlist, "item-current", PlaylistNext, this );
302     */
303     /* One item has been updated */
304     var_AddCallback( p_playlist, "playlist-item-append", ItemAppended, this );
305     var_AddCallback( p_playlist, "playlist-item-deleted", ItemDeleted, this );
306 }
307
308 void PLModel::delCallbacks()
309 {
310     /*
311     var_DelCallback( p_playlist, "item-current", PlaylistNext, this );
312     */
313     var_DelCallback( p_playlist, "intf-change", PlaylistChanged, this );
314     var_DelCallback( p_playlist, "playlist-item-append", ItemAppended, this );
315     var_DelCallback( p_playlist, "playlist-item-deleted", ItemDeleted, this );
316 }
317
318 void PLModel::activateItem( const QModelIndex &index )
319 {
320     assert( index.isValid() );
321     PLItem *item = static_cast<PLItem*>(index.internalPointer());
322     assert( item );
323     PL_LOCK;
324     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, item->i_id );
325     activateItem( p_item );
326     PL_UNLOCK;
327 }
328
329 /* Must be entered with lock */
330 void PLModel::activateItem( playlist_item_t *p_item )
331 {
332     if( !p_item ) return;
333     playlist_item_t *p_parent = p_item;
334     while( p_parent )
335     {
336         if( p_parent->i_id == rootItem->i_id ) break;
337         p_parent = p_parent->p_parent;
338     }
339     if( p_parent )
340         playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, pl_Locked,
341                           p_parent, p_item );
342 }
343
344 /****************** Base model mandatory implementations *****************/
345 QVariant PLModel::data( const QModelIndex &index, int role ) const
346 {
347     if( !index.isValid() ) return QVariant();
348     PLItem *item = static_cast<PLItem*>(index.internalPointer());
349     if( role == Qt::DisplayRole )
350     {
351         if( i_depth == DEPTH_SEL )
352         {
353             vlc_mutex_lock( &item->p_input->lock );
354             QString returninfo = QString( qfu( item->p_input->psz_name ) );
355             vlc_mutex_unlock( &item->p_input->lock );
356             return QVariant(returninfo);
357         }
358
359         int metadata = metaColumn( index.column() );
360         if( metadata == COLUMN_END ) return QVariant();
361
362         QString returninfo;
363         if( metadata == COLUMN_NUMBER )
364             returninfo = QString::number( index.row() + 1 );
365         else
366         {
367             char *psz = psz_column_meta( item->p_input, metadata );
368             returninfo = qfu( psz );
369             free( psz );
370         }
371         return QVariant( returninfo );
372     }
373     else if( role == Qt::DecorationRole && index.column() == 0  )
374     {
375         /* Use to segfault here because i_type wasn't always initialized */
376         if( item->p_input->i_type >= 0 )
377             return QVariant( PLModel::icons[item->p_input->i_type] );
378     }
379     else if( role == Qt::FontRole )
380     {
381         if( isCurrent( index ) )
382         {
383             QFont f; f.setBold( true ); return QVariant( f );
384         }
385     }
386     return QVariant();
387 }
388
389 bool PLModel::isCurrent( const QModelIndex &index ) const
390 {
391     assert( index.isValid() );
392     if( !currentItem ) return false;
393     return static_cast<PLItem*>(index.internalPointer())->p_input == currentItem->p_input;
394 }
395
396 int PLModel::itemId( const QModelIndex &index ) const
397 {
398     assert( index.isValid() );
399     return static_cast<PLItem*>(index.internalPointer())->i_id;
400 }
401
402 QVariant PLModel::headerData( int section, Qt::Orientation orientation,
403                               int role ) const
404 {
405     if (orientation != Qt::Horizontal || role != Qt::DisplayRole)
406         return QVariant();
407
408     if( i_depth == DEPTH_SEL ) return QVariant( QString("") );
409
410     int meta_col = metaColumn( section );
411
412     if( meta_col == COLUMN_END ) return QVariant();
413
414     return QVariant( qfu( psz_column_title( meta_col ) ) );
415 }
416
417 QModelIndex PLModel::index( int row, int column, const QModelIndex &parent )
418                   const
419 {
420     PLItem *parentItem;
421     if( !parent.isValid() )
422         parentItem = rootItem;
423     else
424         parentItem = static_cast<PLItem*>(parent.internalPointer());
425
426     PLItem *childItem = parentItem->child( row );
427     if( childItem )
428         return createIndex( row, column, childItem );
429     else
430         return QModelIndex();
431 }
432
433 /* Return the index of a given item */
434 QModelIndex PLModel::index( PLItem *item, int column ) const
435 {
436     if( !item ) return QModelIndex();
437     const PLItem *parent = item->parent();
438     if( parent )
439         return createIndex( parent->children.lastIndexOf( item ),
440                             column, item );
441     return QModelIndex();
442 }
443
444 QModelIndex PLModel::parent( const QModelIndex &index ) const
445 {
446     if( !index.isValid() ) return QModelIndex();
447
448     PLItem *childItem = static_cast<PLItem*>(index.internalPointer());
449     if( !childItem )
450     {
451         msg_Err( p_playlist, "NULL CHILD" );
452         return QModelIndex();
453     }
454
455     PLItem *parentItem = childItem->parent();
456     if( !parentItem || parentItem == rootItem ) return QModelIndex();
457     if( !parentItem->parentItem )
458     {
459         msg_Err( p_playlist, "No parent parent, trying row 0 " );
460         msg_Err( p_playlist, "----- PLEASE REPORT THIS ------" );
461         return createIndex( 0, 0, parentItem );
462     }
463     QModelIndex ind = createIndex(parentItem->row(), 0, parentItem);
464     return ind;
465 }
466
467 int PLModel::columnCount( const QModelIndex &i) const
468 {
469     int columnCount=0;
470     int metadata=1;
471     if( i_depth == DEPTH_SEL ) return 1;
472
473     while( metadata < COLUMN_END )
474     {
475         if( metadata & i_showflags )
476             columnCount++;
477         metadata <<= 1;
478     }
479     return columnCount;
480 }
481
482 int PLModel::childrenCount( const QModelIndex &parent ) const
483 {
484     return rowCount( parent );
485 }
486
487 int PLModel::rowCount( const QModelIndex &parent ) const
488 {
489     PLItem *parentItem;
490
491     if( !parent.isValid() )
492         parentItem = rootItem;
493     else
494         parentItem = static_cast<PLItem*>(parent.internalPointer());
495
496     return parentItem->childCount();
497 }
498
499 QStringList PLModel::selectedURIs()
500 {
501     QStringList lst;
502     for( int i = 0; i < current_selection.size(); i++ )
503     {
504         PLItem *item = static_cast<PLItem*>
505                     (current_selection[i].internalPointer());
506         if( item )
507         {
508             PL_LOCK;
509             playlist_item_t *p_item = playlist_ItemGetById( p_playlist, item->i_id );
510             if( p_item )
511             {
512                 char *psz = input_item_GetURI( p_item->p_input );
513                 if( psz )
514                 {
515                     lst.append( psz );
516                     free( psz );
517                 }
518             }
519             PL_UNLOCK;
520         }
521     }
522     return lst;
523 }
524
525 /************************* General playlist status ***********************/
526
527 bool PLModel::hasRandom()
528 {
529     return var_GetBool( p_playlist, "random" );
530 }
531 bool PLModel::hasRepeat()
532 {
533     return var_GetBool( p_playlist, "repeat" );
534 }
535 bool PLModel::hasLoop()
536 {
537     return var_GetBool( p_playlist, "loop" );
538 }
539 void PLModel::setLoop( bool on )
540 {
541     var_SetBool( p_playlist, "loop", on ? true:false );
542     config_PutInt( p_playlist, "loop", on ? 1: 0 );
543 }
544 void PLModel::setRepeat( bool on )
545 {
546     var_SetBool( p_playlist, "repeat", on ? true:false );
547     config_PutInt( p_playlist, "repeat", on ? 1: 0 );
548 }
549 void PLModel::setRandom( bool on )
550 {
551     var_SetBool( p_playlist, "random", on ? true:false );
552     config_PutInt( p_playlist, "random", on ? 1: 0 );
553 }
554
555 /************************* Lookups *****************************/
556
557 PLItem *PLModel::FindById( PLItem *root, int i_id )
558 {
559     return FindInner( root, i_id, false );
560 }
561
562 PLItem *PLModel::FindByInput( PLItem *root, int i_id )
563 {
564     PLItem *result = FindInner( root, i_id, true );
565     return result;
566 }
567
568 #define CACHE( i, p ) { i_cached_id = i; p_cached_item = p; }
569 #define ICACHE( i, p ) { i_cached_input_id = i; p_cached_item_bi = p; }
570
571 PLItem * PLModel::FindInner( PLItem *root, int i_id, bool b_input )
572 {
573     if( ( !b_input && i_cached_id == i_id) ||
574         ( b_input && i_cached_input_id ==i_id ) )
575     {
576         return b_input ? p_cached_item_bi : p_cached_item;
577     }
578
579     if( !b_input && root->i_id == i_id )
580     {
581         CACHE( i_id, root );
582         return root;
583     }
584     else if( b_input && root->p_input->i_id == i_id )
585     {
586         ICACHE( i_id, root );
587         return root;
588     }
589
590     QList<PLItem *>::iterator it = root->children.begin();
591     while ( it != root->children.end() )
592     {
593         if( !b_input && (*it)->i_id == i_id )
594         {
595             CACHE( i_id, (*it) );
596             return p_cached_item;
597         }
598         else if( b_input && (*it)->p_input->i_id == i_id )
599         {
600             ICACHE( i_id, (*it) );
601             return p_cached_item_bi;
602         }
603         if( (*it)->children.size() )
604         {
605             PLItem *childFound = FindInner( (*it), i_id, b_input );
606             if( childFound )
607             {
608                 if( b_input )
609                     ICACHE( i_id, childFound )
610                 else
611                     CACHE( i_id, childFound )
612                 return childFound;
613             }
614         }
615         it++;
616     }
617     return NULL;
618 }
619 #undef CACHE
620 #undef ICACHE
621
622 /* computes column id of meta data from visible column index */
623 int PLModel::metaColumn( int column ) const
624 {
625     int metadata = 1;
626     int running_index = -1;
627
628     while( metadata < COLUMN_END )
629     {
630         if( metadata & i_showflags )
631             running_index++;
632         if( running_index == column )
633             break;
634         metadata <<= 1;
635     }
636
637     if( running_index != column ) return COLUMN_END;
638     return metadata;
639 }
640
641 /************************* Updates handling *****************************/
642 void PLModel::customEvent( QEvent *event )
643 {
644     int type = event->type();
645     if( type != ItemAppend_Type &&
646         type != ItemDelete_Type && type != PLUpdate_Type )
647         return;
648
649     PLEvent *ple = static_cast<PLEvent *>(event);
650
651     if( type == ItemAppend_Type )
652         ProcessItemAppend( &ple->add );
653     else if( type == ItemDelete_Type )
654         ProcessItemRemoval( ple->i_id );
655     else
656         rebuild();
657 }
658
659 /**** Events processing ****/
660 void PLModel::ProcessInputItemUpdate( input_thread_t *p_input )
661 {
662     if( !p_input ) return;
663     ProcessInputItemUpdate( input_GetItem( p_input ) );
664     if( p_input && !( p_input->b_dead || !vlc_object_alive( p_input ) ) )
665     {
666         PLItem *item = FindByInput( rootItem, input_GetItem( p_input )->i_id );
667         currentItem = item;
668         emit currentChanged( index( item, 0 ) );
669     }
670     else
671     {
672         currentItem = NULL;
673     }
674 }
675 void PLModel::ProcessInputItemUpdate( input_item_t *p_item )
676 {
677     if( !p_item ||  p_item->i_id <= 0 ) return;
678     PLItem *item = FindByInput( rootItem, p_item->i_id );
679     if( item )
680         UpdateTreeItem( item, true, true);
681 }
682
683 void PLModel::ProcessItemRemoval( int i_id )
684 {
685     if( i_id <= 0 ) return;
686     if( i_id == i_cached_id ) i_cached_id = -1;
687     i_cached_input_id = -1;
688
689     removeItem( i_id );
690 }
691
692 void PLModel::ProcessItemAppend( const playlist_add_t *p_add )
693 {
694     playlist_item_t *p_item = NULL;
695     PLItem *newItem = NULL;
696
697     PLItem *nodeItem = FindById( rootItem, p_add->i_node );
698     if( !nodeItem ) return;
699
700     PL_LOCK;
701     p_item = playlist_ItemGetById( p_playlist, p_add->i_item );
702     if( !p_item || p_item->i_flags & PLAYLIST_DBL_FLAG ) goto end;
703     if( i_depth == DEPTH_SEL && p_item->p_parent &&
704                         p_item->p_parent->i_id != rootItem->i_id )
705         goto end;
706
707     newItem = new PLItem( p_item, nodeItem );
708     PL_UNLOCK;
709
710     beginInsertRows( index( nodeItem, 0 ), nodeItem->childCount(), nodeItem->childCount() );
711     nodeItem->appendChild( newItem );
712     endInsertRows();
713     UpdateTreeItem( newItem, true );
714     return;
715 end:
716     PL_UNLOCK;
717     return;
718 }
719
720
721 void PLModel::rebuild()
722 {
723     rebuild( NULL );
724 }
725
726 void PLModel::rebuild( playlist_item_t *p_root )
727 {
728     playlist_item_t* p_item;
729     /* Remove callbacks before locking to avoid deadlocks */
730     delCallbacks();
731     /* Invalidate cache */
732     i_cached_id = i_cached_input_id = -1;
733
734     if( rootItem ) RemoveChildren( rootItem );
735
736     PL_LOCK;
737     if( p_root )
738     {
739         delete rootItem;
740         rootItem = new PLItem( p_root );
741     }
742     assert( rootItem );
743     /* Recreate from root */
744     UpdateChildren( rootItem );
745     if( (p_item = playlist_CurrentPlayingItem(p_playlist)) )
746         currentItem = FindByInput( rootItem, p_item->p_input->i_id );
747     else
748         currentItem = NULL;
749     PL_UNLOCK;
750
751     /* And signal the view */
752     reset();
753     emit currentChanged( index( currentItem, 0 ) );
754
755     addCallbacks();
756 }
757
758 void PLModel::RemoveItem( PLItem *item )
759 {
760     if( !item ) return;
761     if( currentItem && currentItem->p_input == item->p_input )
762     {
763         currentItem = NULL;
764         emit currentChanged( QModelIndex() );
765     }
766     PLItem *parent = item->parentItem;
767     assert( parent );
768     int i_index = parent->children.indexOf( item );
769     parent->children.removeAt( i_index );
770     delete item;
771 }
772 void PLModel::RemoveChildren( PLItem *root )
773 {
774   if( root->children.size() )
775   {
776       qDeleteAll( root->children );
777       root->children.clear();
778   }
779 }
780
781 /* This function must be entered WITH the playlist lock */
782 void PLModel::UpdateChildren( PLItem *root )
783 {
784     playlist_item_t *p_node = playlist_ItemGetById( p_playlist, root->i_id );
785     UpdateChildren( p_node, root );
786 }
787
788 /* This function must be entered WITH the playlist lock */
789 void PLModel::UpdateChildren( playlist_item_t *p_node, PLItem *root )
790 {
791     for( int i = 0; i < p_node->i_children ; i++ )
792     {
793         if( p_node->pp_children[i]->i_flags & PLAYLIST_DBL_FLAG ) continue;
794         PLItem *newItem =  new PLItem( p_node->pp_children[i], root );
795         root->appendChild( newItem );
796         if( i_depth == DEPTH_PL && p_node->pp_children[i]->i_children != -1 )
797             UpdateChildren( p_node->pp_children[i], newItem );
798     }
799 }
800
801 /* Function doesn't need playlist-lock, as we don't touch playlist_item_t stuff here*/
802 void PLModel::UpdateTreeItem( PLItem *item, bool signal, bool force )
803 {
804     if ( !item || !item->p_input )
805         return;
806     if( !force && i_depth == DEPTH_SEL && item->parentItem &&
807                                  item->parentItem->p_input != rootItem->p_input )
808         return;
809     if( signal )
810         emit dataChanged( index( item, 0 ) , index( item, columnCount( QModelIndex() ) ) );
811 }
812
813 /************************* Actions ******************************/
814
815 /**
816  * Deletion, here we have to do a ugly slow hack as we retrieve the full
817  * list of indexes to delete at once: when we delete a node and all of
818  * its children, we need to update the list.
819  * Todo: investigate whethere we can use ranges to be sure to delete all items?
820  */
821 void PLModel::doDelete( QModelIndexList selected )
822 {
823     for( int i = selected.size() -1 ; i >= 0; i-- )
824     {
825         QModelIndex index = selected[i];
826         if( index.column() != 0 ) continue;
827         PLItem *item = static_cast<PLItem*>(index.internalPointer());
828         if( item )
829         {
830             if( item->children.size() )
831                 recurseDelete( item->children, &selected );
832             doDeleteItem( item, &selected );
833         }
834         if( i > selected.size() ) i = selected.size();
835     }
836 }
837
838 void PLModel::recurseDelete( QList<PLItem*> children, QModelIndexList *fullList )
839 {
840     for( int i = children.size() - 1; i >= 0 ; i-- )
841     {
842         PLItem *item = children[i];
843         if( item->children.size() )
844             recurseDelete( item->children, fullList );
845         doDeleteItem( item, fullList );
846     }
847 }
848
849 void PLModel::doDeleteItem( PLItem *item, QModelIndexList *fullList )
850 {
851     QModelIndex deleteIndex = index( item, 0 );
852     fullList->removeAll( deleteIndex );
853
854     PL_LOCK;
855     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, item->i_id );
856     if( !p_item )
857     {
858         PL_UNLOCK;
859         return;
860     }
861     if( p_item->i_children == -1 )
862         playlist_DeleteFromInput( p_playlist, p_item->p_input, pl_Locked );
863     else
864         playlist_NodeDelete( p_playlist, p_item, true, false );
865     PL_UNLOCK;
866     /* And finally, remove it from the tree */
867     int itemIndex = item->parentItem->children.indexOf( item );
868     beginRemoveRows( index( item->parentItem, 0), itemIndex, itemIndex );
869     RemoveItem( item );
870     endRemoveRows();
871 }
872
873 /******* Volume III: Sorting and searching ********/
874 void PLModel::sort( int column, Qt::SortOrder order )
875 {
876     sort( rootItem->i_id, column, order );
877 }
878
879 void PLModel::sort( int i_root_id, int column, Qt::SortOrder order )
880 {
881     int i_index = -1;
882     int i_flag = 0;
883
884     int i_column = 1;
885     for( i_column = 1; i_column != COLUMN_END; i_column<<=1 )
886     {
887         if( ( shownFlags() & i_column ) )
888             i_index++;
889         if( column == i_index )
890         {
891             i_flag = i_column;
892             break;
893         }
894     }
895
896     PLItem *item = FindById( rootItem, i_root_id );
897     if( !item ) return;
898     QModelIndex qIndex = index( item, 0 );
899     int count = item->children.size();
900     if( count )
901     {
902         beginRemoveRows( qIndex, 0, count - 1 );
903         RemoveChildren( item );
904         endRemoveRows( );
905     }
906
907     PL_LOCK;
908     {
909         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
910                                                         i_root_id );
911         if( p_root && i_flag )
912         {
913             playlist_RecursiveNodeSort( p_playlist, p_root,
914                                         i_column_sorting( i_flag ),
915                                         order == Qt::AscendingOrder ?
916                                             ORDER_NORMAL : ORDER_REVERSE );
917         }
918     }
919     if( count )
920     {
921         beginInsertRows( qIndex, 0, count - 1 );
922         UpdateChildren( item );
923         endInsertRows( );
924     }
925     PL_UNLOCK;
926 }
927
928 void PLModel::search( const QString& search_text )
929 {
930     /** \todo Fire the search with a small delay ? */
931     PL_LOCK;
932     {
933         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
934                                                         rootItem->i_id );
935         assert( p_root );
936         const char *psz_name = search_text.toUtf8().data();
937         playlist_LiveSearchUpdate( p_playlist , p_root, psz_name );
938     }
939     PL_UNLOCK;
940     rebuild();
941 }
942
943 /*********** Popup *********/
944 void PLModel::popup( QModelIndex & index, QPoint &point, QModelIndexList list )
945 {
946     int i_id = index.isValid() ? itemId( index ) : rootItem->i_id;
947
948     PL_LOCK;
949     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, i_id );
950     if( !p_item )
951     {
952         PL_UNLOCK; return;
953     }
954     i_popup_item = index.isValid() ? p_item->i_id : -1;
955     i_popup_parent = index.isValid() ?
956         ( p_item->p_parent ? p_item->p_parent->i_id : -1 ) :
957         ( p_item->i_id );
958     i_popup_column = index.column();
959     /* check whether we are in tree view */
960     bool tree = false;
961     playlist_item_t *p_up = p_item;
962     while( p_up )
963     {
964         if ( p_up == p_playlist->p_root_category ) tree = true;
965         p_up = p_up->p_parent;
966     }
967     PL_UNLOCK;
968
969     current_selection = list;
970     QMenu *menu = new QMenu;
971     if( i_popup_item > -1 )
972     {
973         menu->addAction( qtr(I_POP_PLAY), this, SLOT( popupPlay() ) );
974         menu->addAction( qtr(I_POP_DEL), this, SLOT( popupDel() ) );
975         menu->addSeparator();
976         menu->addAction( qtr(I_POP_STREAM), this, SLOT( popupStream() ) );
977         menu->addAction( qtr(I_POP_SAVE), this, SLOT( popupSave() ) );
978         menu->addSeparator();
979         menu->addAction( qtr(I_POP_INFO), this, SLOT( popupInfo() ) );
980         menu->addSeparator();
981         QMenu *sort_menu = menu->addMenu( qtr( "Sort by ") +
982             qfu( psz_column_title( metaColumn( index.column() ) ) ) );
983         sort_menu->addAction( qtr( "Ascending" ),
984             this, SLOT( popupSortAsc() ) );
985         sort_menu->addAction( qtr( "Descending" ),
986             this, SLOT( popupSortDesc() ) );
987     }
988     if( tree )
989         menu->addAction( qtr(I_POP_ADD), this, SLOT( popupAddNode() ) );
990     if( i_popup_item > -1 )
991     {
992         menu->addSeparator();
993         menu->addAction( qtr( I_POP_EXPLORE ), this, SLOT( popupExplore() ) );
994     }
995     menu->popup( point );
996 }
997
998
999 void PLModel::viewchanged( int meta )
1000 {
1001     assert( meta );
1002     int _meta = meta;
1003     if( rootItem )
1004     {
1005         int index=-1;
1006         while( _meta )
1007         {
1008             index++;
1009             _meta >>= 1;
1010         }
1011
1012         index = __MIN( index, columnCount() );
1013         QModelIndex parent = createIndex( 0, 0, rootItem );
1014
1015         if( i_showflags & meta )
1016             /* Removing columns */
1017         {
1018             beginRemoveColumns( parent, index, index+1 );
1019             i_showflags &= ~( meta );
1020             getSettings()->setValue( "qt-pl-showflags", i_showflags );
1021             endRemoveColumns();
1022         }
1023         else
1024         {
1025             /* Adding columns */
1026             beginInsertColumns( parent, index, index+1 );
1027             i_showflags |= meta;
1028             getSettings()->setValue( "qt-pl-showflags", i_showflags );
1029             endInsertColumns();
1030         }
1031
1032         emit columnsChanged( meta );
1033     }
1034 }
1035
1036 void PLModel::popupDel()
1037 {
1038     doDelete( current_selection );
1039 }
1040
1041 void PLModel::popupPlay()
1042 {
1043     PL_LOCK;
1044     {
1045         playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1046                                                         i_popup_item );
1047         activateItem( p_item );
1048     }
1049     PL_UNLOCK;
1050 }
1051
1052 void PLModel::popupInfo()
1053 {
1054     PL_LOCK;
1055     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1056                                                     i_popup_item );
1057     if( p_item )
1058     {
1059         input_item_t* p_input = p_item->p_input;
1060         vlc_gc_incref( p_input );
1061         PL_UNLOCK;
1062         MediaInfoDialog *mid = new MediaInfoDialog( p_intf, p_input );
1063         vlc_gc_decref( p_input );
1064         mid->setParent( PlaylistDialog::getInstance( p_intf ),
1065                         Qt::Dialog );
1066         mid->show();
1067     } else
1068         PL_UNLOCK;
1069 }
1070
1071 void PLModel::popupStream()
1072 {
1073     QStringList mrls = selectedURIs();
1074     if( !mrls.isEmpty() )
1075         THEDP->streamingDialog( NULL, mrls[0], false );
1076
1077 }
1078
1079 void PLModel::popupSave()
1080 {
1081     QStringList mrls = selectedURIs();
1082     if( !mrls.isEmpty() )
1083         THEDP->streamingDialog( NULL, mrls[0] );
1084 }
1085
1086 #include <QUrl>
1087 #include <QFileInfo>
1088 #include <QDesktopServices>
1089 void PLModel::popupExplore()
1090 {
1091     PL_LOCK;
1092     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1093                                                     i_popup_item );
1094     if( p_item )
1095     {
1096        input_item_t *p_input = p_item->p_input;
1097        char *psz_meta = input_item_GetURI( p_input );
1098        PL_UNLOCK;
1099        if( psz_meta )
1100        {
1101            const char *psz_access;
1102            const char *psz_demux;
1103            char  *psz_path;
1104            input_SplitMRL( &psz_access, &psz_demux, &psz_path, psz_meta );
1105
1106            if( EMPTY_STR( psz_access ) ||
1107                !strncasecmp( psz_access, "file", 4 ) ||
1108                !strncasecmp( psz_access, "dire", 4 ) )
1109            {
1110                QFileInfo info( qfu( psz_meta ) );
1111                QDesktopServices::openUrl(
1112                                QUrl::fromLocalFile( info.absolutePath() ) );
1113            }
1114            free( psz_meta );
1115        }
1116     }
1117     else
1118         PL_UNLOCK;
1119 }
1120
1121 #include <QInputDialog>
1122 void PLModel::popupAddNode()
1123 {
1124     bool ok;
1125     QString name = QInputDialog::getText( PlaylistDialog::getInstance( p_intf ),
1126         qtr( I_POP_ADD ), qtr( "Enter name for new node:" ),
1127         QLineEdit::Normal, QString(), &ok);
1128     if( !ok || name.isEmpty() ) return;
1129     PL_LOCK;
1130     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1131                                                     i_popup_parent );
1132     if( p_item )
1133     {
1134         playlist_NodeCreate( p_playlist, qtu( name ), p_item, 0, NULL );
1135     }
1136     PL_UNLOCK;
1137 }
1138
1139 void PLModel::popupSortAsc()
1140 {
1141     sort( i_popup_parent, i_popup_column, Qt::AscendingOrder );
1142 }
1143
1144 void PLModel::popupSortDesc()
1145 {
1146     sort( i_popup_parent, i_popup_column, Qt::DescendingOrder );
1147 }
1148 /**********************************************************************
1149  * Playlist callbacks
1150  **********************************************************************/
1151 static int PlaylistChanged( vlc_object_t *p_this, const char *psz_variable,
1152                             vlc_value_t oval, vlc_value_t nval, void *param )
1153 {
1154     PLModel *p_model = (PLModel *) param;
1155     PLEvent *event = new PLEvent( PLUpdate_Type, 0 );
1156     QApplication::postEvent( p_model, event );
1157     return VLC_SUCCESS;
1158 }
1159
1160 static int PlaylistNext( vlc_object_t *p_this, const char *psz_variable,
1161                          vlc_value_t oval, vlc_value_t nval, void *param )
1162 {
1163     PLModel *p_model = (PLModel *) param;
1164     PLEvent *event = new PLEvent( ItemUpdate_Type, oval.i_int );
1165     QApplication::postEvent( p_model, event );
1166     event = new PLEvent( ItemUpdate_Type, nval.i_int );
1167     QApplication::postEvent( p_model, event );
1168     return VLC_SUCCESS;
1169 }
1170
1171 static int ItemDeleted( vlc_object_t *p_this, const char *psz_variable,
1172                         vlc_value_t oval, vlc_value_t nval, void *param )
1173 {
1174     PLModel *p_model = (PLModel *) param;
1175     PLEvent *event = new PLEvent( ItemDelete_Type, nval.i_int );
1176     QApplication::postEvent( p_model, event );
1177     return VLC_SUCCESS;
1178 }
1179
1180 static int ItemAppended( vlc_object_t *p_this, const char *psz_variable,
1181                          vlc_value_t oval, vlc_value_t nval, void *param )
1182 {
1183     PLModel *p_model = (PLModel *) param;
1184     const playlist_add_t *p_add = (playlist_add_t *)nval.p_address;
1185     PLEvent *event = new PLEvent( p_add );
1186     QApplication::postEvent( p_model, event );
1187     return VLC_SUCCESS;
1188 }
1189