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