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