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