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