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