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