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