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