]> git.sesse.net Git - vlc/blob - modules/gui/qt4/components/playlist/playlist_model.cpp
Qt, playlist: Move getMeta helper functions to PLModel
[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  *          Jakob Leben <jleben@videolan.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include "qt4.hpp"
31 #include "components/playlist/playlist_model.hpp"
32 #include "dialogs_provider.hpp"                         /* THEDP */
33 #include "input_manager.hpp"                            /* THEMIM */
34 #include "dialogs/mediainfo.hpp"                        /* MediaInfo Dialog */
35 #include "dialogs/playlist.hpp"                         /* Playlist Dialog */
36
37 #include <vlc_intf_strings.h>                           /* I_DIR */
38
39 #include "pixmaps/types/type_unknown.xpm"
40 #include "sorting.h"
41
42 #include <assert.h>
43 #include <QIcon>
44 #include <QFont>
45 #include <QMenu>
46 #include <QUrl>
47 #include <QFileInfo>
48 #include <QDesktopServices>
49 #include <QInputDialog>
50 #include <QSignalMapper>
51 #include <QPixmapCache>
52
53 #define I_NEW_DIR \
54     I_DIR_OR_FOLDER( N_("Create Directory"), N_( "Create Folder" ) )
55 #define I_NEW_DIR_NAME \
56     I_DIR_OR_FOLDER( N_( "Enter name for new directory:" ), \
57                      N_( "Enter name for new folder:" ) )
58
59 QIcon PLModel::icons[ITEM_TYPE_NUMBER];
60
61 /*************************************************************************
62  * Playlist model implementation
63  *************************************************************************/
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                   QObject *parent )         /* Basic Qt parent */
69                   : QAbstractItemModel( parent )
70 {
71     p_intf            = _p_intf;
72     p_playlist        = _p_playlist;
73     i_cached_id       = -1;
74     i_cached_input_id = -1;
75     i_popup_item      = i_popup_parent = -1;
76     sortingMenu       = NULL;
77
78     rootItem          = NULL; /* PLItem rootItem, will be set in rebuild( ) */
79
80     /* Icons initialization */
81 #define ADD_ICON(type, x) icons[ITEM_TYPE_##type] = QIcon( x )
82     ADD_ICON( UNKNOWN , type_unknown_xpm );
83     ADD_ICON( FILE, ":/type/file" );
84     ADD_ICON( DIRECTORY, ":/type/directory" );
85     ADD_ICON( DISC, ":/type/disc" );
86     ADD_ICON( CDDA, ":/type/cdda" );
87     ADD_ICON( CARD, ":/type/capture-card" );
88     ADD_ICON( NET, ":/type/net" );
89     ADD_ICON( PLAYLIST, ":/type/playlist" );
90     ADD_ICON( NODE, ":/type/node" );
91 #undef ADD_ICON
92
93     rebuild( p_root );
94     DCONNECT( THEMIM->getIM(), metaChanged( input_item_t *),
95               this, processInputItemUpdate( input_item_t *) );
96     DCONNECT( THEMIM, inputChanged( input_thread_t * ),
97               this, processInputItemUpdate( input_thread_t* ) );
98     CONNECT( THEMIM, playlistItemAppended( int, int ),
99              this, processItemAppend( int, int ) );
100     CONNECT( THEMIM, playlistItemRemoved( int ),
101              this, processItemRemoval( int ) );
102 }
103
104 PLModel::~PLModel()
105 {
106     delete rootItem;
107     delete sortingMenu;
108 }
109
110 Qt::DropActions PLModel::supportedDropActions() const
111 {
112     return Qt::CopyAction | Qt::MoveAction;
113 }
114
115 Qt::ItemFlags PLModel::flags( const QModelIndex &index ) const
116 {
117     Qt::ItemFlags flags = QAbstractItemModel::flags( index );
118
119     const PLItem *item = index.isValid() ? getItem( index ) : rootItem;
120
121     if( canEdit() )
122     {
123         PL_LOCK;
124         playlist_item_t *plItem =
125             playlist_ItemGetById( p_playlist, item->i_id );
126
127         if ( plItem && ( plItem->i_children > -1 ) )
128             flags |= Qt::ItemIsDropEnabled;
129
130         PL_UNLOCK;
131
132     }
133     flags |= Qt::ItemIsDragEnabled;
134
135     return flags;
136 }
137
138 QStringList PLModel::mimeTypes() const
139 {
140     QStringList types;
141     types << "vlc/qt-input-items";
142     return types;
143 }
144
145 bool modelIndexLessThen( const QModelIndex &i1, const QModelIndex &i2 )
146 {
147     if( !i1.isValid() || !i2.isValid() ) return false;
148     PLItem *item1 = static_cast<PLItem*>( i1.internalPointer() );
149     PLItem *item2 = static_cast<PLItem*>( i2.internalPointer() );
150     if( item1->parent() == item2->parent() ) return i1.row() < i2.row();
151     else return *item1 < *item2;
152 }
153
154 QMimeData *PLModel::mimeData( const QModelIndexList &indexes ) const
155 {
156     PlMimeData *plMimeData = new PlMimeData();
157     QModelIndexList list;
158
159     foreach( const QModelIndex &index, indexes ) {
160         if( index.isValid() && index.column() == 0 )
161             list.append(index);
162     }
163
164     qSort(list.begin(), list.end(), modelIndexLessThen);
165
166     PLItem *item = NULL;
167     foreach( const QModelIndex &index, list ) {
168         if( item )
169         {
170             PLItem *testee = getItem( index );
171             while( testee->parent() )
172             {
173                 if( testee->parent() == item ||
174                     testee->parent() == item->parent() ) break;
175                 testee = testee->parent();
176             }
177             if( testee->parent() == item ) continue;
178             item = getItem( index );
179         }
180         else
181             item = getItem( index );
182
183         plMimeData->appendItem( item->p_input );
184     }
185
186     return plMimeData;
187 }
188
189 /* Drop operation */
190 bool PLModel::dropMimeData( const QMimeData *data, Qt::DropAction action,
191         int row, int column, const QModelIndex &parent )
192 {
193     bool copy = action == Qt::CopyAction;
194     if( !copy && action != Qt::MoveAction )
195         return true;
196
197     const PlMimeData *plMimeData = qobject_cast<const PlMimeData*>( data );
198     if( plMimeData )
199     {
200         if( copy )
201             dropAppendCopy( plMimeData, getItem( parent ), row );
202         else
203             dropMove( plMimeData, getItem( parent ), row );
204     }
205     return true;
206 }
207
208 void PLModel::dropAppendCopy( const PlMimeData *plMimeData, PLItem *target, int pos )
209 {
210     PL_LOCK;
211
212     playlist_item_t *p_parent =
213         playlist_ItemGetByInput( p_playlist, target->p_input );
214     if( !p_parent ) return;
215
216     if( pos == -1 ) pos = PLAYLIST_END;
217
218     QList<input_item_t*> inputItems = plMimeData->inputItems();
219
220     foreach( input_item_t* p_input, inputItems )
221     {
222         playlist_item_t *p_item = playlist_ItemGetByInput( p_playlist, p_input );
223         if( !p_item ) continue;
224         pos = playlist_NodeAddCopy( p_playlist, p_item, p_parent, pos );
225     }
226
227     PL_UNLOCK;
228 }
229
230 void PLModel::dropMove( const PlMimeData * plMimeData, PLItem *target, int row )
231 {
232     QList<input_item_t*> inputItems = plMimeData->inputItems();
233     QList<PLItem*> model_items;
234     playlist_item_t *pp_items[inputItems.size()];
235
236     PL_LOCK;
237
238     playlist_item_t *p_parent =
239         playlist_ItemGetByInput( p_playlist, target->p_input );
240
241     if( !p_parent || row > p_parent->i_children )
242     {
243         PL_UNLOCK; return;
244     }
245
246     int new_pos = row == -1 ? p_parent->i_children : row;
247     int model_pos = new_pos;
248     int i = 0;
249
250     foreach( input_item_t *p_input, inputItems )
251     {
252         playlist_item_t *p_item = playlist_ItemGetByInput( p_playlist, p_input );
253         if( !p_item ) continue;
254
255         PLItem *item = findByInput( rootItem, p_input->i_id );
256         if( !item ) continue;
257
258         /* Better not try to move a node into itself.
259            Abort the whole operation in that case,
260            because it is ambiguous. */
261         PLItem *climber = target;
262         while( climber )
263         {
264             if( climber == item )
265             {
266                 PL_UNLOCK; return;
267             }
268             climber = climber->parentItem;
269         }
270
271         if( item->parentItem == target &&
272             target->children.indexOf( item ) < new_pos )
273             model_pos--;
274
275         model_items.append( item );
276         pp_items[i] = p_item;
277         i++;
278     }
279
280     if( model_items.isEmpty() )
281     {
282         PL_UNLOCK; return;
283     }
284
285     playlist_TreeMoveMany( p_playlist, i, pp_items, p_parent, new_pos );
286
287     PL_UNLOCK;
288
289     foreach( PLItem *item, model_items )
290         takeItem( item );
291
292     insertChildren( target, model_items, model_pos );
293 }
294
295 /* remove item with its id */
296 void PLModel::removeItem( int i_id )
297 {
298     PLItem *item = findById( rootItem, i_id );
299     removeItem( item );
300 }
301
302 void PLModel::activateItem( const QModelIndex &index )
303 {
304     assert( index.isValid() );
305     const PLItem *item = getItem( index );
306     assert( item );
307     PL_LOCK;
308     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, item->i_id );
309     activateItem( p_item );
310     PL_UNLOCK;
311 }
312
313 /* Must be entered with lock */
314 void PLModel::activateItem( playlist_item_t *p_item )
315 {
316     if( !p_item ) return;
317     playlist_item_t *p_parent = p_item;
318     while( p_parent )
319     {
320         if( p_parent->i_id == rootItem->i_id ) break;
321         p_parent = p_parent->p_parent;
322     }
323     if( p_parent )
324         playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, pl_Locked,
325                 p_parent, p_item );
326 }
327
328 /****************** Base model mandatory implementations *****************/
329 QVariant PLModel::data( const QModelIndex &index, const int role ) const
330 {
331     if( !index.isValid() ) return QVariant();
332     const PLItem *item = getItem( index );
333     if( role == Qt::DisplayRole )
334     {
335         int metadata = columnToMeta( index.column() );
336         if( metadata == COLUMN_END ) return QVariant();
337
338         QString returninfo;
339         if( metadata == COLUMN_NUMBER )
340             returninfo = QString::number( index.row() + 1 );
341         else
342         {
343             char *psz = psz_column_meta( item->p_input, metadata );
344             returninfo = qfu( psz );
345             free( psz );
346         }
347         return QVariant( returninfo );
348     }
349     else if( role == Qt::DecorationRole && index.column() == 0  )
350     {
351         /* Used to segfault here because i_type wasn't always initialized */
352         return QVariant( PLModel::icons[item->p_input->i_type] );
353     }
354     else if( role == Qt::FontRole )
355     {
356         QFont f;
357         f.setPointSize( f.pointSize() - 1 );
358         if( isCurrent( index ) )
359             f.setBold( true );
360         return QVariant( f );
361     }
362     else if( role == Qt::BackgroundRole && isCurrent( index ) )
363     {
364         return QVariant( QBrush( Qt::gray ) );
365     }
366     else if( role == IsCurrentRole ) return QVariant( isCurrent( index ) );
367     else if( role == IsLeafNodeRole )
368     {
369         QVariant isLeaf;
370         PL_LOCK;
371         playlist_item_t *plItem =
372             playlist_ItemGetById( p_playlist, item->i_id );
373
374         if( plItem )
375             isLeaf = plItem->i_children == -1;
376
377         PL_UNLOCK;
378         return isLeaf;
379     }
380     else if( role == IsCurrentsParentNodeRole )
381     {
382         return QVariant( isParent( index, currentIndex() ) );
383     }
384     return QVariant();
385 }
386
387 /* Seek from current index toward the top and see if index is one of parent nodes */
388 bool PLModel::isParent( const QModelIndex &index, const QModelIndex &current ) const
389 {
390     if( !index.isValid() )
391         return false;
392
393     if( index == current )
394         return true;
395
396     if( !current.isValid() || !current.parent().isValid() )
397         return false;
398
399     return isParent( index, current.parent() );
400 }
401
402 bool PLModel::isCurrent( const QModelIndex &index ) const
403 {
404     return getItem( index )->p_input == THEMIM->currentInputItem();
405 }
406
407 int PLModel::itemId( const QModelIndex &index ) const
408 {
409     return getItem( index )->i_id;
410 }
411
412 QVariant PLModel::headerData( int section, Qt::Orientation orientation,
413                               int role ) const
414 {
415     if (orientation != Qt::Horizontal || role != Qt::DisplayRole)
416         return QVariant();
417
418     int meta_col = columnToMeta( section );
419
420     if( meta_col == COLUMN_END ) return QVariant();
421
422     return QVariant( qfu( psz_column_title( meta_col ) ) );
423 }
424
425 QModelIndex PLModel::index( const int row, const int column, const QModelIndex &parent )
426                   const
427 {
428     PLItem *parentItem = parent.isValid() ? getItem( parent ) : rootItem;
429
430     PLItem *childItem = parentItem->child( row );
431     if( childItem )
432         return createIndex( row, column, childItem );
433     else
434         return QModelIndex();
435 }
436
437 QModelIndex PLModel::index( const int i_id, const int c )
438 {
439     return index( findById( rootItem, i_id ), c );
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::currentIndex() const
454 {
455     input_thread_t *p_input_thread = THEMIM->getInput();
456     if( !p_input_thread ) return QModelIndex();
457     PLItem *item = findByInput( rootItem, input_GetItem( p_input_thread )->i_id );
458     return index( item, 0 );
459 }
460
461 QModelIndex PLModel::parent( const QModelIndex &index ) const
462 {
463     if( !index.isValid() ) return QModelIndex();
464
465     PLItem *childItem = getItem( index );
466     if( !childItem )
467     {
468         msg_Err( p_playlist, "NULL CHILD" );
469         return QModelIndex();
470     }
471
472     PLItem *parentItem = childItem->parent();
473     if( !parentItem || parentItem == rootItem ) return QModelIndex();
474     if( !parentItem->parentItem )
475     {
476         msg_Err( p_playlist, "No parent parent, trying row 0 " );
477         msg_Err( p_playlist, "----- PLEASE REPORT THIS ------" );
478         return createIndex( 0, 0, parentItem );
479     }
480     return createIndex(parentItem->row(), 0, parentItem);
481 }
482
483 int PLModel::columnCount( const QModelIndex &i) const
484 {
485     return columnFromMeta( COLUMN_END );
486 }
487
488 int PLModel::rowCount( const QModelIndex &parent ) const
489 {
490     const PLItem *parentItem = parent.isValid() ? getItem( parent ) : rootItem;
491     return parentItem->childCount();
492 }
493
494 QStringList PLModel::selectedURIs()
495 {
496     QStringList lst;
497     for( int i = 0; i < current_selection.size(); i++ )
498     {
499         const PLItem *item = getItem( current_selection[i] );
500         if( item )
501         {
502             PL_LOCK;
503             playlist_item_t *p_item = playlist_ItemGetById( p_playlist, item->i_id );
504             if( p_item )
505             {
506                 char *psz = input_item_GetURI( p_item->p_input );
507                 if( psz )
508                 {
509                     lst.append( qfu(psz) );
510                     free( psz );
511                 }
512             }
513             PL_UNLOCK;
514         }
515     }
516     return lst;
517 }
518
519 /************************* Lookups *****************************/
520 PLItem *PLModel::findById( PLItem *root, int i_id ) const
521 {
522     return findInner( root, i_id, false );
523 }
524
525 PLItem *PLModel::findByInput( PLItem *root, int i_id ) const
526 {
527     PLItem *result = findInner( root, i_id, true );
528     return result;
529 }
530
531 PLItem * PLModel::findInner( PLItem *root, int i_id, bool b_input ) const
532 {
533     if( !root ) return NULL;
534
535     if( !b_input && root->i_id == i_id )
536         return root;
537
538     else if( b_input && root->p_input->i_id == i_id )
539         return root;
540
541     QList<PLItem *>::iterator it = root->children.begin();
542     while ( it != root->children.end() )
543     {
544         if( !b_input && (*it)->i_id == i_id )
545             return (*it);
546
547         else if( b_input && (*it)->p_input->i_id == i_id )
548             return (*it);
549
550         if( (*it)->children.size() )
551         {
552             PLItem *childFound = findInner( (*it), i_id, b_input );
553             if( childFound )
554                 return childFound;
555         }
556         it++;
557     }
558     return NULL;
559 }
560
561 int PLModel::columnToMeta( int _column )
562 {
563     int meta = 1;
564     int column = 0;
565
566     while( column != _column && meta != COLUMN_END )
567     {
568         meta <<= 1;
569         column++;
570     }
571
572     return meta;
573 }
574
575 int PLModel::columnFromMeta( int meta_col )
576 {
577     int meta = 1;
578     int column = 0;
579
580     while( meta != meta_col && meta != COLUMN_END )
581     {
582         meta <<= 1;
583         column++;
584     }
585
586     return column;
587 }
588
589 bool PLModel::canEdit() const
590 {
591     return (
592             rootItem != NULL &&
593             (
594              rootItem->p_input == p_playlist->p_playing->p_input ||
595              ( p_playlist->p_media_library &&
596               rootItem->p_input == p_playlist->p_media_library->p_input )
597             )
598            );
599 }
600
601 QString PLModel::getMeta( const QModelIndex & index, int meta )
602 {
603     return index.model()->index( index.row(),
604                                   PLModel::columnFromMeta( meta ),
605                                   index.parent() )
606                                 .data().toString();
607 }
608
609 QPixmap PLModel::getArtPixmap( const QModelIndex & index, const QSize & size )
610 {
611     PLItem *item = static_cast<PLItem*>( index.internalPointer() );
612     assert( item );
613
614     QString artUrl = InputManager::decodeArtURL( item->inputItem() );
615
616     /* If empty, take one of the children art URL */
617     if( artUrl.isEmpty() )
618     {
619         for( int i = 0; i < item->childCount(); i++ )
620         {
621             artUrl = InputManager::decodeArtURL( item->child( i )->inputItem() );
622             if( !artUrl.isEmpty() )
623                 break;
624         }
625     }
626
627     QPixmap artPix;
628     QString key = artUrl + QString("%1%2").arg(size.width()).arg(size.height());
629
630     /* Lookup in the QPixmapCache */
631     if( !QPixmapCache::find( key, artPix ))
632     {
633         if( artUrl.isEmpty() || !artPix.load( artUrl ) )
634         {
635             key = QString("noart%1%2").arg(size.width()).arg(size.height());
636             if( !QPixmapCache::find( key, artPix ) )
637             {
638                 artPix = QPixmap( ":/noart" ).scaled( size,
639                                                       Qt::KeepAspectRatio,
640                                                       Qt::SmoothTransformation );
641                 QPixmapCache::insert( key, artPix );
642             }
643         }
644         else
645         {
646             artPix = artPix.scaled( size, Qt::KeepAspectRatio, Qt::SmoothTransformation );
647             QPixmapCache::insert( key, artPix );
648         }
649     }
650
651     return artPix;
652 }
653 /************************* Updates handling *****************************/
654
655 /**** Events processing ****/
656 void PLModel::processInputItemUpdate( input_thread_t *p_input )
657 {
658     if( !p_input ) return;
659     if( p_input && !( p_input->b_dead || !vlc_object_alive( p_input ) ) )
660     {
661         PLItem *item = findByInput( rootItem, input_GetItem( p_input )->i_id );
662         if( item ) emit currentChanged( index( item, 0 ) );
663     }
664     processInputItemUpdate( input_GetItem( p_input ) );
665 }
666
667 void PLModel::processInputItemUpdate( input_item_t *p_item )
668 {
669     if( !p_item ||  p_item->i_id <= 0 ) return;
670     PLItem *item = findByInput( rootItem, p_item->i_id );
671     if( item )
672         updateTreeItem( item );
673 }
674
675 void PLModel::processItemRemoval( int i_id )
676 {
677     if( i_id <= 0 ) return;
678     removeItem( i_id );
679 }
680
681 void PLModel::processItemAppend( int i_item, int i_parent )
682 {
683     playlist_item_t *p_item = NULL;
684     PLItem *newItem = NULL;
685     input_thread_t *currentInputThread;
686     int pos;
687
688     PLItem *nodeItem = findById( rootItem, i_parent );
689     if( !nodeItem ) return;
690
691     foreach( const PLItem *existing, nodeItem->children )
692         if( existing->i_id == i_item ) return;
693
694     PL_LOCK;
695     p_item = playlist_ItemGetById( p_playlist, i_item );
696     if( !p_item || p_item->i_flags & PLAYLIST_DBL_FLAG )
697     {
698         PL_UNLOCK; return;
699     }
700
701     for( pos = 0; pos < p_item->p_parent->i_children; pos++ )
702         if( p_item->p_parent->pp_children[pos] == p_item ) break;
703
704     newItem = new PLItem( p_item, nodeItem );
705     PL_UNLOCK;
706
707     beginInsertRows( index( nodeItem, 0 ), pos, pos );
708     nodeItem->insertChild( newItem, pos );
709     endInsertRows();
710
711     if( newItem->p_input == THEMIM->currentInputItem() )
712         emit currentChanged( index( newItem, 0 ) );
713 }
714
715 void PLModel::rebuild()
716 {
717     rebuild( NULL );
718 }
719
720 void PLModel::rebuild( playlist_item_t *p_root )
721 {
722     playlist_item_t* p_item;
723
724     /* Invalidate cache */
725     i_cached_id = i_cached_input_id = -1;
726
727     if( rootItem ) rootItem->removeChildren();
728
729     PL_LOCK;
730     if( p_root )
731     {
732         delete rootItem;
733         rootItem = new PLItem( p_root );
734     }
735     assert( rootItem );
736     /* Recreate from root */
737     updateChildren( rootItem );
738     PL_UNLOCK;
739
740     /* And signal the view */
741     reset();
742
743     if( p_root ) emit rootChanged();
744 }
745
746 void PLModel::takeItem( PLItem *item )
747 {
748     assert( item );
749     PLItem *parent = item->parentItem;
750     assert( parent );
751     int i_index = parent->children.indexOf( item );
752
753     beginRemoveRows( index( parent, 0 ), i_index, i_index );
754     parent->takeChildAt( i_index );
755     endRemoveRows();
756 }
757
758 void PLModel::insertChildren( PLItem *node, QList<PLItem*>& items, int i_pos )
759 {
760     assert( node );
761     int count = items.size();
762     if( !count ) return;
763     beginInsertRows( index( node, 0 ), i_pos, i_pos + count - 1 );
764     for( int i = 0; i < count; i++ )
765     {
766         node->children.insert( i_pos + i, items[i] );
767         items[i]->parentItem = node;
768     }
769     endInsertRows();
770 }
771
772 void PLModel::removeItem( PLItem *item )
773 {
774     if( !item ) return;
775
776     i_cached_id = -1;
777     i_cached_input_id = -1;
778
779     if( item->parentItem ) {
780         int i = item->parentItem->children.indexOf( item );
781         beginRemoveRows( index( item->parentItem, 0), i, i );
782         item->parentItem->children.removeAt(i);
783         delete item;
784         endRemoveRows();
785     }
786     else delete item;
787
788     if(item == rootItem)
789     {
790         rootItem = NULL;
791         rebuild( p_playlist->p_playing );
792     }
793 }
794
795 /* This function must be entered WITH the playlist lock */
796 void PLModel::updateChildren( PLItem *root )
797 {
798     playlist_item_t *p_node = playlist_ItemGetById( p_playlist, root->i_id );
799     updateChildren( p_node, root );
800 }
801
802 /* This function must be entered WITH the playlist lock */
803 void PLModel::updateChildren( 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         root->appendChild( newItem );
810         if( p_node->pp_children[i]->i_children != -1 )
811             updateChildren( p_node->pp_children[i], newItem );
812     }
813 }
814
815 /* Function doesn't need playlist-lock, as we don't touch playlist_item_t stuff here*/
816 void PLModel::updateTreeItem( PLItem *item )
817 {
818     if( !item ) return;
819     emit dataChanged( index( item, 0 ) , index( item, columnCount( QModelIndex() ) ) );
820 }
821
822 /************************* Actions ******************************/
823
824 /**
825  * Deletion, don't delete items childrens if item is going to be
826  * delete allready, so we remove childrens from selection-list.
827  */
828 void PLModel::doDelete( QModelIndexList selected )
829 {
830     if( !canEdit() ) return;
831
832     while( !selected.isEmpty() )
833     {
834         QModelIndex index = selected[0];
835         selected.removeAt( 0 );
836
837         if( index.column() != 0 ) continue;
838
839         PLItem *item = getItem( index );
840         if( item->children.size() )
841             recurseDelete( item->children, &selected );
842
843         PL_LOCK;
844         playlist_DeleteFromInput( p_playlist, item->p_input, pl_Locked );
845         PL_UNLOCK;
846
847         removeItem( item );
848     }
849 }
850
851 void PLModel::recurseDelete( QList<PLItem*> children, QModelIndexList *fullList )
852 {
853     for( int i = children.size() - 1; i >= 0 ; i-- )
854     {
855         PLItem *item = children[i];
856         if( item->children.size() )
857             recurseDelete( item->children, fullList );
858         fullList->removeAll( index( item, 0 ) );
859     }
860 }
861
862 /******* Volume III: Sorting and searching ********/
863 void PLModel::sort( const int column, Qt::SortOrder order )
864 {
865     sort( rootItem->i_id, column, order );
866 }
867
868 void PLModel::sort( const int i_root_id, const int column, Qt::SortOrder order )
869 {
870     msg_Dbg( p_intf, "Sorting by column %i, order %i", column, order );
871
872     int meta = columnToMeta( column );
873     if( meta == COLUMN_END ) return;
874
875     PLItem *item = findById( rootItem, i_root_id );
876     if( !item ) return;
877     QModelIndex qIndex = index( item, 0 );
878     int count = item->children.size();
879     if( count )
880     {
881         beginRemoveRows( qIndex, 0, count - 1 );
882         item->removeChildren();
883         endRemoveRows( );
884     }
885
886     PL_LOCK;
887     {
888         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
889                                                         i_root_id );
890         if( p_root )
891         {
892             playlist_RecursiveNodeSort( p_playlist, p_root,
893                                         i_column_sorting( meta ),
894                                         order == Qt::AscendingOrder ?
895                                             ORDER_NORMAL : ORDER_REVERSE );
896         }
897     }
898
899     i_cached_id = i_cached_input_id = -1;
900
901     if( count )
902     {
903         beginInsertRows( qIndex, 0, count - 1 );
904         updateChildren( item );
905         endInsertRows( );
906     }
907     PL_UNLOCK;
908     /* if we have popup item, try to make sure that you keep that item visible */
909     if( i_popup_item > -1 )
910     {
911         PLItem *popupitem = findById( rootItem, i_popup_item );
912         if( popupitem ) emit currentChanged( index( popupitem, 0 ) );
913         /* reset i_popup_item as we don't show it as selected anymore anyway */
914         i_popup_item = -1;
915     }
916     else if( currentIndex().isValid() ) emit currentChanged( currentIndex() );
917 }
918
919 void PLModel::search( const QString& search_text, const QModelIndex & idx, bool b_recursive )
920 {
921     /** \todo Fire the search with a small delay ? */
922     PL_LOCK;
923     {
924         playlist_item_t *p_root = playlist_ItemGetById( p_playlist,
925                                                         itemId( idx ) );
926         assert( p_root );
927         const char *psz_name = qtu( search_text );
928         playlist_LiveSearchUpdate( p_playlist , p_root, psz_name, b_recursive );
929
930         if( idx.isValid() )
931         {
932             PLItem *searchRoot = getItem( idx );
933
934             beginRemoveRows( idx, 0, searchRoot->children.size() - 1 );
935             searchRoot->removeChildren();
936             endRemoveRows( );
937
938             beginInsertRows( idx, 0, searchRoot->children.size() - 1 );
939             updateChildren( searchRoot ); // The PL_LOCK is needed here
940             endInsertRows();
941
942             PL_UNLOCK;
943             return;
944         }
945     }
946     PL_UNLOCK;
947     rebuild();
948 }
949
950 /*********** Popup *********/
951 bool PLModel::popup( const QModelIndex & index, const QPoint &point, const QModelIndexList &list )
952 {
953     int i_id = index.isValid() ? itemId( index ) : rootItem->i_id;
954
955     PL_LOCK;
956     playlist_item_t *p_item = playlist_ItemGetById( p_playlist, i_id );
957     if( !p_item )
958     {
959         PL_UNLOCK;
960         return false;
961     }
962
963     input_item_t *p_input = p_item->p_input;
964     vlc_gc_incref( p_input );
965
966     i_popup_item = index.isValid() ? p_item->i_id : -1;
967     i_popup_parent = index.isValid() ?
968         ( p_item->p_parent ? p_item->p_parent->i_id : -1 ) :
969         ( rootItem->i_id );
970     i_popup_column = index.column();
971
972     bool tree = ( rootItem && rootItem->i_id != p_playlist->p_playing->i_id ) ||
973                 var_InheritBool( p_intf, "playlist-tree" );
974
975     PL_UNLOCK;
976
977     current_selection = list;
978
979     QMenu menu;
980     if( i_popup_item > -1 )
981     {
982         menu.addAction( QIcon( ":/menu/play" ), qtr(I_POP_PLAY), this, SLOT( popupPlay() ) );
983         menu.addAction( QIcon( ":/menu/stream" ),
984                         qtr(I_POP_STREAM), this, SLOT( popupStream() ) );
985         menu.addAction( qtr(I_POP_SAVE), this, SLOT( popupSave() ) );
986         menu.addAction( QIcon( ":/menu/info" ), qtr(I_POP_INFO), this, SLOT( popupInfo() ) );
987         if( !strncasecmp( p_input->psz_uri, "file://", 7 ) )
988             menu.addAction( QIcon( ":/type/folder-grey" ),
989                             qtr( I_POP_EXPLORE ), this, SLOT( popupExplore() ) );
990         menu.addSeparator();
991     }
992     if( canEdit() )
993     {
994         QIcon addIcon( ":/buttons/playlist/playlist_add" );
995         menu.addSeparator();
996         if( tree ) menu.addAction( addIcon, qtr(I_POP_NEWFOLDER), this, SLOT( popupAddNode() ) );
997         if( rootItem->i_id == THEPL->p_playing->i_id )
998         {
999             menu.addAction( addIcon, qtr(I_PL_ADDF), THEDP, SLOT( simplePLAppendDialog()) );
1000             menu.addAction( addIcon, qtr(I_PL_ADDDIR), THEDP, SLOT( PLAppendDir()) );
1001             menu.addAction( addIcon, qtr(I_OP_ADVOP), THEDP, SLOT( PLAppendDialog()) );
1002         }
1003         else if( THEPL->p_media_library &&
1004                     rootItem->i_id == THEPL->p_media_library->i_id )
1005         {
1006             menu.addAction( addIcon, qtr(I_PL_ADDF), THEDP, SLOT( simpleMLAppendDialog()) );
1007             menu.addAction( addIcon, qtr(I_PL_ADDDIR), THEDP, SLOT( MLAppendDir() ) );
1008             menu.addAction( addIcon, qtr(I_OP_ADVOP), THEDP, SLOT( MLAppendDialog() ) );
1009         }
1010     }
1011     if( i_popup_item > -1 )
1012     {
1013         menu.addAction( QIcon( ":/buttons/playlist/playlist_remove" ),
1014                         qtr(I_POP_DEL), this, SLOT( popupDel() ) );
1015         menu.addSeparator();
1016         if( !sortingMenu )
1017         {
1018             sortingMenu = new QMenu( qtr( "Sort by" ) );
1019             sortingMapper = new QSignalMapper( this );
1020             int i, j;
1021             for( i = 1, j = 1; i < COLUMN_END; i <<= 1, j++ )
1022             {
1023                 if( i == COLUMN_NUMBER ) continue;
1024                 QMenu *m = sortingMenu->addMenu( qfu( psz_column_title( i ) ) );
1025                 QAction *asc = m->addAction( qtr("Ascending") );
1026                 QAction *desc = m->addAction( qtr("Descending") );
1027                 sortingMapper->setMapping( asc, j );
1028                 sortingMapper->setMapping( desc, -j );
1029                 CONNECT( asc, triggered(), sortingMapper, map() );
1030                 CONNECT( desc, triggered(), sortingMapper, map() );
1031             }
1032             CONNECT( sortingMapper, mapped( int ), this, popupSort( int ) );
1033         }
1034         menu.addMenu( sortingMenu );
1035     }
1036     vlc_gc_decref( p_input );
1037
1038     if( !menu.isEmpty() )
1039     {
1040         menu.exec( point ); return true;
1041     }
1042     else return false;
1043 }
1044
1045 void PLModel::popupDel()
1046 {
1047     doDelete( current_selection );
1048 }
1049
1050 void PLModel::popupPlay()
1051 {
1052     PL_LOCK;
1053     {
1054         playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1055                                                         i_popup_item );
1056         activateItem( p_item );
1057     }
1058     PL_UNLOCK;
1059 }
1060
1061 void PLModel::popupInfo()
1062 {
1063     PL_LOCK;
1064     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1065                                                     i_popup_item );
1066     if( p_item )
1067     {
1068         input_item_t* p_input = p_item->p_input;
1069         vlc_gc_incref( p_input );
1070         PL_UNLOCK;
1071         MediaInfoDialog *mid = new MediaInfoDialog( p_intf, p_input );
1072         vlc_gc_decref( p_input );
1073         mid->setParent( PlaylistDialog::getInstance( p_intf ),
1074                         Qt::Dialog );
1075         mid->show();
1076     } else
1077         PL_UNLOCK;
1078 }
1079
1080 void PLModel::popupStream()
1081 {
1082     QStringList mrls = selectedURIs();
1083     if( !mrls.isEmpty() )
1084         THEDP->streamingDialog( NULL, mrls[0], false );
1085
1086 }
1087
1088 void PLModel::popupSave()
1089 {
1090     QStringList mrls = selectedURIs();
1091     if( !mrls.isEmpty() )
1092         THEDP->streamingDialog( NULL, mrls[0] );
1093 }
1094
1095 void PLModel::popupExplore()
1096 {
1097     PL_LOCK;
1098     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1099             i_popup_item );
1100     if( p_item )
1101     {
1102         input_item_t *p_input = p_item->p_input;
1103         char *psz_meta = input_item_GetURI( p_input );
1104         PL_UNLOCK;
1105         if( psz_meta )
1106         {
1107             const char *psz_access;
1108             const char *psz_demux;
1109             char  *psz_path;
1110             input_SplitMRL( &psz_access, &psz_demux, &psz_path, psz_meta );
1111
1112             if( !EMPTY_STR( psz_access ) && (
1113                    !strncasecmp( psz_access, "file", 4 ) ||
1114                    !strncasecmp( psz_access, "dire", 4 ) ))
1115             {
1116 #ifdef WIN32
1117                 /* Qt openURL doesn't know to open files that starts with a / or \ */
1118                 if( psz_path[0] == '/' || psz_path[0] == '\\'  )
1119                     psz_path++;
1120 #endif
1121
1122                 QFileInfo info( qfu( decode_URI( psz_path ) ) );
1123                 QDesktopServices::openUrl(
1124                         QUrl::fromLocalFile( info.absolutePath() ) );
1125             }
1126             free( psz_meta );
1127         }
1128     }
1129     else
1130         PL_UNLOCK;
1131 }
1132
1133 void PLModel::popupAddNode()
1134 {
1135     bool ok;
1136     QString name = QInputDialog::getText( PlaylistDialog::getInstance( p_intf ),
1137         qtr( I_NEW_DIR ), qtr( I_NEW_DIR_NAME ),
1138         QLineEdit::Normal, QString(), &ok);
1139     if( !ok || name.isEmpty() ) return;
1140
1141     PL_LOCK;
1142     playlist_item_t *p_item = playlist_ItemGetById( p_playlist,
1143                                                     i_popup_parent );
1144     if( p_item )
1145         playlist_NodeCreate( p_playlist, qtu( name ), p_item, PLAYLIST_END, 0, NULL );
1146     PL_UNLOCK;
1147 }
1148
1149 void PLModel::popupSort( int column )
1150 {
1151     sort( i_popup_parent,
1152           column > 0 ? column - 1 : -column - 1,
1153           column > 0 ? Qt::AscendingOrder : Qt::DescendingOrder );
1154 }
1155
1156 /******************* Drag and Drop helper class ******************/
1157
1158 PlMimeData::PlMimeData( )
1159 { }
1160
1161 PlMimeData::~PlMimeData()
1162 {
1163     foreach( input_item_t *p_item, _inputItems )
1164         vlc_gc_decref( p_item );
1165 }
1166
1167 void PlMimeData::appendItem( input_item_t *p_item )
1168 {
1169     vlc_gc_incref( p_item );
1170     _inputItems.append( p_item );
1171 }
1172
1173 QList<input_item_t*> PlMimeData::inputItems() const
1174 {
1175     return _inputItems;
1176 }
1177
1178 QStringList PlMimeData::formats () const
1179 {
1180     QStringList fmts;
1181     fmts << "vlc/qt-input-items";
1182     return fmts;
1183 }