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