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