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