]> git.sesse.net Git - vlc/blob - modules/gui/macosx/playlist.m
Remove useless parameter
[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 = vlc_sd_GetNames( &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     PL_LOCK;
486     if( playlist_CurrentSize( p_playlist ) >= 2 )
487     {
488         [o_status_field setStringValue: [NSString stringWithFormat:
489                     _NS("%i items"),
490                 playlist_CurrentSize( p_playlist )]];
491     }
492     else
493     {
494         if( playlist_IsEmpty( p_playlist ) )
495             [o_status_field setStringValue: _NS("No items in the playlist")];
496         else
497             [o_status_field setStringValue: _NS("1 item")];
498     }
499     PL_UNLOCK;
500     vlc_object_release( p_playlist );
501
502     [self outlineViewSelectionDidChange: nil];
503 }
504
505 - (void)playModeUpdated
506 {
507     playlist_t *p_playlist = pl_Hold( VLCIntf );
508
509     bool loop = var_GetBool( p_playlist, "loop" );
510     bool repeat = var_GetBool( p_playlist, "repeat" );
511     if( repeat )
512         [[[VLCMain sharedInstance] getControls] repeatOne];
513     else if( loop )
514         [[[VLCMain sharedInstance] getControls] repeatAll];
515     else
516         [[[VLCMain sharedInstance] getControls] repeatOff];
517
518     [[[VLCMain sharedInstance] getControls] shuffle];
519
520     vlc_object_release( p_playlist );
521 }
522
523 - (void)outlineViewSelectionDidChange:(NSNotification *)notification
524 {
525     // FIXME: unsafe
526     playlist_item_t * p_item = [[o_outline_view itemAtRow:[o_outline_view selectedRow]] pointerValue];
527
528     if( p_item )
529     {
530         /* update the state of our Reveal-in-Finder menu items */
531         NSMutableString *o_mrl;
532         char *psz_uri = input_item_GetURI( p_item->p_input );
533         if( psz_uri )
534         {
535             o_mrl = [NSMutableString stringWithUTF8String: psz_uri];
536         
537             /* perform some checks whether it is a file and if it is local at all... */
538             NSRange prefix_range = [o_mrl rangeOfString: @"file:"];
539             if( prefix_range.location != NSNotFound )
540                 [o_mrl deleteCharactersInRange: prefix_range];
541             
542             if( [o_mrl characterAtIndex:0] == '/' )
543             {
544                 [o_mi_revealInFinder setEnabled: YES];
545                 [o_mm_mi_revealInFinder setEnabled: YES];
546                 return;
547             }
548         }
549         [o_mi_revealInFinder setEnabled: NO];
550         [o_mm_mi_revealInFinder setEnabled: NO];
551     }
552 }
553
554 - (BOOL)isSelectionEmpty
555 {
556     return [o_outline_view selectedRow] == -1;
557 }
558
559 - (void)updateRowSelection
560 {
561     int i_row;
562     unsigned int j;
563
564     // FIXME: unsafe
565     playlist_t *p_playlist = pl_Hold( VLCIntf );
566     playlist_item_t *p_item, *p_temp_item;
567     NSMutableArray *o_array = [NSMutableArray array];
568
569     p_item = playlist_CurrentPlayingItem( p_playlist );
570     if( p_item == NULL )
571     {
572         pl_Release( VLCIntf );
573         return;
574     }
575
576     p_temp_item = p_item;
577     while( p_temp_item->p_parent )
578     {
579         [o_array insertObject: [NSValue valueWithPointer: p_temp_item] atIndex: 0];
580         p_temp_item = p_temp_item->p_parent;
581     }
582
583     for( j = 0; j < [o_array count] - 1; j++ )
584     {
585         id o_item;
586         if( ( o_item = [o_outline_dict objectForKey:
587                             [NSString stringWithFormat: @"%p",
588                             [[o_array objectAtIndex:j] pointerValue]]] ) != nil )
589         {
590             [o_outline_view expandItem: o_item];
591         }
592
593     }
594
595     pl_Release( VLCIntf );
596 }
597
598 /* Check if p_item is a child of p_node recursively. We need to check the item
599    existence first since OSX sometimes tries to redraw items that have been
600    deleted. We don't do it when not required since this verification takes
601    quite a long time on big playlists (yes, pretty hacky). */
602
603 - (BOOL)isItem: (playlist_item_t *)p_item
604                     inNode: (playlist_item_t *)p_node
605                     checkItemExistence:(BOOL)b_check
606                     locked:(BOOL)b_locked
607
608 {
609     playlist_t * p_playlist = pl_Hold( VLCIntf );
610     playlist_item_t *p_temp_item = p_item;
611
612     if( p_node == p_item )
613     {
614         vlc_object_release(p_playlist);
615         return YES;
616     }
617
618     if( p_node->i_children < 1)
619     {
620         vlc_object_release(p_playlist);
621         return NO;
622     }
623
624     if ( p_temp_item )
625     {
626         int i;
627         if(!b_locked) PL_LOCK;
628
629         if( b_check )
630         {
631         /* Since outlineView: willDisplayCell:... may call this function with
632            p_items that don't exist anymore, first check if the item is still
633            in the playlist. Any cleaner solution welcomed. */
634             for( i = 0; i < p_playlist->all_items.i_size; i++ )
635             {
636                 if( ARRAY_VAL( p_playlist->all_items, i) == p_item ) break;
637                 else if ( i == p_playlist->all_items.i_size - 1 )
638                 {
639                     if(!b_locked) PL_UNLOCK;
640                     vlc_object_release( p_playlist );
641                     return NO;
642                 }
643             }
644         }
645
646         while( p_temp_item )
647         {
648             p_temp_item = p_temp_item->p_parent;
649             if( p_temp_item == p_node )
650             {
651                 if(!b_locked) PL_UNLOCK;
652                 vlc_object_release( p_playlist );
653                 return YES;
654             }
655         }
656         if(!b_locked) PL_UNLOCK;
657     }
658
659     vlc_object_release( p_playlist );
660     return NO;
661 }
662
663 - (BOOL)isItem: (playlist_item_t *)p_item
664                     inNode: (playlist_item_t *)p_node
665                     checkItemExistence:(BOOL)b_check
666 {
667     [self isItem:p_item inNode:p_node checkItemExistence:b_check locked:NO];
668 }
669
670 /* This method is usefull for instance to remove the selected children of an
671    already selected node */
672 - (void)removeItemsFrom:(id)o_items ifChildrenOf:(id)o_nodes
673 {
674     unsigned int i, j;
675     for( i = 0 ; i < [o_items count] ; i++ )
676     {
677         for ( j = 0 ; j < [o_nodes count] ; j++ )
678         {
679             if( o_items == o_nodes)
680             {
681                 if( j == i ) continue;
682             }
683             if( [self isItem: [[o_items objectAtIndex:i] pointerValue]
684                     inNode: [[o_nodes objectAtIndex:j] pointerValue]
685                     checkItemExistence: NO locked:NO] )
686             {
687                 [o_items removeObjectAtIndex:i];
688                 /* We need to execute the next iteration with the same index
689                    since the current item has been deleted */
690                 i--;
691                 break;
692             }
693         }
694     }
695 }
696
697 - (IBAction)savePlaylist:(id)sender
698 {
699     playlist_t * p_playlist = pl_Hold( VLCIntf );
700
701     NSSavePanel *o_save_panel = [NSSavePanel savePanel];
702     NSString * o_name = [NSString stringWithFormat: @"%@", _NS("Untitled")];
703
704     //[o_save_panel setAllowedFileTypes: [NSArray arrayWithObjects: @"m3u", @"xpf", nil] ];
705     [o_save_panel setTitle: _NS("Save Playlist")];
706     [o_save_panel setPrompt: _NS("Save")];
707     [o_save_panel setAccessoryView: o_save_accessory_view];
708
709     if( [o_save_panel runModalForDirectory: nil
710             file: o_name] == NSOKButton )
711     {
712         NSString *o_filename = [o_save_panel filename];
713
714         if( [o_save_accessory_popup indexOfSelectedItem] == 1 )
715         {
716             NSString * o_real_filename;
717             NSRange range;
718             range.location = [o_filename length] - [@".xspf" length];
719             range.length = [@".xspf" length];
720
721             if( [o_filename compare:@".xspf" options: NSCaseInsensitiveSearch
722                                              range: range] != NSOrderedSame )
723             {
724                 o_real_filename = [NSString stringWithFormat: @"%@.xspf", o_filename];
725             }
726             else
727             {
728                 o_real_filename = o_filename;
729             }
730             playlist_Export( p_playlist,
731                 [o_real_filename fileSystemRepresentation],
732                 p_playlist->p_local_category, "export-xspf" );
733         }
734         else
735         {
736             NSString * o_real_filename;
737             NSRange range;
738             range.location = [o_filename length] - [@".m3u" length];
739             range.length = [@".m3u" length];
740
741             if( [o_filename compare:@".m3u" options: NSCaseInsensitiveSearch
742                                              range: range] != NSOrderedSame )
743             {
744                 o_real_filename = [NSString stringWithFormat: @"%@.m3u", o_filename];
745             }
746             else
747             {
748                 o_real_filename = o_filename;
749             }
750             playlist_Export( p_playlist,
751                 [o_real_filename fileSystemRepresentation],
752                 p_playlist->p_local_category, "export-m3u" );
753         }
754     }
755     vlc_object_release( p_playlist );
756 }
757
758 /* When called retrieves the selected outlineview row and plays that node or item */
759 - (IBAction)playItem:(id)sender
760 {
761     intf_thread_t * p_intf = VLCIntf;
762     playlist_t * p_playlist = pl_Hold( p_intf );
763
764     playlist_item_t *p_item;
765     playlist_item_t *p_node = NULL;
766
767     p_item = [[o_outline_view itemAtRow:[o_outline_view selectedRow]] pointerValue];
768
769     if( p_item )
770     {
771         if( p_item->i_children == -1 )
772         {
773             p_node = p_item->p_parent;
774
775         }
776         else
777         {
778             p_node = p_item;
779             if( p_node->i_children > 0 && p_node->pp_children[0]->i_children == -1 )
780             {
781                 p_item = p_node->pp_children[0];
782             }
783             else
784             {
785                 p_item = NULL;
786             }
787         }
788         playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, pl_Unlocked, p_node, p_item );
789     }
790     vlc_object_release( p_playlist );
791 }
792
793 - (IBAction)revealItemInFinder:(id)sender
794 {
795     playlist_item_t * p_item = [[o_outline_view itemAtRow:[o_outline_view selectedRow]] pointerValue];
796     NSMutableString * o_mrl = nil;
797
798     if(! p_item || !p_item->p_input )
799         return;
800     
801     char *psz_uri = input_item_GetURI( p_item->p_input );
802     if( psz_uri )
803         o_mrl = [NSMutableString stringWithUTF8String: psz_uri];
804
805     /* perform some checks whether it is a file and if it is local at all... */
806     NSRange prefix_range = [o_mrl rangeOfString: @"file:"];
807     if( prefix_range.location != NSNotFound )
808         [o_mrl deleteCharactersInRange: prefix_range];
809     
810     if( [o_mrl characterAtIndex:0] == '/' )
811         [[NSWorkspace sharedWorkspace] selectFile: o_mrl inFileViewerRootedAtPath: o_mrl];
812 }    
813
814 /* When called retrieves the selected outlineview row and plays that node or item */
815 - (IBAction)preparseItem:(id)sender
816 {
817     int i_count;
818     NSMutableArray *o_to_preparse;
819     intf_thread_t * p_intf = VLCIntf;
820     playlist_t * p_playlist = pl_Hold( p_intf );
821  
822     o_to_preparse = [NSMutableArray arrayWithArray:[[o_outline_view selectedRowEnumerator] allObjects]];
823     i_count = [o_to_preparse count];
824
825     int i, i_row;
826     NSNumber *o_number;
827     playlist_item_t *p_item = NULL;
828
829     for( i = 0; i < i_count; i++ )
830     {
831         o_number = [o_to_preparse lastObject];
832         i_row = [o_number intValue];
833         p_item = [[o_outline_view itemAtRow:i_row] pointerValue];
834         [o_to_preparse removeObject: o_number];
835         [o_outline_view deselectRow: i_row];
836
837         if( p_item )
838         {
839             if( p_item->i_children == -1 )
840             {
841                 playlist_PreparseEnqueue( p_playlist, p_item->p_input, pl_Unlocked );
842             }
843             else
844             {
845                 msg_Dbg( p_intf, "preparsing nodes not implemented" );
846             }
847         }
848     }
849     vlc_object_release( p_playlist );
850     [self playlistUpdated];
851 }
852
853 - (IBAction)downloadCoverArt:(id)sender
854 {
855     int i_count;
856     NSMutableArray *o_to_preparse;
857     intf_thread_t * p_intf = VLCIntf;
858     playlist_t * p_playlist = pl_Hold( p_intf );
859
860     o_to_preparse = [NSMutableArray arrayWithArray:[[o_outline_view selectedRowEnumerator] allObjects]];
861     i_count = [o_to_preparse count];
862
863     int i, i_row;
864     NSNumber *o_number;
865     playlist_item_t *p_item = NULL;
866
867     for( i = 0; i < i_count; i++ )
868     {
869         o_number = [o_to_preparse lastObject];
870         i_row = [o_number intValue];
871         p_item = [[o_outline_view itemAtRow:i_row] pointerValue];
872         [o_to_preparse removeObject: o_number];
873         [o_outline_view deselectRow: i_row];
874
875         if( p_item && p_item->i_children == -1 )
876         {
877             playlist_AskForArtEnqueue( p_playlist, p_item->p_input, pl_Unlocked );
878         }
879     }
880     vlc_object_release( p_playlist );
881     [self playlistUpdated];
882 }
883
884 - (IBAction)servicesChange:(id)sender
885 {
886     NSMenuItem *o_mi = (NSMenuItem *)sender;
887     NSString *o_string = [o_mi representedObject];
888     playlist_t * p_playlist = pl_Hold( VLCIntf );
889     if( !playlist_IsServicesDiscoveryLoaded( p_playlist, [o_string UTF8String] ) )
890         playlist_ServicesDiscoveryAdd( p_playlist, [o_string UTF8String] );
891     else
892         playlist_ServicesDiscoveryRemove( p_playlist, [o_string UTF8String] );
893
894     [o_mi setState: playlist_IsServicesDiscoveryLoaded( p_playlist,
895                                           [o_string UTF8String] ) ? YES : NO];
896
897     vlc_object_release( p_playlist );
898     [self playlistUpdated];
899     return;
900 }
901
902 - (IBAction)selectAll:(id)sender
903 {
904     [o_outline_view selectAll: nil];
905 }
906
907 - (IBAction)deleteItem:(id)sender
908 {
909     int i_count, i_row;
910     NSMutableArray *o_to_delete;
911     NSNumber *o_number;
912
913     playlist_t * p_playlist;
914     intf_thread_t * p_intf = VLCIntf;
915
916     o_to_delete = [NSMutableArray arrayWithArray:[[o_outline_view selectedRowEnumerator] allObjects]];
917     i_count = [o_to_delete count];
918
919     p_playlist = pl_Hold( p_intf );
920
921     PL_LOCK;
922     for( int i = 0; i < i_count; i++ )
923     {
924         o_number = [o_to_delete lastObject];
925         i_row = [o_number intValue];
926         id o_item = [o_outline_view itemAtRow: i_row];
927         playlist_item_t *p_item = [o_item pointerValue];
928 #ifndef NDEBUG
929         msg_Dbg( p_intf, "deleting item %i (of %i) with id \"%i\", pointerValue \"%p\" and %i children", i+1, i_count, 
930                 p_item->p_input->i_id, [o_item pointerValue], p_item->i_children +1 );
931 #endif
932         [o_to_delete removeObject: o_number];
933         [o_outline_view deselectRow: i_row];
934
935         if( p_item->i_children != -1 )
936         //is a node and not an item
937         {
938             if( playlist_Status( p_playlist ) != PLAYLIST_STOPPED &&
939                 [self isItem: playlist_CurrentPlayingItem( p_playlist ) inNode:
940                         ((playlist_item_t *)[o_item pointerValue])
941                         checkItemExistence: NO locked:YES] == YES )
942                 // if current item is in selected node and is playing then stop playlist
943                 playlist_Control(p_playlist, PLAYLIST_STOP, pl_Locked );
944     
945             playlist_NodeDelete( p_playlist, p_item, true, false );
946         }
947         else
948             playlist_DeleteFromInput( p_playlist, p_item->p_input->i_id, pl_Locked );
949     }
950     PL_UNLOCK;
951
952     [self playlistUpdated];
953     vlc_object_release( p_playlist );
954 }
955
956 - (IBAction)sortNodeByName:(id)sender
957 {
958     [self sortNode: SORT_TITLE];
959 }
960
961 - (IBAction)sortNodeByAuthor:(id)sender
962 {
963     [self sortNode: SORT_ARTIST];
964 }
965
966 - (void)sortNode:(int)i_mode
967 {
968     playlist_t * p_playlist = pl_Hold( VLCIntf );
969     playlist_item_t * p_item;
970
971     if( [o_outline_view selectedRow] > -1 )
972     {
973         p_item = [[o_outline_view itemAtRow: [o_outline_view selectedRow]] pointerValue];
974     }
975     else
976     /*If no item is selected, sort the whole playlist*/
977     {
978         p_item = p_playlist->p_root_category;
979     }
980
981     if( p_item->i_children > -1 ) // the item is a node
982     {
983         PL_LOCK;
984         playlist_RecursiveNodeSort( p_playlist, p_item, i_mode, ORDER_NORMAL );
985         PL_UNLOCK;
986     }
987     else
988     {
989         PL_LOCK;
990         playlist_RecursiveNodeSort( p_playlist,
991                 p_item->p_parent, i_mode, ORDER_NORMAL );
992         PL_UNLOCK;
993     }
994     vlc_object_release( p_playlist );
995     [self playlistUpdated];
996 }
997
998 - (input_item_t *)createItem:(NSDictionary *)o_one_item
999 {
1000     intf_thread_t * p_intf = VLCIntf;
1001     playlist_t * p_playlist = pl_Hold( p_intf );
1002
1003     input_item_t *p_input;
1004     int i;
1005     BOOL b_rem = FALSE, b_dir = FALSE;
1006     NSString *o_uri, *o_name;
1007     NSArray *o_options;
1008     NSURL *o_true_file;
1009
1010     /* Get the item */
1011     o_uri = (NSString *)[o_one_item objectForKey: @"ITEM_URL"];
1012     o_name = (NSString *)[o_one_item objectForKey: @"ITEM_NAME"];
1013     o_options = (NSArray *)[o_one_item objectForKey: @"ITEM_OPTIONS"];
1014
1015     /* Find the name for a disc entry (i know, can you believe the trouble?) */
1016     if( ( !o_name || [o_name isEqualToString:@""] ) && [o_uri rangeOfString: @"/dev/"].location != NSNotFound )
1017     {
1018         int i_count, i_index;
1019         struct statfs *mounts = NULL;
1020
1021         i_count = getmntinfo (&mounts, MNT_NOWAIT);
1022         /* getmntinfo returns a pointer to static data. Do not free. */
1023         for( i_index = 0 ; i_index < i_count; i_index++ )
1024         {
1025             NSMutableString *o_temp, *o_temp2;
1026             o_temp = [NSMutableString stringWithString: o_uri];
1027             o_temp2 = [NSMutableString stringWithUTF8String: mounts[i_index].f_mntfromname];
1028             [o_temp replaceOccurrencesOfString: @"/dev/rdisk" withString: @"/dev/disk" options:NSLiteralSearch range:NSMakeRange(0, [o_temp length]) ];
1029             [o_temp2 replaceOccurrencesOfString: @"s0" withString: @"" options:NSLiteralSearch range:NSMakeRange(0, [o_temp2 length]) ];
1030             [o_temp2 replaceOccurrencesOfString: @"s1" withString: @"" options:NSLiteralSearch range:NSMakeRange(0, [o_temp2 length]) ];
1031
1032             if( strstr( [o_temp fileSystemRepresentation], [o_temp2 fileSystemRepresentation] ) != NULL )
1033             {
1034                 o_name = [[NSFileManager defaultManager] displayNameAtPath: [NSString stringWithUTF8String:mounts[i_index].f_mntonname]];
1035             }
1036         }
1037     }
1038     /* If no name, then make a guess */
1039     if( !o_name) o_name = [[NSFileManager defaultManager] displayNameAtPath: o_uri];
1040
1041     if( [[NSFileManager defaultManager] fileExistsAtPath:o_uri isDirectory:&b_dir] && b_dir &&
1042         [[NSWorkspace sharedWorkspace] getFileSystemInfoForPath: o_uri isRemovable: &b_rem
1043                 isWritable:NULL isUnmountable:NULL description:NULL type:NULL] && b_rem   )
1044     {
1045         /* All of this is to make sure CD's play when you D&D them on VLC */
1046         /* Converts mountpoint to a /dev file */
1047         struct statfs *buf;
1048         char *psz_dev;
1049         NSMutableString *o_temp;
1050
1051         buf = (struct statfs *) malloc (sizeof(struct statfs));
1052         statfs( [o_uri fileSystemRepresentation], buf );
1053         psz_dev = strdup(buf->f_mntfromname);
1054         o_temp = [NSMutableString stringWithUTF8String: psz_dev ];
1055         [o_temp replaceOccurrencesOfString: @"/dev/disk" withString: @"/dev/rdisk" options:NSLiteralSearch range:NSMakeRange(0, [o_temp length]) ];
1056         [o_temp replaceOccurrencesOfString: @"s0" withString: @"" options:NSLiteralSearch range:NSMakeRange(0, [o_temp length]) ];
1057         [o_temp replaceOccurrencesOfString: @"s1" withString: @"" options:NSLiteralSearch range:NSMakeRange(0, [o_temp length]) ];
1058         o_uri = o_temp;
1059     }
1060
1061     p_input = input_item_New( p_playlist, [o_uri fileSystemRepresentation], [o_name UTF8String] );
1062     if( !p_input )
1063        return NULL;
1064
1065     if( o_options )
1066     {
1067         for( i = 0; i < (int)[o_options count]; i++ )
1068         {
1069             input_item_AddOption( p_input, strdup( [[o_options objectAtIndex:i] UTF8String] ) );
1070         }
1071     }
1072
1073     /* Recent documents menu */
1074     o_true_file = [NSURL fileURLWithPath: o_uri];
1075     if( o_true_file != nil && (BOOL)config_GetInt( p_playlist, "macosx-recentitems" ) == YES )
1076     {
1077         [[NSDocumentController sharedDocumentController]
1078             noteNewRecentDocumentURL: o_true_file];
1079     }
1080
1081     vlc_object_release( p_playlist );
1082     return p_input;
1083 }
1084
1085 - (void)appendArray:(NSArray*)o_array atPos:(int)i_position enqueue:(BOOL)b_enqueue
1086 {
1087     int i_item;
1088     playlist_t * p_playlist = pl_Hold( VLCIntf );
1089
1090     PL_LOCK;
1091     for( i_item = 0; i_item < (int)[o_array count]; i_item++ )
1092     {
1093         input_item_t *p_input;
1094         NSDictionary *o_one_item;
1095
1096         /* Get the item */
1097         o_one_item = [o_array objectAtIndex: i_item];
1098         p_input = [self createItem: o_one_item];
1099         if( !p_input )
1100         {
1101             continue;
1102         }
1103
1104         /* Add the item */
1105         /* FIXME: playlist_AddInput() can fail */
1106         
1107         playlist_AddInput( p_playlist, p_input, PLAYLIST_INSERT,
1108              i_position == -1 ? PLAYLIST_END : i_position + i_item, true,
1109          pl_Locked );
1110
1111         if( i_item == 0 && !b_enqueue )
1112         {
1113             playlist_item_t *p_item = NULL;
1114             playlist_item_t *p_node = NULL;
1115             p_item = playlist_ItemGetByInput( p_playlist, p_input, pl_Locked );
1116             if( p_item )
1117             {
1118                 if( p_item->i_children == -1 )
1119                     p_node = p_item->p_parent;
1120                 else
1121                 {
1122                     p_node = p_item;
1123                     if( p_node->i_children > 0 && p_node->pp_children[0]->i_children == -1 )
1124                         p_item = p_node->pp_children[0];
1125                     else
1126                         p_item = NULL;
1127                 }
1128                 playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, pl_Locked, p_node, p_item );
1129             }
1130         }
1131         vlc_gc_decref( p_input );
1132     }
1133     PL_UNLOCK;
1134
1135     [self playlistUpdated];
1136     vlc_object_release( p_playlist );
1137 }
1138
1139 - (void)appendNodeArray:(NSArray*)o_array inNode:(playlist_item_t *)p_node atPos:(int)i_position enqueue:(BOOL)b_enqueue
1140 {
1141     int i_item;
1142     playlist_t * p_playlist = pl_Hold( VLCIntf );
1143
1144     for( i_item = 0; i_item < (int)[o_array count]; i_item++ )
1145     {
1146         input_item_t *p_input;
1147         NSDictionary *o_one_item;
1148
1149         /* Get the item */
1150         o_one_item = [o_array objectAtIndex: i_item];
1151         p_input = [self createItem: o_one_item];
1152
1153         if( !p_input ) continue;
1154
1155         /* Add the item */
1156         /* FIXME: playlist_BothAddInput() can fail */
1157         PL_LOCK;
1158         playlist_BothAddInput( p_playlist, p_input, p_node,
1159                                       PLAYLIST_INSERT,
1160                                       i_position == -1 ?
1161                                       PLAYLIST_END : i_position + i_item,
1162                                       NULL, NULL, pl_Locked );
1163
1164
1165         if( i_item == 0 && !b_enqueue )
1166         {
1167             playlist_item_t *p_item;
1168             p_item = playlist_ItemGetByInput( p_playlist, p_input, pl_Locked );
1169             playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, pl_Locked, p_node, p_item );
1170         }
1171         PL_UNLOCK;
1172         vlc_gc_decref( p_input );
1173     }
1174     [self playlistUpdated];
1175     vlc_object_release( p_playlist );
1176 }
1177
1178 - (NSMutableArray *)subSearchItem:(playlist_item_t *)p_item
1179 {
1180     playlist_t *p_playlist = pl_Hold( VLCIntf );
1181     playlist_item_t *p_selected_item;
1182     int i_current, i_selected_row;
1183
1184     i_selected_row = [o_outline_view selectedRow];
1185     if (i_selected_row < 0)
1186         i_selected_row = 0;
1187
1188     p_selected_item = (playlist_item_t *)[[o_outline_view itemAtRow:
1189                                             i_selected_row] pointerValue];
1190
1191     for( i_current = 0; i_current < p_item->i_children ; i_current++ )
1192     {
1193         char *psz_temp;
1194         NSString *o_current_name, *o_current_author;
1195
1196         PL_LOCK;
1197         o_current_name = [NSString stringWithUTF8String:
1198             p_item->pp_children[i_current]->p_input->psz_name];
1199         psz_temp = input_item_GetInfo( p_item->p_input ,
1200                    _("Meta-information"),_("Artist") );
1201         o_current_author = [NSString stringWithUTF8String: psz_temp];
1202         free( psz_temp);
1203         PL_UNLOCK;
1204
1205         if( p_selected_item == p_item->pp_children[i_current] &&
1206                     b_selected_item_met == NO )
1207         {
1208             b_selected_item_met = YES;
1209         }
1210         else if( p_selected_item == p_item->pp_children[i_current] &&
1211                     b_selected_item_met == YES )
1212         {
1213             vlc_object_release( p_playlist );
1214             return NULL;
1215         }
1216         else if( b_selected_item_met == YES &&
1217                     ( [o_current_name rangeOfString:[o_search_field
1218                         stringValue] options:NSCaseInsensitiveSearch].length ||
1219                       [o_current_author rangeOfString:[o_search_field
1220                         stringValue] options:NSCaseInsensitiveSearch].length ) )
1221         {
1222             vlc_object_release( p_playlist );
1223             /*Adds the parent items in the result array as well, so that we can
1224             expand the tree*/
1225             return [NSMutableArray arrayWithObject: [NSValue
1226                             valueWithPointer: p_item->pp_children[i_current]]];
1227         }
1228         if( p_item->pp_children[i_current]->i_children > 0 )
1229         {
1230             id o_result = [self subSearchItem:
1231                                             p_item->pp_children[i_current]];
1232             if( o_result != NULL )
1233             {
1234                 vlc_object_release( p_playlist );
1235                 [o_result insertObject: [NSValue valueWithPointer:
1236                                 p_item->pp_children[i_current]] atIndex:0];
1237                 return o_result;
1238             }
1239         }
1240     }
1241     vlc_object_release( p_playlist );
1242     return NULL;
1243 }
1244
1245 - (IBAction)searchItem:(id)sender
1246 {
1247     playlist_t * p_playlist = pl_Hold( VLCIntf );
1248     id o_result;
1249
1250     unsigned int i;
1251     int i_row = -1;
1252
1253     b_selected_item_met = NO;
1254
1255         /*First, only search after the selected item:*
1256          *(b_selected_item_met = NO)                 */
1257     o_result = [self subSearchItem:p_playlist->p_root_category];
1258     if( o_result == NULL )
1259     {
1260         /* If the first search failed, search again from the beginning */
1261         o_result = [self subSearchItem:p_playlist->p_root_category];
1262     }
1263     if( o_result != NULL )
1264     {
1265         int i_start;
1266         if( [[o_result objectAtIndex: 0] pointerValue] ==
1267                                                     p_playlist->p_local_category )
1268         i_start = 1;
1269         else
1270         i_start = 0;
1271
1272         for( i = i_start ; i < [o_result count] - 1 ; i++ )
1273         {
1274             [o_outline_view expandItem: [o_outline_dict objectForKey:
1275                         [NSString stringWithFormat: @"%p",
1276                         [[o_result objectAtIndex: i] pointerValue]]]];
1277         }
1278         i_row = [o_outline_view rowForItem: [o_outline_dict objectForKey:
1279                         [NSString stringWithFormat: @"%p",
1280                         [[o_result objectAtIndex: [o_result count] - 1 ]
1281                         pointerValue]]]];
1282     }
1283     if( i_row > -1 )
1284     {
1285         [o_outline_view selectRow:i_row byExtendingSelection: NO];
1286         [o_outline_view scrollRowToVisible: i_row];
1287     }
1288     vlc_object_release( p_playlist );
1289 }
1290
1291 - (IBAction)recursiveExpandNode:(id)sender
1292 {
1293     id o_item = [o_outline_view itemAtRow: [o_outline_view selectedRow]];
1294     playlist_item_t *p_item = (playlist_item_t *)[o_item pointerValue];
1295
1296     if( ![[o_outline_view dataSource] outlineView: o_outline_view
1297                                                     isItemExpandable: o_item] )
1298     {
1299         o_item = [o_outline_dict objectForKey: [NSString
1300                    stringWithFormat: @"%p", p_item->p_parent]];
1301     }
1302
1303     /* We need to collapse the node first, since OSX refuses to recursively
1304        expand an already expanded node, even if children nodes are collapsed. */
1305     [o_outline_view collapseItem: o_item collapseChildren: YES];
1306     [o_outline_view expandItem: o_item expandChildren: YES];
1307 }
1308
1309 - (NSMenu *)menuForEvent:(NSEvent *)o_event
1310 {
1311     NSPoint pt;
1312     bool b_rows;
1313     bool b_item_sel;
1314
1315     pt = [o_outline_view convertPoint: [o_event locationInWindow]
1316                                                  fromView: nil];
1317     int row = [o_outline_view rowAtPoint:pt];
1318     if( row != -1 )
1319         [o_outline_view selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
1320
1321     b_item_sel = ( row != -1 && [o_outline_view selectedRow] != -1 );
1322     b_rows = [o_outline_view numberOfRows] != 0;
1323
1324     [o_mi_play setEnabled: b_item_sel];
1325     [o_mi_delete setEnabled: b_item_sel];
1326     [o_mi_selectall setEnabled: b_rows];
1327     [o_mi_info setEnabled: b_item_sel];
1328     [o_mi_preparse setEnabled: b_item_sel];
1329     [o_mi_recursive_expand setEnabled: b_item_sel];
1330     [o_mi_sort_name setEnabled: b_item_sel];
1331     [o_mi_sort_author setEnabled: b_item_sel];
1332
1333     return( o_ctx_menu );
1334 }
1335
1336 - (void)outlineView: (NSOutlineView *)o_tv
1337                   didClickTableColumn:(NSTableColumn *)o_tc
1338 {
1339     int i_mode, i_type = 0;
1340     intf_thread_t *p_intf = VLCIntf;
1341
1342     playlist_t *p_playlist = pl_Hold( p_intf );
1343
1344     /* Check whether the selected table column header corresponds to a
1345        sortable table column*/
1346     if( !( o_tc == o_tc_name || o_tc == o_tc_author ) )
1347     {
1348         vlc_object_release( p_playlist );
1349         return;
1350     }
1351
1352     if( o_tc_sortColumn == o_tc )
1353     {
1354         b_isSortDescending = !b_isSortDescending;
1355     }
1356     else
1357     {
1358         b_isSortDescending = false;
1359     }
1360
1361     if( o_tc == o_tc_name )
1362     {
1363         i_mode = SORT_TITLE;
1364     }
1365     else if( o_tc == o_tc_author )
1366     {
1367         i_mode = SORT_ARTIST;
1368     }
1369
1370     if( b_isSortDescending )
1371     {
1372         i_type = ORDER_REVERSE;
1373     }
1374     else
1375     {
1376         i_type = ORDER_NORMAL;
1377     }
1378
1379     PL_LOCK;
1380     playlist_RecursiveNodeSort( p_playlist, p_playlist->p_root_category, i_mode, i_type );
1381     PL_UNLOCK;
1382
1383     vlc_object_release( p_playlist );
1384     [self playlistUpdated];
1385
1386     o_tc_sortColumn = o_tc;
1387     [o_outline_view setHighlightedTableColumn:o_tc];
1388
1389     if( b_isSortDescending )
1390     {
1391         [o_outline_view setIndicatorImage:o_descendingSortingImage
1392                                                         inTableColumn:o_tc];
1393     }
1394     else
1395     {
1396         [o_outline_view setIndicatorImage:o_ascendingSortingImage
1397                                                         inTableColumn:o_tc];
1398     }
1399 }
1400
1401
1402 - (void)outlineView:(NSOutlineView *)outlineView
1403                                 willDisplayCell:(id)cell
1404                                 forTableColumn:(NSTableColumn *)tableColumn
1405                                 item:(id)item
1406 {
1407     playlist_t *p_playlist = pl_Hold( VLCIntf );
1408
1409     id o_playing_item;
1410
1411     o_playing_item = [o_outline_dict objectForKey:
1412                 [NSString stringWithFormat:@"%p",  playlist_CurrentPlayingItem( p_playlist )]];
1413
1414     if( [self isItem: [o_playing_item pointerValue] inNode:
1415                         [item pointerValue] checkItemExistence: YES]
1416                         || [o_playing_item isEqual: item] )
1417     {
1418         [cell setFont: [[NSFontManager sharedFontManager] convertFont:[cell font] toHaveTrait:NSBoldFontMask]];
1419     }
1420     else
1421     {
1422         [cell setFont: [[NSFontManager sharedFontManager] convertFont:[cell font] toNotHaveTrait:NSBoldFontMask]];
1423     }
1424     vlc_object_release( p_playlist );
1425 }
1426
1427 - (IBAction)addNode:(id)sender
1428 {
1429     /* we have to create a new thread here because otherwise we would block the
1430      * interface since the interaction-stuff and this code would run in the same
1431      * thread */
1432     [NSThread detachNewThreadSelector: @selector(addNodeThreadedly)
1433         toTarget: self withObject:nil];
1434     [self playlistUpdated];
1435 }
1436
1437 - (void)addNodeThreadedly
1438 {
1439     NSAutoreleasePool * ourPool = [[NSAutoreleasePool alloc] init];
1440
1441     /* simply adds a new node to the end of the playlist */
1442     playlist_t * p_playlist = pl_Hold( VLCIntf );
1443     vlc_thread_set_priority( p_playlist, VLC_THREAD_PRIORITY_LOW );
1444
1445     int ret_v;
1446     char *psz_name = NULL;
1447     ret_v = intf_UserStringInput( p_playlist, _("New Node"),
1448         _("Please enter a name for the new node."), &psz_name );
1449
1450     PL_LOCK;
1451     if( ret_v != DIALOG_CANCELLED && psz_name )
1452     {
1453         playlist_NodeCreate( p_playlist, psz_name,
1454                                       p_playlist->p_local_category, 0, NULL );
1455     }
1456     else if(! config_GetInt( p_playlist, "interact" ) )
1457     {
1458         /* in case that the interaction is disabled, just give it a bogus name */
1459         playlist_NodeCreate( p_playlist, _("Empty Folder"),
1460                                       p_playlist->p_local_category, 0, NULL );
1461     }
1462     PL_UNLOCK;
1463
1464     free( psz_name );
1465     pl_Release( VLCIntf );
1466     [ourPool release];
1467 }
1468
1469 @end
1470
1471 @implementation VLCPlaylist (NSOutlineViewDataSource)
1472
1473 - (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item
1474 {
1475     id o_value = [super outlineView: outlineView child: index ofItem: item];
1476     playlist_t *p_playlist = pl_Hold( VLCIntf );
1477
1478     PL_LOCK;
1479     if( playlist_CurrentSize( p_playlist )  >= 2 )
1480     {
1481         [o_status_field setStringValue: [NSString stringWithFormat:
1482                     _NS("%i items"),
1483              playlist_CurrentSize( p_playlist )]];
1484     }
1485     else
1486     {
1487         if( playlist_IsEmpty( p_playlist ) )
1488         {
1489             [o_status_field setStringValue: _NS("No items in the playlist")];
1490         }
1491         else
1492         {
1493             [o_status_field setStringValue: _NS("1 item")];
1494         }
1495     }
1496     PL_UNLOCK;
1497
1498     vlc_object_release( p_playlist );
1499
1500     [o_outline_dict setObject:o_value forKey:[NSString stringWithFormat:@"%p",
1501                                                     [o_value pointerValue]]];
1502     return o_value;
1503
1504 }
1505
1506 /* Required for drag & drop and reordering */
1507 - (BOOL)outlineView:(NSOutlineView *)outlineView writeItems:(NSArray *)items toPasteboard:(NSPasteboard *)pboard
1508 {
1509     unsigned int i;
1510     playlist_t *p_playlist = pl_Hold( VLCIntf );
1511
1512     /* First remove the items that were moved during the last drag & drop
1513        operation */
1514     [o_items_array removeAllObjects];
1515     [o_nodes_array removeAllObjects];
1516
1517     for( i = 0 ; i < [items count] ; i++ )
1518     {
1519         id o_item = [items objectAtIndex: i];
1520
1521         /* Refuse to move items that are not in the General Node
1522            (Service Discovery) */
1523         if( ![self isItem: [o_item pointerValue] inNode:
1524                         p_playlist->p_local_category checkItemExistence: NO] &&
1525             var_CreateGetBool( p_playlist, "media-library" ) &&
1526             ![self isItem: [o_item pointerValue] inNode:
1527                         p_playlist->p_ml_category checkItemExistence: NO] ||
1528             [o_item pointerValue] == p_playlist->p_local_category ||
1529             [o_item pointerValue] == p_playlist->p_ml_category )
1530         {
1531             vlc_object_release(p_playlist);
1532             return NO;
1533         }
1534         /* Fill the items and nodes to move in 2 different arrays */
1535         if( ((playlist_item_t *)[o_item pointerValue])->i_children > 0 )
1536             [o_nodes_array addObject: o_item];
1537         else
1538             [o_items_array addObject: o_item];
1539     }
1540
1541     /* Now we need to check if there are selected items that are in already
1542        selected nodes. In that case, we only want to move the nodes */
1543     [self removeItemsFrom: o_nodes_array ifChildrenOf: o_nodes_array];
1544     [self removeItemsFrom: o_items_array ifChildrenOf: o_nodes_array];
1545
1546     /* We add the "VLCPlaylistItemPboardType" type to be able to recognize
1547        a Drop operation coming from the playlist. */
1548
1549     [pboard declareTypes: [NSArray arrayWithObjects:
1550         @"VLCPlaylistItemPboardType", nil] owner: self];
1551     [pboard setData:[NSData data] forType:@"VLCPlaylistItemPboardType"];
1552
1553     vlc_object_release(p_playlist);
1554     return YES;
1555 }
1556
1557 - (NSDragOperation)outlineView:(NSOutlineView *)outlineView validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(int)index
1558 {
1559     playlist_t *p_playlist = pl_Hold( VLCIntf );
1560     NSPasteboard *o_pasteboard = [info draggingPasteboard];
1561
1562     if( !p_playlist ) return NSDragOperationNone;
1563
1564     /* Dropping ON items is not allowed if item is not a node */
1565     if( item )
1566     {
1567         if( index == NSOutlineViewDropOnItemIndex &&
1568                 ((playlist_item_t *)[item pointerValue])->i_children == -1 )
1569         {
1570             vlc_object_release( p_playlist );
1571             return NSDragOperationNone;
1572         }
1573     }
1574
1575     /* Don't allow on drop on playlist root element's child */
1576     if( !item && index != NSOutlineViewDropOnItemIndex)
1577     {
1578         vlc_object_release( p_playlist );
1579         return NSDragOperationNone;
1580     }
1581
1582     /* We refuse to drop an item in anything else than a child of the General
1583        Node. We still accept items that would be root nodes of the outlineview
1584        however, to allow drop in an empty playlist. */
1585     if( !( ([self isItem: [item pointerValue] inNode: p_playlist->p_local_category checkItemExistence: NO] || 
1586         ( var_CreateGetBool( p_playlist, "media-library" ) && [self isItem: [item pointerValue] inNode: p_playlist->p_ml_category checkItemExistence: NO] ) ) || item == nil ) )
1587     {
1588         vlc_object_release( p_playlist );
1589         return NSDragOperationNone;
1590     }
1591
1592     /* Drop from the Playlist */
1593     if( [[o_pasteboard types] containsObject: @"VLCPlaylistItemPboardType"] )
1594     {
1595         unsigned int i;
1596         for( i = 0 ; i < [o_nodes_array count] ; i++ )
1597         {
1598             /* We refuse to Drop in a child of an item we are moving */
1599             if( [self isItem: [item pointerValue] inNode:
1600                     [[o_nodes_array objectAtIndex: i] pointerValue]
1601                     checkItemExistence: NO] )
1602             {
1603                 vlc_object_release( p_playlist );
1604                 return NSDragOperationNone;
1605             }
1606         }
1607         vlc_object_release( p_playlist );
1608         return NSDragOperationMove;
1609     }
1610
1611     /* Drop from the Finder */
1612     else if( [[o_pasteboard types] containsObject: NSFilenamesPboardType] )
1613     {
1614         vlc_object_release( p_playlist );
1615         return NSDragOperationGeneric;
1616     }
1617     vlc_object_release( p_playlist );
1618     return NSDragOperationNone;
1619 }
1620
1621 - (BOOL)outlineView:(NSOutlineView *)outlineView acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(int)index
1622 {
1623     playlist_t * p_playlist =  pl_Hold( VLCIntf );
1624     NSPasteboard *o_pasteboard = [info draggingPasteboard];
1625
1626     /* Drag & Drop inside the playlist */
1627     if( [[o_pasteboard types] containsObject: @"VLCPlaylistItemPboardType"] )
1628     {
1629         int i_row, i_removed_from_node = 0;
1630         unsigned int i;
1631         playlist_item_t *p_new_parent, *p_item = NULL;
1632         NSArray *o_all_items = [o_nodes_array arrayByAddingObjectsFromArray:
1633                                                                 o_items_array];
1634         /* If the item is to be dropped as root item of the outline, make it a
1635            child of the General node.
1636            Else, choose the proposed parent as parent. */
1637         if( item == nil ) p_new_parent = p_playlist->p_local_category;
1638         else p_new_parent = [item pointerValue];
1639
1640         /* Make sure the proposed parent is a node.
1641            (This should never be true) */
1642         if( p_new_parent->i_children < 0 )
1643         {
1644             vlc_object_release( p_playlist );
1645             return NO;
1646         }
1647
1648         for( i = 0; i < [o_all_items count]; i++ )
1649         {
1650             playlist_item_t *p_old_parent = NULL;
1651             int i_old_index = 0;
1652
1653             p_item = [[o_all_items objectAtIndex:i] pointerValue];
1654             p_old_parent = p_item->p_parent;
1655             if( !p_old_parent )
1656             continue;
1657             /* We may need the old index later */
1658             if( p_new_parent == p_old_parent )
1659             {
1660                 int j;
1661                 for( j = 0; j < p_old_parent->i_children; j++ )
1662                 {
1663                     if( p_old_parent->pp_children[j] == p_item )
1664                     {
1665                         i_old_index = j;
1666                         break;
1667                     }
1668                 }
1669             }
1670
1671             PL_LOCK;
1672             // Actually detach the item from the old position
1673             if( playlist_NodeRemoveItem( p_playlist, p_item, p_old_parent ) ==
1674                 VLC_SUCCESS )
1675             {
1676                 int i_new_index;
1677                 /* Calculate the new index */
1678                 if( index == -1 )
1679                 i_new_index = -1;
1680                 /* If we move the item in the same node, we need to take into
1681                    account that one item will be deleted */
1682                 else
1683                 {
1684                     if ((p_new_parent == p_old_parent &&
1685                                    i_old_index < index + (int)i) )
1686                     {
1687                         i_removed_from_node++;
1688                     }
1689                     i_new_index = index + i - i_removed_from_node;
1690                 }
1691                 // Reattach the item to the new position
1692                 playlist_NodeInsert( p_playlist, p_item, p_new_parent, i_new_index );
1693             }
1694             PL_UNLOCK;
1695         }
1696         [self playlistUpdated];
1697         i_row = [o_outline_view rowForItem:[o_outline_dict
1698             objectForKey:[NSString stringWithFormat: @"%p",
1699             [[o_all_items objectAtIndex: 0] pointerValue]]]];
1700
1701         if( i_row == -1 )
1702         {
1703             i_row = [o_outline_view rowForItem:[o_outline_dict
1704             objectForKey:[NSString stringWithFormat: @"%p", p_new_parent]]];
1705         }
1706
1707         [o_outline_view deselectAll: self];
1708         [o_outline_view selectRow: i_row byExtendingSelection: NO];
1709         [o_outline_view scrollRowToVisible: i_row];
1710
1711         vlc_object_release( p_playlist );
1712         return YES;
1713     }
1714
1715     else if( [[o_pasteboard types] containsObject: NSFilenamesPboardType] )
1716     {
1717         int i;
1718         playlist_item_t *p_node = [item pointerValue];
1719
1720         NSArray *o_array = [NSArray array];
1721         NSArray *o_values = [[o_pasteboard propertyListForType:
1722                                         NSFilenamesPboardType]
1723                                 sortedArrayUsingSelector:
1724                                         @selector(caseInsensitiveCompare:)];
1725
1726         for( i = 0; i < (int)[o_values count]; i++)
1727         {
1728             NSDictionary *o_dic;
1729             o_dic = [NSDictionary dictionaryWithObject:[o_values
1730                         objectAtIndex:i] forKey:@"ITEM_URL"];
1731             o_array = [o_array arrayByAddingObject: o_dic];
1732         }
1733
1734         if ( item == nil )
1735         {
1736             [self appendArray:o_array atPos:index enqueue: YES];
1737         }
1738         else
1739         {
1740             assert( p_node->i_children != -1 );
1741             [self appendNodeArray:o_array inNode: p_node
1742                 atPos:index enqueue:YES];
1743         }
1744         vlc_object_release( p_playlist );
1745         return YES;
1746     }
1747     vlc_object_release( p_playlist );
1748     return NO;
1749 }
1750 @end
1751
1752