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