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