]> git.sesse.net Git - vlc/blob - modules/gui/macosx/playlist.m
* forward-port [17568]
[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_interaction.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     intf_thread_t *p_intf = VLCIntf;
246     playlist_item_t *p_item;
247     
248     if( item == nil || ![item isKindOfClass: [NSValue class]] ) return( @"error" );
249     
250     p_item = (playlist_item_t *)[item pointerValue];
251     if( p_item == NULL )
252     {
253         return( @"error");
254     }
255 //NSLog( @"values for %p", p_item ); 
256     
257     if( [[o_tc identifier] isEqualToString:@"1"] )
258     {
259         /* sanity check to prevent the NSString class from crashing */
260         if( p_item->input.psz_name != NULL )
261         {
262             o_value = [NSString stringWithUTF8String:
263                 p_item->input.psz_name];
264             if( o_value == NULL )
265                 o_value = [NSString stringWithCString:
266                     p_item->input.psz_name];
267         }
268     }
269     else if( [[o_tc identifier] isEqualToString:@"2"] && p_item->p_input->p_meta &&
270         p_item->p_input->p_meta->psz_artist && *p_item->p_input->p_meta->psz_artist )
271     {
272         o_value = [NSString stringWithUTF8String:
273             p_item->p_input->p_meta->psz_artist];
274         if( o_value == NULL )
275             o_value = [NSString stringWithCString:
276                 p_item->p_input->p_meta->psz_artist];
277     }
278     else if( [[o_tc identifier] isEqualToString:@"3"] )
279     {
280         char psz_duration[MSTRTIME_MAX_SIZE];
281         mtime_t dur = p_item->p_input->i_duration;
282         if( dur != -1 )
283         {
284             secstotimestr( psz_duration, dur/1000000 );
285             o_value = [NSString stringWithUTF8String: psz_duration];
286         }
287         else
288         {
289             o_value = @"-:--:--";
290         }
291     }
292
293     return( o_value );
294 }
295
296 @end
297
298 /*****************************************************************************
299  * VLCPlaylistWizard implementation
300  *****************************************************************************/
301 @implementation VLCPlaylistWizard
302
303 - (IBAction)reloadOutlineView
304 {
305     /* Only reload the outlineview if the wizard window is open since this can
306        be quite long on big playlists */
307     if( [[o_outline_view window] isVisible] )
308     {
309         [o_outline_view reloadData];
310     }
311 }
312
313 @end
314
315 /*****************************************************************************
316  * extension to NSOutlineView's interface to fix compilation warnings
317  * and let us access these 2 functions properly
318  * this uses a private Apple-API, but works fine on all current OSX releases
319  * keep checking for compatiblity with future releases though
320  *****************************************************************************/
321
322 @interface NSOutlineView (UndocumentedSortImages)
323 + (NSImage *)_defaultTableHeaderSortImage;
324 + (NSImage *)_defaultTableHeaderReverseSortImage;
325 @end
326
327
328 /*****************************************************************************
329  * VLCPlaylist implementation
330  *****************************************************************************/
331 @implementation VLCPlaylist
332
333 - (id)init
334 {
335     self = [super init];
336     if ( self != nil )
337     {
338         o_nodes_array = [[NSMutableArray alloc] init];
339         o_items_array = [[NSMutableArray alloc] init];
340     }
341     return self;
342 }
343
344 - (void)awakeFromNib
345 {
346     playlist_t * p_playlist = pl_Yield( VLCIntf );
347     vlc_list_t *p_list = vlc_list_find( p_playlist, VLC_OBJECT_MODULE,
348                                         FIND_ANYWHERE );
349
350     int i_index;
351
352     [super awakeFromNib];
353
354     [o_outline_view setDoubleAction: @selector(playItem:)];
355
356     [o_outline_view registerForDraggedTypes:
357         [NSArray arrayWithObjects: NSFilenamesPboardType,
358         @"VLCPlaylistItemPboardType", nil]];
359     [o_outline_view setIntercellSpacing: NSMakeSize (0.0, 1.0)];
360
361     /* this uses private Apple API which works fine until 10.4, 
362      * but keep checking in the future!
363      * These methods are being added artificially to NSOutlineView's interface above */
364     o_ascendingSortingImage = [[NSOutlineView class] _defaultTableHeaderSortImage];
365     o_descendingSortingImage = [[NSOutlineView class] _defaultTableHeaderReverseSortImage];
366
367     o_tc_sortColumn = nil;
368
369     for( i_index = 0; i_index < p_list->i_count; i_index++ )
370     {
371         vlc_bool_t  b_enabled;
372         char        *objectname;
373         NSMenuItem  *o_lmi;
374         module_t    *p_parser = (module_t *)p_list->p_values[i_index].p_object ;
375
376         if( !strcmp( p_parser->psz_capability, "services_discovery" ) )
377         {
378             /* Check for submodules */
379             int i = -1;
380             while( p_parser->pp_shortcuts[++i] != NULL ); i--;
381
382             /* Check whether to enable these menuitems */
383             objectname = i>=0 ? p_parser->pp_shortcuts[i] : p_parser->psz_object_name;
384             b_enabled = playlist_IsServicesDiscoveryLoaded( p_playlist, objectname );
385             
386             /* Create the menu entries used in the playlist menu */
387             o_lmi = [[o_mi_services submenu] addItemWithTitle:
388                      [NSString stringWithUTF8String:
389                      p_parser->psz_longname ? p_parser->psz_longname :
390                      ( p_parser->psz_shortname ? p_parser->psz_shortname:
391                      objectname)]
392                                              action: @selector(servicesChange:)
393                                              keyEquivalent: @""];
394             [o_lmi setTarget: self];
395             [o_lmi setRepresentedObject: [NSString stringWithCString: objectname]];
396             if( b_enabled ) [o_lmi setState: NSOnState];
397                 
398             /* Create the menu entries for the main menu */
399             o_lmi = [[o_mm_mi_services submenu] addItemWithTitle:
400                      [NSString stringWithUTF8String:
401                      p_parser->psz_longname ? p_parser->psz_longname :
402                      ( p_parser->psz_shortname ? p_parser->psz_shortname:
403                      objectname)]
404                                              action: @selector(servicesChange:)
405                                              keyEquivalent: @""];
406             [o_lmi setTarget: self];
407             [o_lmi setRepresentedObject: [NSString stringWithCString:objectname]];
408             if( b_enabled ) [o_lmi setState: NSOnState];
409         }
410     }
411     vlc_list_release( p_list );
412     vlc_object_release( p_playlist );
413
414     //[self playlistUpdated];
415 }
416
417 - (void)searchfieldChanged:(NSNotification *)o_notification
418 {
419     [o_search_field setStringValue:[[o_notification object] stringValue]];
420 }
421
422 - (void)initStrings
423 {
424     [super initStrings];
425
426     [o_mi_save_playlist setTitle: _NS("Save Playlist...")];
427     [o_mi_play setTitle: _NS("Play")];
428     [o_mi_delete setTitle: _NS("Delete")];
429     [o_mi_recursive_expand setTitle: _NS("Expand Node")];
430     [o_mi_selectall setTitle: _NS("Select All")];
431     [o_mi_info setTitle: _NS("Information")];
432     [o_mi_preparse setTitle: _NS("Get Stream Information")];
433     [o_mi_sort_name setTitle: _NS("Sort Node by Name")];
434     [o_mi_sort_author setTitle: _NS("Sort Node by Author")];
435     [o_mi_services setTitle: _NS("Services discovery")];
436     [o_status_field setStringValue: [NSString stringWithFormat:
437                         _NS("No items in the playlist")]];
438
439 #if 0
440     [o_search_button setTitle: _NS("Search")];
441 #endif
442     [o_search_field setToolTip: _NS("Search in Playlist")];
443     [o_mi_addNode setTitle: _NS("Add Folder to Playlist")];
444
445     [o_save_accessory_text setStringValue: _NS("File Format:")];
446     [[o_save_accessory_popup itemAtIndex:0] setTitle: _NS("Extended M3U")];
447     [[o_save_accessory_popup itemAtIndex:1] setTitle: _NS("XML Shareable Playlist Format (XSPF)")];
448 }
449
450 - (void)playlistUpdated
451 {
452     unsigned int i;
453
454     /* Clear indications of any existing column sorting */
455     for( i = 0 ; i < [[o_outline_view tableColumns] count] ; i++ )
456     {
457         [o_outline_view setIndicatorImage:nil inTableColumn:
458                             [[o_outline_view tableColumns] objectAtIndex:i]];
459     }
460
461     [o_outline_view setHighlightedTableColumn:nil];
462     o_tc_sortColumn = nil;
463     // TODO Find a way to keep the dict size to a minimum
464     //[o_outline_dict removeAllObjects];
465     [o_outline_view reloadData];
466     [[[[VLCMain sharedInstance] getWizard] getPlaylistWizard] reloadOutlineView];
467     [[[[VLCMain sharedInstance] getBookmarks] getDataTable] reloadData];
468
469     playlist_t *p_playlist = pl_Yield( VLCIntf );
470
471     if( playlist_CurrentSize( p_playlist ) >= 2 )
472     {
473         [o_status_field setStringValue: [NSString stringWithFormat:
474                     _NS("%i items in the playlist"),
475                                 playlist_CurrentSize( p_playlist )]];
476     }
477     else
478     {
479         if( playlist_IsEmpty( p_playlist ) )
480         {
481             [o_status_field setStringValue: _NS("No items in the playlist")];
482         }
483         else
484         {
485             [o_status_field setStringValue: _NS("1 item in the playlist")];
486         }
487     }
488     vlc_object_release( p_playlist );
489 }
490
491 - (void)playModeUpdated
492 {
493     playlist_t *p_playlist = pl_Yield( VLCIntf );
494     vlc_value_t val, val2;
495
496     var_Get( p_playlist, "loop", &val2 );
497     var_Get( p_playlist, "repeat", &val );
498     if( val.b_bool == VLC_TRUE )
499     {
500         [[[VLCMain sharedInstance] getControls] repeatOne];
501    }
502     else if( val2.b_bool == VLC_TRUE )
503     {
504         [[[VLCMain sharedInstance] getControls] repeatAll];
505     }
506     else
507     {
508         [[[VLCMain sharedInstance] getControls] repeatOff];
509     }
510
511     [[[VLCMain sharedInstance] getControls] shuffle];
512
513     vlc_object_release( p_playlist );
514 }
515
516 - (void)updateRowSelection
517 {
518     int i_row;
519     unsigned int j;
520
521     playlist_t *p_playlist = pl_Yield( VLCIntf );
522     playlist_item_t *p_item, *p_temp_item;
523     NSMutableArray *o_array = [NSMutableArray array];
524
525     p_item = p_playlist->status.p_item;
526     if( p_item == NULL )
527     {
528         vlc_object_release(p_playlist);
529         return;
530     }
531
532     p_temp_item = p_item;
533     while( p_temp_item->p_parent )
534     {
535         [o_array insertObject: [NSValue valueWithPointer: p_temp_item] atIndex: 0];
536         p_temp_item = p_temp_item->p_parent;
537         /*for (i = 0 ; i < p_temp_item->i_parents ; i++)
538         {
539             if( p_temp_item->pp_parents[i]->i_view == i_current_view )
540             {
541                 p_temp_item = p_temp_item->pp_parents[i]->p_parent;
542                 break;
543             }
544         }*/
545     }
546
547     for( j = 0; j < [o_array count] - 1; j++ )
548     {
549         id o_item;
550         if( ( o_item = [o_outline_dict objectForKey:
551                             [NSString stringWithFormat: @"%p",
552                             [[o_array objectAtIndex:j] pointerValue]]] ) != nil )
553         {
554             [o_outline_view expandItem: o_item];
555         }
556
557     }
558
559     i_row = [o_outline_view rowForItem:[o_outline_dict
560             objectForKey:[NSString stringWithFormat: @"%p", p_item]]];
561
562     [o_outline_view selectRow: i_row byExtendingSelection: NO];
563     [o_outline_view scrollRowToVisible: i_row];
564
565     vlc_object_release( p_playlist );
566
567     /* update our info-panel to reflect the new item */
568     [[[VLCMain sharedInstance] getInfo] updatePanel];
569 }
570
571 /* Check if p_item is a child of p_node recursively. We need to check the item
572    existence first since OSX sometimes tries to redraw items that have been
573    deleted. We don't do it when not required  since this verification takes
574    quite a long time on big playlists (yes, pretty hacky). */
575 - (BOOL)isItem: (playlist_item_t *)p_item
576                     inNode: (playlist_item_t *)p_node
577                     checkItemExistence:(BOOL)b_check
578
579 {
580     playlist_t * p_playlist = pl_Yield( VLCIntf );
581     playlist_item_t *p_temp_item = p_item;
582
583     if( p_node == p_item )
584     {
585         vlc_object_release(p_playlist);
586         return YES;
587     }
588
589     if( p_node->i_children < 1)
590     {
591         vlc_object_release(p_playlist);
592         return NO;
593     }
594
595     if ( p_temp_item )
596     {
597         int i;
598         vlc_mutex_lock( &p_playlist->object_lock );
599
600         if( b_check )
601         {
602         /* Since outlineView: willDisplayCell:... may call this function with
603            p_items that don't exist anymore, first check if the item is still
604            in the playlist. Any cleaner solution welcomed. */
605             for( i = 0; i < p_playlist->all_items.i_size; i++ )
606             {
607                 if( ARRAY_VAL( p_playlist->all_items, i) == p_item ) break;
608                 else if ( i == p_playlist->all_items.i_size - 1 )
609                 {
610                     vlc_object_release( p_playlist );
611                     vlc_mutex_unlock( &p_playlist->object_lock );
612                     return NO;
613                 }
614             }
615         }
616
617         while( p_temp_item )
618         {
619             p_temp_item = p_temp_item->p_parent;
620             if( p_temp_item == p_node )
621             {
622                  vlc_mutex_unlock( &p_playlist->object_lock );
623                  vlc_object_release( p_playlist );
624                  return YES;
625             }
626         }
627         vlc_mutex_unlock( &p_playlist->object_lock );
628     }
629
630     vlc_object_release( p_playlist );
631     return NO;
632 }
633
634 /* This method is usefull for instance to remove the selected children of an
635    already selected node */
636 - (void)removeItemsFrom:(id)o_items ifChildrenOf:(id)o_nodes
637 {
638     unsigned int i, j;
639     for( i = 0 ; i < [o_items count] ; i++ )
640     {
641         for ( j = 0 ; j < [o_nodes count] ; j++ )
642         {
643             if( o_items == o_nodes)
644             {
645                 if( j == i ) continue;
646             }
647             if( [self isItem: [[o_items objectAtIndex:i] pointerValue]
648                     inNode: [[o_nodes objectAtIndex:j] pointerValue]
649                     checkItemExistence: NO] )
650             {
651                 [o_items removeObjectAtIndex:i];
652                 /* We need to execute the next iteration with the same index
653                    since the current item has been deleted */
654                 i--;
655                 break;
656             }
657         }
658     }
659
660 }
661
662 - (IBAction)savePlaylist:(id)sender
663 {
664     intf_thread_t * p_intf = VLCIntf;
665     playlist_t * p_playlist = pl_Yield( p_intf );
666
667     NSSavePanel *o_save_panel = [NSSavePanel savePanel];
668     NSString * o_name = [NSString stringWithFormat: @"%@", _NS("Untitled")];
669
670     //[o_save_panel setAllowedFileTypes: [NSArray arrayWithObjects: @"m3u", @"xpf", nil] ];
671     [o_save_panel setTitle: _NS("Save Playlist")];
672     [o_save_panel setPrompt: _NS("Save")];
673     [o_save_panel setAccessoryView: o_save_accessory_view];
674
675     if( [o_save_panel runModalForDirectory: nil
676             file: o_name] == NSOKButton )
677     {
678         NSString *o_filename = [o_save_panel filename];
679
680         if( [o_save_accessory_popup indexOfSelectedItem] == 1 )
681         {
682             NSString * o_real_filename;
683             NSRange range;
684             range.location = [o_filename length] - [@".xspf" length];
685             range.length = [@".xspf" length];
686
687             if( [o_filename compare:@".xspf" options: NSCaseInsensitiveSearch
688                                              range: range] != NSOrderedSame )
689             {
690                 o_real_filename = [NSString stringWithFormat: @"%@.xspf", o_filename];
691             }
692             else
693             {
694                 o_real_filename = o_filename;
695             }
696             playlist_Export( p_playlist, 
697                 [o_real_filename fileSystemRepresentation], 
698                 p_playlist->p_local_category, "export-xspf" );
699         }
700         else
701         {
702             NSString * o_real_filename;
703             NSRange range;
704             range.location = [o_filename length] - [@".m3u" length];
705             range.length = [@".m3u" length];
706
707             if( [o_filename compare:@".m3u" options: NSCaseInsensitiveSearch
708                                              range: range] != NSOrderedSame )
709             {
710                 o_real_filename = [NSString stringWithFormat: @"%@.m3u", o_filename];
711             }
712             else
713             {
714                 o_real_filename = o_filename;
715             }
716             playlist_Export( p_playlist, 
717                 [o_real_filename fileSystemRepresentation],
718                 p_playlist->p_local_category, "export-m3u" );
719         }
720     }
721     vlc_object_release( p_playlist );
722 }
723
724 /* When called retrieves the selected outlineview row and plays that node or item */
725 - (IBAction)playItem:(id)sender
726 {
727     intf_thread_t * p_intf = VLCIntf;
728     playlist_t * p_playlist = pl_Yield( p_intf );
729
730     playlist_item_t *p_item;
731     playlist_item_t *p_node = NULL;
732
733     p_item = [[o_outline_view itemAtRow:[o_outline_view selectedRow]] pointerValue];
734
735     if( p_item )
736     {
737         if( p_item->i_children == -1 )
738         {
739             p_node = p_item->p_parent;
740
741         }
742         else
743         {
744             p_node = p_item;
745             if( p_node->i_children > 0 && p_node->pp_children[0]->i_children == -1 )
746             {
747                 p_item = p_node->pp_children[0];
748             }
749             else
750             {
751                 p_item = NULL;
752             }
753         }
754         playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, p_node, p_item );
755     }
756     vlc_object_release( p_playlist );
757 }
758
759 /* When called retrieves the selected outlineview row and plays that node or item */
760 - (IBAction)preparseItem:(id)sender
761 {
762     int i_count;
763     NSMutableArray *o_to_preparse;
764     intf_thread_t * p_intf = VLCIntf;
765     playlist_t * p_playlist = pl_Yield( p_intf );
766                                                        
767     o_to_preparse = [NSMutableArray arrayWithArray:[[o_outline_view selectedRowEnumerator] allObjects]];
768     i_count = [o_to_preparse count];
769
770     int i, i_row;
771     NSNumber *o_number;
772     playlist_item_t *p_item = NULL;
773
774     for( i = 0; i < i_count; i++ )
775     {
776         o_number = [o_to_preparse lastObject];
777         i_row = [o_number intValue];
778         p_item = [[o_outline_view itemAtRow:i_row] pointerValue];
779         [o_to_preparse removeObject: o_number];
780         [o_outline_view deselectRow: i_row];
781
782         if( p_item )
783         {
784             if( p_item->i_children == -1 )
785             {
786                 playlist_PreparseEnqueue( p_playlist, p_item->p_input );
787             }
788             else
789             {
790                 msg_Dbg( p_intf, "preparse of nodes not yet implemented" );
791             }
792         }
793     }
794     vlc_object_release( p_playlist );
795     [self playlistUpdated];
796 }
797
798 - (IBAction)servicesChange:(id)sender
799 {
800     NSMenuItem *o_mi = (NSMenuItem *)sender;
801     NSString *o_string = [o_mi representedObject];
802     playlist_t * p_playlist = pl_Yield( VLCIntf );
803     if( !playlist_IsServicesDiscoveryLoaded( p_playlist, [o_string cString] ) )
804         playlist_ServicesDiscoveryAdd( p_playlist, [o_string cString] );
805     else
806         playlist_ServicesDiscoveryRemove( p_playlist, [o_string cString] );
807
808     [o_mi setState: playlist_IsServicesDiscoveryLoaded( p_playlist,
809                                           [o_string cString] ) ? YES : NO];
810
811     vlc_object_release( p_playlist );
812     [self playlistUpdated];
813     return;
814 }
815
816 - (IBAction)selectAll:(id)sender
817 {
818     [o_outline_view selectAll: nil];
819 }
820
821 - (IBAction)deleteItem:(id)sender
822 {
823     int i, i_count, i_row;
824     NSMutableArray *o_to_delete;
825     NSNumber *o_number;
826
827     playlist_t * p_playlist;
828     intf_thread_t * p_intf = VLCIntf;
829
830     p_playlist = pl_Yield( p_intf );
831
832     o_to_delete = [NSMutableArray arrayWithArray:[[o_outline_view selectedRowEnumerator] allObjects]];
833     i_count = [o_to_delete count];
834
835     for( i = 0; i < i_count; i++ )
836     {
837         o_number = [o_to_delete lastObject];
838         i_row = [o_number intValue];
839         id o_item = [o_outline_view itemAtRow: i_row];
840         playlist_item_t *p_item = [o_item pointerValue];
841         [o_to_delete removeObject: o_number];
842         [o_outline_view deselectRow: i_row];
843
844         if( [[o_outline_view dataSource] outlineView:o_outline_view
845                                         numberOfChildrenOfItem: o_item]  > 0 )
846         //is a node and not an item
847         {
848             if( p_playlist->status.i_status != PLAYLIST_STOPPED &&
849                 [self isItem: p_playlist->status.p_item inNode:
850                         ((playlist_item_t *)[o_item pointerValue])
851                         checkItemExistence: NO] == YES )
852             {
853                 // if current item is in selected node and is playing then stop playlist
854                 playlist_Stop( p_playlist );
855             }
856             vlc_mutex_lock( &p_playlist->object_lock );
857             playlist_NodeDelete( p_playlist, p_item, VLC_TRUE, VLC_FALSE );
858             vlc_mutex_unlock( &p_playlist->object_lock );
859         }
860         else
861         {
862             playlist_LockDelete( p_playlist, p_item->i_id );
863         }
864     }
865     [self playlistUpdated];
866     vlc_object_release( p_playlist );
867 }
868
869 - (IBAction)sortNodeByName:(id)sender
870 {
871     [self sortNode: SORT_TITLE];
872 }
873
874 - (IBAction)sortNodeByAuthor:(id)sender
875 {
876     [self sortNode: SORT_ARTIST];
877 }
878
879 - (void)sortNode:(int)i_mode
880 {
881     playlist_t * p_playlist = pl_Yield( VLCIntf );
882     playlist_item_t * p_item;
883
884     if( [o_outline_view selectedRow] > -1 )
885     {
886         p_item = [[o_outline_view itemAtRow: [o_outline_view selectedRow]]
887                                                                 pointerValue];
888     }
889     else
890     /*If no item is selected, sort the whole playlist*/
891     {
892         p_item = p_playlist->p_root_category;
893     }
894
895     if( p_item->i_children > -1 ) // the item is a node
896     {
897         vlc_mutex_lock( &p_playlist->object_lock );
898         playlist_RecursiveNodeSort( p_playlist, p_item, i_mode, ORDER_NORMAL );
899         vlc_mutex_unlock( &p_playlist->object_lock );
900     }
901     else
902     {
903         vlc_mutex_lock( &p_playlist->object_lock );
904         playlist_RecursiveNodeSort( p_playlist,
905                 p_item->p_parent, i_mode, ORDER_NORMAL );
906         vlc_mutex_unlock( &p_playlist->object_lock );
907     }
908     vlc_object_release( p_playlist );
909     [self playlistUpdated];
910 }
911
912 - (input_item_t *)createItem:(NSDictionary *)o_one_item
913 {
914     intf_thread_t * p_intf = VLCIntf;
915     playlist_t * p_playlist = pl_Yield( p_intf );
916
917     input_item_t *p_input;
918     int i;
919     BOOL b_rem = FALSE, b_dir = FALSE;
920     NSString *o_uri, *o_name;
921     NSArray *o_options;
922     NSURL *o_true_file;
923
924     /* Get the item */
925     o_uri = (NSString *)[o_one_item objectForKey: @"ITEM_URL"];
926     o_name = (NSString *)[o_one_item objectForKey: @"ITEM_NAME"];
927     o_options = (NSArray *)[o_one_item objectForKey: @"ITEM_OPTIONS"];
928
929     /* Find the name for a disc entry ( i know, can you believe the trouble?) */
930     if( ( !o_name || [o_name isEqualToString:@""] ) && [o_uri rangeOfString: @"/dev/"].location != NSNotFound )
931     {
932         int i_count, i_index;
933         struct statfs *mounts = NULL;
934
935         i_count = getmntinfo (&mounts, MNT_NOWAIT);
936         /* getmntinfo returns a pointer to static data. Do not free. */
937         for( i_index = 0 ; i_index < i_count; i_index++ )
938         {
939             NSMutableString *o_temp, *o_temp2;
940             o_temp = [NSMutableString stringWithString: o_uri];
941             o_temp2 = [NSMutableString stringWithCString: mounts[i_index].f_mntfromname];
942             [o_temp replaceOccurrencesOfString: @"/dev/rdisk" withString: @"/dev/disk" options:nil range:NSMakeRange(0, [o_temp length]) ];
943             [o_temp2 replaceOccurrencesOfString: @"s0" withString: @"" options:nil range:NSMakeRange(0, [o_temp2 length]) ];
944             [o_temp2 replaceOccurrencesOfString: @"s1" withString: @"" options:nil range:NSMakeRange(0, [o_temp2 length]) ];
945
946             if( strstr( [o_temp fileSystemRepresentation], [o_temp2 fileSystemRepresentation] ) != NULL )
947             {
948                 o_name = [[NSFileManager defaultManager] displayNameAtPath: [NSString stringWithCString:mounts[i_index].f_mntonname]];
949             }
950         }
951     }
952     /* If no name, then make a guess */
953     if( !o_name) o_name = [[NSFileManager defaultManager] displayNameAtPath: o_uri];
954
955     if( [[NSFileManager defaultManager] fileExistsAtPath:o_uri isDirectory:&b_dir] && b_dir &&
956         [[NSWorkspace sharedWorkspace] getFileSystemInfoForPath: o_uri isRemovable: &b_rem
957                 isWritable:NULL isUnmountable:NULL description:NULL type:NULL] && b_rem   )
958     {
959         /* All of this is to make sure CD's play when you D&D them on VLC */
960         /* Converts mountpoint to a /dev file */
961         struct statfs *buf;
962         char *psz_dev;
963         NSMutableString *o_temp;
964
965         buf = (struct statfs *) malloc (sizeof(struct statfs));
966         statfs( [o_uri fileSystemRepresentation], buf );
967         psz_dev = strdup(buf->f_mntfromname);
968         o_temp = [NSMutableString stringWithCString: psz_dev ];
969         [o_temp replaceOccurrencesOfString: @"/dev/disk" withString: @"/dev/rdisk" options:nil range:NSMakeRange(0, [o_temp length]) ];
970         [o_temp replaceOccurrencesOfString: @"s0" withString: @"" options:nil range:NSMakeRange(0, [o_temp length]) ];
971         [o_temp replaceOccurrencesOfString: @"s1" withString: @"" options:nil range:NSMakeRange(0, [o_temp length]) ];
972         o_uri = o_temp;
973     }
974
975     p_input = input_ItemNew( p_playlist, [o_uri fileSystemRepresentation], [o_name UTF8String] );
976     if( !p_input )
977        return NULL;
978
979     if( o_options )
980     {
981         for( i = 0; i < (int)[o_options count]; i++ )
982         {
983             input_ItemAddOption( p_input, strdup( [[o_options objectAtIndex:i] UTF8String] ) );
984         }
985     }
986
987     /* Recent documents menu */
988     o_true_file = [NSURL fileURLWithPath: o_uri];
989     if( o_true_file != nil )
990     {
991         [[NSDocumentController sharedDocumentController]
992             noteNewRecentDocumentURL: o_true_file];
993     }
994
995     vlc_object_release( p_playlist );
996     return p_input;
997 }
998
999 - (void)appendArray:(NSArray*)o_array atPos:(int)i_position enqueue:(BOOL)b_enqueue
1000 {
1001     int i_item;
1002     playlist_t * p_playlist = pl_Yield( VLCIntf );
1003
1004     for( i_item = 0; i_item < (int)[o_array count]; i_item++ )
1005     {
1006         input_item_t *p_input;
1007         NSDictionary *o_one_item;
1008
1009         /* Get the item */
1010         o_one_item = [o_array objectAtIndex: i_item];
1011         p_input = [self createItem: o_one_item];
1012         if( !p_input )
1013         {
1014             continue;
1015         }
1016
1017         /* Add the item */
1018         playlist_PlaylistAddInput( p_playlist, p_input, PLAYLIST_INSERT,
1019                         i_position == -1 ? PLAYLIST_END : i_position + i_item );
1020
1021         if( i_item == 0 && !b_enqueue )
1022         {
1023             playlist_item_t *p_item;
1024             p_item = playlist_ItemGetByInput( p_playlist, p_input );
1025             playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, NULL, p_item );
1026         }
1027         else
1028         {
1029             playlist_item_t *p_item;
1030             p_item = playlist_ItemGetByInput( p_playlist, p_input );
1031             playlist_Control( p_playlist, PLAYLIST_PREPARSE, p_item );
1032         }
1033     }
1034     [self playlistUpdated];
1035     vlc_object_release( p_playlist );
1036 }
1037
1038 - (void)appendNodeArray:(NSArray*)o_array inNode:(playlist_item_t *)p_node atPos:(int)i_position enqueue:(BOOL)b_enqueue
1039 {
1040     int i_item;
1041     playlist_t * p_playlist = pl_Yield( VLCIntf );
1042
1043     for( i_item = 0; i_item < (int)[o_array count]; i_item++ )
1044     {
1045         input_item_t *p_input;
1046         NSDictionary *o_one_item;
1047
1048         /* Get the item */
1049         o_one_item = [o_array objectAtIndex: i_item];
1050         p_input = [self createItem: o_one_item];
1051         if( !p_input )
1052         {
1053             continue;
1054         }
1055
1056         /* Add the item */
1057        playlist_NodeAddInput( p_playlist, p_input, p_node,
1058                                       PLAYLIST_INSERT,
1059                                       i_position == -1 ?
1060                                       PLAYLIST_END : i_position + i_item );
1061
1062
1063         if( i_item == 0 && !b_enqueue )
1064         {
1065             playlist_item_t *p_item;
1066             p_item = playlist_ItemGetByInput( p_playlist, p_input );
1067             playlist_Control( p_playlist, PLAYLIST_VIEWPLAY, NULL, p_item );
1068         }
1069         else
1070         {
1071             playlist_item_t *p_item;
1072             p_item = playlist_ItemGetByInput( p_playlist, p_input );
1073             playlist_Control( p_playlist, PLAYLIST_PREPARSE, p_item );
1074         }
1075     }
1076     [self playlistUpdated];
1077     vlc_object_release( p_playlist );
1078 }
1079
1080 - (NSMutableArray *)subSearchItem:(playlist_item_t *)p_item
1081 {
1082     playlist_t *p_playlist = pl_Yield( VLCIntf );
1083     playlist_item_t *p_selected_item;
1084     int i_current, i_selected_row;
1085
1086     i_selected_row = [o_outline_view selectedRow];
1087     if (i_selected_row < 0)
1088         i_selected_row = 0;
1089
1090     p_selected_item = (playlist_item_t *)[[o_outline_view itemAtRow:
1091                                             i_selected_row] pointerValue];
1092
1093     for( i_current = 0; i_current < p_item->i_children ; i_current++ )
1094     {
1095         char *psz_temp;
1096         NSString *o_current_name, *o_current_author;
1097
1098         vlc_mutex_lock( &p_playlist->object_lock );
1099         o_current_name = [NSString stringWithUTF8String:
1100             p_item->pp_children[i_current]->p_input->psz_name];
1101         psz_temp = input_ItemGetInfo( p_item->p_input ,
1102                    _("Meta-information"),_("Artist") );
1103         o_current_author = [NSString stringWithUTF8String: psz_temp];
1104         free( psz_temp);
1105         vlc_mutex_unlock( &p_playlist->object_lock );
1106
1107         if( p_selected_item == p_item->pp_children[i_current] &&
1108                     b_selected_item_met == NO )
1109         {
1110             b_selected_item_met = YES;
1111         }
1112         else if( p_selected_item == p_item->pp_children[i_current] &&
1113                     b_selected_item_met == YES )
1114         {
1115             vlc_object_release( p_playlist );
1116             return NULL;
1117         }
1118         else if( b_selected_item_met == YES &&
1119                     ( [o_current_name rangeOfString:[o_search_field
1120                         stringValue] options:NSCaseInsensitiveSearch ].length ||
1121                       [o_current_author rangeOfString:[o_search_field
1122                         stringValue] options:NSCaseInsensitiveSearch ].length ) )
1123         {
1124             vlc_object_release( p_playlist );
1125             /*Adds the parent items in the result array as well, so that we can
1126             expand the tree*/
1127             return [NSMutableArray arrayWithObject: [NSValue
1128                             valueWithPointer: p_item->pp_children[i_current]]];
1129         }
1130         if( p_item->pp_children[i_current]->i_children > 0 )
1131         {
1132             id o_result = [self subSearchItem:
1133                                             p_item->pp_children[i_current]];
1134             if( o_result != NULL )
1135             {
1136                 vlc_object_release( p_playlist );
1137                 [o_result insertObject: [NSValue valueWithPointer:
1138                                 p_item->pp_children[i_current]] atIndex:0];
1139                 return o_result;
1140             }
1141         }
1142     }
1143     vlc_object_release( p_playlist );
1144     return NULL;
1145 }
1146
1147 - (IBAction)searchItem:(id)sender
1148 {
1149     playlist_t * p_playlist = pl_Yield( VLCIntf );
1150     id o_result;
1151
1152     unsigned int i;
1153     int i_row = -1;
1154
1155     b_selected_item_met = NO;
1156
1157         /*First, only search after the selected item:*
1158          *(b_selected_item_met = NO)                 */
1159     o_result = [self subSearchItem:p_playlist->p_root_category];
1160     if( o_result == NULL )
1161     {
1162         /* If the first search failed, search again from the beginning */
1163         o_result = [self subSearchItem:p_playlist->p_root_category];
1164     }
1165     if( o_result != NULL )
1166     {
1167         int i_start;
1168         if( [[o_result objectAtIndex: 0] pointerValue] ==
1169                                                     p_playlist->p_local_category )
1170         i_start = 1;
1171         else
1172         i_start = 0;
1173
1174         for( i = i_start ; i < [o_result count] - 1 ; i++ )
1175         {
1176             [o_outline_view expandItem: [o_outline_dict objectForKey:
1177                         [NSString stringWithFormat: @"%p",
1178                         [[o_result objectAtIndex: i] pointerValue]]]];
1179         }
1180         i_row = [o_outline_view rowForItem: [o_outline_dict objectForKey:
1181                         [NSString stringWithFormat: @"%p",
1182                         [[o_result objectAtIndex: [o_result count] - 1 ]
1183                         pointerValue]]]];
1184     }
1185     if( i_row > -1 )
1186     {
1187         [o_outline_view selectRow:i_row byExtendingSelection: NO];
1188         [o_outline_view scrollRowToVisible: i_row];
1189     }
1190     vlc_object_release( p_playlist );
1191 }
1192
1193 - (IBAction)recursiveExpandNode:(id)sender
1194 {
1195     id o_item = [o_outline_view itemAtRow: [o_outline_view selectedRow]];
1196     playlist_item_t *p_item = (playlist_item_t *)[o_item pointerValue];
1197
1198     if( ![[o_outline_view dataSource] outlineView: o_outline_view
1199                                                     isItemExpandable: o_item] )
1200     {
1201         o_item = [o_outline_dict objectForKey: [NSString
1202                    stringWithFormat: @"%p", p_item->p_parent]];
1203     }
1204
1205     /* We need to collapse the node first, since OSX refuses to recursively
1206        expand an already expanded node, even if children nodes are collapsed. */
1207     [o_outline_view collapseItem: o_item collapseChildren: YES];
1208     [o_outline_view expandItem: o_item expandChildren: YES];
1209 }
1210
1211 - (NSMenu *)menuForEvent:(NSEvent *)o_event
1212 {
1213     NSPoint pt;
1214     vlc_bool_t b_rows;
1215     vlc_bool_t b_item_sel;
1216
1217     pt = [o_outline_view convertPoint: [o_event locationInWindow]
1218                                                  fromView: nil];
1219     b_item_sel = ( [o_outline_view rowAtPoint: pt] != -1 &&
1220                    [o_outline_view selectedRow] != -1 );
1221     b_rows = [o_outline_view numberOfRows] != 0;
1222
1223     [o_mi_play setEnabled: b_item_sel];
1224     [o_mi_delete setEnabled: b_item_sel];
1225     [o_mi_selectall setEnabled: b_rows];
1226     [o_mi_info setEnabled: b_item_sel];
1227     [o_mi_preparse setEnabled: b_item_sel];
1228     [o_mi_recursive_expand setEnabled: b_item_sel];
1229     [o_mi_sort_name setEnabled: b_item_sel];
1230     [o_mi_sort_author setEnabled: b_item_sel];
1231
1232     return( o_ctx_menu );
1233 }
1234
1235 - (void)outlineView: (NSTableView*)o_tv
1236                   didClickTableColumn:(NSTableColumn *)o_tc
1237 {
1238     int i_mode = 0, i_type;
1239     intf_thread_t *p_intf = VLCIntf;
1240
1241     playlist_t *p_playlist = pl_Yield( p_intf );
1242
1243     /* Check whether the selected table column header corresponds to a
1244        sortable table column*/
1245     if( !( o_tc == o_tc_name || o_tc == o_tc_author ) )
1246     {
1247         vlc_object_release( p_playlist );
1248         return;
1249     }
1250
1251     if( o_tc_sortColumn == o_tc )
1252     {
1253         b_isSortDescending = !b_isSortDescending;
1254     }
1255     else
1256     {
1257         b_isSortDescending = VLC_FALSE;
1258     }
1259
1260     if( o_tc == o_tc_name )
1261     {
1262         i_mode = SORT_TITLE;
1263     }
1264     else if( o_tc == o_tc_author )
1265     {
1266         i_mode = SORT_ARTIST;
1267     }
1268
1269     if( b_isSortDescending )
1270     {
1271         i_type = ORDER_REVERSE;
1272     }
1273     else
1274     {
1275         i_type = ORDER_NORMAL;
1276     }
1277
1278     vlc_mutex_lock( &p_playlist->object_lock );
1279     playlist_RecursiveNodeSort( p_playlist, p_playlist->p_root_category, i_mode, i_type );
1280     vlc_mutex_unlock( &p_playlist->object_lock );
1281
1282     vlc_object_release( p_playlist );
1283     [self playlistUpdated];
1284
1285     o_tc_sortColumn = o_tc;
1286     [o_outline_view setHighlightedTableColumn:o_tc];
1287
1288     if( b_isSortDescending )
1289     {
1290         [o_outline_view setIndicatorImage:o_descendingSortingImage
1291                                                         inTableColumn:o_tc];
1292     }
1293     else
1294     {
1295         [o_outline_view setIndicatorImage:o_ascendingSortingImage
1296                                                         inTableColumn:o_tc];
1297     }
1298 }
1299
1300
1301 - (void)outlineView:(NSOutlineView *)outlineView
1302                                 willDisplayCell:(id)cell
1303                                 forTableColumn:(NSTableColumn *)tableColumn
1304                                 item:(id)item
1305 {
1306     playlist_t *p_playlist = pl_Yield( VLCIntf );
1307
1308     id o_playing_item;
1309
1310     o_playing_item = [o_outline_dict objectForKey:
1311                 [NSString stringWithFormat:@"%p",  p_playlist->status.p_item]];
1312
1313     if( [self isItem: [o_playing_item pointerValue] inNode:
1314                         [item pointerValue] checkItemExistence: YES]
1315                         || [o_playing_item isEqual: item] )
1316     {
1317         [cell setFont: [NSFont boldSystemFontOfSize: 0]];
1318     }
1319     else
1320     {
1321         [cell setFont: [NSFont systemFontOfSize: 0]];
1322     }
1323     vlc_object_release( p_playlist );
1324 }
1325
1326 - (IBAction)addNode:(id)sender
1327 {
1328     /* we have to create a new thread here because otherwise we would block the
1329      * interface since the interaction-stuff and this code would run in the same
1330      * thread */
1331     [NSThread detachNewThreadSelector: @selector(addNodeThreadedly) 
1332         toTarget: self withObject:nil];
1333     [self playlistUpdated];
1334 }
1335
1336 - (void)addNodeThreadedly
1337 {
1338     NSAutoreleasePool * ourPool = [[NSAutoreleasePool alloc] init];
1339
1340     /* simply adds a new node to the end of the playlist */
1341     playlist_t * p_playlist = pl_Yield( VLCIntf );
1342     vlc_thread_set_priority( p_playlist, VLC_THREAD_PRIORITY_LOW );
1343
1344     int ret_v;
1345     char *psz_name = NULL;
1346     playlist_item_t * p_item;
1347     ret_v = intf_UserStringInput( p_playlist, _("New Node"), 
1348         _("Please enter a name for the new node."), &psz_name );
1349     if( psz_name != NULL && psz_name != "" )
1350         p_item = playlist_NodeCreate( p_playlist, psz_name, 
1351                                             p_playlist->p_local_category );
1352     else
1353         p_item = playlist_NodeCreate( p_playlist, _("Empty Folder"), 
1354                                             p_playlist->p_local_category );
1355
1356     if(! p_item )
1357         msg_Warn( VLCIntf, "node creation failed" );
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