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