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