]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/playlist/playlist_model.cpp
qt4: let the main popup menu take ownership of the sort sub-menu
[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     }
172     flags |= Qt::ItemIsDragEnabled;
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     sort( rootItem->i_id, column, order );
896 }
897
898 void PLModel::sort( int i_root_id, int column, Qt::SortOrder order )
899 {
900     int i_index = -1;
901     int i_flag = 0;
902
903     int i_column = 1;
904     for( i_column = 1; i_column != COLUMN_END; i_column<<=1 )
905     {
906         if( ( shownFlags() & i_column ) )
907             i_index++;
908         if( column == i_index )
909         {
910             i_flag = i_column;
911             goto next;
912         }
913     }
914
915
916 next:
917     PL_LOCK;
918     {
919         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
920                                                         i_root_id );
921         if( p_root && i_flag )
922         {
923             playlist_RecursiveNodeSort( p_playlist, p_root,
924                                         i_column_sorting( i_flag ),
925                                         order == Qt::AscendingOrder ?
926                                             ORDER_NORMAL : ORDER_REVERSE );
927         }
928     }
929     PL_UNLOCK;
930     rebuild();
931 }
932
933 void PLModel::search( const QString& search_text )
934 {
935     /** \todo Fire the search with a small delay ? */
936     PL_LOCK;
937     {
938         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
939                                                         rootItem->i_id );
940         assert( p_root );
941         const char *psz_name = search_text.toUtf8().data();
942         playlist_LiveSearchUpdate( p_playlist , p_root, psz_name );
943     }
944     PL_UNLOCK;
945     rebuild();
946 }
947
948 /*********** Popup *********/
949 void PLModel::popup( QModelIndex & index, QPoint &point, QModelIndexList list )
950 {
951     int i_id;
952     if( index.isValid() ) i_id = itemId( index );
953     else i_id = rootItem->i_id;
954     i_popup_column = index.column();
955     PL_LOCK;
956     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, i_id );
957     if( p_item )
958     {
959         i_popup_item = p_item->i_id;
960         i_popup_parent = p_item->p_parent ? p_item->p_parent->i_id : -1;
961         bool node = p_item->i_children > -1;
962         bool tree = false;
963         if( node )
964         {
965             /* check whether we are in tree view */
966             playlist_item_t *p_up = p_item;
967             while( p_up )
968             {
969                 if ( p_up == p_playlist->p_root_category ) tree = true;
970                 p_up = p_up->p_parent;
971             }
972         }
973         PL_UNLOCK;
974
975         current_selection = list;
976         QMenu *menu = new QMenu;
977         if( index.isValid() )
978         {
979             menu->addAction( qtr(I_POP_PLAY), this, SLOT( popupPlay() ) );
980             menu->addAction( qtr(I_POP_DEL), this, SLOT( popupDel() ) );
981             menu->addSeparator();
982             menu->addAction( qtr(I_POP_STREAM), this, SLOT( popupStream() ) );
983             menu->addAction( qtr(I_POP_SAVE), this, SLOT( popupSave() ) );
984             menu->addSeparator();
985             menu->addAction( qtr(I_POP_INFO), this, SLOT( popupInfo() ) );
986             if( node )
987             {
988                 menu->addSeparator();
989                 QMenu *sort_menu = menu->addMenu( qtr(I_POP_SORT) );
990                 sort_menu->addAction( qtr( "Ascending" ),
991                     this, SLOT( popupSortAsc() ) );
992                 sort_menu->addAction( qtr( "Descending" ),
993                     this, SLOT( popupSortDesc() ) );
994             }
995         }
996         if( node && tree )
997                 menu->addAction( qtr(I_POP_ADD), this, SLOT( popupAddNode() ) );
998         if( index.isValid() )
999         {
1000             menu->addSeparator();
1001             menu->addAction( qtr( I_POP_EXPLORE ), this, SLOT( popupExplore() ) );
1002         }
1003         menu->popup( point );
1004     }
1005     else
1006         PL_UNLOCK;
1007 }
1008
1009
1010 void PLModel::viewchanged( int meta )
1011 {
1012     assert( meta );
1013     int _meta = meta;
1014     if( rootItem )
1015     {
1016         int index=-1;
1017         while( _meta )
1018         {
1019             index++;
1020             _meta >>= 1;
1021         }
1022
1023         /* UNUSED        emit layoutAboutToBeChanged(); */
1024         index = __MIN( index, columnCount() );
1025         QModelIndex parent = createIndex( 0, 0, rootItem );
1026
1027         if( i_showflags & meta )
1028             /* Removing columns */
1029         {
1030             emit beginRemoveColumns( parent, index, index+1 );
1031             i_showflags &= ~( meta );
1032             getSettings()->setValue( "qt-pl-showflags", i_showflags );
1033             emit endRemoveColumns();
1034         }
1035         else
1036         {
1037             /* Adding columns */
1038             emit beginInsertColumns( parent, index, index+1 );
1039             i_showflags |= meta;
1040             getSettings()->setValue( "qt-pl-showflags", i_showflags );
1041             emit endInsertColumns();
1042         }
1043         emit columnsChanged( meta );
1044         rebuild();
1045     }
1046 }
1047
1048 void PLModel::popupDel()
1049 {
1050     doDelete( current_selection );
1051 }
1052
1053 void PLModel::popupPlay()
1054 {
1055     PL_LOCK;
1056     {
1057         playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1058                                                         i_popup_item );
1059         activateItem( p_item );
1060     }
1061     PL_UNLOCK;
1062 }
1063
1064 void PLModel::popupInfo()
1065 {
1066     PL_LOCK;
1067     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1068                                                     i_popup_item );
1069     if( p_item )
1070     {
1071         input_item_t* p_input = p_item->p_input;
1072         vlc_gc_incref( p_input );
1073         PL_UNLOCK;
1074         MediaInfoDialog *mid = new MediaInfoDialog( p_intf, p_input );
1075         vlc_gc_decref( p_input );
1076         mid->setParent( PlaylistDialog::getInstance( p_intf ),
1077                         Qt::Dialog );
1078         mid->show();
1079     } else
1080         PL_UNLOCK;
1081 }
1082
1083 void PLModel::popupStream()
1084 {
1085     QStringList mrls = selectedURIs();
1086     if( !mrls.isEmpty() )
1087         THEDP->streamingDialog( NULL, mrls[0], false );
1088
1089 }
1090
1091 void PLModel::popupSave()
1092 {
1093     QStringList mrls = selectedURIs();
1094     if( !mrls.isEmpty() )
1095         THEDP->streamingDialog( NULL, mrls[0] );
1096 }
1097
1098 #include <QUrl>
1099 #include <QFileInfo>
1100 #include <QDesktopServices>
1101 void PLModel::popupExplore()
1102 {
1103     PL_LOCK;
1104     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1105                                                     i_popup_item );
1106     if( p_item )
1107     {
1108        input_item_t *p_input = p_item->p_input;
1109        char *psz_meta = input_item_GetURI( p_input );
1110        PL_UNLOCK;
1111        if( psz_meta )
1112        {
1113            const char *psz_access;
1114            const char *psz_demux;
1115            char  *psz_path;
1116            input_SplitMRL( &psz_access, &psz_demux, &psz_path, psz_meta );
1117
1118            if( EMPTY_STR( psz_access ) ||
1119                !strncasecmp( psz_access, "file", 4 ) ||
1120                !strncasecmp( psz_access, "dire", 4 ) )
1121            {
1122                QFileInfo info( qfu( psz_meta ) );
1123                QDesktopServices::openUrl(
1124                                QUrl::fromLocalFile( info.absolutePath() ) );
1125            }
1126            free( psz_meta );
1127        }
1128     }
1129     else
1130         PL_UNLOCK;
1131 }
1132
1133 #include <QInputDialog>
1134 void PLModel::popupAddNode()
1135 {
1136     bool ok;
1137     QString name = QInputDialog::getText( PlaylistDialog::getInstance( p_intf ),
1138         qtr( I_POP_ADD ), qtr( "Enter name for new node:" ),
1139         QLineEdit::Normal, QString(), &ok);
1140     if( !ok || name.isEmpty() ) return;
1141     PL_LOCK;
1142     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1143                                                     i_popup_item );
1144     if( p_item )
1145     {
1146         playlist_NodeCreate( p_playlist, qtu( name ), p_item, 0, NULL );
1147     }
1148     PL_UNLOCK;
1149 }
1150
1151 void PLModel::popupSortAsc()
1152 {
1153     sort( i_popup_item, i_popup_column, Qt::AscendingOrder );
1154 }
1155
1156 void PLModel::popupSortDesc()
1157 {
1158     sort( i_popup_item, i_popup_column, Qt::DescendingOrder );
1159 }
1160 /**********************************************************************
1161  * Playlist callbacks
1162  **********************************************************************/
1163 static int PlaylistChanged( 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( PLUpdate_Type, 0 );
1168     QApplication::postEvent( p_model, event );
1169     return VLC_SUCCESS;
1170 }
1171
1172 static int PlaylistNext( 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     PLEvent *event = new PLEvent( ItemUpdate_Type, oval.i_int );
1177     QApplication::postEvent( p_model, event );
1178     event = new PLEvent( ItemUpdate_Type, nval.i_int );
1179     QApplication::postEvent( p_model, event );
1180     return VLC_SUCCESS;
1181 }
1182
1183 static int ItemDeleted( vlc_object_t *p_this, const char *psz_variable,
1184                         vlc_value_t oval, vlc_value_t nval, void *param )
1185 {
1186     PLModel *p_model = (PLModel *) param;
1187     PLEvent *event = new PLEvent( ItemDelete_Type, nval.i_int );
1188     QApplication::postEvent( p_model, event );
1189     return VLC_SUCCESS;
1190 }
1191
1192 static int ItemAppended( vlc_object_t *p_this, const char *psz_variable,
1193                          vlc_value_t oval, vlc_value_t nval, void *param )
1194 {
1195     PLModel *p_model = (PLModel *) param;
1196     const playlist_add_t *p_add = (playlist_add_t *)nval.p_address;
1197     PLEvent *event = new PLEvent( p_add );
1198     QApplication::postEvent( p_model, event );
1199     return VLC_SUCCESS;
1200 }
1201