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