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