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