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