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