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