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