]> git.sesse.net Git - vlc/blob - modules/gui/macosx/MainWindow.m
macosx: simplify ea98fcfc
[vlc] / modules / gui / macosx / MainWindow.m
1 /*****************************************************************************
2  * MainWindow.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2012 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Felix Paul Kühne <fkuehne -at- videolan -dot- org>
8  *          Jon Lech Johansen <jon-vl@nanocrew.net>
9  *          Christophe Massiot <massiot@via.ecp.fr>
10  *          Derk-Jan Hartman <hartman at videolan.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 #import "CompatibilityFixes.h"
28 #import "MainWindow.h"
29 #import "intf.h"
30 #import "CoreInteraction.h"
31 #import "AudioEffects.h"
32 #import "MainMenu.h"
33 #import "open.h"
34 #import "controls.h" // TODO: remove me
35 #import "playlist.h"
36 #import "SideBarItem.h"
37 #import <math.h>
38 #import <vlc_playlist.h>
39 #import <vlc_url.h>
40 #import <vlc_strings.h>
41 #import <vlc_services_discovery.h>
42
43 #import "ControlsBar.h"
44 #import "VideoView.h"
45 #import "VLCVoutWindowController.h"
46
47
48 @interface VLCMainWindow (Internal)
49 - (void)resizePlaylistAfterCollapse;
50 - (void)makeSplitViewVisible;
51 - (void)makeSplitViewHidden;
52 - (void)showPodcastControls;
53 - (void)hidePodcastControls;
54 @end
55
56
57 @implementation VLCMainWindow
58
59 @synthesize fullscreen=b_fullscreen;
60 @synthesize nativeFullscreenMode=b_nativeFullscreenMode;
61 @synthesize nonembedded=b_nonembedded;
62 @synthesize fsPanel=o_fspanel;
63
64 static VLCMainWindow *_o_sharedInstance = nil;
65
66 + (VLCMainWindow *)sharedInstance
67 {
68     return _o_sharedInstance ? _o_sharedInstance : [[self alloc] init];
69 }
70
71 #pragma mark -
72 #pragma mark Initialization
73
74 - (id)init
75 {
76     if (_o_sharedInstance) {
77         [self dealloc];
78         return _o_sharedInstance;
79     } else
80         _o_sharedInstance = [super init];
81
82     return _o_sharedInstance;
83 }
84
85 - (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)styleMask
86                   backing:(NSBackingStoreType)backingType defer:(BOOL)flag
87 {
88     self = [super initWithContentRect:contentRect styleMask:styleMask
89                               backing:backingType defer:flag];
90     _o_sharedInstance = self;
91
92     [[VLCMain sharedInstance] updateTogglePlaylistState];
93
94     return self;
95 }
96
97 - (BOOL)isEvent:(NSEvent *)o_event forKey:(const char *)keyString
98 {
99     char *key;
100     NSString *o_key;
101
102     key = config_GetPsz(VLCIntf, keyString);
103     o_key = [NSString stringWithFormat:@"%s", key];
104     FREENULL(key);
105
106     unsigned int i_keyModifiers = [[VLCStringUtility sharedInstance] VLCModifiersToCocoa:o_key];
107
108     NSString * characters = [o_event charactersIgnoringModifiers];
109     if ([characters length] > 0) {
110         return [[characters lowercaseString] isEqualToString: [[VLCStringUtility sharedInstance] VLCKeyToString: o_key]] &&
111                 (i_keyModifiers & NSShiftKeyMask)     == ([o_event modifierFlags] & NSShiftKeyMask) &&
112                 (i_keyModifiers & NSControlKeyMask)   == ([o_event modifierFlags] & NSControlKeyMask) &&
113                 (i_keyModifiers & NSAlternateKeyMask) == ([o_event modifierFlags] & NSAlternateKeyMask) &&
114                 (i_keyModifiers & NSCommandKeyMask)   == ([o_event modifierFlags] & NSCommandKeyMask);
115     }
116     return NO;
117 }
118
119 - (BOOL)performKeyEquivalent:(NSEvent *)o_event
120 {
121     BOOL b_force = NO;
122     // these are key events which should be handled by vlc core, but are attached to a main menu item
123     if (![self isEvent: o_event forKey: "key-vol-up"] &&
124         ![self isEvent: o_event forKey: "key-vol-down"] &&
125         ![self isEvent: o_event forKey: "key-vol-mute"]) {
126         /* We indeed want to prioritize some Cocoa key equivalent against libvlc,
127          so we perform the menu equivalent now. */
128         if ([[NSApp mainMenu] performKeyEquivalent:o_event])
129             return TRUE;
130     }
131     else
132         b_force = YES;
133
134     return [[VLCMain sharedInstance] hasDefinedShortcutKey:o_event force:b_force] ||
135            [(VLCControls *)[[VLCMain sharedInstance] controls] keyEvent:o_event];
136 }
137
138 - (void)dealloc
139 {
140     if (b_dark_interface)
141         [o_color_backdrop release];
142
143     [[NSNotificationCenter defaultCenter] removeObserver: self];
144     [o_sidebaritems release];
145
146     [super dealloc];
147 }
148
149 - (void)awakeFromNib
150 {
151     BOOL b_splitviewShouldBeHidden = NO;
152
153     /* setup the styled interface */
154     b_nativeFullscreenMode = NO;
155 #ifdef MAC_OS_X_VERSION_10_7
156     if (!OSX_SNOW_LEOPARD)
157         b_nativeFullscreenMode = var_InheritBool(VLCIntf, "macosx-nativefullscreenmode");
158 #endif
159     t_hide_mouse_timer = nil;
160     [self useOptimizedDrawing: YES];
161
162     [[o_search_fld cell] setPlaceholderString: _NS("Search")];
163     [[o_search_fld cell] accessibilitySetOverrideValue:_NS("Enter a term to search the playlist. Results will be selected in the table.") forAttribute:NSAccessibilityDescriptionAttribute];
164
165     [o_dropzone_btn setTitle: _NS("Open media...")];
166     [[o_dropzone_btn cell] accessibilitySetOverrideValue:_NS("Click to open an advanced dialog to select the media to play. You can also drop files here to play.") forAttribute:NSAccessibilityDescriptionAttribute];
167     [o_dropzone_lbl setStringValue: _NS("Drop media here")];
168
169     [o_podcast_add_btn setTitle: _NS("Subscribe")];
170     [o_podcast_remove_btn setTitle: _NS("Unsubscribe")];
171     [o_podcast_subscribe_title_lbl setStringValue: _NS("Subscribe to a podcast")];
172     [o_podcast_subscribe_subtitle_lbl setStringValue: _NS("Enter URL of the podcast to subscribe to:")];
173     [o_podcast_subscribe_cancel_btn setTitle: _NS("Cancel")];
174     [o_podcast_subscribe_ok_btn setTitle: _NS("Subscribe")];
175     [o_podcast_unsubscribe_title_lbl setStringValue: _NS("Unsubscribe from a podcast")];
176     [o_podcast_unsubscribe_subtitle_lbl setStringValue: _NS("Select the podcast you would like to unsubscribe from:")];
177     [o_podcast_unsubscribe_ok_btn setTitle: _NS("Unsubscribe")];
178     [o_podcast_unsubscribe_cancel_btn setTitle: _NS("Cancel")];
179
180     /* interface builder action */
181     float f_threshold_height = f_min_video_height + [[o_controls_bar bottomBarView] frame].size.height;
182     if (b_dark_interface)
183         f_threshold_height += [o_titlebar_view frame].size.height;
184     if ([[self contentView] frame].size.height < f_threshold_height)
185         b_splitviewShouldBeHidden = YES;
186
187     [self setDelegate: self];
188     [self setExcludedFromWindowsMenu: YES];
189     [self setAcceptsMouseMovedEvents: YES];
190     // Set that here as IB seems to be buggy
191     if (b_dark_interface) {
192         [self setContentMinSize:NSMakeSize(604., 288. + [o_titlebar_view frame].size.height)];
193     } else {
194         [self setContentMinSize:NSMakeSize(604., 288.)];
195     }
196
197     [self setTitle: _NS("VLC media player")];
198
199     b_dropzone_active = YES;
200     [o_dropzone_view setFrame: [o_playlist_table frame]];
201     [o_left_split_view setFrame: [o_sidebar_view frame]];
202
203     if (b_nativeFullscreenMode) {
204         [self setCollectionBehavior: NSWindowCollectionBehaviorFullScreenPrimary];
205     } else {
206         [o_titlebar_view setFullscreenButtonHidden: YES];
207     }
208
209     if (!OSX_SNOW_LEOPARD) {
210         /* the default small size of the search field is slightly different on Lion, let's work-around that */
211         NSRect frame;
212         frame = [o_search_fld frame];
213         frame.origin.y = frame.origin.y + 2.0;
214         frame.size.height = frame.size.height - 1.0;
215         [o_search_fld setFrame: frame];
216     }
217
218     /* create the sidebar */
219     o_sidebaritems = [[NSMutableArray alloc] init];
220     SideBarItem *libraryItem = [SideBarItem itemWithTitle:_NS("LIBRARY") identifier:@"library"];
221     SideBarItem *playlistItem = [SideBarItem itemWithTitle:_NS("Playlist") identifier:@"playlist"];
222     [playlistItem setIcon: [NSImage imageNamed:@"sidebar-playlist"]];
223     SideBarItem *medialibraryItem = [SideBarItem itemWithTitle:_NS("Media Library") identifier:@"medialibrary"];
224     [medialibraryItem setIcon: [NSImage imageNamed:@"sidebar-playlist"]];
225     SideBarItem *mycompItem = [SideBarItem itemWithTitle:_NS("MY COMPUTER") identifier:@"mycomputer"];
226     SideBarItem *devicesItem = [SideBarItem itemWithTitle:_NS("DEVICES") identifier:@"devices"];
227     SideBarItem *lanItem = [SideBarItem itemWithTitle:_NS("LOCAL NETWORK") identifier:@"localnetwork"];
228     SideBarItem *internetItem = [SideBarItem itemWithTitle:_NS("INTERNET") identifier:@"internet"];
229
230     /* SD subnodes, inspired by the Qt4 intf */
231     char **ppsz_longnames;
232     int *p_categories;
233     char **ppsz_names = vlc_sd_GetNames(pl_Get(VLCIntf), &ppsz_longnames, &p_categories);
234     if (!ppsz_names)
235         msg_Err(VLCIntf, "no sd item found"); //TODO
236     char **ppsz_name = ppsz_names, **ppsz_longname = ppsz_longnames;
237     int *p_category = p_categories;
238     NSMutableArray *internetItems = [[NSMutableArray alloc] init];
239     NSMutableArray *devicesItems = [[NSMutableArray alloc] init];
240     NSMutableArray *lanItems = [[NSMutableArray alloc] init];
241     NSMutableArray *mycompItems = [[NSMutableArray alloc] init];
242     NSString *o_identifier;
243     for (; *ppsz_name; ppsz_name++, ppsz_longname++, p_category++) {
244         o_identifier = [NSString stringWithCString: *ppsz_name encoding: NSUTF8StringEncoding];
245         switch (*p_category) {
246             case SD_CAT_INTERNET:
247                     [internetItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
248                     if (!strncmp(*ppsz_name, "podcast", 7))
249                         [[internetItems lastObject] setIcon: [NSImage imageNamed:@"sidebar-podcast"]];
250                     else
251                         [[internetItems lastObject] setIcon: [NSImage imageNamed:@"NSApplicationIcon"]];
252                     [[internetItems lastObject] setSdtype: SD_CAT_INTERNET];
253                     [[internetItems lastObject] setUntranslatedTitle: [NSString stringWithUTF8String: *ppsz_longname]];
254                 break;
255             case SD_CAT_DEVICES:
256                     [devicesItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
257                     [[devicesItems lastObject] setIcon: [NSImage imageNamed:@"NSApplicationIcon"]];
258                     [[devicesItems lastObject] setSdtype: SD_CAT_DEVICES];
259                     [[devicesItems lastObject] setUntranslatedTitle: [NSString stringWithUTF8String: *ppsz_longname]];
260                 break;
261             case SD_CAT_LAN:
262                     [lanItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
263                     [[lanItems lastObject] setIcon: [NSImage imageNamed:@"sidebar-local"]];
264                     [[lanItems lastObject] setSdtype: SD_CAT_LAN];
265                     [[lanItems lastObject] setUntranslatedTitle: [NSString stringWithUTF8String: *ppsz_longname]];
266                 break;
267             case SD_CAT_MYCOMPUTER:
268                     [mycompItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
269                     if (!strncmp(*ppsz_name, "video_dir", 9))
270                         [[mycompItems lastObject] setIcon: [NSImage imageNamed:@"sidebar-movie"]];
271                     else if (!strncmp(*ppsz_name, "audio_dir", 9))
272                         [[mycompItems lastObject] setIcon: [NSImage imageNamed:@"sidebar-music"]];
273                     else if (!strncmp(*ppsz_name, "picture_dir", 11))
274                         [[mycompItems lastObject] setIcon: [NSImage imageNamed:@"sidebar-pictures"]];
275                     else
276                         [[mycompItems lastObject] setIcon: [NSImage imageNamed:@"NSApplicationIcon"]];
277                     [[mycompItems lastObject] setUntranslatedTitle: [NSString stringWithUTF8String: *ppsz_longname]];
278                     [[mycompItems lastObject] setSdtype: SD_CAT_MYCOMPUTER];
279                 break;
280             default:
281                 msg_Warn(VLCIntf, "unknown SD type found, skipping (%s)", *ppsz_name);
282                 break;
283         }
284
285         free(*ppsz_name);
286         free(*ppsz_longname);
287     }
288     [mycompItem setChildren: [NSArray arrayWithArray: mycompItems]];
289     [devicesItem setChildren: [NSArray arrayWithArray: devicesItems]];
290     [lanItem setChildren: [NSArray arrayWithArray: lanItems]];
291     [internetItem setChildren: [NSArray arrayWithArray: internetItems]];
292     [mycompItems release];
293     [devicesItems release];
294     [lanItems release];
295     [internetItems release];
296     free(ppsz_names);
297     free(ppsz_longnames);
298     free(p_categories);
299
300     [libraryItem setChildren: [NSArray arrayWithObjects: playlistItem, medialibraryItem, nil]];
301     [o_sidebaritems addObject: libraryItem];
302     if ([mycompItem hasChildren])
303         [o_sidebaritems addObject: mycompItem];
304     if ([devicesItem hasChildren])
305         [o_sidebaritems addObject: devicesItem];
306     if ([lanItem hasChildren])
307         [o_sidebaritems addObject: lanItem];
308     if ([internetItem hasChildren])
309         [o_sidebaritems addObject: internetItem];
310
311     [o_sidebar_view reloadData];
312     [o_sidebar_view selectRowIndexes:[NSIndexSet indexSetWithIndex:1] byExtendingSelection:NO];
313     [o_sidebar_view setDropItem:playlistItem dropChildIndex:NSOutlineViewDropOnItemIndex];
314     [o_sidebar_view registerForDraggedTypes:[NSArray arrayWithObjects: NSFilenamesPboardType, @"VLCPlaylistItemPboardType", nil]];
315
316     [o_sidebar_view setAutosaveName:@"mainwindow-sidebar"];
317     [(PXSourceList *)o_sidebar_view setDataSource:self];
318     [o_sidebar_view setDelegate:self];
319     [o_sidebar_view setAutosaveExpandedItems:YES];
320
321     [o_sidebar_view expandItem: libraryItem expandChildren: YES];
322
323     /* make sure we display the desired default appearance when VLC launches for the first time */
324     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
325     if (![defaults objectForKey:@"VLCFirstRun"]) {
326         [defaults setObject:[NSDate date] forKey:@"VLCFirstRun"];
327
328         NSUInteger i_sidebaritem_count = [o_sidebaritems count];
329         for (NSUInteger x = 0; x < i_sidebaritem_count; x++)
330             [o_sidebar_view expandItem: [o_sidebaritems objectAtIndex: x] expandChildren: YES];
331     }
332
333     if (b_dark_interface) {
334         [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(windowResizedOrMoved:) name: NSWindowDidResizeNotification object: nil];
335         [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(windowResizedOrMoved:) name: NSWindowDidMoveNotification object: nil];
336
337         [self setBackgroundColor: [NSColor clearColor]];
338         [self setOpaque: NO];
339         [self display];
340         [self setHasShadow:NO];
341         [self setHasShadow:YES];
342
343         NSRect winrect = [self frame];
344         CGFloat f_titleBarHeight = [o_titlebar_view frame].size.height;
345
346         [o_titlebar_view setFrame: NSMakeRect(0, winrect.size.height - f_titleBarHeight,
347                                               winrect.size.width, f_titleBarHeight)];
348         [[self contentView] addSubview: o_titlebar_view positioned: NSWindowAbove relativeTo: o_split_view];
349
350         if (winrect.size.height > 100) {
351             [self setFrame: winrect display:YES animate:YES];
352             previousSavedFrame = winrect;
353         }
354
355         winrect = [o_split_view frame];
356         winrect.size.height = winrect.size.height - f_titleBarHeight;
357         [o_split_view setFrame: winrect];
358         [o_video_view setFrame: winrect];
359
360         o_color_backdrop = [[VLCColorView alloc] initWithFrame: [o_split_view frame]];
361         [[self contentView] addSubview: o_color_backdrop positioned: NSWindowBelow relativeTo: o_split_view];
362         [o_color_backdrop setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable];
363
364     } else {
365         [o_video_view setFrame: [o_split_view frame]];
366         [o_playlist_table setBorderType: NSNoBorder];
367         [o_sidebar_scrollview setBorderType: NSNoBorder];
368     }
369
370     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(someWindowWillClose:) name: NSWindowWillCloseNotification object: nil];
371     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(someWindowWillMiniaturize:) name: NSWindowWillMiniaturizeNotification object:nil];
372     [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(applicationWillTerminate:) name: NSApplicationWillTerminateNotification object: nil];
373
374     [o_split_view setAutosaveName:@"10thanniversary-splitview"];
375     if (b_splitviewShouldBeHidden) {
376         [self hideSplitView];
377         i_lastSplitViewHeight = 300;
378     }
379
380     /* sanity check for the window size */
381     NSRect frame = [self frame];
382     NSSize screenSize = [[self screen] frame].size;
383     if (screenSize.width <= frame.size.width || screenSize.height <= frame.size.height) {
384         nativeVideoSize = screenSize;
385         [self resizeWindow];
386     }
387
388     // update fs button to reflect state for next startup
389     if (var_InheritBool(pl_Get(VLCIntf), "fullscreen")) {
390         [o_controls_bar setFullscreenState:YES];
391     }
392 }
393
394 #pragma mark -
395
396 - (VLCMainWindowControlsBar *)controlsBar;
397 {
398     return (VLCMainWindowControlsBar *)o_controls_bar;
399 }
400
401 - (void)resizePlaylistAfterCollapse
402 {
403     NSRect plrect;
404     plrect = [o_playlist_table frame];
405     plrect.size.height = i_lastSplitViewHeight - 20.0; // actual pl top bar height, which differs from its frame
406     [[o_playlist_table animator] setFrame: plrect];
407
408     NSRect rightSplitRect;
409     rightSplitRect = [o_right_split_view frame];
410     plrect = [o_dropzone_box frame];
411     plrect.origin.x = (rightSplitRect.size.width - plrect.size.width) / 2;
412     plrect.origin.y = (rightSplitRect.size.height - plrect.size.height) / 2;
413     [[o_dropzone_box animator] setFrame: plrect];
414 }
415
416 - (void)makeSplitViewVisible
417 {
418     if (b_dark_interface)
419         [self setContentMinSize: NSMakeSize(604., 288. + [o_titlebar_view frame].size.height)];
420     else
421         [self setContentMinSize: NSMakeSize(604., 288.)];
422
423     NSRect old_frame = [self frame];
424     float newHeight = [self minSize].height;
425     if (old_frame.size.height < newHeight) {
426         NSRect new_frame = old_frame;
427         new_frame.origin.y = old_frame.origin.y + old_frame.size.height - newHeight;
428         new_frame.size.height = newHeight;
429
430         [[self animator] setFrame: new_frame display: YES animate: YES];
431     }
432
433     [o_video_view setHidden: YES];
434     [o_split_view setHidden: NO];
435     [self makeFirstResponder: nil];
436
437 }
438
439 - (void)makeSplitViewHidden
440 {
441     if (b_dark_interface)
442         [self setContentMinSize: NSMakeSize(604., f_min_video_height + [o_titlebar_view frame].size.height)];
443     else
444         [self setContentMinSize: NSMakeSize(604., f_min_video_height)];
445
446     [o_split_view setHidden: YES];
447     [o_video_view setHidden: NO];
448
449     if ([[o_video_view subviews] count] > 0)
450         [self makeFirstResponder: [[o_video_view subviews] objectAtIndex:0]];
451 }
452
453 // only exception for an controls bar button action
454 - (IBAction)togglePlaylist:(id)sender
455 {
456     if (![self isVisible] && sender != nil) {
457         [self makeKeyAndOrderFront: sender];
458         return;
459     }
460
461     BOOL b_activeVideo = [[VLCMain sharedInstance] activeVideoPlayback];
462     BOOL b_restored = NO;
463
464     // TODO: implement toggle playlist in this situation (triggerd via menu item).
465     // but for now we block this case, to avoid displaying only the half
466     if (b_nativeFullscreenMode && b_fullscreen && b_activeVideo && sender != nil)
467         return;
468
469     if (b_dropzone_active && ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) != 0) {
470         [self hideDropZone];
471         return;
472     }
473
474     if (!(b_nativeFullscreenMode && b_fullscreen) && !b_splitview_removed && ((([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) != 0 && b_activeVideo)
475                                                                               || (b_nonembedded && sender != nil)
476                                                                               || (!b_activeVideo && sender != nil)
477                                                                               || b_minimized_view))
478         [self hideSplitView];
479     else {
480         if (b_splitview_removed) {
481             if (!b_nonembedded || (sender != nil && b_nonembedded))
482                 [self showSplitView];
483
484             if (sender == nil)
485                 b_minimized_view = YES;
486             else
487                 b_minimized_view = NO;
488
489             if (b_activeVideo)
490                 b_restored = YES;
491         }
492
493         if (!b_nonembedded) {
494             if (([o_video_view isHidden] && b_activeVideo) || b_restored || (b_activeVideo && sender == nil))
495                 [self makeSplitViewHidden];
496             else
497                 [self makeSplitViewVisible];
498         } else {
499             [o_split_view setHidden: NO];
500             [o_playlist_table setHidden: NO];
501             [o_video_view setHidden: YES];
502         }
503     }
504 }
505
506 - (IBAction)dropzoneButtonAction:(id)sender
507 {
508     [[[VLCMain sharedInstance] open] openFileGeneric];
509 }
510
511 #pragma mark -
512 #pragma mark overwritten default functionality
513
514 - (void)windowResizedOrMoved:(NSNotification *)notification
515 {
516     [self saveFrameUsingName: [self frameAutosaveName]];
517 }
518
519 - (void)applicationWillTerminate:(NSNotification *)notification
520 {
521     [self saveFrameUsingName: [self frameAutosaveName]];
522 }
523
524
525 - (void)someWindowWillClose:(NSNotification *)notification
526 {
527     id obj = [notification object];
528
529     if ([obj class] == [VLCVideoWindowCommon class] || [obj class] == [VLCDetachedVideoWindow class] || ([obj class] == [VLCMainWindow class] && !b_nonembedded)) {
530         if ([[VLCMain sharedInstance] activeVideoPlayback])
531             [[VLCCoreInteraction sharedInstance] stop];
532     }
533 }
534
535 - (void)someWindowWillMiniaturize:(NSNotification *)notification
536 {
537     if (config_GetInt(VLCIntf, "macosx-pause-minimized")) {
538         id obj = [notification object];
539
540         if ([obj class] == [VLCVideoWindowCommon class] || [obj class] == [VLCDetachedVideoWindow class] || ([obj class] == [VLCMainWindow class] && !b_nonembedded)) {
541             if ([[VLCMain sharedInstance] activeVideoPlayback])
542                 [[VLCCoreInteraction sharedInstance] pause];
543         }
544     }
545 }
546
547 #pragma mark -
548 #pragma mark Update interface and respond to foreign events
549 - (void)showDropZone
550 {
551     b_dropzone_active = YES;
552     [o_right_split_view addSubview: o_dropzone_view positioned:NSWindowAbove relativeTo:o_playlist_table];
553     [o_dropzone_view setFrame: [o_playlist_table frame]];
554     [[o_playlist_table animator] setHidden:YES];
555 }
556
557 - (void)hideDropZone
558 {
559     b_dropzone_active = NO;
560     [o_dropzone_view removeFromSuperview];
561     [[o_playlist_table animator] setHidden: NO];
562 }
563
564 - (void)hideSplitView
565 {
566     NSRect winrect = [self frame];
567     i_lastSplitViewHeight = [o_split_view frame].size.height;
568     winrect.size.height = winrect.size.height - i_lastSplitViewHeight;
569     winrect.origin.y = winrect.origin.y + i_lastSplitViewHeight;
570     [self setFrame: winrect display: YES animate: YES];
571     [self performSelector:@selector(hideDropZone) withObject:nil afterDelay:0.1];
572     if (b_dark_interface) {
573         [self setContentMinSize: NSMakeSize(604., [[o_controls_bar bottomBarView] frame].size.height + [o_titlebar_view frame].size.height)];
574         [self setContentMaxSize: NSMakeSize(FLT_MAX, [[o_controls_bar bottomBarView] frame].size.height + [o_titlebar_view frame].size.height)];
575     } else {
576         [self setContentMinSize: NSMakeSize(604., [[o_controls_bar bottomBarView] frame].size.height)];
577         [self setContentMaxSize: NSMakeSize(FLT_MAX, [[o_controls_bar bottomBarView] frame].size.height)];
578     }
579
580     b_splitview_removed = YES;
581 }
582
583 - (void)showSplitView
584 {
585     [self updateWindow];
586     if (b_dark_interface)
587         [self setContentMinSize:NSMakeSize(604., 288. + [o_titlebar_view frame].size.height)];
588     else
589         [self setContentMinSize:NSMakeSize(604., 288.)];
590     [self setContentMaxSize: NSMakeSize(FLT_MAX, FLT_MAX)];
591
592     NSRect winrect;
593     winrect = [self frame];
594     winrect.size.height = winrect.size.height + i_lastSplitViewHeight;
595     winrect.origin.y = winrect.origin.y - i_lastSplitViewHeight;
596     [self setFrame: winrect display: YES animate: YES];
597
598     [self performSelector:@selector(resizePlaylistAfterCollapse) withObject: nil afterDelay:0.75];
599
600     b_splitview_removed = NO;
601 }
602
603 - (void)updateTimeSlider
604 {
605     [o_controls_bar updateTimeSlider];
606     [[self controlsBar] updatePosAndTimeInFSPanel:o_fspanel];
607
608     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(updateTimeSlider)];
609 }
610
611 - (void)updateName
612 {
613     input_thread_t * p_input;
614     p_input = pl_CurrentInput(VLCIntf);
615     if (p_input) {
616         NSString *aString;
617         char *format = var_InheritString(VLCIntf, "input-title-format");
618         char *formated = str_format_meta(pl_Get(VLCIntf), format);
619         free(format);
620         aString = [NSString stringWithUTF8String:formated];
621         free(formated);
622
623         char *uri = input_item_GetURI(input_GetItem(p_input));
624
625         NSURL * o_url = [NSURL URLWithString: [NSString stringWithUTF8String: uri]];
626         if ([o_url isFileURL]) {
627             [self setRepresentedURL: o_url];
628             [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
629                 [o_window setRepresentedURL:o_url];
630             }];
631         } else {
632             [self setRepresentedURL: nil];
633             [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
634                 [o_window setRepresentedURL:nil];
635             }];
636         }
637         free(uri);
638
639         if ([aString isEqualToString:@""]) {
640             if ([o_url isFileURL])
641                 aString = [[NSFileManager defaultManager] displayNameAtPath: [o_url path]];
642             else
643                 aString = [o_url absoluteString];
644         }
645
646         if ([aString length] > 0) {
647             [self setTitle: aString];
648             [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
649                 [o_window setTitle:aString];
650             }];
651
652             [o_fspanel setStreamTitle: aString];
653         } else {
654            [self setTitle: _NS("VLC media player")];
655             [self setRepresentedURL: nil];
656         }
657
658         vlc_object_release(p_input);
659     } else {
660         [self setTitle: _NS("VLC media player")];
661         [self setRepresentedURL: nil];
662     }
663 }
664
665 - (void)updateWindow
666 {
667     [o_controls_bar updateControls];
668     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(updateControls)];
669
670     bool b_seekable = false;
671
672     playlist_t * p_playlist = pl_Get(VLCIntf);
673     input_thread_t * p_input = playlist_CurrentInput(p_playlist);
674     if (p_input) {
675         /* seekable streams */
676         b_seekable = var_GetBool(p_input, "can-seek");
677
678         vlc_object_release(p_input);
679     }
680
681     [self updateTimeSlider];
682     if ([o_fspanel respondsToSelector:@selector(setSeekable:)])
683         [o_fspanel setSeekable: b_seekable];
684
685     PL_LOCK;
686     if ([[[VLCMain sharedInstance] playlist] currentPlaylistRoot] != p_playlist->p_local_category || p_playlist->p_local_category->i_children > 0)
687         [self hideDropZone];
688     else
689         [self showDropZone];
690     PL_UNLOCK;
691     [o_sidebar_view setNeedsDisplay:YES];
692 }
693
694 - (void)setPause
695 {
696     [o_controls_bar setPause];
697     [o_fspanel setPause];
698
699     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(setPause)];
700 }
701
702 - (void)setPlay
703 {
704     [o_controls_bar setPlay];
705     [o_fspanel setPlay];
706
707     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(setPlay)];
708
709 }
710
711 - (void)updateVolumeSlider
712 {
713     [[self controlsBar] updateVolumeSlider];
714     [o_fspanel setVolumeLevel: [[VLCCoreInteraction sharedInstance] volume]];
715 }
716
717 #pragma mark -
718 #pragma mark Video Output handling
719
720 - (void)setVideoplayEnabled
721 {
722     BOOL b_videoPlayback = [[VLCMain sharedInstance] activeVideoPlayback];
723
724     if (b_videoPlayback) {
725         if (!b_fullscreen)
726             frameBeforePlayback = [self frame];
727     } else {
728         if (!b_nonembedded && !b_fullscreen && frameBeforePlayback.size.width > 0 && frameBeforePlayback.size.height > 0)
729             [[self animator] setFrame:frameBeforePlayback display:YES];
730
731         // update fs button to reflect state for next startup
732         if (var_InheritBool(pl_Get(VLCIntf), "fullscreen")) {
733             [o_controls_bar setFullscreenState:YES];
734         }
735
736         [self makeFirstResponder: nil];
737
738         if ([self level] != NSNormalWindowLevel)
739             [self setLevel: NSNormalWindowLevel];
740
741         // restore alpha value to 1 for the case that macosx-opaqueness is set to < 1
742         [self setAlphaValue:1.0];
743     }
744
745     if (b_nativeFullscreenMode) {
746         if ([NSApp presentationOptions] & NSApplicationPresentationFullScreen)
747             [[o_controls_bar bottomBarView] setHidden: b_videoPlayback];
748         else
749             [[o_controls_bar bottomBarView] setHidden: NO];
750         if (b_videoPlayback && b_fullscreen)
751             [o_fspanel setActive: nil];
752         if (!b_videoPlayback)
753             [o_fspanel setNonActive: nil];
754     }
755 }
756
757 //  Called automatically if window's acceptsMouseMovedEvents property is true
758 - (void)mouseMoved:(NSEvent *)theEvent
759 {
760     if (b_fullscreen)
761         [self recreateHideMouseTimer];
762
763     [super mouseMoved: theEvent];
764 }
765
766 - (void)recreateHideMouseTimer
767 {
768     if (t_hide_mouse_timer != nil) {
769         [t_hide_mouse_timer invalidate];
770         [t_hide_mouse_timer release];
771     }
772
773     t_hide_mouse_timer = [NSTimer scheduledTimerWithTimeInterval:2
774                                                           target:self
775                                                         selector:@selector(hideMouseCursor:)
776                                                         userInfo:nil
777                                                          repeats:NO];
778     [t_hide_mouse_timer retain];
779 }
780
781 //  NSTimer selectors require this function signature as per Apple's docs
782 - (void)hideMouseCursor:(NSTimer *)timer
783 {
784     [NSCursor setHiddenUntilMouseMoves: YES];
785 }
786
787
788 #pragma mark -
789 #pragma mark Fullscreen support
790
791 - (void)showFullscreenController
792 {
793      if (b_fullscreen && [[VLCMain sharedInstance] activeVideoPlayback])
794         [o_fspanel fadeIn];
795 }
796
797 - (void)makeKeyAndOrderFront: (id)sender
798 {
799     /* Hack
800      * when we exit fullscreen and fade out, we may endup in
801      * having a window that is faded. We can't have it fade in unless we
802      * animate again. */
803
804     if (!b_window_is_invisible) {
805         /* Make sure we don't do it too much */
806         [super makeKeyAndOrderFront: sender];
807         return;
808     }
809
810     [super setAlphaValue:0.0f];
811     [super makeKeyAndOrderFront: sender];
812
813     NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:2];
814     [dict setObject:self forKey:NSViewAnimationTargetKey];
815     [dict setObject:NSViewAnimationFadeInEffect forKey:NSViewAnimationEffectKey];
816
817     o_makekey_anim = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict]];
818     [dict release];
819
820     [o_makekey_anim setAnimationBlockingMode: NSAnimationNonblocking];
821     [o_makekey_anim setDuration: 0.1];
822     [o_makekey_anim setFrameRate: 30];
823     [o_makekey_anim setDelegate: self];
824
825     [o_makekey_anim startAnimation];
826     b_window_is_invisible = NO;
827
828     /* fullscreenAnimation will be unlocked when animation ends */
829 }
830
831 #pragma mark -
832 #pragma mark Lion native fullscreen handling
833 - (void)windowWillEnterFullScreen:(NSNotification *)notification
834 {
835     // workaround, see #6668
836     [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
837
838     var_SetBool(pl_Get(VLCIntf), "fullscreen", true);
839
840     vout_thread_t *p_vout = getVout();
841     if (p_vout) {
842         var_SetBool(p_vout, "fullscreen", true);
843         vlc_object_release(p_vout);
844     }
845
846     [o_video_view setFrame: [[self contentView] frame]];
847     b_fullscreen = YES;
848
849     [self recreateHideMouseTimer];
850     i_originalLevel = [self level];
851     [self setLevel:NSNormalWindowLevel];
852
853     if (b_dark_interface) {
854         [o_titlebar_view removeFromSuperviewWithoutNeedingDisplay];
855
856         NSRect winrect;
857         CGFloat f_titleBarHeight = [o_titlebar_view frame].size.height;
858         winrect = [self frame];
859
860         winrect.size.height = winrect.size.height - f_titleBarHeight;
861         [self setFrame: winrect display:NO animate:NO];
862         winrect = [o_split_view frame];
863         winrect.size.height = winrect.size.height + f_titleBarHeight;
864         [o_split_view setFrame: winrect];
865     }
866
867     if ([[VLCMain sharedInstance] activeVideoPlayback])
868         [[o_controls_bar bottomBarView] setHidden: YES];
869
870     [self setMovableByWindowBackground: NO];
871 }
872
873 - (void)windowDidEnterFullScreen:(NSNotification *)notification
874 {
875     // Indeed, we somehow can have an "inactive" fullscreen (but a visible window!).
876     // But this creates some problems when leaving fs over remote intfs, so activate app here.
877     [NSApp activateIgnoringOtherApps:YES];
878
879     [o_fspanel setVoutWasUpdated: self];
880     [o_fspanel setActive: nil];
881
882     NSArray *subviews = [[self videoView] subviews];
883     NSUInteger count = [subviews count];
884
885     for (NSUInteger x = 0; x < count; x++) {
886         if ([[subviews objectAtIndex:x] respondsToSelector:@selector(reshape)])
887             [[subviews objectAtIndex:x] reshape];
888     }
889
890 }
891
892 - (void)windowWillExitFullScreen:(NSNotification *)notification
893 {
894
895     var_SetBool(pl_Get(VLCIntf), "fullscreen", false);
896
897     vout_thread_t *p_vout = getVout();
898     if (p_vout) {
899         var_SetBool(p_vout, "fullscreen", false);
900         vlc_object_release(p_vout);
901     }
902
903     [o_video_view setFrame: [o_split_view frame]];
904     [NSCursor setHiddenUntilMouseMoves: NO];
905     [o_fspanel setNonActive: nil];
906     [self setLevel:i_originalLevel];
907     b_fullscreen = NO;
908
909     if (b_dark_interface) {
910         NSRect winrect;
911         CGFloat f_titleBarHeight = [o_titlebar_view frame].size.height;
912         winrect = [self frame];
913
914         [o_titlebar_view setFrame: NSMakeRect(0, winrect.size.height - f_titleBarHeight,
915                                               winrect.size.width, f_titleBarHeight)];
916         [[self contentView] addSubview: o_titlebar_view];
917
918         winrect.size.height = winrect.size.height + f_titleBarHeight;
919         [self setFrame: winrect display:NO animate:NO];
920         winrect = [o_split_view frame];
921         winrect.size.height = winrect.size.height - f_titleBarHeight;
922         [o_split_view setFrame: winrect];
923         [o_video_view setFrame: winrect];
924     }
925
926     if ([[VLCMain sharedInstance] activeVideoPlayback])
927         [[o_controls_bar bottomBarView] setHidden: NO];
928
929     [self setMovableByWindowBackground: YES];
930 }
931
932 #pragma mark -
933 #pragma mark split view delegate
934 - (CGFloat)splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)dividerIndex
935 {
936     if (dividerIndex == 0)
937         return 300.;
938     else
939         return proposedMax;
940 }
941
942 - (CGFloat)splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)dividerIndex
943 {
944     if (dividerIndex == 0)
945         return 100.;
946     else
947         return proposedMin;
948 }
949
950 - (BOOL)splitView:(NSSplitView *)splitView canCollapseSubview:(NSView *)subview
951 {
952     return ([subview isEqual:o_left_split_view]);
953 }
954
955 - (BOOL)splitView:(NSSplitView *)splitView shouldAdjustSizeOfSubview:(NSView *)subview
956 {
957     if ([subview isEqual:o_left_split_view])
958         return NO;
959     return YES;
960 }
961
962 #pragma mark -
963 #pragma mark Side Bar Data handling
964 /* taken under BSD-new from the PXSourceList sample project, adapted for VLC */
965 - (NSUInteger)sourceList:(PXSourceList*)sourceList numberOfChildrenOfItem:(id)item
966 {
967     //Works the same way as the NSOutlineView data source: `nil` means a parent item
968     if (item==nil)
969         return [o_sidebaritems count];
970     else
971         return [[item children] count];
972 }
973
974
975 - (id)sourceList:(PXSourceList*)aSourceList child:(NSUInteger)index ofItem:(id)item
976 {
977     //Works the same way as the NSOutlineView data source: `nil` means a parent item
978     if (item==nil)
979         return [o_sidebaritems objectAtIndex:index];
980     else
981         return [[item children] objectAtIndex:index];
982 }
983
984
985 - (id)sourceList:(PXSourceList*)aSourceList objectValueForItem:(id)item
986 {
987     return [item title];
988 }
989
990 - (void)sourceList:(PXSourceList*)aSourceList setObjectValue:(id)object forItem:(id)item
991 {
992     [item setTitle:object];
993 }
994
995 - (BOOL)sourceList:(PXSourceList*)aSourceList isItemExpandable:(id)item
996 {
997     return [item hasChildren];
998 }
999
1000
1001 - (BOOL)sourceList:(PXSourceList*)aSourceList itemHasBadge:(id)item
1002 {
1003     if ([[item identifier] isEqualToString: @"playlist"] || [[item identifier] isEqualToString: @"medialibrary"])
1004         return YES;
1005
1006     return [item hasBadge];
1007 }
1008
1009
1010 - (NSInteger)sourceList:(PXSourceList*)aSourceList badgeValueForItem:(id)item
1011 {
1012     playlist_t * p_playlist = pl_Get(VLCIntf);
1013     NSInteger i_playlist_size;
1014
1015     if ([[item identifier] isEqualToString: @"playlist"]) {
1016         PL_LOCK;
1017         i_playlist_size = p_playlist->p_local_category->i_children;
1018         PL_UNLOCK;
1019
1020         return i_playlist_size;
1021     }
1022     if ([[item identifier] isEqualToString: @"medialibrary"]) {
1023         PL_LOCK;
1024         i_playlist_size = p_playlist->p_ml_category->i_children;
1025         PL_UNLOCK;
1026
1027         return i_playlist_size;
1028     }
1029
1030     return [item badgeValue];
1031 }
1032
1033
1034 - (BOOL)sourceList:(PXSourceList*)aSourceList itemHasIcon:(id)item
1035 {
1036     return [item hasIcon];
1037 }
1038
1039
1040 - (NSImage*)sourceList:(PXSourceList*)aSourceList iconForItem:(id)item
1041 {
1042     return [item icon];
1043 }
1044
1045 - (NSMenu*)sourceList:(PXSourceList*)aSourceList menuForEvent:(NSEvent*)theEvent item:(id)item
1046 {
1047     if ([theEvent type] == NSRightMouseDown || ([theEvent type] == NSLeftMouseDown && ([theEvent modifierFlags] & NSControlKeyMask) == NSControlKeyMask)) {
1048         if (item != nil) {
1049             NSMenu * m;
1050             if ([item sdtype] > 0)
1051             {
1052                 m = [[NSMenu alloc] init];
1053                 playlist_t * p_playlist = pl_Get(VLCIntf);
1054                 BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [[item identifier] UTF8String]);
1055                 if (!sd_loaded)
1056                     [m addItemWithTitle:_NS("Enable") action:@selector(sdmenuhandler:) keyEquivalent:@""];
1057                 else
1058                     [m addItemWithTitle:_NS("Disable") action:@selector(sdmenuhandler:) keyEquivalent:@""];
1059                 [[m itemAtIndex:0] setRepresentedObject: [item identifier]];
1060             }
1061             return [m autorelease];
1062         }
1063     }
1064
1065     return nil;
1066 }
1067
1068 - (IBAction)sdmenuhandler:(id)sender
1069 {
1070     NSString * identifier = [sender representedObject];
1071     if ([identifier length] > 0 && ![identifier isEqualToString:@"lua{sd='freebox',longname='Freebox TV'}"]) {
1072         playlist_t * p_playlist = pl_Get(VLCIntf);
1073         BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [identifier UTF8String]);
1074
1075         if (!sd_loaded)
1076             playlist_ServicesDiscoveryAdd(p_playlist, [identifier UTF8String]);
1077         else
1078             playlist_ServicesDiscoveryRemove(p_playlist, [identifier UTF8String]);
1079     }
1080 }
1081
1082 #pragma mark -
1083 #pragma mark Side Bar Delegate Methods
1084 /* taken under BSD-new from the PXSourceList sample project, adapted for VLC */
1085 - (BOOL)sourceList:(PXSourceList*)aSourceList isGroupAlwaysExpanded:(id)group
1086 {
1087     if ([[group identifier] isEqualToString:@"library"])
1088         return YES;
1089
1090     return NO;
1091 }
1092
1093 - (void)sourceListSelectionDidChange:(NSNotification *)notification
1094 {
1095     playlist_t * p_playlist = pl_Get(VLCIntf);
1096
1097     NSIndexSet *selectedIndexes = [o_sidebar_view selectedRowIndexes];
1098     id item = [o_sidebar_view itemAtRow:[selectedIndexes firstIndex]];
1099
1100
1101     //Set the label text to represent the new selection
1102     if ([item sdtype] > -1 && [[item identifier] length] > 0) {
1103         BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [[item identifier] UTF8String]);
1104         if (!sd_loaded)
1105             playlist_ServicesDiscoveryAdd(p_playlist, [[item identifier] UTF8String]);
1106     }
1107
1108     [o_chosen_category_lbl setStringValue:[item title]];
1109
1110     if ([[item identifier] isEqualToString:@"playlist"]) {
1111         [[[VLCMain sharedInstance] playlist] setPlaylistRoot:p_playlist->p_local_category];
1112     } else if ([[item identifier] isEqualToString:@"medialibrary"]) {
1113         [[[VLCMain sharedInstance] playlist] setPlaylistRoot:p_playlist->p_ml_category];
1114     } else {
1115         playlist_item_t * pl_item;
1116         PL_LOCK;
1117         pl_item = playlist_ChildSearchName(p_playlist->p_root, [[item untranslatedTitle] UTF8String]);
1118         PL_UNLOCK;
1119         [[[VLCMain sharedInstance] playlist] setPlaylistRoot: pl_item];
1120     }
1121
1122     PL_LOCK;
1123     if ([[[VLCMain sharedInstance] playlist] currentPlaylistRoot] != p_playlist->p_local_category || p_playlist->p_local_category->i_children > 0)
1124         [self hideDropZone];
1125     else
1126         [self showDropZone];
1127     PL_UNLOCK;
1128
1129     if ([[item identifier] isEqualToString:@"podcast{longname=\"Podcasts\"}"])
1130         [self showPodcastControls];
1131     else
1132         [self hidePodcastControls];
1133 }
1134
1135 - (NSDragOperation)sourceList:(PXSourceList *)aSourceList validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
1136 {
1137     if ([[item identifier] isEqualToString:@"playlist"] || [[item identifier] isEqualToString:@"medialibrary"]) {
1138         NSPasteboard *o_pasteboard = [info draggingPasteboard];
1139         if ([[o_pasteboard types] containsObject: @"VLCPlaylistItemPboardType"] || [[o_pasteboard types] containsObject: NSFilenamesPboardType])
1140             return NSDragOperationGeneric;
1141     }
1142     return NSDragOperationNone;
1143 }
1144
1145 - (BOOL)sourceList:(PXSourceList *)aSourceList acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
1146 {
1147     NSPasteboard *o_pasteboard = [info draggingPasteboard];
1148
1149     playlist_t * p_playlist = pl_Get(VLCIntf);
1150     playlist_item_t *p_node;
1151
1152     if ([[item identifier] isEqualToString:@"playlist"])
1153         p_node = p_playlist->p_local_category;
1154     else
1155         p_node = p_playlist->p_ml_category;
1156
1157     if ([[o_pasteboard types] containsObject: NSFilenamesPboardType]) {
1158         NSArray *o_values = [[o_pasteboard propertyListForType: NSFilenamesPboardType] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
1159         NSUInteger count = [o_values count];
1160         NSMutableArray *o_array = [NSMutableArray arrayWithCapacity:count];
1161
1162         for(NSUInteger i = 0; i < count; i++) {
1163             NSDictionary *o_dic;
1164             char *psz_uri = vlc_path2uri([[o_values objectAtIndex:i] UTF8String], NULL);
1165             if (!psz_uri)
1166                 continue;
1167
1168             o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1169
1170             free(psz_uri);
1171
1172             [o_array addObject: o_dic];
1173         }
1174
1175         [[[VLCMain sharedInstance] playlist] appendNodeArray:o_array inNode: p_node atPos:-1 enqueue:YES];
1176         return YES;
1177     }
1178     else if ([[o_pasteboard types] containsObject: @"VLCPlaylistItemPboardType"]) {
1179         NSArray * array = [[[VLCMain sharedInstance] playlist] draggedItems];
1180
1181         NSUInteger count = [array count];
1182         playlist_item_t * p_item = NULL;
1183
1184         PL_LOCK;
1185         for(NSUInteger i = 0; i < count; i++) {
1186             p_item = [[array objectAtIndex:i] pointerValue];
1187             if (!p_item) continue;
1188             playlist_NodeAddCopy(p_playlist, p_item, p_node, PLAYLIST_END);
1189         }
1190         PL_UNLOCK;
1191
1192         return YES;
1193     }
1194     return NO;
1195 }
1196
1197 - (id)sourceList:(PXSourceList *)aSourceList persistentObjectForItem:(id)item
1198 {
1199     return [item identifier];
1200 }
1201
1202 - (id)sourceList:(PXSourceList *)aSourceList itemForPersistentObject:(id)object
1203 {
1204     /* the following code assumes for sakes of simplicity that only the top level
1205      * items are allowed to have children */
1206
1207     NSArray * array = [NSArray arrayWithArray: o_sidebaritems]; // read-only arrays are noticebly faster
1208     NSUInteger count = [array count];
1209     if (count < 1)
1210         return nil;
1211
1212     for (NSUInteger x = 0; x < count; x++) {
1213         id item = [array objectAtIndex: x]; // save one objc selector call
1214         if ([[item identifier] isEqualToString:object])
1215             return item;
1216     }
1217
1218     return nil;
1219 }
1220
1221 #pragma mark -
1222 #pragma mark Podcast
1223
1224 - (IBAction)addPodcast:(id)sender
1225 {
1226     [NSApp beginSheet:o_podcast_subscribe_window modalForWindow:self modalDelegate:self didEndSelector:NULL contextInfo:nil];
1227 }
1228
1229 - (IBAction)addPodcastWindowAction:(id)sender
1230 {
1231     [o_podcast_subscribe_window orderOut:sender];
1232     [NSApp endSheet: o_podcast_subscribe_window];
1233
1234     if (sender == o_podcast_subscribe_ok_btn && [[o_podcast_subscribe_url_fld stringValue] length] > 0) {
1235         NSMutableString * podcastConf = [[NSMutableString alloc] init];
1236         if (config_GetPsz(VLCIntf, "podcast-urls") != NULL)
1237             [podcastConf appendFormat:@"%s|", config_GetPsz(VLCIntf, "podcast-urls")];
1238
1239         [podcastConf appendString: [o_podcast_subscribe_url_fld stringValue]];
1240         config_PutPsz(VLCIntf, "podcast-urls", [podcastConf UTF8String]);
1241
1242         vlc_object_t *p_obj = (vlc_object_t*)vlc_object_find_name(VLCIntf->p_libvlc, "podcast");
1243         if (p_obj) {
1244             var_SetString(p_obj, "podcast-urls", [podcastConf UTF8String]);
1245             vlc_object_release(p_obj);
1246         }
1247         [podcastConf release];
1248     }
1249 }
1250
1251 - (IBAction)removePodcast:(id)sender
1252 {
1253     if (config_GetPsz(VLCIntf, "podcast-urls") != NULL) {
1254         [o_podcast_unsubscribe_pop removeAllItems];
1255         [o_podcast_unsubscribe_pop addItemsWithTitles:[[NSString stringWithUTF8String:config_GetPsz(VLCIntf, "podcast-urls")] componentsSeparatedByString:@"|"]];
1256         [NSApp beginSheet:o_podcast_unsubscribe_window modalForWindow:self modalDelegate:self didEndSelector:NULL contextInfo:nil];
1257     }
1258 }
1259
1260 - (IBAction)removePodcastWindowAction:(id)sender
1261 {
1262     [o_podcast_unsubscribe_window orderOut:sender];
1263     [NSApp endSheet: o_podcast_unsubscribe_window];
1264
1265     if (sender == o_podcast_unsubscribe_ok_btn) {
1266         NSMutableArray * urls = [[NSMutableArray alloc] initWithArray:[[NSString stringWithUTF8String:config_GetPsz(VLCIntf, "podcast-urls")] componentsSeparatedByString:@"|"]];
1267         [urls removeObjectAtIndex: [o_podcast_unsubscribe_pop indexOfSelectedItem]];
1268         config_PutPsz(VLCIntf, "podcast-urls", [[urls componentsJoinedByString:@"|"] UTF8String]);
1269         [urls release];
1270
1271         vlc_object_t *p_obj = (vlc_object_t*)vlc_object_find_name(VLCIntf->p_libvlc, "podcast");
1272         if (p_obj) {
1273             var_SetString(p_obj, "podcast-urls", config_GetPsz(VLCIntf, "podcast-urls"));
1274             vlc_object_release(p_obj);
1275         }
1276
1277         /* reload the podcast module, since it won't update its list when removing podcasts */
1278         playlist_t * p_playlist = pl_Get(VLCIntf);
1279         if (playlist_IsServicesDiscoveryLoaded(p_playlist, "podcast{longname=\"Podcasts\"}")) {
1280             playlist_ServicesDiscoveryRemove(p_playlist, "podcast{longname=\"Podcasts\"}");
1281             playlist_ServicesDiscoveryAdd(p_playlist, "podcast{longname=\"Podcasts\"}");
1282             [o_playlist_table reloadData];
1283         }
1284
1285     }
1286 }
1287
1288 - (void)showPodcastControls
1289 {
1290     NSRect podcastViewDimensions = [o_podcast_view frame];
1291     NSRect rightSplitRect = [o_right_split_view frame];
1292     NSRect playlistTableRect = [o_playlist_table frame];
1293
1294     podcastViewDimensions.size.width = rightSplitRect.size.width;
1295     podcastViewDimensions.origin.x = podcastViewDimensions.origin.y = .0;
1296     [o_podcast_view setFrame:podcastViewDimensions];
1297
1298     playlistTableRect.origin.y = playlistTableRect.origin.y + podcastViewDimensions.size.height;
1299     playlistTableRect.size.height = playlistTableRect.size.height - podcastViewDimensions.size.height;
1300     [o_playlist_table setFrame:playlistTableRect];
1301     [o_playlist_table setNeedsDisplay:YES];
1302
1303     [o_right_split_view addSubview: o_podcast_view positioned: NSWindowAbove relativeTo: o_right_split_view];
1304     b_podcastView_displayed = YES;
1305 }
1306
1307 - (void)hidePodcastControls
1308 {
1309     if (b_podcastView_displayed) {
1310         NSRect podcastViewDimensions = [o_podcast_view frame];
1311         NSRect playlistTableRect = [o_playlist_table frame];
1312
1313         playlistTableRect.origin.y = playlistTableRect.origin.y - podcastViewDimensions.size.height;
1314         playlistTableRect.size.height = playlistTableRect.size.height + podcastViewDimensions.size.height;
1315
1316         [o_podcast_view removeFromSuperviewWithoutNeedingDisplay];
1317         [o_playlist_table setFrame: playlistTableRect];
1318         b_podcastView_displayed = NO;
1319     }
1320 }
1321
1322 @end
1323
1324 @implementation VLCDetachedVideoWindow
1325
1326 - (void)awakeFromNib
1327 {
1328     [self setAcceptsMouseMovedEvents: YES];
1329
1330     if (b_dark_interface) {
1331         [self setBackgroundColor: [NSColor clearColor]];
1332
1333         [self setOpaque: NO];
1334         [self display];
1335         [self setHasShadow:NO];
1336         [self setHasShadow:YES];
1337
1338         NSRect winrect = [self frame];
1339         CGFloat f_titleBarHeight = [o_titlebar_view frame].size.height;
1340
1341         [self setTitle: _NS("VLC media player")];
1342         [o_titlebar_view setFrame: NSMakeRect(0, winrect.size.height - f_titleBarHeight, winrect.size.width, f_titleBarHeight)];
1343         [[self contentView] addSubview: o_titlebar_view positioned: NSWindowAbove relativeTo: nil];
1344
1345         // native fs not supported with detached view yet
1346         [o_titlebar_view setFullscreenButtonHidden: YES];
1347     } else {
1348         [self setBackgroundColor: [NSColor blackColor]];
1349     }
1350
1351     NSRect videoViewRect = [[self contentView] bounds];
1352     if (b_dark_interface)
1353         videoViewRect.size.height -= [o_titlebar_view frame].size.height;
1354     CGFloat f_bottomBarHeight = [[[self controlsBar] bottomBarView] frame].size.height;
1355     videoViewRect.size.height -= f_bottomBarHeight;
1356     videoViewRect.origin.y = f_bottomBarHeight;
1357     [o_video_view setFrame: videoViewRect];
1358
1359     if (b_dark_interface) {
1360         o_color_backdrop = [[VLCColorView alloc] initWithFrame: [o_video_view frame]];
1361         [[self contentView] addSubview: o_color_backdrop positioned: NSWindowBelow relativeTo: o_video_view];
1362         [o_color_backdrop setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable];
1363
1364         [self setContentMinSize: NSMakeSize(363., f_min_video_height + [[[self controlsBar] bottomBarView] frame].size.height + [o_titlebar_view frame].size.height)];
1365     } else {
1366         [self setContentMinSize: NSMakeSize(363., f_min_video_height + [[[self controlsBar] bottomBarView] frame].size.height)];
1367     }
1368 }
1369
1370 - (void)dealloc
1371 {
1372     if (b_dark_interface)
1373         [o_color_backdrop release];
1374
1375     [super dealloc];
1376 }
1377
1378 @end