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