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