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