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