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