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