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