]> git.sesse.net Git - vlc/blob - modules/gui/macosx/playlist.m
825f1c298ecf5e97bebb63b75a59364ef21d16ef
[vlc] / modules / gui / macosx / playlist.m
1 /*****************************************************************************
2  * playlist.m: MacOS X interface module
3  *****************************************************************************
4 * Copyright (C) 2002-2014 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  *          Felix Paul Kühne <fkuehne at videolan dot org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /* TODO
28  * add 'icons' for different types of nodes? (http://www.cocoadev.com/index.pl?IconAndTextInTableCell)
29  * reimplement enable/disable item
30  */
31
32
33 /*****************************************************************************
34  * Preamble
35  *****************************************************************************/
36 #include <stdlib.h>                                      /* malloc(), free() */
37 #include <sys/param.h>                                    /* for MAXPATHLEN */
38 #include <string.h>
39 #include <math.h>
40 #include <sys/mount.h>
41
42 #import "CompatibilityFixes.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 "misc.h"
51 #import "open.h"
52 #import "MainMenu.h"
53 #import "CoreInteraction.h"
54
55 #include <vlc_keys.h>
56 #import <vlc_interface.h>
57 #include <vlc_url.h>
58
59 /*****************************************************************************
60  * VLCPlaylistView implementation
61  *****************************************************************************/
62 @implementation VLCPlaylistView
63
64 - (NSMenu *)menuForEvent:(NSEvent *)o_event
65 {
66     return([(VLCPlaylist *)[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         key = [[o_event characters] characterAtIndex: 0];
75
76     switch(key) {
77         case NSDeleteCharacter:
78         case NSDeleteFunctionKey:
79         case NSDeleteCharFunctionKey:
80         case NSBackspaceCharacter:
81             [(VLCPlaylist *)[self delegate] deleteItem:self];
82             break;
83
84         case NSEnterCharacter:
85         case NSCarriageReturnCharacter:
86             [(VLCPlaylist *)[[VLCMain sharedInstance] playlist] playItem:nil];
87             break;
88
89         default:
90             [super keyDown: o_event];
91             break;
92     }
93 }
94
95 - (BOOL)validateMenuItem:(NSMenuItem *)item
96 {
97     if (([self numberOfSelectedRows] >= 1 && [item action] == @selector(delete:)) || [item action] == @selector(selectAll:))
98         return YES;
99
100     return NO;
101 }
102
103 - (BOOL)acceptsFirstResponder
104 {
105     return YES;
106 }
107
108 - (BOOL)becomeFirstResponder
109 {
110     [self setNeedsDisplay:YES];
111     return YES;
112 }
113
114 - (BOOL)resignFirstResponder
115 {
116     [self setNeedsDisplay:YES];
117     return YES;
118 }
119
120 - (IBAction)delete:(id)sender
121 {
122     [[[VLCMain sharedInstance] playlist] deleteItem: sender];
123 }
124
125 @end
126
127 /*****************************************************************************
128  * VLCPlaylistWizard implementation
129  *****************************************************************************/
130 @implementation VLCPlaylistWizard
131
132 - (IBAction)reloadOutlineView
133 {
134     /* Only reload the outlineview if the wizard window is open since this can
135        be quite long on big playlists */
136
137
138     // to be removed
139 }
140
141 @end
142
143 /*****************************************************************************
144  * An extension to NSOutlineView's interface to fix compilation warnings
145  * and let us access these 2 functions properly.
146  * This uses a private API, but works fine on all current OSX releases.
147  * Radar ID 11739459 request a public API for this. However, it is probably
148  * easier and faster to recreate similar looking bitmaps ourselves.
149  *****************************************************************************/
150
151 @interface NSOutlineView (UndocumentedSortImages)
152 + (NSImage *)_defaultTableHeaderSortImage;
153 + (NSImage *)_defaultTableHeaderReverseSortImage;
154 @end
155
156
157 /*****************************************************************************
158  * VLCPlaylist implementation
159  *****************************************************************************/
160 @interface VLCPlaylist ()
161 {
162     NSImage *o_descendingSortingImage;
163     NSImage *o_ascendingSortingImage;
164
165     BOOL b_selected_item_met;
166     BOOL b_isSortDescending;
167     id o_tc_sortColumn;
168     NSUInteger retainedRowSelection;
169
170     BOOL b_playlistmenu_nib_loaded;
171     BOOL b_view_setup;
172 }
173
174 - (void)saveTableColumns;
175 @end
176
177 @implementation VLCPlaylist
178
179 + (void)initialize
180 {
181     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
182     NSMutableArray *o_columnArray = [[NSMutableArray alloc] init];
183     [o_columnArray addObject: [NSArray arrayWithObjects:TITLE_COLUMN, [NSNumber numberWithFloat:190.], nil]];
184     [o_columnArray addObject: [NSArray arrayWithObjects:ARTIST_COLUMN, [NSNumber numberWithFloat:95.], nil]];
185     [o_columnArray addObject: [NSArray arrayWithObjects:DURATION_COLUMN, [NSNumber numberWithFloat:95.], nil]];
186
187     NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
188                                  [NSArray arrayWithArray:o_columnArray], @"PlaylistColumnSelection",
189                                  [NSArray array], @"recentlyPlayedMediaList",
190                                  [NSDictionary dictionary], @"recentlyPlayedMedia", nil];
191
192     [defaults registerDefaults:appDefaults];
193     [o_columnArray release];
194 }
195
196 - (PLModel *)model
197 {
198     return o_model;
199 }
200
201 - (void)reloadStyles
202 {
203     NSFont *fontToUse;
204     CGFloat rowHeight;
205     if (config_GetInt(VLCIntf, "macosx-large-text")) {
206         fontToUse = [NSFont systemFontOfSize:13.];
207         rowHeight = 21.;
208     } else {
209         fontToUse = [NSFont systemFontOfSize:11.];
210         rowHeight = 16.;
211     }
212
213     NSArray *columns = [o_outline_view tableColumns];
214     NSUInteger count = columns.count;
215     for (NSUInteger x = 0; x < count; x++)
216         [[[columns objectAtIndex:x] dataCell] setFont:fontToUse];
217     [o_outline_view setRowHeight:rowHeight];
218 }
219
220 - (void)dealloc
221 {
222     [super dealloc];
223 }
224
225 - (void)awakeFromNib
226 {
227     if (b_view_setup)
228         return;
229
230     playlist_t * p_playlist = pl_Get(VLCIntf);
231
232     [self reloadStyles];
233     [self initStrings];
234
235     o_model = [[PLModel alloc] initWithOutlineView:o_outline_view playlist:p_playlist rootItem:p_playlist->p_playing playlistObject:self];
236     [o_outline_view setDataSource:o_model];
237     [o_outline_view reloadData];
238
239     [o_outline_view setTarget: self];
240     [o_outline_view setDoubleAction: @selector(playItem:)];
241
242     [o_outline_view setAllowsEmptySelection: NO];
243     [o_outline_view registerForDraggedTypes: [NSArray arrayWithObjects:NSFilenamesPboardType, @"VLCPlaylistItemPboardType", nil]];
244     [o_outline_view setIntercellSpacing: NSMakeSize (0.0, 1.0)];
245
246     /* This uses a private API, but works fine on all current OSX releases.
247      * Radar ID 11739459 request a public API for this. However, it is probably
248      * easier and faster to recreate similar looking bitmaps ourselves. */
249     o_ascendingSortingImage = [[NSOutlineView class] _defaultTableHeaderSortImage];
250     o_descendingSortingImage = [[NSOutlineView class] _defaultTableHeaderReverseSortImage];
251
252     o_tc_sortColumn = nil;
253
254     NSArray * o_columnArray = [[NSUserDefaults standardUserDefaults] arrayForKey:@"PlaylistColumnSelection"];
255     NSUInteger count = [o_columnArray count];
256
257     id o_menu = [[VLCMain sharedInstance] mainMenu];
258     NSString * o_column;
259
260     NSMenu *o_context_menu = [o_menu setupPlaylistTableColumnsMenu];
261     [o_playlist_header setMenu: o_context_menu];
262
263     for (NSUInteger i = 0; i < count; i++) {
264         o_column = [[o_columnArray objectAtIndex:i] objectAtIndex:0];
265         if ([o_column isEqualToString:@"status"])
266             continue;
267
268         if(![o_menu setPlaylistColumnTableState: NSOnState forColumn: o_column])
269             continue;
270
271         [[o_outline_view tableColumnWithIdentifier: o_column] setWidth: [[[o_columnArray objectAtIndex:i] objectAtIndex:1] floatValue]];
272     }
273
274     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(applicationWillTerminate:) name: NSApplicationWillTerminateNotification object: nil];
275
276     b_view_setup = YES;
277 }
278
279 - (void)applicationWillTerminate:(NSNotification *)notification
280 {
281     /* let's make sure we save the correct widths and positions, since this likely changed since the last time the user played with the column selection */
282     [self saveTableColumns];
283 }
284
285 - (void)initStrings
286 {
287     [o_mi_play setTitle: _NS("Play")];
288     [o_mi_delete setTitle: _NS("Delete")];
289     [o_mi_recursive_expand setTitle: _NS("Expand Node")];
290     [o_mi_selectall setTitle: _NS("Select All")];
291     [o_mi_info setTitle: _NS("Media Information...")];
292     [o_mi_dl_cover_art setTitle: _NS("Download Cover Art")];
293     [o_mi_preparse setTitle: _NS("Fetch Meta Data")];
294     [o_mi_revealInFinder setTitle: _NS("Reveal in Finder")];
295     [o_mi_sort_name setTitle: _NS("Sort Node by Name")];
296     [o_mi_sort_author setTitle: _NS("Sort Node by Author")];
297
298     [o_search_field setToolTip: _NS("Search in Playlist")];
299 }
300
301 - (void)playlistUpdated
302 {
303     [o_outline_view reloadData];
304 }
305
306 - (void)outlineViewSelectionDidChange:(NSNotification *)notification
307 {
308 //    // FIXME: unsafe
309 //    playlist_item_t * p_item = [[o_outline_view itemAtRow:[o_outline_view selectedRow]] pointerValue];
310 //
311 //    if (p_item) {
312 //        /* update the state of our Reveal-in-Finder menu items */
313 //        NSMutableString *o_mrl;
314 //        char *psz_uri = input_item_GetURI(p_item->p_input);
315 //
316 //        [o_mi_revealInFinder setEnabled: NO];
317 //        [o_mm_mi_revealInFinder setEnabled: NO];
318 //        if (psz_uri) {
319 //            o_mrl = [NSMutableString stringWithUTF8String: psz_uri];
320 //
321 //            /* perform some checks whether it is a file and if it is local at all... */
322 //            NSRange prefix_range = [o_mrl rangeOfString: @"file:"];
323 //            if (prefix_range.location != NSNotFound)
324 //                [o_mrl deleteCharactersInRange: prefix_range];
325 //
326 //            if ([o_mrl characterAtIndex:0] == '/') {
327 //                [o_mi_revealInFinder setEnabled: YES];
328 //                [o_mm_mi_revealInFinder setEnabled: YES];
329 //            }
330 //            free(psz_uri);
331 //        }
332 //
333 //        /* update our info-panel to reflect the new item */
334 //        [[[VLCMain sharedInstance] info] updatePanelWithItem:p_item->p_input];
335 //    }
336 }
337
338 - (BOOL)isSelectionEmpty
339 {
340     return [o_outline_view selectedRow] == -1;
341 }
342
343 - (void)currentlyPlayingItemChanged
344 {
345     PLItem *item = [[self model] currentlyPlayingItem];
346     if (!item)
347         return;
348
349     // select item
350     NSInteger itemIndex = [o_outline_view rowForItem:item];
351     if (itemIndex < 0) {
352         // expand if needed
353         while (item != nil) {
354             PLItem *parent = [item parent];
355
356             if (![o_outline_view isExpandable: parent])
357                 break;
358             if (![o_outline_view isItemExpanded: parent])
359                 [o_outline_view expandItem: parent];
360             item = parent;
361         }
362
363         // search for row again
364         itemIndex = [o_outline_view rowForItem:item];
365         if (itemIndex < 0) {
366             return;
367         }
368     }
369
370     [o_outline_view selectRowIndexes: [NSIndexSet indexSetWithIndex: itemIndex] byExtendingSelection: NO];
371 }
372
373 - (IBAction)savePlaylist:(id)sender
374 {
375     playlist_t * p_playlist = pl_Get(VLCIntf);
376
377     NSSavePanel *o_save_panel = [NSSavePanel savePanel];
378     NSString * o_name = [NSString stringWithFormat: @"%@", _NS("Untitled")];
379
380     [NSBundle loadNibNamed:@"PlaylistAccessoryView" owner:self];
381
382     [o_save_accessory_text setStringValue: _NS("File Format:")];
383     [[o_save_accessory_popup itemAtIndex:0] setTitle: _NS("Extended M3U")];
384     [[o_save_accessory_popup itemAtIndex:1] setTitle: _NS("XML Shareable Playlist Format (XSPF)")];
385     [[o_save_accessory_popup itemAtIndex:2] setTitle: _NS("HTML playlist")];
386
387     [o_save_panel setTitle: _NS("Save Playlist")];
388     [o_save_panel setPrompt: _NS("Save")];
389     [o_save_panel setAccessoryView: o_save_accessory_view];
390     [o_save_panel setNameFieldStringValue: o_name];
391
392     if ([o_save_panel runModal] == NSFileHandlingPanelOKButton) {
393         NSString *o_filename = [[o_save_panel URL] path];
394
395         if ([o_save_accessory_popup indexOfSelectedItem] == 0) {
396             NSString * o_real_filename;
397             NSRange range;
398             range.location = [o_filename length] - [@".m3u" length];
399             range.length = [@".m3u" length];
400
401             if ([o_filename compare:@".m3u" options: NSCaseInsensitiveSearch range: range] != NSOrderedSame)
402                 o_real_filename = [NSString stringWithFormat: @"%@.m3u", o_filename];
403             else
404                 o_real_filename = o_filename;
405
406             playlist_Export(p_playlist,
407                 [o_real_filename fileSystemRepresentation],
408                 p_playlist->p_local_category, "export-m3u");
409         } else if ([o_save_accessory_popup indexOfSelectedItem] == 1) {
410             NSString * o_real_filename;
411             NSRange range;
412             range.location = [o_filename length] - [@".xspf" length];
413             range.length = [@".xspf" length];
414
415             if ([o_filename compare:@".xspf" options: NSCaseInsensitiveSearch range: range] != NSOrderedSame)
416                 o_real_filename = [NSString stringWithFormat: @"%@.xspf", o_filename];
417             else
418                 o_real_filename = o_filename;
419
420             playlist_Export(p_playlist,
421                 [o_real_filename fileSystemRepresentation],
422                 p_playlist->p_local_category, "export-xspf");
423         } else {
424             NSString * o_real_filename;
425             NSRange range;
426             range.location = [o_filename length] - [@".html" length];
427             range.length = [@".html" length];
428
429             if ([o_filename compare:@".html" options: NSCaseInsensitiveSearch range: range] != NSOrderedSame)
430                 o_real_filename = [NSString stringWithFormat: @"%@.html", o_filename];
431             else
432                 o_real_filename = o_filename;
433
434             playlist_Export(p_playlist,
435                 [o_real_filename fileSystemRepresentation],
436                 p_playlist->p_local_category, "export-html");
437         }
438     }
439 }
440
441 /* When called retrieves the selected outlineview row and plays that node or item */
442 - (IBAction)playItem:(id)sender
443 {
444     playlist_t *p_playlist = pl_Get(VLCIntf);
445
446     // ignore clicks on column header when handling double action
447     if (sender == o_outline_view && [o_outline_view clickedRow] == -1)
448         return;
449
450     PLItem *o_item = [o_outline_view itemAtRow:[o_outline_view selectedRow]];
451     if (!o_item)
452         return;
453
454     PL_LOCK;
455     playlist_item_t *p_item = playlist_ItemGetById(p_playlist, [o_item plItemId]);
456     playlist_item_t *p_node = playlist_ItemGetById(p_playlist, [[[self model] rootItem] plItemId]);
457
458     if (p_item && p_node) {
459         playlist_Control(p_playlist, PLAYLIST_VIEWPLAY, pl_Locked, p_node, p_item);
460     }
461     PL_UNLOCK;
462 }
463
464 - (IBAction)revealItemInFinder:(id)sender
465 {
466     NSIndexSet *selectedRows = [o_outline_view selectedRowIndexes];
467     [selectedRows enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
468
469         PLItem *o_item = [o_outline_view itemAtRow:idx];
470
471         /* perform some checks whether it is a file and if it is local at all... */
472         char *psz_url = input_item_GetURI([o_item input]);
473         NSURL *url = [NSURL URLWithString:toNSStr(psz_url)];
474         free(psz_url);
475         if (![url isFileURL])
476             return;
477         if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]])
478             return;
479
480         msg_Dbg(VLCIntf, "Reveal url %s in finder", [[url path] UTF8String]);
481         [[NSWorkspace sharedWorkspace] selectFile: [url path] inFileViewerRootedAtPath: [url path]];
482     }];
483
484 }
485
486 /* When called retrieves the selected outlineview row and plays that node or item */
487 - (IBAction)preparseItem:(id)sender
488 {
489     int i_count;
490     NSIndexSet *o_selected_indexes;
491     intf_thread_t * p_intf = VLCIntf;
492     playlist_t * p_playlist = pl_Get(p_intf);
493     playlist_item_t *p_item = NULL;
494
495     o_selected_indexes = [o_outline_view selectedRowIndexes];
496     i_count = [o_selected_indexes count];
497
498     NSUInteger indexes[i_count];
499     [o_selected_indexes getIndexes:indexes maxCount:i_count inIndexRange:nil];
500     for (int i = 0; i < i_count; i++) {
501         PLItem *o_item = [o_outline_view itemAtRow:indexes[i]];
502         [o_outline_view deselectRow: indexes[i]];
503
504         if (![o_item isLeaf]) {
505             msg_Dbg(p_intf, "preparsing nodes not implemented");
506             continue;
507         }
508
509         libvlc_MetaRequest(p_intf->p_libvlc, [o_item input], META_REQUEST_OPTION_NONE);
510
511     }
512     [self playlistUpdated];
513 }
514
515 - (IBAction)downloadCoverArt:(id)sender
516 {
517     int i_count;
518     NSIndexSet *o_selected_indexes;
519     intf_thread_t * p_intf = VLCIntf;
520     playlist_t * p_playlist = pl_Get(p_intf);
521     playlist_item_t *p_item = NULL;
522
523     o_selected_indexes = [o_outline_view selectedRowIndexes];
524     i_count = [o_selected_indexes count];
525
526     NSUInteger indexes[i_count];
527     [o_selected_indexes getIndexes:indexes maxCount:i_count inIndexRange:nil];
528     for (int i = 0; i < i_count; i++) {
529         PLItem *o_item = [o_outline_view itemAtRow: indexes[i]];
530
531         if (![o_item isLeaf])
532             continue;
533
534         libvlc_ArtRequest(p_intf->p_libvlc, [o_item input], META_REQUEST_OPTION_NONE);
535     }
536     [self playlistUpdated];
537 }
538
539 - (IBAction)selectAll:(id)sender
540 {
541     [o_outline_view selectAll: nil];
542 }
543
544 - (IBAction)showInfoPanel:(id)sender
545 {
546     [[[VLCMain sharedInstance] info] initPanel];
547 }
548
549 - (void)deletionCompleted
550 {
551     // retain selection before deletion
552     [o_outline_view selectRowIndexes:[NSIndexSet indexSetWithIndex:retainedRowSelection] byExtendingSelection:NO];
553 }
554
555 - (IBAction)deleteItem:(id)sender
556 {
557     playlist_t * p_playlist = pl_Get(VLCIntf);
558
559     // check if deletion is allowed
560     if (![[self model] editAllowed])
561         return;
562
563     NSIndexSet *o_selected_indexes = [o_outline_view selectedRowIndexes];
564     retainedRowSelection = [o_selected_indexes firstIndex];
565     if (retainedRowSelection == NSNotFound)
566         retainedRowSelection = 0;
567
568     [o_selected_indexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
569         PLItem *o_item = [o_outline_view itemAtRow: idx];
570         if (!o_item)
571             return;
572
573         // model deletion is done via callback
574         playlist_DeleteFromInput(p_playlist, [o_item input], pl_Unlocked);
575     }];
576 }
577
578 - (IBAction)sortNodeByName:(id)sender
579 {
580     [self sortNode: SORT_TITLE];
581 }
582
583 - (IBAction)sortNodeByAuthor:(id)sender
584 {
585     [self sortNode: SORT_ARTIST];
586 }
587
588 - (void)sortNode:(int)i_mode
589 {
590     playlist_t * p_playlist = pl_Get(VLCIntf);
591     playlist_item_t * p_item;
592
593     // TODO why do we need this kind of sort? It looks crap and confusing...
594
595 //    if ([o_outline_view selectedRow] > -1) {
596 //        p_item = [[o_outline_view itemAtRow: [o_outline_view selectedRow]] pointerValue];
597 //        if (!p_item)
598 //            return;
599 //    } else
600 //        p_item = [self currentPlaylistRoot]; // If no item is selected, sort the whole playlist
601 //
602 //    PL_LOCK;
603 //    if (p_item->i_children > -1) // the item is a node
604 //        playlist_RecursiveNodeSort(p_playlist, p_item, i_mode, ORDER_NORMAL);
605 //    else
606 //        playlist_RecursiveNodeSort(p_playlist, p_item->p_parent, i_mode, ORDER_NORMAL);
607 //
608 //    PL_UNLOCK;
609 //    [self playlistUpdated];
610 }
611
612 - (input_item_t *)createItem:(NSDictionary *)o_one_item
613 {
614     intf_thread_t * p_intf = VLCIntf;
615     playlist_t * p_playlist = pl_Get(p_intf);
616
617     input_item_t *p_input;
618     BOOL b_rem = FALSE, b_dir = FALSE, b_writable = FALSE;
619     NSString *o_uri, *o_name, *o_path;
620     NSURL * o_nsurl;
621     NSArray *o_options;
622     NSURL *o_true_file;
623
624     /* Get the item */
625     o_uri = (NSString *)[o_one_item objectForKey: @"ITEM_URL"];
626     o_nsurl = [NSURL URLWithString: o_uri];
627     o_path = [o_nsurl path];
628     o_name = (NSString *)[o_one_item objectForKey: @"ITEM_NAME"];
629     o_options = (NSArray *)[o_one_item objectForKey: @"ITEM_OPTIONS"];
630
631     if ([[NSFileManager defaultManager] fileExistsAtPath:o_path isDirectory:&b_dir] && b_dir &&
632         [[NSWorkspace sharedWorkspace] getFileSystemInfoForPath:o_path isRemovable: &b_rem
633                                                      isWritable:&b_writable isUnmountable:NULL description:NULL type:NULL] && b_rem && !b_writable && [o_nsurl isFileURL]) {
634
635         NSString *diskType = [VLCOpen getVolumeTypeFromMountPath: o_path];
636         msg_Dbg(p_intf, "detected optical media of type %s in the file input", [diskType UTF8String]);
637
638         if ([diskType isEqualToString: kVLCMediaDVD])
639             o_uri = [NSString stringWithFormat: @"dvdnav://%@", [VLCOpen getBSDNodeFromMountPath: o_path]];
640         else if ([diskType isEqualToString: kVLCMediaVideoTSFolder])
641             o_uri = [NSString stringWithFormat: @"dvdnav://%@", o_path];
642         else if ([diskType isEqualToString: kVLCMediaAudioCD])
643             o_uri = [NSString stringWithFormat: @"cdda://%@", [VLCOpen getBSDNodeFromMountPath: o_path]];
644         else if ([diskType isEqualToString: kVLCMediaVCD])
645             o_uri = [NSString stringWithFormat: @"vcd://%@#0:0", [VLCOpen getBSDNodeFromMountPath: o_path]];
646         else if ([diskType isEqualToString: kVLCMediaSVCD])
647             o_uri = [NSString stringWithFormat: @"vcd://%@@0:0", [VLCOpen getBSDNodeFromMountPath: o_path]];
648         else if ([diskType isEqualToString: kVLCMediaBD] || [diskType isEqualToString: kVLCMediaBDMVFolder])
649             o_uri = [NSString stringWithFormat: @"bluray://%@", o_path];
650         else
651             msg_Warn(VLCIntf, "unknown disk type, treating %s as regular input", [o_path UTF8String]);
652
653         p_input = input_item_New([o_uri UTF8String], [[[NSFileManager defaultManager] displayNameAtPath: o_path] UTF8String]);
654     }
655     else
656         p_input = input_item_New([o_uri fileSystemRepresentation], o_name ? [o_name UTF8String] : NULL);
657
658     if (!p_input)
659         return NULL;
660
661     if (o_options) {
662         NSUInteger count = [o_options count];
663         for (NSUInteger i = 0; i < count; i++)
664             input_item_AddOption(p_input, [[o_options objectAtIndex:i] UTF8String], VLC_INPUT_OPTION_TRUSTED);
665     }
666
667     /* Recent documents menu */
668     if (o_nsurl != nil && (BOOL)config_GetInt(p_playlist, "macosx-recentitems") == YES)
669         [[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL: o_nsurl];
670
671     return p_input;
672 }
673
674 - (void)addPlaylistItems:(NSArray*)o_array
675 {
676
677     int i_plItemId = -1;
678
679     // add items directly to media library if this is the current root
680     if ([[self model] currentRootType] == ROOT_TYPE_MEDIALIBRARY)
681         i_plItemId = [[[self model] rootItem] plItemId];
682
683     BOOL b_autoplay = var_InheritBool(VLCIntf, "macosx-autoplay");
684
685     [self addPlaylistItems:o_array withParentItemId:i_plItemId atPos:-1 startPlayback:b_autoplay];
686 }
687
688 - (void)addPlaylistItems:(NSArray*)o_array withParentItemId:(int)i_plItemId atPos:(int)i_position startPlayback:(BOOL)b_start
689 {
690     playlist_t * p_playlist = pl_Get(VLCIntf);
691     PL_LOCK;
692
693     playlist_item_t *p_parent = NULL;
694     if (i_plItemId >= 0)
695         p_parent = playlist_ItemGetById(p_playlist, i_plItemId);
696     else
697         p_parent = p_playlist->p_playing;
698
699     if (!p_parent) {
700         PL_UNLOCK;
701         return;
702     }
703
704     NSUInteger count = [o_array count];
705     int i_current_offset = 0;
706     for (NSUInteger i = 0; i < count; ++i) {
707
708         NSDictionary *o_current_item = [o_array objectAtIndex:i];
709         input_item_t *p_input = [self createItem: o_current_item];
710         if (!p_input)
711             continue;
712
713         int i_pos = (i_position == -1) ? PLAYLIST_END : i_position + i_current_offset++;
714         playlist_item_t *p_item = playlist_NodeAddInput(p_playlist, p_input, p_parent,
715                                                         PLAYLIST_INSERT, i_pos, pl_Locked);
716         if (!p_item)
717             continue;
718
719         if (i == 0 && b_start) {
720             playlist_Control(p_playlist, PLAYLIST_VIEWPLAY, pl_Locked, p_parent, p_item);
721         }
722         input_item_Release(p_input);
723     }
724     PL_UNLOCK;
725 }
726
727
728 - (IBAction)searchItem:(id)sender
729 {
730     [[self model] searchUpdate:[o_search_field stringValue]];
731 }
732
733 - (IBAction)recursiveExpandNode:(id)sender
734 {
735     NSIndexSet * selectedRows = [o_outline_view selectedRowIndexes];
736     NSUInteger count = [selectedRows count];
737     NSUInteger indexes[count];
738     [selectedRows getIndexes:indexes maxCount:count inIndexRange:nil];
739
740     id o_item;
741     playlist_item_t *p_item;
742     for (NSUInteger i = 0; i < count; i++) {
743         o_item = [o_outline_view itemAtRow: indexes[i]];
744
745         /* We need to collapse the node first, since OSX refuses to recursively
746          expand an already expanded node, even if children nodes are collapsed. */
747         if ([o_outline_view isExpandable:o_item]) {
748             [o_outline_view collapseItem: o_item collapseChildren: YES];
749             [o_outline_view expandItem: o_item expandChildren: YES];
750         }
751
752         selectedRows = [o_outline_view selectedRowIndexes];
753         [selectedRows getIndexes:indexes maxCount:count inIndexRange:nil];
754     }
755 }
756
757 - (NSMenu *)menuForEvent:(NSEvent *)o_event
758 {
759     if (!b_playlistmenu_nib_loaded)
760         b_playlistmenu_nib_loaded = [NSBundle loadNibNamed:@"PlaylistMenu" owner:self];
761
762     NSPoint pt;
763     bool b_rows;
764     bool b_item_sel;
765
766     pt = [o_outline_view convertPoint: [o_event locationInWindow] fromView: nil];
767     int row = [o_outline_view rowAtPoint:pt];
768     if (row != -1 && ![[o_outline_view selectedRowIndexes] containsIndex: row])
769         [o_outline_view selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
770
771     b_item_sel = (row != -1 && [o_outline_view selectedRow] != -1);
772     b_rows = [o_outline_view numberOfRows] != 0;
773
774     playlist_t *p_playlist = pl_Get(VLCIntf);
775     bool b_del_allowed = [[self model] editAllowed];
776
777     [o_mi_play setEnabled: b_item_sel];
778     [o_mi_delete setEnabled: b_item_sel && b_del_allowed];
779     [o_mi_selectall setEnabled: b_rows];
780     [o_mi_info setEnabled: b_item_sel];
781     [o_mi_preparse setEnabled: b_item_sel];
782     [o_mi_recursive_expand setEnabled: b_item_sel];
783     [o_mi_sort_name setEnabled: b_item_sel];
784     [o_mi_sort_author setEnabled: b_item_sel];
785     [o_mi_dl_cover_art setEnabled: b_item_sel];
786
787     return o_ctx_menu;
788 }
789
790 - (void)outlineView: (NSOutlineView *)o_tv didClickTableColumn:(NSTableColumn *)o_tc
791 {
792     int i_mode, i_type = 0;
793     intf_thread_t *p_intf = VLCIntf;
794     NSString * o_identifier = [o_tc identifier];
795
796     playlist_t *p_playlist = pl_Get(p_intf);
797
798     if (o_tc_sortColumn == o_tc)
799         b_isSortDescending = !b_isSortDescending;
800     else
801         b_isSortDescending = false;
802
803     if (b_isSortDescending)
804         i_type = ORDER_REVERSE;
805     else
806         i_type = ORDER_NORMAL;
807
808     [[self model] sortForColumn:o_identifier withMode:i_type];
809
810     // TODO rework, why do we need a full call here?
811 //    [self playlistUpdated];
812
813     /* Clear indications of any existing column sorting */
814     NSUInteger count = [[o_outline_view tableColumns] count];
815     for (NSUInteger i = 0 ; i < count ; i++)
816         [o_outline_view setIndicatorImage:nil inTableColumn: [[o_outline_view tableColumns] objectAtIndex:i]];
817
818     [o_outline_view setHighlightedTableColumn:nil];
819     o_tc_sortColumn = nil;
820
821
822     o_tc_sortColumn = o_tc;
823     [o_outline_view setHighlightedTableColumn:o_tc];
824
825     if (b_isSortDescending)
826         [o_outline_view setIndicatorImage:o_descendingSortingImage inTableColumn:o_tc];
827     else
828         [o_outline_view setIndicatorImage:o_ascendingSortingImage inTableColumn:o_tc];
829 }
830
831
832 - (void)outlineView:(NSOutlineView *)outlineView
833     willDisplayCell:(id)cell
834      forTableColumn:(NSTableColumn *)tableColumn
835                item:(id)item
836 {
837     /* this method can be called when VLC is already dead, hence the extra checks */
838     intf_thread_t * p_intf = VLCIntf;
839     if (!p_intf)
840         return;
841     playlist_t *p_playlist = pl_Get(p_intf);
842
843     NSFont *fontToUse;
844     if (config_GetInt(VLCIntf, "macosx-large-text"))
845         fontToUse = [NSFont systemFontOfSize:13.];
846     else
847         fontToUse = [NSFont systemFontOfSize:11.];
848
849     BOOL b_is_playing = NO;
850     PL_LOCK;
851     playlist_item_t *p_current_item = playlist_CurrentPlayingItem(p_playlist);
852     if (p_current_item) {
853         b_is_playing = p_current_item->i_id == [item plItemId];
854     }
855     PL_UNLOCK;
856
857     /*
858      TODO: repaint all items bold:
859      [self isItem: [o_playing_item pointerValue] inNode: [item pointerValue] checkItemExistence:YES locked:NO]
860      || [o_playing_item isEqual: item]
861      */
862
863     if (b_is_playing)
864         [cell setFont: [[NSFontManager sharedFontManager] convertFont:fontToUse toHaveTrait:NSBoldFontMask]];
865     else
866         [cell setFont: [[NSFontManager sharedFontManager] convertFont:fontToUse toNotHaveTrait:NSBoldFontMask]];
867 }
868
869 // TODO remove method
870 - (NSArray *)draggedItems
871 {
872     return [[self model] draggedItems];
873 }
874
875 - (void)setColumn: (NSString *)o_column state: (NSInteger)i_state translationDict:(NSDictionary *)o_dict
876 {
877     NSTableColumn * o_work_tc;
878
879     if (i_state == NSOnState) {
880         NSString *o_title = [o_dict objectForKey:o_column];
881         if (!o_title)
882             return;
883
884         o_work_tc = [[NSTableColumn alloc] initWithIdentifier: o_column];
885         [o_work_tc setEditable: NO];
886         [[o_work_tc dataCell] setFont: [NSFont controlContentFontOfSize:11.]];
887
888         [[o_work_tc headerCell] setStringValue: [o_dict objectForKey:o_column]];
889
890         if ([o_column isEqualToString: TRACKNUM_COLUMN]) {
891             [o_work_tc setWidth: 20.];
892             [o_work_tc setResizingMask: NSTableColumnNoResizing];
893             [[o_work_tc headerCell] setStringValue: @"#"];
894         }
895
896         [o_outline_view addTableColumn: o_work_tc];
897         [o_work_tc release];
898         [o_outline_view reloadData];
899         [o_outline_view setNeedsDisplay: YES];
900     }
901     else
902         [o_outline_view removeTableColumn: [o_outline_view tableColumnWithIdentifier: o_column]];
903
904     [o_outline_view setOutlineTableColumn: [o_outline_view tableColumnWithIdentifier:TITLE_COLUMN]];
905 }
906
907 - (void)saveTableColumns
908 {
909     NSMutableArray * o_arrayToSave = [[NSMutableArray alloc] init];
910     NSArray * o_columns = [[NSArray alloc] initWithArray:[o_outline_view tableColumns]];
911     NSUInteger count = [o_columns count];
912     NSTableColumn * o_currentColumn;
913     for (NSUInteger i = 0; i < count; i++) {
914         o_currentColumn = [o_columns objectAtIndex:i];
915         [o_arrayToSave addObject:[NSArray arrayWithObjects:[o_currentColumn identifier], [NSNumber numberWithFloat:[o_currentColumn width]], nil]];
916     }
917     [[NSUserDefaults standardUserDefaults] setObject: o_arrayToSave forKey:@"PlaylistColumnSelection"];
918     [[NSUserDefaults standardUserDefaults] synchronize];
919     [o_columns release];
920     [o_arrayToSave release];
921 }
922
923 - (BOOL)isValidResumeItem:(input_item_t *)p_item
924 {
925     char *psz_url = input_item_GetURI(p_item);
926     NSString *o_url_string = toNSStr(psz_url);
927     free(psz_url);
928
929     if ([o_url_string isEqualToString:@""])
930         return NO;
931
932     NSURL *o_url = [NSURL URLWithString:o_url_string];
933
934     if (![o_url isFileURL])
935         return NO;
936
937     BOOL isDir = false;
938     if (![[NSFileManager defaultManager] fileExistsAtPath:[o_url path] isDirectory:&isDir])
939         return NO;
940
941     if (isDir)
942         return NO;
943
944     return YES;
945 }
946
947 - (void)updateAlertWindow:(NSTimer *)timer
948 {
949     NSAlert *alert = [timer userInfo];
950
951     --currentResumeTimeout;
952     if (currentResumeTimeout <= 0) {
953         [[alert window] close];
954         [NSApp abortModal];
955     }
956
957     NSString *buttonLabel = _NS("Restart playback");
958     buttonLabel = [buttonLabel stringByAppendingFormat:@" (%d)", currentResumeTimeout];
959
960     [[[alert buttons] objectAtIndex:2] setTitle:buttonLabel];
961 }
962
963 - (void)continuePlaybackWhereYouLeftOff:(input_thread_t *)p_input_thread
964 {
965     NSDictionary *recentlyPlayedFiles = [[NSUserDefaults standardUserDefaults] objectForKey:@"recentlyPlayedMedia"];
966     if (!recentlyPlayedFiles)
967         return;
968
969     input_item_t *p_item = input_GetItem(p_input_thread);
970     if (!p_item)
971         return;
972
973     /* allow the user to over-write the start/stop/run-time */
974     if (var_GetFloat(p_input_thread, "run-time") > 0 ||
975         var_GetFloat(p_input_thread, "start-time") > 0 ||
976         var_GetFloat(p_input_thread, "stop-time") > 0) {
977         return;
978     }
979
980     /* check for file existance before resuming */
981     if (![self isValidResumeItem:p_item])
982         return;
983
984     char *psz_url = decode_URI(input_item_GetURI(p_item));
985     if (!psz_url)
986         return;
987     NSString *url = toNSStr(psz_url);
988     free(psz_url);
989
990     NSNumber *lastPosition = [recentlyPlayedFiles objectForKey:url];
991     if (!lastPosition || lastPosition.intValue <= 0)
992         return;
993
994     int settingValue = config_GetInt(VLCIntf, "macosx-continue-playback");
995     if (settingValue == 2) // never resume
996         return;
997
998     NSInteger returnValue = NSAlertErrorReturn;
999     if (settingValue == 0) { // ask
1000
1001         char *psz_title_name = input_item_GetTitleFbName(p_item);
1002         NSString *o_title = toNSStr(psz_title_name);
1003         free(psz_title_name);
1004
1005         currentResumeTimeout = 6;
1006         NSString *o_restartButtonLabel = _NS("Restart playback");
1007         o_restartButtonLabel = [o_restartButtonLabel stringByAppendingFormat:@" (%d)", currentResumeTimeout];
1008         NSAlert *theAlert = [NSAlert alertWithMessageText:_NS("Continue playback?") defaultButton:_NS("Continue") alternateButton:o_restartButtonLabel otherButton:_NS("Always continue") informativeTextWithFormat:_NS("Playback of \"%@\" will continue at %@"), o_title, [[VLCStringUtility sharedInstance] stringForTime:lastPosition.intValue]];
1009
1010         NSTimer *timer = [NSTimer timerWithTimeInterval:1
1011                                                  target:self
1012                                                selector:@selector(updateAlertWindow:)
1013                                                userInfo:theAlert
1014                                                 repeats:YES];
1015
1016         [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSModalPanelRunLoopMode];
1017
1018         returnValue = [theAlert runModal];
1019         [timer invalidate];
1020
1021         // restart button was pressed or timeout happened
1022         if (returnValue == NSAlertAlternateReturn ||
1023             returnValue == NSRunAbortedResponse)
1024             return;
1025     }
1026
1027     mtime_t lastPos = (mtime_t)lastPosition.intValue * 1000000;
1028     msg_Dbg(VLCIntf, "continuing playback at %lld", lastPos);
1029     var_SetTime(p_input_thread, "time", lastPos);
1030
1031     if (returnValue == NSAlertOtherReturn)
1032         config_PutInt(VLCIntf, "macosx-continue-playback", 1);
1033 }
1034
1035 - (void)storePlaybackPositionForItem:(input_thread_t *)p_input_thread
1036 {
1037     if (!var_InheritBool(VLCIntf, "macosx-recentitems"))
1038         return;
1039
1040     input_item_t *p_item = input_GetItem(p_input_thread);
1041     if (!p_item)
1042         return;
1043
1044     if (![self isValidResumeItem:p_item])
1045         return;
1046
1047     char *psz_url = decode_URI(input_item_GetURI(p_item));
1048     if (!psz_url)
1049         return;
1050     NSString *url = toNSStr(psz_url);
1051     free(psz_url);
1052
1053     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
1054     NSMutableDictionary *mutDict = [[NSMutableDictionary alloc] initWithDictionary:[defaults objectForKey:@"recentlyPlayedMedia"]];
1055
1056     float relativePos = var_GetFloat(p_input_thread, "position");
1057     mtime_t pos = var_GetTime(p_input_thread, "time") / 1000000;
1058     mtime_t dur = input_item_GetDuration(p_item) / 1000000;
1059
1060     NSMutableArray *mediaList = [[defaults objectForKey:@"recentlyPlayedMediaList"] mutableCopy];
1061
1062     if (relativePos > .05 && relativePos < .95 && dur > 180) {
1063         [mutDict setObject:[NSNumber numberWithInt:pos] forKey:url];
1064
1065         [mediaList removeObject:url];
1066         [mediaList addObject:url];
1067         NSUInteger mediaListCount = mediaList.count;
1068         if (mediaListCount > 30) {
1069             for (NSUInteger x = 0; x < mediaListCount - 30; x++) {
1070                 [mutDict removeObjectForKey:[mediaList objectAtIndex:0]];
1071                 [mediaList removeObjectAtIndex:0];
1072             }
1073         }
1074     } else {
1075         [mutDict removeObjectForKey:url];
1076         [mediaList removeObject:url];
1077     }
1078     [defaults setObject:mutDict forKey:@"recentlyPlayedMedia"];
1079     [defaults setObject:mediaList forKey:@"recentlyPlayedMediaList"];
1080     [defaults synchronize];
1081
1082     [mutDict release];
1083     [mediaList release];
1084 }
1085
1086 @end