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