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