]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/playlist/playlist_model.cpp
qt4: delete the callbacks only if they already exist.
[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, true );
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, false );
711 }
712
713 void PLModel::rebuild( playlist_item_t *p_root, bool b_first )
714 {
715     playlist_item_t* p_item;
716     /* Remove callbacks before locking to avoid deadlocks
717        The first time the callbacks are not present so
718        don't try to delete them */
719     if( !b_first )
720         delCallbacks();
721
722     /* Invalidate cache */
723     i_cached_id = i_cached_input_id = -1;
724
725     if( rootItem ) rootItem->removeChildren();
726
727     PL_LOCK;
728     if( p_root )
729     {
730         delete rootItem;
731         rootItem = new PLItem( p_root );
732     }
733     assert( rootItem );
734     /* Recreate from root */
735     updateChildren( rootItem );
736     if( (p_item = playlist_CurrentPlayingItem(p_playlist)) )
737         currentItem = findByInput( rootItem, p_item->p_input->i_id );
738     else
739         currentItem = NULL;
740     PL_UNLOCK;
741
742     /* And signal the view */
743     reset();
744
745     emit currentChanged( index( currentItem, 0 ) );
746
747     addCallbacks();
748 }
749
750 void PLModel::takeItem( PLItem *item )
751 {
752     assert( item );
753     PLItem *parent = item->parentItem;
754     assert( parent );
755     int i_index = parent->children.indexOf( item );
756
757     beginRemoveRows( index( parent, 0 ), i_index, i_index );
758     parent->takeChildAt( i_index );
759     endRemoveRows();
760 }
761
762 void PLModel::insertChildren( PLItem *node, QList<PLItem*>& items, int i_pos )
763 {
764     assert( node );
765     int count = items.size();
766     if( !count ) return;
767     beginInsertRows( index( node, 0 ), i_pos, i_pos + count - 1 );
768     for( int i = 0; i < count; i++ )
769     {
770         node->children.insert( i_pos + i, items[i] );
771         items[i]->parentItem = node;
772     }
773     endInsertRows();
774 }
775
776 void PLModel::removeItem( PLItem *item )
777 {
778     if( !item ) return;
779     if( currentItem == item )
780     {
781         currentItem = NULL;
782         emit currentChanged( QModelIndex() );
783     }
784     PLItem *parent = item->parentItem;
785     assert( parent );
786     parent->removeChild( item );
787 }
788
789 /* This function must be entered WITH the playlist lock */
790 void PLModel::updateChildren( PLItem *root )
791 {
792     playlist_item_t *p_node = playlist_ItemGetById( p_playlist, root->i_id );
793     updateChildren( p_node, root );
794 }
795
796 /* This function must be entered WITH the playlist lock */
797 void PLModel::updateChildren( playlist_item_t *p_node, PLItem *root )
798 {
799     playlist_item_t *p_item = playlist_CurrentPlayingItem(p_playlist);
800     for( int i = 0; i < p_node->i_children ; i++ )
801     {
802         if( p_node->pp_children[i]->i_flags & PLAYLIST_DBL_FLAG ) continue;
803         PLItem *newItem =  new PLItem( p_node->pp_children[i], root );
804         root->appendChild( newItem );
805         if( p_item && newItem->p_input == p_item->p_input )
806         {
807             currentItem = newItem;
808             emit currentChanged( index( currentItem, 0 ) );
809         }
810         if( i_depth == DEPTH_PL && p_node->pp_children[i]->i_children != -1 )
811             updateChildren( p_node->pp_children[i], newItem );
812     }
813 }
814
815 /* Function doesn't need playlist-lock, as we don't touch playlist_item_t stuff here*/
816 void PLModel::updateTreeItem( PLItem *item, bool signal, bool force )
817 {
818     if ( !item || !item->p_input )
819         return;
820     if( !force && i_depth == DEPTH_SEL && item->parentItem &&
821                                  item->parentItem->p_input != rootItem->p_input )
822         return;
823     if( signal )
824         emit dataChanged( index( item, 0 ) , index( item, columnCount( QModelIndex() ) ) );
825 }
826
827 /************************* Actions ******************************/
828
829 /**
830  * Deletion, here we have to do a ugly slow hack as we retrieve the full
831  * list of indexes to delete at once: when we delete a node and all of
832  * its children, we need to update the list.
833  * Todo: investigate whethere we can use ranges to be sure to delete all items?
834  */
835 void PLModel::doDelete( QModelIndexList selected )
836 {
837     for( int i = selected.size() -1 ; i >= 0; i-- )
838     {
839         QModelIndex index = selected[i];
840         if( index.column() != 0 ) continue;
841         PLItem *item = getItem( index );
842         if( item )
843         {
844             if( item->children.size() )
845                 recurseDelete( item->children, &selected );
846             doDeleteItem( item, &selected );
847         }
848         if( i > selected.size() ) i = selected.size();
849     }
850 }
851
852 void PLModel::recurseDelete( QList<PLItem*> children, QModelIndexList *fullList )
853 {
854     for( int i = children.size() - 1; i >= 0 ; i-- )
855     {
856         PLItem *item = children[i];
857         if( item->children.size() )
858             recurseDelete( item->children, fullList );
859         doDeleteItem( item, fullList );
860     }
861 }
862
863 void PLModel::doDeleteItem( PLItem *item, QModelIndexList *fullList )
864 {
865     QModelIndex deleteIndex = index( item, 0 );
866     fullList->removeAll( deleteIndex );
867
868     PL_LOCK;
869     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, item->i_id );
870     if( !p_item )
871     {
872         PL_UNLOCK;
873         return;
874     }
875     if( p_item->i_children == -1 )
876         playlist_DeleteFromInput( p_playlist, p_item->p_input, pl_Locked );
877     else
878         playlist_NodeDelete( p_playlist, p_item, true, false );
879     PL_UNLOCK;
880     /* And finally, remove it from the tree */
881     int itemIndex = item->parentItem->children.indexOf( item );
882     beginRemoveRows( index( item->parentItem, 0), itemIndex, itemIndex );
883     removeItem( item );
884     endRemoveRows();
885 }
886
887 /******* Volume III: Sorting and searching ********/
888 void PLModel::sort( int column, Qt::SortOrder order )
889 {
890     sort( rootItem->i_id, column, order );
891 }
892
893 void PLModel::sort( int i_root_id, int column, Qt::SortOrder order )
894 {
895     int meta = columnToMeta( column );
896     if( meta == COLUMN_END ) return;
897
898     PLItem *item = findById( rootItem, i_root_id );
899     if( !item ) return;
900     QModelIndex qIndex = index( item, 0 );
901     int count = item->children.size();
902     if( count )
903     {
904         beginRemoveRows( qIndex, 0, count - 1 );
905         item->removeChildren();
906         endRemoveRows( );
907     }
908
909     PL_LOCK;
910     {
911         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
912                                                         i_root_id );
913         if( p_root )
914         {
915             playlist_RecursiveNodeSort( p_playlist, p_root,
916                                         i_column_sorting( meta ),
917                                         order == Qt::AscendingOrder ?
918                                             ORDER_NORMAL : ORDER_REVERSE );
919         }
920     }
921     if( count )
922     {
923         beginInsertRows( qIndex, 0, count - 1 );
924         updateChildren( item );
925         endInsertRows( );
926     }
927     PL_UNLOCK;
928 }
929
930 void PLModel::search( const QString& search_text )
931 {
932     /** \todo Fire the search with a small delay ? */
933     PL_LOCK;
934     {
935         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
936                                                         rootItem->i_id );
937         assert( p_root );
938         const char *psz_name = search_text.toUtf8().data();
939         playlist_LiveSearchUpdate( p_playlist , p_root, psz_name );
940     }
941     PL_UNLOCK;
942     rebuild();
943 }
944
945 /*********** Popup *********/
946 void PLModel::popup( QModelIndex & index, QPoint &point, QModelIndexList list )
947 {
948     int i_id = index.isValid() ? itemId( index ) : rootItem->i_id;
949
950     PL_LOCK;
951     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, i_id );
952     if( !p_item )
953     {
954         PL_UNLOCK; return;
955     }
956     i_popup_item = index.isValid() ? p_item->i_id : -1;
957     i_popup_parent = index.isValid() ?
958         ( p_item->p_parent ? p_item->p_parent->i_id : -1 ) :
959         ( p_item->i_id );
960     i_popup_column = index.column();
961     /* check whether we are in tree view */
962     bool tree = false;
963     playlist_item_t *p_up = p_item;
964     while( p_up )
965     {
966         if ( p_up == p_playlist->p_root_category ) tree = true;
967         p_up = p_up->p_parent;
968     }
969     PL_UNLOCK;
970
971     current_selection = list;
972     QMenu *menu = new QMenu;
973     if( i_popup_item > -1 )
974     {
975         menu->addAction( qtr(I_POP_PLAY), this, SLOT( popupPlay() ) );
976         menu->addAction( qtr(I_POP_DEL), this, SLOT( popupDel() ) );
977         menu->addSeparator();
978         menu->addAction( qtr(I_POP_STREAM), this, SLOT( popupStream() ) );
979         menu->addAction( qtr(I_POP_SAVE), this, SLOT( popupSave() ) );
980         menu->addSeparator();
981         menu->addAction( qtr(I_POP_INFO), this, SLOT( popupInfo() ) );
982         menu->addSeparator();
983         QMenu *sort_menu = menu->addMenu( qtr( "Sort by ") +
984             qfu( psz_column_title( columnToMeta( index.column() ) ) ) );
985         sort_menu->addAction( qtr( "Ascending" ),
986             this, SLOT( popupSortAsc() ) );
987         sort_menu->addAction( qtr( "Descending" ),
988             this, SLOT( popupSortDesc() ) );
989     }
990     if( tree )
991         menu->addAction( qtr(I_POP_ADD), this, SLOT( popupAddNode() ) );
992     if( i_popup_item > -1 )
993     {
994         menu->addSeparator();
995         menu->addAction( qtr( I_POP_EXPLORE ), this, SLOT( popupExplore() ) );
996     }
997     menu->popup( point );
998 }
999
1000 void PLModel::popupDel()
1001 {
1002     doDelete( current_selection );
1003 }
1004
1005 void PLModel::popupPlay()
1006 {
1007     PL_LOCK;
1008     {
1009         playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1010                                                         i_popup_item );
1011         activateItem( p_item );
1012     }
1013     PL_UNLOCK;
1014 }
1015
1016 void PLModel::popupInfo()
1017 {
1018     PL_LOCK;
1019     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1020                                                     i_popup_item );
1021     if( p_item )
1022     {
1023         input_item_t* p_input = p_item->p_input;
1024         vlc_gc_incref( p_input );
1025         PL_UNLOCK;
1026         MediaInfoDialog *mid = new MediaInfoDialog( p_intf, p_input );
1027         vlc_gc_decref( p_input );
1028         mid->setParent( PlaylistDialog::getInstance( p_intf ),
1029                         Qt::Dialog );
1030         mid->show();
1031     } else
1032         PL_UNLOCK;
1033 }
1034
1035 void PLModel::popupStream()
1036 {
1037     QStringList mrls = selectedURIs();
1038     if( !mrls.isEmpty() )
1039         THEDP->streamingDialog( NULL, mrls[0], false );
1040
1041 }
1042
1043 void PLModel::popupSave()
1044 {
1045     QStringList mrls = selectedURIs();
1046     if( !mrls.isEmpty() )
1047         THEDP->streamingDialog( NULL, mrls[0] );
1048 }
1049
1050 #include <QUrl>
1051 #include <QFileInfo>
1052 #include <QDesktopServices>
1053 void PLModel::popupExplore()
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        char *psz_meta = input_item_GetURI( p_input );
1062        PL_UNLOCK;
1063        if( psz_meta )
1064        {
1065            const char *psz_access;
1066            const char *psz_demux;
1067            char  *psz_path;
1068            input_SplitMRL( &psz_access, &psz_demux, &psz_path, psz_meta );
1069
1070            if( EMPTY_STR( psz_access ) ||
1071                !strncasecmp( psz_access, "file", 4 ) ||
1072                !strncasecmp( psz_access, "dire", 4 ) )
1073            {
1074                QFileInfo info( qfu( psz_meta ) );
1075                QDesktopServices::openUrl(
1076                                QUrl::fromLocalFile( info.absolutePath() ) );
1077            }
1078            free( psz_meta );
1079        }
1080     }
1081     else
1082         PL_UNLOCK;
1083 }
1084
1085 #include <QInputDialog>
1086 void PLModel::popupAddNode()
1087 {
1088     bool ok;
1089     QString name = QInputDialog::getText( PlaylistDialog::getInstance( p_intf ),
1090         qtr( I_POP_ADD ), qtr( "Enter name for new node:" ),
1091         QLineEdit::Normal, QString(), &ok);
1092     if( !ok || name.isEmpty() ) return;
1093     PL_LOCK;
1094     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1095                                                     i_popup_parent );
1096     if( p_item )
1097     {
1098         playlist_NodeCreate( p_playlist, qtu( name ), p_item, 0, NULL );
1099     }
1100     PL_UNLOCK;
1101 }
1102
1103 void PLModel::popupSortAsc()
1104 {
1105     sort( i_popup_parent, i_popup_column, Qt::AscendingOrder );
1106 }
1107
1108 void PLModel::popupSortDesc()
1109 {
1110     sort( i_popup_parent, i_popup_column, Qt::DescendingOrder );
1111 }
1112 /**********************************************************************
1113  * Playlist callbacks
1114  **********************************************************************/
1115
1116 static int ItemDeleted( vlc_object_t *p_this, const char *psz_variable,
1117                         vlc_value_t oval, vlc_value_t nval, void *param )
1118 {
1119     PLModel *p_model = (PLModel *) param;
1120     PLEvent *event = new PLEvent( ItemDelete_Type, nval.i_int );
1121     QApplication::postEvent( p_model, event );
1122     return VLC_SUCCESS;
1123 }
1124
1125 static int ItemAppended( vlc_object_t *p_this, const char *psz_variable,
1126                          vlc_value_t oval, vlc_value_t nval, void *param )
1127 {
1128     PLModel *p_model = (PLModel *) param;
1129     const playlist_add_t *p_add = (playlist_add_t *)nval.p_address;
1130     PLEvent *event = new PLEvent( p_add );
1131     QApplication::postEvent( p_model, event );
1132     return VLC_SUCCESS;
1133 }
1134