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