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