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