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