]> git.sesse.net Git - vlc/blob - modules/gui/macosx/playlist.m
macosx: Use font from the Nib in the playlist.
[vlc] / modules / gui / macosx / playlist.m
1 /*****************************************************************************
2  * playlist.m: MacOS X interface module
3  *****************************************************************************
4 * Copyright (C) 2002-2008 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8  *          Derk-Jan Hartman <hartman at videola/n dot org>
9  *          Benjamin Pracht <bigben at videolab dot 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 /* TODO
27  * add 'icons' for different types of nodes? (http://www.cocoadev.com/index.pl?IconAndTextInTableCell)
28  * reimplement enable/disable item
29  * create a new 'tool' button (see the gear button in the Finder window) for 'actions'
30    (adding service discovery, other views, new node/playlist, save node/playlist) stuff like that
31  */
32
33
34 /*****************************************************************************
35  * Preamble
36  *****************************************************************************/
37 #include <stdlib.h>                                      /* malloc(), free() */
38 #include <sys/param.h>                                    /* for MAXPATHLEN */
39 #include <string.h>
40 #include <math.h>
41 #include <sys/mount.h>
42 #include <vlc_keys.h>
43
44 #import "intf.h"
45 #import "wizard.h"
46 #import "bookmarks.h"
47 #import "playlistinfo.h"
48 #import "playlist.h"
49 #import "controls.h"
50 #import "vlc_osd.h"
51 #import "misc.h"
52 #import <vlc_interface.h>
53
54 /*****************************************************************************
55  * VLCPlaylistView implementation
56  *****************************************************************************/
57 @implementation VLCPlaylistView
58
59 - (NSMenu *)menuForEvent:(NSEvent *)o_event
60 {
61     return( [[self delegate] menuForEvent: o_event] );
62 }
63
64 - (void)keyDown:(NSEvent *)o_event
65 {
66     unichar key = 0;
67
68     if( [[o_event characters] length] )
69     {
70         key = [[o_event characters] characterAtIndex: 0];
71     }
72
73     switch( key )
74     {
75         case NSDeleteCharacter:
76         case NSDeleteFunctionKey:
77         case NSDeleteCharFunctionKey:
78         case NSBackspaceCharacter:
79             [[self delegate] deleteItem:self];
80             break;
81
82         case NSEnterCharacter:
83         case NSCarriageReturnCharacter:
84             [(VLCPlaylist *)[[VLCMain sharedInstance] getPlaylist] playItem:self];
85             break;
86
87         default:
88             [super keyDown: o_event];
89             break;
90     }
91 }
92
93 @end
94
95 /*****************************************************************************
96  * VLCPlaylistCommon implementation
97  *
98  * This class the superclass of the VLCPlaylist and VLCPlaylistWizard.
99  * It contains the common methods and elements of these 2 entities.
100  *****************************************************************************/
101 @implementation VLCPlaylistCommon
102
103 - (id)init
104 {
105     self = [super init];
106     if ( self != nil )
107     {
108         o_outline_dict = [[NSMutableDictionary alloc] init];
109     }
110     return self;
111 }
112 - (void)awakeFromNib
113 {
114     playlist_t * p_playlist = pl_Yield( VLCIntf );
115     [o_outline_view setTarget: self];
116     [o_outline_view setDelegate: self];
117     [o_outline_view setDataSource: self];
118
119     vlc_object_release( p_playlist );
120     [self initStrings];
121 }
122
123 - (void)initStrings
124 {
125     [[o_tc_name headerCell] setStringValue:_NS("Name")];
126     [[o_tc_author headerCell] setStringValue:_NS("Author")];
127     [[o_tc_duration headerCell] setStringValue:_NS("Duration")];
128 }
129
130 - (NSOutlineView *)outlineView
131 {
132     return o_outline_view;
133 }
134
135 - (playlist_item_t *)selectedPlaylistItem
136 {
137     return [[o_outline_view itemAtRow: [o_outline_view selectedRow]]
138                                                                 pointerValue];
139 }
140
141 @end
142
143 @implementation VLCPlaylistCommon (NSOutlineViewDataSource)
144
145 /* return the number of children for Obj-C pointer item */ /* DONE */
146 - (int)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
147 {
148     int i_return = 0;
149     playlist_item_t *p_item = NULL;
150     playlist_t * p_playlist = pl_Yield( VLCIntf );
151     assert( outlineView == o_outline_view );
152
153     if( !item )
154         p_item = p_playlist->p_root_category;
155     else
156         p_item = (playlist_item_t *)[item pointerValue];
157
158     if( p_item )
159         i_return = p_item->i_children;
160
161     pl_Release( VLCIntf );
162
163     return i_return > 0 ? i_return : 0;
164 }
165
166 /* return the child at index for the Obj-C pointer item */ /* DONE */
167 - (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item
168 {
169     playlist_item_t *p_return = NULL, *p_item = NULL;
170     NSValue *o_value;
171     playlist_t * p_playlist = pl_Yield( VLCIntf );
172
173     if( item == nil )
174     {
175         /* root object */
176         p_item = p_playlist->p_root_category;
177     }
178     else
179     {
180         p_item = (playlist_item_t *)[item pointerValue];
181     }
182     if( p_item && index < p_item->i_children && index >= 0 )
183         p_return = p_item->pp_children[index];
184  
185     vlc_object_release( p_playlist );
186
187     o_value = [o_outline_dict objectForKey:[NSString stringWithFormat: @"%p", p_return]];
188
189     if( o_value == nil )
190     {
191         msg_Warn( VLCIntf, "playlist item misses pointer value, adding one" );
192         o_value = [[NSValue valueWithPointer: p_return] retain];
193     }
194     return o_value;
195 }
196
197 /* is the item expandable */
198 - (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
199 {
200     int i_return = 0;
201     playlist_t *p_playlist = pl_Yield( VLCIntf );
202
203     if( item == nil )
204     {
205         /* root object */
206         if( p_playlist->p_root_category )
207         {
208             i_return = p_playlist->p_root_category->i_children;
209         }
210     }
211     else
212     {
213         playlist_item_t *p_item = (playlist_item_t *)[item pointerValue];
214         if( p_item )
215             i_return = p_item->i_children;
216     }
217     vlc_object_release( p_playlist );
218
219     return (i_return > 0);
220 }
221
222 /* retrieve the string values for the cells */
223 - (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)o_tc byItem:(id)item
224 {
225     id o_value = nil;
226     playlist_item_t *p_item;
227
228     /* For error handling */
229     static BOOL attempted_reload = NO;
230
231     if( item == nil || ![item isKindOfClass: [NSValue class]] )
232     {
233         /* Attempt to fix the error by asking for a data redisplay
234          * This might cause infinite loop, so add a small check */
235         if( !attempted_reload )
236         {
237             attempted_reload = YES;
238             [outlineView reloadData];
239         }
240         return @"error" ;
241     }
242  
243     p_item = (playlist_item_t *)[item pointerValue];
244     if( !p_item || !p_item->p_input )
245     {
246         /* Attempt to fix the error by asking for a data redisplay
247          * This might cause infinite loop, so add a small check */
248         if( !attempted_reload )
249         {
250             attempted_reload = YES;
251             [outlineView reloadData];
252         }
253         return @"error";
254     }
255  
256     attempted_reload = NO;
257
258     if( [[o_tc identifier] isEqualToString:@"1"] )
259     {
260         /* sanity check to prevent the NSString class from crashing */
261         char *psz_title =  input_item_GetTitle( p_item->p_input );
262         if( !EMPTY_STR( psz_title ) )
263         {
264             o_value = [NSString stringWithUTF8String: psz_title];
265         }
266         else
267         {
268             char *psz_name = input_item_GetName( p_item->p_input );
269             if( !EMPTY_STR( psz_name ) )
270             {
271                 o_value = [NSString stringWithUTF8String: psz_name];
272             }
273             free( psz_name );
274         }
275         free( psz_title );
276     }
277     else
278     {
279         char *psz_artist = input_item_GetArtist( p_item->p_input );
280         if( [[o_tc identifier] isEqualToString:@"2"] && !EMPTY_STR( psz_artist ) )
281         {
282             o_value = [NSString stringWithUTF8String: psz_artist];
283         }
284         else if( [[o_tc identifier] isEqualToString:@"3"] )
285         {
286             char psz_duration[MSTRTIME_MAX_SIZE];
287             mtime_t dur = input_item_GetDuration( p_item->p_input );
288             if( dur != -1 )
289             {
290                 secstotimestr( psz_duration, dur/1000000 );
291                 o_value = [NSString stringWithUTF8String: psz_duration];
292             }
293             else
294             {
295                 o_value = @"--:--";
296             }
297         }
298         free( psz_artist );
299     }
300     return o_value;
301 }
302
303 @end
304
305 /*****************************************************************************
306  * VLCPlaylistWizard implementation
307  *****************************************************************************/
308 @implementation VLCPlaylistWizard
309
310 - (IBAction)reloadOutlineView
311 {
312     /* Only reload the outlineview if the wizard window is open since this can
313        be quite long on big playlists */
314     if( [[o_outline_view window] isVisible] )
315     {
316         [o_outline_view reloadData];
317     }
318 }
319
320 @end
321
322 /*****************************************************************************
323  * extension to NSOutlineView's interface to fix compilation warnings
324  * and let us access these 2 functions properly
325  * this uses a private Apple-API, but works fine on all current OSX releases
326  * keep checking for compatiblity with future releases though
327  *****************************************************************************/
328
329 @interface NSOutlineView (UndocumentedSortImages)
330 + (NSImage *)_defaultTableHeaderSortImage;
331 + (NSImage *)_defaultTableHeaderReverseSortImage;
332 @end
333
334
335 /*****************************************************************************
336  * VLCPlaylist implementation
337  *****************************************************************************/
338 @implementation VLCPlaylist
339
340 - (id)init
341 {
342     self = [super init];
343     if ( self != nil )
344     {
345         o_nodes_array = [[NSMutableArray alloc] init];
346         o_items_array = [[NSMutableArray alloc] init];
347     }
348     return self;
349 }
350
351 - (void)awakeFromNib
352 {
353     playlist_t * p_playlist = pl_Yield( VLCIntf );
354
355     int i;
356
357     [super awakeFromNib];
358
359     [o_outline_view setDoubleAction: @selector(playItem:)];
360
361     [o_outline_view registerForDraggedTypes:
362         [NSArray arrayWithObjects: NSFilenamesPboardType,
363         @"VLCPlaylistItemPboardType", nil]];
364     [o_outline_view setIntercellSpacing: NSMakeSize (0.0, 1.0)];
365
366     /* This uses private Apple API which works fine until 10.5.
367      * We need to keep checking in the future!
368      * These methods are being added artificially to NSOutlineView's interface above */
369     o_ascendingSortingImage = [[NSOutlineView class] _defaultTableHeaderSortImage];
370     o_descendingSortingImage = [[NSOutlineView class] _defaultTableHeaderReverseSortImage];
371
372     o_tc_sortColumn = nil;
373
374     char ** ppsz_name;
375     char ** ppsz_services = services_discovery_GetServicesNames( p_playlist, &ppsz_name );
376     if( !ppsz_services )
377     {
378         vlc_object_release( p_playlist );
379         return;
380     }
381     
382     for( i = 0; ppsz_services[i]; i++ )
383     {
384         bool  b_enabled;
385         NSMenuItem  *o_lmi;
386
387         char * name = ppsz_name[i] ? ppsz_name[i] : ppsz_services[i];
388         /* Check whether to enable these menuitems */
389         b_enabled = playlist_IsServicesDiscoveryLoaded( p_playlist, ppsz_services[i] );
390
391         /* Create the menu entries used in the playlist menu */
392         o_lmi = [[o_mi_services submenu] addItemWithTitle:
393                  [NSString stringWithUTF8String: name]
394                                          action: @selector(servicesChange:)
395                                          keyEquivalent: @""];
396         [o_lmi setTarget: self];
397         [o_lmi setRepresentedObject: [NSString stringWithUTF8String: ppsz_services[i]]];
398         if( b_enabled ) [o_lmi setState: NSOnState];
399
400         /* Create the menu entries for the main menu */
401         o_lmi = [[o_mm_mi_services submenu] addItemWithTitle:
402                  [NSString stringWithUTF8String: name]
403                                          action: @selector(servicesChange:)
404                                          keyEquivalent: @""];
405         [o_lmi setTarget: self];
406         [o_lmi setRepresentedObject: [NSString stringWithUTF8String: ppsz_services[i]]];
407         if( b_enabled ) [o_lmi setState: NSOnState];
408
409         free( ppsz_services[i] );
410         free( ppsz_name[i] );
411     }
412     free( ppsz_services );
413     free( ppsz_name );
414
415     vlc_object_release( p_playlist );
416 }
417
418 - (void)searchfieldChanged:(NSNotification *)o_notification
419 {
420     [o_search_field setStringValue:[[o_notification object] stringValue]];
421 }
422
423 - (void)initStrings
424 {
425     [super initStrings];
426
427     [o_mi_save_playlist setTitle: _NS("Save Playlist...")];
428     [o_mi_play setTitle: _NS("Play")];
429     [o_mi_delete setTitle: _NS("Delete")];
430     [o_mi_recursive_expand setTitle: _NS("Expand Node")];
431     [o_mi_selectall setTitle: _NS("Select All")];
432     [o_mi_info setTitle: _NS("Information")];
433     [o_mi_preparse setTitle: _NS("Get Stream Information")];
434     [o_mi_sort_name setTitle: _NS("Sort Node by Name")];
435     [o_mi_sort_author setTitle: _NS("Sort Node by Author")];
436     [o_mi_services setTitle: _NS("Services discovery")];
437     [o_status_field setStringValue: _NS("No items in the playlist")];
438
439     [o_search_field setToolTip: _NS("Search in Playlist")];
440     [o_mi_addNode setTitle: _NS("Add Folder to Playlist")];
441
442     [o_save_accessory_text setStringValue: _NS("File Format:")];
443     [[o_save_accessory_popup itemAtIndex:0] setTitle: _NS("Extended M3U")];
444     [[o_save_accessory_popup itemAtIndex:1] setTitle: _NS("XML Shareable Playlist Format (XSPF)")];
445 }
446
447 - (void)playlistUpdated
448 {
449     /* Clear indications of any existing column sorting */
450     for( unsigned int i = 0 ; i < [[o_outline_view tableColumns] count] ; i++ )
451     {
452         [o_outline_view setIndicatorImage:nil inTableColumn:
453                             [[o_outline_view tableColumns] objectAtIndex:i]];
454     }
455
456     [o_outline_view setHighlightedTableColumn:nil];
457     o_tc_sortColumn = nil;
458     // TODO Find a way to keep the dict size to a minimum
459     //[o_outline_dict removeAllObjects];
460     [o_outline_view reloadData];
461     [[[[VLCMain sharedInstance] getWizard] getPlaylistWizard] reloadOutlineView];
462     [[[[VLCMain sharedInstance] getBookmarks] getDataTable] reloadData];
463
464     playlist_t *p_playlist = pl_Yield( VLCIntf );
465
466     if( playlist_CurrentSize( p_playlist ) >= 2 )
467     {
468         [o_status_field setStringValue: [NSString stringWithFormat:
469                     _NS("%i items"),
470                 playlist_CurrentSize( p_playlist )]];
471     }
472     else
473     {
474         if( playlist_IsEmpty( p_playlist ) )
475             [o_status_field setStringValue: _NS("No items in the playlist")];
476         else
477             [o_status_field setStringValue: _NS("1 item")];
478     }
479     vlc_object_release( p_playlist );
480 }
481
482 - (void)playModeUpdated
483 {
484     playlist_t *p_playlist = pl_Yield( VLCIntf );
485
486     bool loop = var_GetBool( p_playlist, "loop" );
487     bool repeat = var_GetBool( p_playlist, "repeat" );
488     if( repeat )
489         [[[VLCMain sharedInstance] getControls] repeatOne];
490     else if( loop )
491         [[[VLCMain sharedInstance] getControls] repeatAll];
492     else
493         [[[VLCMain sharedInstance] getControls] repeatOff];
494
495     [[[VLCMain sharedInstance] getControls] shuffle];
496
497     vlc_object_release( p_playlist );
498 }
499
500 - (void)updateRowSelection
501 {
502     int i_row;
503     unsigned int j;
504
505     playlist_t *p_playlist = pl_Yield( VLCIntf );
506     playlist_item_t *p_item, *p_temp_item;
507     NSMutableArray *o_array = [NSMutableArray array];
508
509     p_item = p_playlist->status.p_item;
510     if( p_item == NULL )
511     {
512         vlc_object_release(p_playlist);
513         return;
514     }
515
516     p_temp_item = p_item;
517     while( p_temp_item->p_parent )
518     {
519         [o_array insertObject: [NSValue valueWithPointer: p_temp_item] atIndex: 0];
520         p_temp_item = p_temp_item->p_parent;
521     }
522
523     for( j = 0; j < [o_array count] - 1; j++ )
524     {
525         id o_item;
526         if( ( o_item = [o_outline_dict objectForKey:
527                             [NSString stringWithFormat: @"%p",
528                             [[o_array objectAtIndex:j] pointerValue]]] ) != nil )
529         {
530             [o_outline_view expandItem: o_item];
531         }
532
533     }
534
535     vlc_object_release( p_playlist );
536
537     /* update our info-panel to reflect the new item */
538     [[[VLCMain sharedInstance] getInfo] updatePanel];
539 }
540
541 /* Check if p_item is a child of p_node recursively. We need to check the item
542    existence first since OSX sometimes tries to redraw items that have been
543    deleted. We don't do it when not required  since this verification takes
544    quite a long time on big playlists (yes, pretty hacky). */
545 - (BOOL)isItem: (playlist_item_t *)p_item
546                     inNode: (playlist_item_t *)p_node
547                     checkItemExistence:(BOOL)b_check
548
549 {
550     playlist_t * p_playlist = pl_Yield( VLCIntf );
551     playlist_item_t *p_temp_item = p_item;
552
553     if( p_node == p_item )
554     {
555         vlc_object_release(p_playlist);
556         return YES;
557     }
558
559     if( p_node->i_children < 1)
560     {
561         vlc_object_release(p_playlist);
562         return NO;
563     }
564
565     if ( p_temp_item )
566     {
567         int i;
568         PL_LOCK;
569
570         if( b_check )
571         {
572         /* Since outlineView: willDisplayCell:... may call this function with
573            p_items that don't exist anymore, first check if the item is still
574            in the playlist. Any cleaner solution welcomed. */
575             for( i = 0; i < p_playlist->all_items.i_size; i++ )
576             {
577                 if( ARRAY_VAL( p_playlist->all_items, i) == p_item ) break;
578                 else if ( i == p_playlist->all_items.i_size - 1 )
579                 {
580                     vlc_object_release( p_playlist );
581                     PL_UNLOCK;
582                     return NO;
583                 }
584             }
585         }
586
587         while( p_temp_item )
588         {
589             p_temp_item = p_temp_item->p_parent;
590             if( p_temp_item == p_node )
591             {
592                 PL_UNLOCK;
593                 vlc_object_release( p_playlist );
594                 return YES;
595             }
596         }
597         PL_UNLOCK;
598     }
599
600     vlc_object_release( p_playlist );
601     return NO;
602 }
603
604 /* This method is usefull for instance to remove the selected children of an
605    already selected node */
606 - (void)removeItemsFrom:(id)o_items ifChildrenOf:(id)o_nodes
607 {
608     unsigned int i, j;
609     for( i = 0 ; i < [o_items count] ; i++ )
610     {
611         for ( j = 0 ; j < [o_nodes count] ; j++ )
612         {
613             if( o_items == o_nodes)
614             {
615                 if( j == i ) continue;
616             }
617             if( [self isItem: [[o_items objectAtIndex:i] pointerValue]
618                     inNode: [[o_nodes objectAtIndex:j] pointerValue]
619                     checkItemExistence: NO] )
620             {
621                 [o_items removeObjectAtIndex:i];
622                 /* We need to execute the next iteration with the same index
623                    since the current item has been deleted */
624                 i--;
625                 break;
626             }
627         }
628     }
629
630 }
631
632 - (IBAction)savePlaylist:(id)sender
633 {
634     playlist_t * p_playlist = pl_Yield( VLCIntf );
635
636     NSSavePanel *o_save_panel = [NSSavePanel savePanel];
637     NSString * o_name = [NSString stringWithFormat: @"%@", _NS("Untitled")];
638
639     //[o_save_panel setAllowedFileTypes: [NSArray arrayWithObjects: @"m3u", @"xpf", nil] ];
640     [o_save_panel setTitle: _NS("Save Playlist")];
641     [o_save_panel setPrompt: _NS("Save")];
642     [o_save_panel setAccessoryView: o_save_accessory_view];
643
644     if( [o_save_panel runModalForDirectory: nil
645             file: o_name] == NSOKButton )
646     {
647         NSString *o_filename = [o_save_panel filename];
648
649         if( [o_save_accessory_popup indexOfSelectedItem] == 1 )
650         {
651             NSString * o_real_filename;
652             NSRange range;
653             range.location = [o_filename length] - [@".xspf" length];
654             range.length = [@".xspf" length];
655
656             if( [o_filename compare:@".xspf" options: NSCaseInsensitiveSearch
657                                              range: range] != NSOrderedSame )
658             {
659                 o_real_filename = [NSString stringWithFormat: @"%@.xspf", o_filename];
660             }
661             else
662             {
663                 o_real_filename = o_filename;
664             }
665             playlist_Export( p_playlist,
666                 [o_real_filename fileSystemRepresentation],
667                 p_playlist->p_local_category, "export-xspf" );
668         }
669         else
670         {
671             NSString * o_real_filename;
672             NSRange range;
673             range.location = [o_filename length] - [@".m3u" length];
674             range.length = [@".m3u" length];
675
676             if( [o_filename compare:@".m3u" options: NSCaseInsensitiveSearch
677                                              range: range] != NSOrderedSame )
678             {
679                 o_real_filename = [NSString stringWithFormat: @"%@.m3u", o_filename];
680             }
681             else
682             {
683                 o_real_filename = o_filename;
684             }
685             playlist_Export( p_playlist,
686                 [o_real_filename fileSystemRepresentation],
687                 p_playlist->p_local_category, "export-m3u" );
688         }
689     }
690     vlc_object_release( p_playlist );
691 }
692
693 /* When called retrieves the selected outlineview row and plays that node or item */
694 - (IBAction)playItem:(id)sender
695 {
696     intf_thread_t * p_intf = VLCIntf;
697     playlist_t * p_playlist = pl_Yield( p_intf );
698
699     playlist_item_t *p_item;
700     playlist_item_t *p_node = NULL;
701
702     p_item = [[o_outline_view itemAtRow:[o_outline_view selectedRow]] pointerValue];
703
704     if( p_item )
705     {
706         if( p_item->i_children == -1 )
707         {
708             p_node = p_item->p_parent;
709
710         }
711         else
712         {
713             p_node = p_item;
714             if( p_node->i_children > 0 && p_node->pp_children[0]->i_children == -1 )
715             {
716                 p_item = p_node->pp_children[0];
717             }
718             else
719             {
720                 p_item = NULL;
721             }
722         }
723         playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, true, p_node, p_item );
724     }
725     vlc_object_release( p_playlist );
726 }
727
728 /* When called retrieves the selected outlineview row and plays that node or item */
729 - (IBAction)preparseItem:(id)sender
730 {
731     int i_count;
732     NSMutableArray *o_to_preparse;
733     intf_thread_t * p_intf = VLCIntf;
734     playlist_t * p_playlist = pl_Yield( p_intf );
735  
736     o_to_preparse = [NSMutableArray arrayWithArray:[[o_outline_view selectedRowEnumerator] allObjects]];
737     i_count = [o_to_preparse count];
738
739     int i, i_row;
740     NSNumber *o_number;
741     playlist_item_t *p_item = NULL;
742
743     for( i = 0; i < i_count; i++ )
744     {
745         o_number = [o_to_preparse lastObject];
746         i_row = [o_number intValue];
747         p_item = [[o_outline_view itemAtRow:i_row] pointerValue];
748         [o_to_preparse removeObject: o_number];
749         [o_outline_view deselectRow: i_row];
750
751         if( p_item )
752         {
753             if( p_item->i_children == -1 )
754             {
755                 playlist_PreparseEnqueue( p_playlist, p_item->p_input );
756             }
757             else
758             {
759                 msg_Dbg( p_intf, "preparsing nodes not implemented" );
760             }
761         }
762     }
763     vlc_object_release( p_playlist );
764     [self playlistUpdated];
765 }
766
767 - (IBAction)servicesChange:(id)sender
768 {
769     NSMenuItem *o_mi = (NSMenuItem *)sender;
770     NSString *o_string = [o_mi representedObject];
771     playlist_t * p_playlist = pl_Yield( VLCIntf );
772     if( !playlist_IsServicesDiscoveryLoaded( p_playlist, [o_string UTF8String] ) )
773         playlist_ServicesDiscoveryAdd( p_playlist, [o_string UTF8String] );
774     else
775         playlist_ServicesDiscoveryRemove( p_playlist, [o_string UTF8String] );
776
777     [o_mi setState: playlist_IsServicesDiscoveryLoaded( p_playlist,
778                                           [o_string UTF8String] ) ? YES : NO];
779
780     vlc_object_release( p_playlist );
781     [self playlistUpdated];
782     return;
783 }
784
785 - (IBAction)selectAll:(id)sender
786 {
787     [o_outline_view selectAll: nil];
788 }
789
790 - (IBAction)deleteItem:(id)sender
791 {
792     int i_count, i_row;
793     NSMutableArray *o_to_delete;
794     NSNumber *o_number;
795
796     playlist_t * p_playlist;
797     intf_thread_t * p_intf = VLCIntf;
798
799     o_to_delete = [NSMutableArray arrayWithArray:[[o_outline_view selectedRowEnumerator] allObjects]];
800     i_count = [o_to_delete count];
801
802     p_playlist = pl_Yield( p_intf );
803
804     PL_LOCK;
805     for( int i = 0; i < i_count; i++ )
806     {
807         o_number = [o_to_delete lastObject];
808         i_row = [o_number intValue];
809         id o_item = [o_outline_view itemAtRow: i_row];
810         playlist_item_t *p_item = [o_item pointerValue];
811 #ifndef NDEBUG
812         msg_Dbg( p_intf, "deleting item %i (of %i) with id \"%i\", pointerValue \"%p\" and %i children", i+1, i_count, 
813                 p_item->p_input->i_id, [o_item pointerValue], p_item->i_children +1 );
814 #endif
815         [o_to_delete removeObject: o_number];
816         [o_outline_view deselectRow: i_row];
817
818         if( p_item->i_children != -1 )
819         //is a node and not an item
820         {
821             if( p_playlist->status.i_status != PLAYLIST_STOPPED &&
822                 [self isItem: p_playlist->status.p_item inNode:
823                         ((playlist_item_t *)[o_item pointerValue])
824                         checkItemExistence: NO] == YES )
825                 // if current item is in selected node and is playing then stop playlist
826                 playlist_Stop( p_playlist );
827     
828             playlist_NodeDelete( p_playlist, p_item, true, false );
829         }
830         else
831             playlist_DeleteFromInput( p_playlist, p_item->p_input->i_id, true );
832     }
833     PL_UNLOCK;
834
835     [self playlistUpdated];
836     vlc_object_release( p_playlist );
837 }
838
839 - (IBAction)sortNodeByName:(id)sender
840 {
841     [self sortNode: SORT_TITLE];
842 }
843
844 - (IBAction)sortNodeByAuthor:(id)sender
845 {
846     [self sortNode: SORT_ARTIST];
847 }
848
849 - (void)sortNode:(int)i_mode
850 {
851     playlist_t * p_playlist = pl_Yield( VLCIntf );
852     playlist_item_t * p_item;
853
854     if( [o_outline_view selectedRow] > -1 )
855     {
856         p_item = [[o_outline_view itemAtRow: [o_outline_view selectedRow]] pointerValue];
857     }
858     else
859     /*If no item is selected, sort the whole playlist*/
860     {
861         p_item = p_playlist->p_root_category;
862     }
863
864     if( p_item->i_children > -1 ) // the item is a node
865     {
866         PL_LOCK;
867         playlist_RecursiveNodeSort( p_playlist, p_item, i_mode, ORDER_NORMAL );
868         PL_UNLOCK;
869     }
870     else
871     {
872         PL_LOCK;
873         playlist_RecursiveNodeSort( p_playlist,
874                 p_item->p_parent, i_mode, ORDER_NORMAL );
875         PL_UNLOCK;
876     }
877     vlc_object_release( p_playlist );
878     [self playlistUpdated];
879 }
880
881 - (input_item_t *)createItem:(NSDictionary *)o_one_item
882 {
883     intf_thread_t * p_intf = VLCIntf;
884     playlist_t * p_playlist = pl_Yield( p_intf );
885
886     input_item_t *p_input;
887     int i;
888     BOOL b_rem = FALSE, b_dir = FALSE;
889     NSString *o_uri, *o_name;
890     NSArray *o_options;
891     NSURL *o_true_file;
892
893     /* Get the item */
894     o_uri = (NSString *)[o_one_item objectForKey: @"ITEM_URL"];
895     o_name = (NSString *)[o_one_item objectForKey: @"ITEM_NAME"];
896     o_options = (NSArray *)[o_one_item objectForKey: @"ITEM_OPTIONS"];
897
898     /* Find the name for a disc entry (i know, can you believe the trouble?) */
899     if( ( !o_name || [o_name isEqualToString:@""] ) && [o_uri rangeOfString: @"/dev/"].location != NSNotFound )
900     {
901         int i_count, i_index;
902         struct statfs *mounts = NULL;
903
904         i_count = getmntinfo (&mounts, MNT_NOWAIT);
905         /* getmntinfo returns a pointer to static data. Do not free. */
906         for( i_index = 0 ; i_index < i_count; i_index++ )
907         {
908             NSMutableString *o_temp, *o_temp2;
909             o_temp = [NSMutableString stringWithString: o_uri];
910             o_temp2 = [NSMutableString stringWithUTF8String: mounts[i_index].f_mntfromname];
911             [o_temp replaceOccurrencesOfString: @"/dev/rdisk" withString: @"/dev/disk" options:NSLiteralSearch range:NSMakeRange(0, [o_temp length]) ];
912             [o_temp2 replaceOccurrencesOfString: @"s0" withString: @"" options:NSLiteralSearch range:NSMakeRange(0, [o_temp2 length]) ];
913             [o_temp2 replaceOccurrencesOfString: @"s1" withString: @"" options:NSLiteralSearch range:NSMakeRange(0, [o_temp2 length]) ];
914
915             if( strstr( [o_temp fileSystemRepresentation], [o_temp2 fileSystemRepresentation] ) != NULL )
916             {
917                 o_name = [[NSFileManager defaultManager] displayNameAtPath: [NSString stringWithUTF8String:mounts[i_index].f_mntonname]];
918             }
919         }
920     }
921     /* If no name, then make a guess */
922     if( !o_name) o_name = [[NSFileManager defaultManager] displayNameAtPath: o_uri];
923
924     if( [[NSFileManager defaultManager] fileExistsAtPath:o_uri isDirectory:&b_dir] && b_dir &&
925         [[NSWorkspace sharedWorkspace] getFileSystemInfoForPath: o_uri isRemovable: &b_rem
926                 isWritable:NULL isUnmountable:NULL description:NULL type:NULL] && b_rem   )
927     {
928         /* All of this is to make sure CD's play when you D&D them on VLC */
929         /* Converts mountpoint to a /dev file */
930         struct statfs *buf;
931         char *psz_dev;
932         NSMutableString *o_temp;
933
934         buf = (struct statfs *) malloc (sizeof(struct statfs));
935         statfs( [o_uri fileSystemRepresentation], buf );
936         psz_dev = strdup(buf->f_mntfromname);
937         o_temp = [NSMutableString stringWithUTF8String: psz_dev ];
938         [o_temp replaceOccurrencesOfString: @"/dev/disk" withString: @"/dev/rdisk" options:NSLiteralSearch range:NSMakeRange(0, [o_temp length]) ];
939         [o_temp replaceOccurrencesOfString: @"s0" withString: @"" options:NSLiteralSearch range:NSMakeRange(0, [o_temp length]) ];
940         [o_temp replaceOccurrencesOfString: @"s1" withString: @"" options:NSLiteralSearch range:NSMakeRange(0, [o_temp length]) ];
941         o_uri = o_temp;
942     }
943
944     p_input = input_ItemNew( p_playlist, [o_uri fileSystemRepresentation], [o_name UTF8String] );
945     if( !p_input )
946        return NULL;
947
948     if( o_options )
949     {
950         for( i = 0; i < (int)[o_options count]; i++ )
951         {
952             input_ItemAddOption( p_input, strdup( [[o_options objectAtIndex:i] UTF8String] ) );
953         }
954     }
955
956     /* Recent documents menu */
957     o_true_file = [NSURL fileURLWithPath: o_uri];
958     if( o_true_file != nil && (BOOL)config_GetInt( p_playlist, "macosx-recentitems" ) == YES )
959     {
960         [[NSDocumentController sharedDocumentController]
961             noteNewRecentDocumentURL: o_true_file];
962     }
963
964     vlc_object_release( p_playlist );
965     return p_input;
966 }
967
968 - (void)appendArray:(NSArray*)o_array atPos:(int)i_position enqueue:(BOOL)b_enqueue
969 {
970     int i_item;
971     playlist_t * p_playlist = pl_Yield( VLCIntf );
972
973     for( i_item = 0; i_item < (int)[o_array count]; i_item++ )
974     {
975         input_item_t *p_input;
976         NSDictionary *o_one_item;
977
978         /* Get the item */
979         o_one_item = [o_array objectAtIndex: i_item];
980         p_input = [self createItem: o_one_item];
981         if( !p_input )
982         {
983             continue;
984         }
985
986         /* Add the item */
987         /* FIXME: playlist_AddInput() can fail */
988         playlist_AddInput( p_playlist, p_input, PLAYLIST_INSERT,
989              i_position == -1 ? PLAYLIST_END : i_position + i_item, true,
990          false );
991
992         if( i_item == 0 && !b_enqueue )
993         {
994             playlist_item_t *p_item;
995             p_item = playlist_ItemGetByInput( p_playlist, p_input, true );
996             playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, true, NULL, p_item );
997         }
998         else
999         {
1000             playlist_item_t *p_item;
1001             p_item = playlist_ItemGetByInput( p_playlist, p_input, true );
1002             playlist_Control( p_playlist, PLAYLIST_SKIP, true, p_item );
1003         }
1004         vlc_gc_decref( p_input );
1005     }
1006     [self playlistUpdated];
1007     vlc_object_release( p_playlist );
1008 }
1009
1010 - (void)appendNodeArray:(NSArray*)o_array inNode:(playlist_item_t *)p_node atPos:(int)i_position enqueue:(BOOL)b_enqueue
1011 {
1012     int i_item;
1013     playlist_t * p_playlist = pl_Yield( VLCIntf );
1014
1015     for( i_item = 0; i_item < (int)[o_array count]; i_item++ )
1016     {
1017         input_item_t *p_input;
1018         NSDictionary *o_one_item;
1019
1020         /* Get the item */
1021         o_one_item = [o_array objectAtIndex: i_item];
1022         p_input = [self createItem: o_one_item];
1023         if( !p_input )
1024         {
1025             continue;
1026         }
1027
1028         /* Add the item */
1029         /* FIXME: playlist_NodeAddInput() can fail */
1030        playlist_NodeAddInput( p_playlist, p_input, p_node,
1031                                       PLAYLIST_INSERT,
1032                                       i_position == -1 ?
1033                                       PLAYLIST_END : i_position + i_item, false );
1034
1035
1036         if( i_item == 0 && !b_enqueue )
1037         {
1038             playlist_item_t *p_item;
1039             p_item = playlist_ItemGetByInput( p_playlist, p_input, true );
1040             playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, true, NULL, p_item );
1041         }
1042         else
1043         {
1044             playlist_item_t *p_item;
1045             p_item = playlist_ItemGetByInput( p_playlist, p_input, true );
1046             playlist_Control( p_playlist, PLAYLIST_SKIP, true, p_item );
1047         }
1048         vlc_gc_decref( p_input );
1049     }
1050     [self playlistUpdated];
1051     vlc_object_release( p_playlist );
1052 }
1053
1054 - (NSMutableArray *)subSearchItem:(playlist_item_t *)p_item
1055 {
1056     playlist_t *p_playlist = pl_Yield( VLCIntf );
1057     playlist_item_t *p_selected_item;
1058     int i_current, i_selected_row;
1059
1060     i_selected_row = [o_outline_view selectedRow];
1061     if (i_selected_row < 0)
1062         i_selected_row = 0;
1063
1064     p_selected_item = (playlist_item_t *)[[o_outline_view itemAtRow:
1065                                             i_selected_row] pointerValue];
1066
1067     for( i_current = 0; i_current < p_item->i_children ; i_current++ )
1068     {
1069         char *psz_temp;
1070         NSString *o_current_name, *o_current_author;
1071
1072         PL_LOCK;
1073         o_current_name = [NSString stringWithUTF8String:
1074             p_item->pp_children[i_current]->p_input->psz_name];
1075         psz_temp = input_ItemGetInfo( p_item->p_input ,
1076                    _("Meta-information"),_("Artist") );
1077         o_current_author = [NSString stringWithUTF8String: psz_temp];
1078         free( psz_temp);
1079         PL_UNLOCK;
1080
1081         if( p_selected_item == p_item->pp_children[i_current] &&
1082                     b_selected_item_met == NO )
1083         {
1084             b_selected_item_met = YES;
1085         }
1086         else if( p_selected_item == p_item->pp_children[i_current] &&
1087                     b_selected_item_met == YES )
1088         {
1089             vlc_object_release( p_playlist );
1090             return NULL;
1091         }
1092         else if( b_selected_item_met == YES &&
1093                     ( [o_current_name rangeOfString:[o_search_field
1094                         stringValue] options:NSCaseInsensitiveSearch].length ||
1095                       [o_current_author rangeOfString:[o_search_field
1096                         stringValue] options:NSCaseInsensitiveSearch].length ) )
1097         {
1098             vlc_object_release( p_playlist );
1099             /*Adds the parent items in the result array as well, so that we can
1100             expand the tree*/
1101             return [NSMutableArray arrayWithObject: [NSValue
1102                             valueWithPointer: p_item->pp_children[i_current]]];
1103         }
1104         if( p_item->pp_children[i_current]->i_children > 0 )
1105         {
1106             id o_result = [self subSearchItem:
1107                                             p_item->pp_children[i_current]];
1108             if( o_result != NULL )
1109             {
1110                 vlc_object_release( p_playlist );
1111                 [o_result insertObject: [NSValue valueWithPointer:
1112                                 p_item->pp_children[i_current]] atIndex:0];
1113                 return o_result;
1114             }
1115         }
1116     }
1117     vlc_object_release( p_playlist );
1118     return NULL;
1119 }
1120
1121 - (IBAction)searchItem:(id)sender
1122 {
1123     playlist_t * p_playlist = pl_Yield( VLCIntf );
1124     id o_result;
1125
1126     unsigned int i;
1127     int i_row = -1;
1128
1129     b_selected_item_met = NO;
1130
1131         /*First, only search after the selected item:*
1132          *(b_selected_item_met = NO)                 */
1133     o_result = [self subSearchItem:p_playlist->p_root_category];
1134     if( o_result == NULL )
1135     {
1136         /* If the first search failed, search again from the beginning */
1137         o_result = [self subSearchItem:p_playlist->p_root_category];
1138     }
1139     if( o_result != NULL )
1140     {
1141         int i_start;
1142         if( [[o_result objectAtIndex: 0] pointerValue] ==
1143                                                     p_playlist->p_local_category )
1144         i_start = 1;
1145         else
1146         i_start = 0;
1147
1148         for( i = i_start ; i < [o_result count] - 1 ; i++ )
1149         {
1150             [o_outline_view expandItem: [o_outline_dict objectForKey:
1151                         [NSString stringWithFormat: @"%p",
1152                         [[o_result objectAtIndex: i] pointerValue]]]];
1153         }
1154         i_row = [o_outline_view rowForItem: [o_outline_dict objectForKey:
1155                         [NSString stringWithFormat: @"%p",
1156                         [[o_result objectAtIndex: [o_result count] - 1 ]
1157                         pointerValue]]]];
1158     }
1159     if( i_row > -1 )
1160     {
1161         [o_outline_view selectRow:i_row byExtendingSelection: NO];
1162         [o_outline_view scrollRowToVisible: i_row];
1163     }
1164     vlc_object_release( p_playlist );
1165 }
1166
1167 - (IBAction)recursiveExpandNode:(id)sender
1168 {
1169     id o_item = [o_outline_view itemAtRow: [o_outline_view selectedRow]];
1170     playlist_item_t *p_item = (playlist_item_t *)[o_item pointerValue];
1171
1172     if( ![[o_outline_view dataSource] outlineView: o_outline_view
1173                                                     isItemExpandable: o_item] )
1174     {
1175         o_item = [o_outline_dict objectForKey: [NSString
1176                    stringWithFormat: @"%p", p_item->p_parent]];
1177     }
1178
1179     /* We need to collapse the node first, since OSX refuses to recursively
1180        expand an already expanded node, even if children nodes are collapsed. */
1181     [o_outline_view collapseItem: o_item collapseChildren: YES];
1182     [o_outline_view expandItem: o_item expandChildren: YES];
1183 }
1184
1185 - (NSMenu *)menuForEvent:(NSEvent *)o_event
1186 {
1187     NSPoint pt;
1188     bool b_rows;
1189     bool b_item_sel;
1190
1191     pt = [o_outline_view convertPoint: [o_event locationInWindow]
1192                                                  fromView: nil];
1193     b_item_sel = ( [o_outline_view rowAtPoint: pt] != -1 &&
1194                    [o_outline_view selectedRow] != -1 );
1195     b_rows = [o_outline_view numberOfRows] != 0;
1196
1197     [o_mi_play setEnabled: b_item_sel];
1198     [o_mi_delete setEnabled: b_item_sel];
1199     [o_mi_selectall setEnabled: b_rows];
1200     [o_mi_info setEnabled: b_item_sel];
1201     [o_mi_preparse setEnabled: b_item_sel];
1202     [o_mi_recursive_expand setEnabled: b_item_sel];
1203     [o_mi_sort_name setEnabled: b_item_sel];
1204     [o_mi_sort_author setEnabled: b_item_sel];
1205
1206     return( o_ctx_menu );
1207 }
1208
1209 - (void)outlineView: (NSTableView*)o_tv
1210                   didClickTableColumn:(NSTableColumn *)o_tc
1211 {
1212     int i_mode = 0, i_type;
1213     intf_thread_t *p_intf = VLCIntf;
1214
1215     playlist_t *p_playlist = pl_Yield( p_intf );
1216
1217     /* Check whether the selected table column header corresponds to a
1218        sortable table column*/
1219     if( !( o_tc == o_tc_name || o_tc == o_tc_author ) )
1220     {
1221         vlc_object_release( p_playlist );
1222         return;
1223     }
1224
1225     if( o_tc_sortColumn == o_tc )
1226     {
1227         b_isSortDescending = !b_isSortDescending;
1228     }
1229     else
1230     {
1231         b_isSortDescending = false;
1232     }
1233
1234     if( o_tc == o_tc_name )
1235     {
1236         i_mode = SORT_TITLE;
1237     }
1238     else if( o_tc == o_tc_author )
1239     {
1240         i_mode = SORT_ARTIST;
1241     }
1242
1243     if( b_isSortDescending )
1244     {
1245         i_type = ORDER_REVERSE;
1246     }
1247     else
1248     {
1249         i_type = ORDER_NORMAL;
1250     }
1251
1252     vlc_object_lock( p_playlist );
1253     playlist_RecursiveNodeSort( p_playlist, p_playlist->p_root_category, i_mode, i_type );
1254     vlc_object_unlock( p_playlist );
1255
1256     vlc_object_release( p_playlist );
1257     [self playlistUpdated];
1258
1259     o_tc_sortColumn = o_tc;
1260     [o_outline_view setHighlightedTableColumn:o_tc];
1261
1262     if( b_isSortDescending )
1263     {
1264         [o_outline_view setIndicatorImage:o_descendingSortingImage
1265                                                         inTableColumn:o_tc];
1266     }
1267     else
1268     {
1269         [o_outline_view setIndicatorImage:o_ascendingSortingImage
1270                                                         inTableColumn:o_tc];
1271     }
1272 }
1273
1274
1275 - (void)outlineView:(NSOutlineView *)outlineView
1276                                 willDisplayCell:(id)cell
1277                                 forTableColumn:(NSTableColumn *)tableColumn
1278                                 item:(id)item
1279 {
1280     playlist_t *p_playlist = pl_Yield( VLCIntf );
1281
1282     id o_playing_item;
1283
1284     o_playing_item = [o_outline_dict objectForKey:
1285                 [NSString stringWithFormat:@"%p",  p_playlist->status.p_item]];
1286
1287     if( [self isItem: [o_playing_item pointerValue] inNode:
1288                         [item pointerValue] checkItemExistence: YES]
1289                         || [o_playing_item isEqual: item] )
1290     {
1291         [cell setFont: [[NSFontManager sharedFontManager] convertFont:[cell font] toHaveTrait:NSBoldFontMask]];
1292     }
1293     else
1294     {
1295         [cell setFont: [[NSFontManager sharedFontManager] convertFont:[cell font] toNotHaveTrait:NSBoldFontMask]];
1296     }
1297     vlc_object_release( p_playlist );
1298 }
1299
1300 - (IBAction)addNode:(id)sender
1301 {
1302     /* we have to create a new thread here because otherwise we would block the
1303      * interface since the interaction-stuff and this code would run in the same
1304      * thread */
1305     [NSThread detachNewThreadSelector: @selector(addNodeThreadedly)
1306         toTarget: self withObject:nil];
1307     [self playlistUpdated];
1308 }
1309
1310 - (void)addNodeThreadedly
1311 {
1312     NSAutoreleasePool * ourPool = [[NSAutoreleasePool alloc] init];
1313
1314     /* simply adds a new node to the end of the playlist */
1315     playlist_t * p_playlist = pl_Yield( VLCIntf );
1316     vlc_thread_set_priority( p_playlist, VLC_THREAD_PRIORITY_LOW );
1317
1318     int ret_v;
1319     char *psz_name = NULL;
1320     playlist_item_t * p_item;
1321     ret_v = intf_UserStringInput( p_playlist, _("New Node"),
1322         _("Please enter a name for the new node."), &psz_name );
1323
1324     if( ret_v != DIALOG_CANCELLED && psz_name && *psz_name )
1325         p_item = playlist_NodeCreate( p_playlist, psz_name,
1326                                       p_playlist->p_local_category, 0, NULL );
1327     else if(! config_GetInt( p_playlist, "interact" ) )
1328     {
1329         /* in case that the interaction is disabled, just give it a bogus name */
1330         p_item = playlist_NodeCreate( p_playlist, _("Empty Folder"),
1331                                       p_playlist->p_local_category, 0, NULL );
1332     }
1333
1334     if(! p_item )
1335         msg_Warn( VLCIntf, "node creation failed or cancelled by user" );
1336
1337     vlc_object_release( p_playlist );
1338     [ourPool release];
1339 }
1340
1341 @end
1342
1343 @implementation VLCPlaylist (NSOutlineViewDataSource)
1344
1345 - (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item
1346 {
1347     id o_value = [super outlineView: outlineView child: index ofItem: item];
1348     playlist_t *p_playlist = pl_Yield( VLCIntf );
1349
1350     if( playlist_CurrentSize( p_playlist )  >= 2 )
1351     {
1352         [o_status_field setStringValue: [NSString stringWithFormat:
1353                     _NS("%i items"),
1354              playlist_CurrentSize( p_playlist )]];
1355     }
1356     else
1357     {
1358         if( playlist_IsEmpty( p_playlist ) )
1359         {
1360             [o_status_field setStringValue: _NS("No items in the playlist")];
1361         }
1362         else
1363         {
1364             [o_status_field setStringValue: _NS("1 item")];
1365         }
1366     }
1367     vlc_object_release( p_playlist );
1368
1369     [o_outline_dict setObject:o_value forKey:[NSString stringWithFormat:@"%p",
1370                                                     [o_value pointerValue]]];
1371     return o_value;
1372
1373 }
1374
1375 /* Required for drag & drop and reordering */
1376 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
1377 {
1378     unsigned int i;
1379     playlist_t *p_playlist = pl_Yield( VLCIntf );
1380
1381     /* First remove the items that were moved during the last drag & drop
1382        operation */
1383     [o_items_array removeAllObjects];
1384     [o_nodes_array removeAllObjects];
1385
1386     for( i = 0 ; i < [items count] ; i++ )
1387     {
1388         id o_item = [items objectAtIndex: i];
1389
1390         /* Refuse to move items that are not in the General Node
1391            (Service Discovery) */
1392         if( ![self isItem: [o_item pointerValue] inNode:
1393                         p_playlist->p_local_category checkItemExistence: NO] &&
1394             ( var_CreateGetBool( p_playlist, "media-library" ) &&
1395             ![self isItem: [o_item pointerValue] inNode:
1396                         p_playlist->p_ml_category checkItemExistence: NO]) )
1397         {
1398             vlc_object_release(p_playlist);
1399             return NO;
1400         }
1401         /* Fill the items and nodes to move in 2 different arrays */
1402         if( ((playlist_item_t *)[o_item pointerValue])->i_children > 0 )
1403             [o_nodes_array addObject: o_item];
1404         else
1405             [o_items_array addObject: o_item];
1406     }
1407
1408     /* Now we need to check if there are selected items that are in already
1409        selected nodes. In that case, we only want to move the nodes */
1410     [self removeItemsFrom: o_nodes_array ifChildrenOf: o_nodes_array];
1411     [self removeItemsFrom: o_items_array ifChildrenOf: o_nodes_array];
1412
1413     /* We add the "VLCPlaylistItemPboardType" type to be able to recognize
1414        a Drop operation coming from the playlist. */
1415
1416     [pboard declareTypes: [NSArray arrayWithObjects:
1417         @"VLCPlaylistItemPboardType", nil] owner: self];
1418     [pboard setData:[NSData data] forType:@"VLCPlaylistItemPboardType"];
1419
1420     vlc_object_release(p_playlist);
1421     return YES;
1422 }
1423
1424 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(int)index
1425 {
1426     playlist_t *p_playlist = pl_Yield( VLCIntf );
1427     NSPasteboard *o_pasteboard = [info draggingPasteboard];
1428
1429     if( !p_playlist ) return NSDragOperationNone;
1430
1431     /* Dropping ON items is not allowed if item is not a node */
1432     if( item )
1433     {
1434         if( index == NSOutlineViewDropOnItemIndex &&
1435                 ((playlist_item_t *)[item pointerValue])->i_children == -1 )
1436         {
1437             vlc_object_release( p_playlist );
1438             return NSDragOperationNone;
1439         }
1440     }
1441
1442     /* Don't allow on drop on playlist root element's child */
1443     if( !item && index != NSOutlineViewDropOnItemIndex)
1444     {
1445         vlc_object_release( p_playlist );
1446         return NSDragOperationNone;
1447     }
1448
1449     /* We refuse to drop an item in anything else than a child of the General
1450        Node. We still accept items that would be root nodes of the outlineview
1451        however, to allow drop in an empty playlist. */
1452     if( !( ([self isItem: [item pointerValue] inNode: p_playlist->p_local_category checkItemExistence: NO] || 
1453         ( var_CreateGetBool( p_playlist, "media-library" ) && [self isItem: [item pointerValue] inNode: p_playlist->p_ml_category checkItemExistence: NO] ) ) || item == nil ) )
1454     {
1455         vlc_object_release( p_playlist );
1456         return NSDragOperationNone;
1457     }
1458
1459     /* Drop from the Playlist */
1460     if( [[o_pasteboard types] containsObject: @"VLCPlaylistItemPboardType"] )
1461     {
1462         unsigned int i;
1463         for( i = 0 ; i < [o_nodes_array count] ; i++ )
1464         {
1465             /* We refuse to Drop in a child of an item we are moving */
1466             if( [self isItem: [item pointerValue] inNode:
1467                     [[o_nodes_array objectAtIndex: i] pointerValue]
1468                     checkItemExistence: NO] )
1469             {
1470                 vlc_object_release( p_playlist );
1471                 return NSDragOperationNone;
1472             }
1473         }
1474         vlc_object_release( p_playlist );
1475         return NSDragOperationMove;
1476     }
1477
1478     /* Drop from the Finder */
1479     else if( [[o_pasteboard types] containsObject: NSFilenamesPboardType] )
1480     {
1481         vlc_object_release( p_playlist );
1482         return NSDragOperationGeneric;
1483     }
1484     vlc_object_release( p_playlist );
1485     return NSDragOperationNone;
1486 }
1487
1488 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(int)index
1489 {
1490     playlist_t * p_playlist =  pl_Yield( VLCIntf );
1491     NSPasteboard *o_pasteboard = [info draggingPasteboard];
1492
1493     /* Drag & Drop inside the playlist */
1494     if( [[o_pasteboard types] containsObject: @"VLCPlaylistItemPboardType"] )
1495     {
1496         int i_row, i_removed_from_node = 0;
1497         unsigned int i;
1498         playlist_item_t *p_new_parent, *p_item = NULL;
1499         NSArray *o_all_items = [o_nodes_array arrayByAddingObjectsFromArray:
1500                                                                 o_items_array];
1501         /* If the item is to be dropped as root item of the outline, make it a
1502            child of the General node.
1503            Else, choose the proposed parent as parent. */
1504         if( item == nil ) p_new_parent = p_playlist->p_local_category;
1505         else p_new_parent = [item pointerValue];
1506
1507         /* Make sure the proposed parent is a node.
1508            (This should never be true) */
1509         if( p_new_parent->i_children < 0 )
1510         {
1511             vlc_object_release( p_playlist );
1512             return NO;
1513         }
1514
1515         for( i = 0; i < [o_all_items count]; i++ )
1516         {
1517             playlist_item_t *p_old_parent = NULL;
1518             int i_old_index = 0;
1519
1520             p_item = [[o_all_items objectAtIndex:i] pointerValue];
1521             p_old_parent = p_item->p_parent;
1522             if( !p_old_parent )
1523             continue;
1524             /* We may need the old index later */
1525             if( p_new_parent == p_old_parent )
1526             {
1527                 int j;
1528                 for( j = 0; j < p_old_parent->i_children; j++ )
1529                 {
1530                     if( p_old_parent->pp_children[j] == p_item )
1531                     {
1532                         i_old_index = j;
1533                         break;
1534                     }
1535                 }
1536             }
1537
1538             PL_LOCK;
1539             // Actually detach the item from the old position
1540             if( playlist_NodeRemoveItem( p_playlist, p_item, p_old_parent ) ==
1541                 VLC_SUCCESS )
1542             {
1543                 int i_new_index;
1544                 /* Calculate the new index */
1545                 if( index == -1 )
1546                 i_new_index = -1;
1547                 /* If we move the item in the same node, we need to take into
1548                    account that one item will be deleted */
1549                 else
1550                 {
1551                     if ((p_new_parent == p_old_parent &&
1552                                    i_old_index < index + (int)i) )
1553                     {
1554                         i_removed_from_node++;
1555                     }
1556                     i_new_index = index + i - i_removed_from_node;
1557                 }
1558                 // Reattach the item to the new position
1559                 playlist_NodeInsert( p_playlist, p_item, p_new_parent, i_new_index );
1560             }
1561             PL_UNLOCK;
1562         }
1563         [self playlistUpdated];
1564         i_row = [o_outline_view rowForItem:[o_outline_dict
1565             objectForKey:[NSString stringWithFormat: @"%p",
1566             [[o_all_items objectAtIndex: 0] pointerValue]]]];
1567
1568         if( i_row == -1 )
1569         {
1570             i_row = [o_outline_view rowForItem:[o_outline_dict
1571             objectForKey:[NSString stringWithFormat: @"%p", p_new_parent]]];
1572         }
1573
1574         [o_outline_view deselectAll: self];
1575         [o_outline_view selectRow: i_row byExtendingSelection: NO];
1576         [o_outline_view scrollRowToVisible: i_row];
1577
1578         vlc_object_release( p_playlist );
1579         return YES;
1580     }
1581
1582     else if( [[o_pasteboard types] containsObject: NSFilenamesPboardType] )
1583     {
1584         int i;
1585         playlist_item_t *p_node = [item pointerValue];
1586
1587         NSArray *o_array = [NSArray array];
1588         NSArray *o_values = [[o_pasteboard propertyListForType:
1589                                         NSFilenamesPboardType]
1590                                 sortedArrayUsingSelector:
1591                                         @selector(caseInsensitiveCompare:)];
1592
1593         for( i = 0; i < (int)[o_values count]; i++)
1594         {
1595             NSDictionary *o_dic;
1596             o_dic = [NSDictionary dictionaryWithObject:[o_values
1597                         objectAtIndex:i] forKey:@"ITEM_URL"];
1598             o_array = [o_array arrayByAddingObject: o_dic];
1599         }
1600
1601         if ( item == nil )
1602         {
1603             [self appendArray: o_array atPos: index enqueue: YES];
1604         }
1605         /* This should never occur */
1606         else if( p_node->i_children == -1 )
1607         {
1608             vlc_object_release( p_playlist );
1609             return NO;
1610         }
1611         else
1612         {
1613             [self appendNodeArray: o_array inNode: p_node
1614                 atPos: index enqueue: YES];
1615         }
1616         vlc_object_release( p_playlist );
1617         return YES;
1618     }
1619     vlc_object_release( p_playlist );
1620     return NO;
1621 }
1622 @end
1623
1624