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