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