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