]> git.sesse.net Git - vlc/blob - modules/gui/macosx/MainWindow.m
macosx: fix and improve window level handling
[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     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mainSplitViewWillResizeSubviews:) name:NSSplitViewWillResizeSubviewsNotification object:o_split_view];
374
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     /* restore split view */
393     i_lastLeftSplitViewWidth = 200;
394     /* trick NSSplitView implementation, which pretends to know better than us */
395     if (!config_GetInt(VLCIntf, "macosx-show-sidebar"))
396         [self performSelector:@selector(toggleLeftSubSplitView) withObject:nil afterDelay:0.05];
397 }
398
399 #pragma mark -
400 #pragma mark appearance management
401
402 - (VLCMainWindowControlsBar *)controlsBar;
403 {
404     return (VLCMainWindowControlsBar *)o_controls_bar;
405 }
406
407 - (void)resizePlaylistAfterCollapse
408 {
409     NSRect plrect;
410     plrect = [o_playlist_table frame];
411     plrect.size.height = i_lastSplitViewHeight - 20.0; // actual pl top bar height, which differs from its frame
412     [[o_playlist_table animator] setFrame: plrect];
413
414     NSRect rightSplitRect;
415     rightSplitRect = [o_right_split_view frame];
416     plrect = [o_dropzone_box frame];
417     plrect.origin.x = (rightSplitRect.size.width - plrect.size.width) / 2;
418     plrect.origin.y = (rightSplitRect.size.height - plrect.size.height) / 2;
419     [[o_dropzone_box animator] setFrame: plrect];
420 }
421
422 - (void)makeSplitViewVisible
423 {
424     if (b_dark_interface)
425         [self setContentMinSize: NSMakeSize(604., 288. + [o_titlebar_view frame].size.height)];
426     else
427         [self setContentMinSize: NSMakeSize(604., 288.)];
428
429     NSRect old_frame = [self frame];
430     float newHeight = [self minSize].height;
431     if (old_frame.size.height < newHeight) {
432         NSRect new_frame = old_frame;
433         new_frame.origin.y = old_frame.origin.y + old_frame.size.height - newHeight;
434         new_frame.size.height = newHeight;
435
436         [[self animator] setFrame: new_frame display: YES animate: YES];
437     }
438
439     [o_video_view setHidden: YES];
440     [o_split_view setHidden: NO];
441     [self makeFirstResponder: nil];
442
443 }
444
445 - (void)makeSplitViewHidden
446 {
447     if (b_dark_interface)
448         [self setContentMinSize: NSMakeSize(604., f_min_video_height + [o_titlebar_view frame].size.height)];
449     else
450         [self setContentMinSize: NSMakeSize(604., f_min_video_height)];
451
452     [o_split_view setHidden: YES];
453     [o_video_view setHidden: NO];
454
455     if ([[o_video_view subviews] count] > 0)
456         [self makeFirstResponder: [[o_video_view subviews] objectAtIndex:0]];
457 }
458
459 // only exception for an controls bar button action
460 - (IBAction)togglePlaylist:(id)sender
461 {
462     if (![self isVisible] && sender != nil) {
463         [self makeKeyAndOrderFront: sender];
464         return;
465     }
466
467     BOOL b_activeVideo = [[VLCMain sharedInstance] activeVideoPlayback];
468     BOOL b_restored = NO;
469
470     // TODO: implement toggle playlist in this situation (triggerd via menu item).
471     // but for now we block this case, to avoid displaying only the half
472     if (b_nativeFullscreenMode && b_fullscreen && b_activeVideo && sender != nil)
473         return;
474
475     if (b_dropzone_active && ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) != 0) {
476         [self hideDropZone];
477         return;
478     }
479
480     if (!(b_nativeFullscreenMode && b_fullscreen) && !b_splitview_removed && ((([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask) != 0 && b_activeVideo)
481                                                                               || (b_nonembedded && sender != nil)
482                                                                               || (!b_activeVideo && sender != nil)
483                                                                               || b_minimized_view))
484         [self hideSplitView];
485     else {
486         if (b_splitview_removed) {
487             if (!b_nonembedded || (sender != nil && b_nonembedded))
488                 [self showSplitView];
489
490             if (sender == nil)
491                 b_minimized_view = YES;
492             else
493                 b_minimized_view = NO;
494
495             if (b_activeVideo)
496                 b_restored = YES;
497         }
498
499         if (!b_nonembedded) {
500             if (([o_video_view isHidden] && b_activeVideo) || b_restored || (b_activeVideo && sender == nil))
501                 [self makeSplitViewHidden];
502             else
503                 [self makeSplitViewVisible];
504         } else {
505             [o_split_view setHidden: NO];
506             [o_playlist_table setHidden: NO];
507             [o_video_view setHidden: YES];
508         }
509     }
510 }
511
512 - (IBAction)dropzoneButtonAction:(id)sender
513 {
514     [[[VLCMain sharedInstance] open] openFileGeneric];
515 }
516
517 #pragma mark -
518 #pragma mark overwritten default functionality
519
520 - (void)windowResizedOrMoved:(NSNotification *)notification
521 {
522     [self saveFrameUsingName: [self frameAutosaveName]];
523 }
524
525 - (void)applicationWillTerminate:(NSNotification *)notification
526 {
527     config_PutInt(VLCIntf, "macosx-show-sidebar", ![o_split_view isSubviewCollapsed:o_left_split_view]);
528
529     [self saveFrameUsingName: [self frameAutosaveName]];
530 }
531
532
533 - (void)someWindowWillClose:(NSNotification *)notification
534 {
535     id obj = [notification object];
536
537     if ([obj class] == [VLCVideoWindowCommon class] || [obj class] == [VLCDetachedVideoWindow class] || ([obj class] == [VLCMainWindow class] && !b_nonembedded)) {
538         if ([[VLCMain sharedInstance] activeVideoPlayback])
539             [[VLCCoreInteraction sharedInstance] stop];
540     }
541 }
542
543 - (void)someWindowWillMiniaturize:(NSNotification *)notification
544 {
545     if (config_GetInt(VLCIntf, "macosx-pause-minimized")) {
546         id obj = [notification object];
547
548         if ([obj class] == [VLCVideoWindowCommon class] || [obj class] == [VLCDetachedVideoWindow class] || ([obj class] == [VLCMainWindow class] && !b_nonembedded)) {
549             if ([[VLCMain sharedInstance] activeVideoPlayback])
550                 [[VLCCoreInteraction sharedInstance] pause];
551         }
552     }
553 }
554
555 #pragma mark -
556 #pragma mark Update interface and respond to foreign events
557 - (void)showDropZone
558 {
559     b_dropzone_active = YES;
560     [o_right_split_view addSubview: o_dropzone_view positioned:NSWindowAbove relativeTo:o_playlist_table];
561     [o_dropzone_view setFrame: [o_playlist_table frame]];
562     [[o_playlist_table animator] setHidden:YES];
563 }
564
565 - (void)hideDropZone
566 {
567     b_dropzone_active = NO;
568     [o_dropzone_view removeFromSuperview];
569     [[o_playlist_table animator] setHidden: NO];
570 }
571
572 - (void)hideSplitView
573 {
574     NSRect winrect = [self frame];
575     i_lastSplitViewHeight = [o_split_view frame].size.height;
576     winrect.size.height = winrect.size.height - i_lastSplitViewHeight;
577     winrect.origin.y = winrect.origin.y + i_lastSplitViewHeight;
578     [self setFrame: winrect display: YES animate: YES];
579     [self performSelector:@selector(hideDropZone) withObject:nil afterDelay:0.1];
580     if (b_dark_interface) {
581         [self setContentMinSize: NSMakeSize(604., [[o_controls_bar bottomBarView] frame].size.height + [o_titlebar_view frame].size.height)];
582         [self setContentMaxSize: NSMakeSize(FLT_MAX, [[o_controls_bar bottomBarView] frame].size.height + [o_titlebar_view frame].size.height)];
583     } else {
584         [self setContentMinSize: NSMakeSize(604., [[o_controls_bar bottomBarView] frame].size.height)];
585         [self setContentMaxSize: NSMakeSize(FLT_MAX, [[o_controls_bar bottomBarView] frame].size.height)];
586     }
587
588     b_splitview_removed = YES;
589 }
590
591 - (void)showSplitView
592 {
593     [self updateWindow];
594     if (b_dark_interface)
595         [self setContentMinSize:NSMakeSize(604., 288. + [o_titlebar_view frame].size.height)];
596     else
597         [self setContentMinSize:NSMakeSize(604., 288.)];
598     [self setContentMaxSize: NSMakeSize(FLT_MAX, FLT_MAX)];
599
600     NSRect winrect;
601     winrect = [self frame];
602     winrect.size.height = winrect.size.height + i_lastSplitViewHeight;
603     winrect.origin.y = winrect.origin.y - i_lastSplitViewHeight;
604     [self setFrame: winrect display: YES animate: YES];
605
606     [self performSelector:@selector(resizePlaylistAfterCollapse) withObject: nil afterDelay:0.75];
607
608     b_splitview_removed = NO;
609 }
610
611 - (void)updateTimeSlider
612 {
613     [o_controls_bar updateTimeSlider];
614     [[self controlsBar] updatePosAndTimeInFSPanel:o_fspanel];
615
616     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(updateTimeSlider)];
617 }
618
619 - (void)updateName
620 {
621     input_thread_t * p_input;
622     p_input = pl_CurrentInput(VLCIntf);
623     if (p_input) {
624         NSString *aString;
625         char *format = var_InheritString(VLCIntf, "input-title-format");
626         char *formated = str_format_meta(pl_Get(VLCIntf), format);
627         free(format);
628         aString = [NSString stringWithUTF8String:formated];
629         free(formated);
630
631         char *uri = input_item_GetURI(input_GetItem(p_input));
632
633         NSURL * o_url = [NSURL URLWithString: [NSString stringWithUTF8String: uri]];
634         if ([o_url isFileURL]) {
635             [self setRepresentedURL: o_url];
636             [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
637                 [o_window setRepresentedURL:o_url];
638             }];
639         } else {
640             [self setRepresentedURL: nil];
641             [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
642                 [o_window setRepresentedURL:nil];
643             }];
644         }
645         free(uri);
646
647         if ([aString isEqualToString:@""]) {
648             if ([o_url isFileURL])
649                 aString = [[NSFileManager defaultManager] displayNameAtPath: [o_url path]];
650             else
651                 aString = [o_url absoluteString];
652         }
653
654         if ([aString length] > 0) {
655             [self setTitle: aString];
656             [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
657                 [o_window setTitle:aString];
658             }];
659
660             [o_fspanel setStreamTitle: aString];
661         } else {
662            [self setTitle: _NS("VLC media player")];
663             [self setRepresentedURL: nil];
664         }
665
666         vlc_object_release(p_input);
667     } else {
668         [self setTitle: _NS("VLC media player")];
669         [self setRepresentedURL: nil];
670     }
671 }
672
673 - (void)updateWindow
674 {
675     [o_controls_bar updateControls];
676     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(updateControls)];
677
678     bool b_seekable = false;
679
680     playlist_t * p_playlist = pl_Get(VLCIntf);
681     input_thread_t * p_input = playlist_CurrentInput(p_playlist);
682     if (p_input) {
683         /* seekable streams */
684         b_seekable = var_GetBool(p_input, "can-seek");
685
686         vlc_object_release(p_input);
687     }
688
689     [self updateTimeSlider];
690     if ([o_fspanel respondsToSelector:@selector(setSeekable:)])
691         [o_fspanel setSeekable: b_seekable];
692
693     PL_LOCK;
694     if ([[[VLCMain sharedInstance] playlist] currentPlaylistRoot] != p_playlist->p_local_category || p_playlist->p_local_category->i_children > 0)
695         [self hideDropZone];
696     else
697         [self showDropZone];
698     PL_UNLOCK;
699     [o_sidebar_view setNeedsDisplay:YES];
700 }
701
702 - (void)setPause
703 {
704     [o_controls_bar setPause];
705     [o_fspanel setPause];
706
707     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(setPause)];
708 }
709
710 - (void)setPlay
711 {
712     [o_controls_bar setPlay];
713     [o_fspanel setPlay];
714
715     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(setPlay)];
716
717 }
718
719 - (void)updateVolumeSlider
720 {
721     [[self controlsBar] updateVolumeSlider];
722     [o_fspanel setVolumeLevel: [[VLCCoreInteraction sharedInstance] volume]];
723 }
724
725 #pragma mark -
726 #pragma mark Video Output handling
727
728 - (void)setVideoplayEnabled
729 {
730     BOOL b_videoPlayback = [[VLCMain sharedInstance] activeVideoPlayback];
731
732     if (b_videoPlayback) {
733         if (!b_fullscreen)
734             frameBeforePlayback = [self frame];
735     } else {
736         if (!b_nonembedded && !b_fullscreen && frameBeforePlayback.size.width > 0 && frameBeforePlayback.size.height > 0)
737             [[self animator] setFrame:frameBeforePlayback display:YES];
738
739         // update fs button to reflect state for next startup
740         if (var_InheritBool(pl_Get(VLCIntf), "fullscreen")) {
741             [o_controls_bar setFullscreenState:YES];
742         }
743
744         [self makeFirstResponder: nil];
745         [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: NSNormalWindowLevel];
746
747         // restore alpha value to 1 for the case that macosx-opaqueness is set to < 1
748         [self setAlphaValue:1.0];
749     }
750
751     if (b_nativeFullscreenMode) {
752         if ([NSApp presentationOptions] & NSApplicationPresentationFullScreen)
753             [[o_controls_bar bottomBarView] setHidden: b_videoPlayback];
754         else
755             [[o_controls_bar bottomBarView] setHidden: NO];
756         if (b_videoPlayback && b_fullscreen)
757             [o_fspanel setActive: nil];
758         if (!b_videoPlayback)
759             [o_fspanel setNonActive: nil];
760     }
761 }
762
763 //  Called automatically if window's acceptsMouseMovedEvents property is true
764 - (void)mouseMoved:(NSEvent *)theEvent
765 {
766     if (b_fullscreen)
767         [self recreateHideMouseTimer];
768
769     [super mouseMoved: theEvent];
770 }
771
772 - (void)recreateHideMouseTimer
773 {
774     if (t_hide_mouse_timer != nil) {
775         [t_hide_mouse_timer invalidate];
776         [t_hide_mouse_timer release];
777     }
778
779     t_hide_mouse_timer = [NSTimer scheduledTimerWithTimeInterval:2
780                                                           target:self
781                                                         selector:@selector(hideMouseCursor:)
782                                                         userInfo:nil
783                                                          repeats:NO];
784     [t_hide_mouse_timer retain];
785 }
786
787 //  NSTimer selectors require this function signature as per Apple's docs
788 - (void)hideMouseCursor:(NSTimer *)timer
789 {
790     [NSCursor setHiddenUntilMouseMoves: YES];
791 }
792
793
794 #pragma mark -
795 #pragma mark Fullscreen support
796
797 - (void)showFullscreenController
798 {
799      if (b_fullscreen && [[VLCMain sharedInstance] activeVideoPlayback])
800         [o_fspanel fadeIn];
801 }
802
803 - (void)makeKeyAndOrderFront: (id)sender
804 {
805     /* Hack
806      * when we exit fullscreen and fade out, we may endup in
807      * having a window that is faded. We can't have it fade in unless we
808      * animate again. */
809
810     if (!b_window_is_invisible) {
811         /* Make sure we don't do it too much */
812         [super makeKeyAndOrderFront: sender];
813         return;
814     }
815
816     [super setAlphaValue:0.0f];
817     [super makeKeyAndOrderFront: sender];
818
819     NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:2];
820     [dict setObject:self forKey:NSViewAnimationTargetKey];
821     [dict setObject:NSViewAnimationFadeInEffect forKey:NSViewAnimationEffectKey];
822
823     o_makekey_anim = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict]];
824     [dict release];
825
826     [o_makekey_anim setAnimationBlockingMode: NSAnimationNonblocking];
827     [o_makekey_anim setDuration: 0.1];
828     [o_makekey_anim setFrameRate: 30];
829     [o_makekey_anim setDelegate: self];
830
831     [o_makekey_anim startAnimation];
832     b_window_is_invisible = NO;
833
834     /* fullscreenAnimation will be unlocked when animation ends */
835 }
836
837 #pragma mark -
838 #pragma mark Lion native fullscreen handling
839 - (void)windowWillEnterFullScreen:(NSNotification *)notification
840 {
841     // workaround, see #6668
842     [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
843
844     var_SetBool(pl_Get(VLCIntf), "fullscreen", true);
845
846     vout_thread_t *p_vout = getVout();
847     if (p_vout) {
848         var_SetBool(p_vout, "fullscreen", true);
849         vlc_object_release(p_vout);
850     }
851
852     [o_video_view setFrame: [[self contentView] frame]];
853     b_fullscreen = YES;
854
855     [self recreateHideMouseTimer];
856     i_originalLevel = [self level];
857     [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: NSNormalWindowLevel];
858     [self setLevel:NSNormalWindowLevel];
859
860     if (b_dark_interface) {
861         [o_titlebar_view removeFromSuperviewWithoutNeedingDisplay];
862
863         NSRect winrect;
864         CGFloat f_titleBarHeight = [o_titlebar_view frame].size.height;
865         winrect = [self frame];
866
867         winrect.size.height = winrect.size.height - f_titleBarHeight;
868         [self setFrame: winrect display:NO animate:NO];
869         winrect = [o_split_view frame];
870         winrect.size.height = winrect.size.height + f_titleBarHeight;
871         [o_split_view setFrame: winrect];
872     }
873
874     if ([[VLCMain sharedInstance] activeVideoPlayback])
875         [[o_controls_bar bottomBarView] setHidden: YES];
876
877     [self setMovableByWindowBackground: NO];
878 }
879
880 - (void)windowDidEnterFullScreen:(NSNotification *)notification
881 {
882     // Indeed, we somehow can have an "inactive" fullscreen (but a visible window!).
883     // But this creates some problems when leaving fs over remote intfs, so activate app here.
884     [NSApp activateIgnoringOtherApps:YES];
885
886     [o_fspanel setVoutWasUpdated: self];
887     [o_fspanel setActive: nil];
888
889     NSArray *subviews = [[self videoView] subviews];
890     NSUInteger count = [subviews count];
891
892     for (NSUInteger x = 0; x < count; x++) {
893         if ([[subviews objectAtIndex:x] respondsToSelector:@selector(reshape)])
894             [[subviews objectAtIndex:x] reshape];
895     }
896
897 }
898
899 - (void)windowWillExitFullScreen:(NSNotification *)notification
900 {
901     var_SetBool(pl_Get(VLCIntf), "fullscreen", false);
902
903     vout_thread_t *p_vout = getVout();
904     if (p_vout) {
905         var_SetBool(p_vout, "fullscreen", false);
906         vlc_object_release(p_vout);
907     }
908
909     [o_video_view setFrame: [o_split_view frame]];
910     [NSCursor setHiddenUntilMouseMoves: NO];
911     [o_fspanel setNonActive: nil];
912     [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: i_originalLevel];
913     [self setLevel:i_originalLevel];
914
915     b_fullscreen = NO;
916
917     if (b_dark_interface) {
918         NSRect winrect;
919         CGFloat f_titleBarHeight = [o_titlebar_view frame].size.height;
920         winrect = [self frame];
921
922         [o_titlebar_view setFrame: NSMakeRect(0, winrect.size.height - f_titleBarHeight,
923                                               winrect.size.width, f_titleBarHeight)];
924         [[self contentView] addSubview: o_titlebar_view];
925
926         winrect.size.height = winrect.size.height + f_titleBarHeight;
927         [self setFrame: winrect display:NO animate:NO];
928         winrect = [o_split_view frame];
929         winrect.size.height = winrect.size.height - f_titleBarHeight;
930         [o_split_view setFrame: winrect];
931         [o_video_view setFrame: winrect];
932     }
933
934     if ([[VLCMain sharedInstance] activeVideoPlayback])
935         [[o_controls_bar bottomBarView] setHidden: NO];
936
937     [self setMovableByWindowBackground: YES];
938 }
939
940 #pragma mark -
941 #pragma mark split view delegate
942 - (CGFloat)splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)dividerIndex
943 {
944     if (dividerIndex == 0)
945         return 300.;
946     else
947         return proposedMax;
948 }
949
950 - (CGFloat)splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)dividerIndex
951 {
952     if (dividerIndex == 0)
953         return 100.;
954     else
955         return proposedMin;
956 }
957
958 - (BOOL)splitView:(NSSplitView *)splitView canCollapseSubview:(NSView *)subview
959 {
960     return ([subview isEqual:o_left_split_view]);
961 }
962
963 - (BOOL)splitView:(NSSplitView *)splitView shouldAdjustSizeOfSubview:(NSView *)subview
964 {
965     if ([subview isEqual:o_left_split_view])
966         return NO;
967     return YES;
968 }
969
970 - (void)mainSplitViewWillResizeSubviews:(id)object
971 {
972     i_lastLeftSplitViewWidth = [o_left_split_view frame].size.width;
973     config_PutInt(VLCIntf, "macosx-show-sidebar", ![o_split_view isSubviewCollapsed:o_left_split_view]);
974     [[[VLCMain sharedInstance] mainMenu] updateSidebarMenuItem];
975 }
976
977 - (void)toggleLeftSubSplitView
978 {
979     [o_split_view adjustSubviews];
980     if ([o_split_view isSubviewCollapsed:o_left_split_view])
981         [o_split_view setPosition:i_lastLeftSplitViewWidth ofDividerAtIndex:0];
982     else
983         [o_split_view setPosition:[o_split_view minPossiblePositionOfDividerAtIndex:0] ofDividerAtIndex:0];
984 }
985
986 #pragma mark -
987 #pragma mark Side Bar Data handling
988 /* taken under BSD-new from the PXSourceList sample project, adapted for VLC */
989 - (NSUInteger)sourceList:(PXSourceList*)sourceList numberOfChildrenOfItem:(id)item
990 {
991     //Works the same way as the NSOutlineView data source: `nil` means a parent item
992     if (item==nil)
993         return [o_sidebaritems count];
994     else
995         return [[item children] count];
996 }
997
998
999 - (id)sourceList:(PXSourceList*)aSourceList child:(NSUInteger)index ofItem:(id)item
1000 {
1001     //Works the same way as the NSOutlineView data source: `nil` means a parent item
1002     if (item==nil)
1003         return [o_sidebaritems objectAtIndex:index];
1004     else
1005         return [[item children] objectAtIndex:index];
1006 }
1007
1008
1009 - (id)sourceList:(PXSourceList*)aSourceList objectValueForItem:(id)item
1010 {
1011     return [item title];
1012 }
1013
1014 - (void)sourceList:(PXSourceList*)aSourceList setObjectValue:(id)object forItem:(id)item
1015 {
1016     [item setTitle:object];
1017 }
1018
1019 - (BOOL)sourceList:(PXSourceList*)aSourceList isItemExpandable:(id)item
1020 {
1021     return [item hasChildren];
1022 }
1023
1024
1025 - (BOOL)sourceList:(PXSourceList*)aSourceList itemHasBadge:(id)item
1026 {
1027     if ([[item identifier] isEqualToString: @"playlist"] || [[item identifier] isEqualToString: @"medialibrary"])
1028         return YES;
1029
1030     return [item hasBadge];
1031 }
1032
1033
1034 - (NSInteger)sourceList:(PXSourceList*)aSourceList badgeValueForItem:(id)item
1035 {
1036     playlist_t * p_playlist = pl_Get(VLCIntf);
1037     NSInteger i_playlist_size;
1038
1039     if ([[item identifier] isEqualToString: @"playlist"]) {
1040         PL_LOCK;
1041         i_playlist_size = p_playlist->p_local_category->i_children;
1042         PL_UNLOCK;
1043
1044         return i_playlist_size;
1045     }
1046     if ([[item identifier] isEqualToString: @"medialibrary"]) {
1047         PL_LOCK;
1048         i_playlist_size = p_playlist->p_ml_category->i_children;
1049         PL_UNLOCK;
1050
1051         return i_playlist_size;
1052     }
1053
1054     return [item badgeValue];
1055 }
1056
1057
1058 - (BOOL)sourceList:(PXSourceList*)aSourceList itemHasIcon:(id)item
1059 {
1060     return [item hasIcon];
1061 }
1062
1063
1064 - (NSImage*)sourceList:(PXSourceList*)aSourceList iconForItem:(id)item
1065 {
1066     return [item icon];
1067 }
1068
1069 - (NSMenu*)sourceList:(PXSourceList*)aSourceList menuForEvent:(NSEvent*)theEvent item:(id)item
1070 {
1071     if ([theEvent type] == NSRightMouseDown || ([theEvent type] == NSLeftMouseDown && ([theEvent modifierFlags] & NSControlKeyMask) == NSControlKeyMask)) {
1072         if (item != nil) {
1073             NSMenu * m;
1074             if ([item sdtype] > 0)
1075             {
1076                 m = [[NSMenu alloc] init];
1077                 playlist_t * p_playlist = pl_Get(VLCIntf);
1078                 BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [[item identifier] UTF8String]);
1079                 if (!sd_loaded)
1080                     [m addItemWithTitle:_NS("Enable") action:@selector(sdmenuhandler:) keyEquivalent:@""];
1081                 else
1082                     [m addItemWithTitle:_NS("Disable") action:@selector(sdmenuhandler:) keyEquivalent:@""];
1083                 [[m itemAtIndex:0] setRepresentedObject: [item identifier]];
1084             }
1085             return [m autorelease];
1086         }
1087     }
1088
1089     return nil;
1090 }
1091
1092 - (IBAction)sdmenuhandler:(id)sender
1093 {
1094     NSString * identifier = [sender representedObject];
1095     if ([identifier length] > 0 && ![identifier isEqualToString:@"lua{sd='freebox',longname='Freebox TV'}"]) {
1096         playlist_t * p_playlist = pl_Get(VLCIntf);
1097         BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [identifier UTF8String]);
1098
1099         if (!sd_loaded)
1100             playlist_ServicesDiscoveryAdd(p_playlist, [identifier UTF8String]);
1101         else
1102             playlist_ServicesDiscoveryRemove(p_playlist, [identifier UTF8String]);
1103     }
1104 }
1105
1106 #pragma mark -
1107 #pragma mark Side Bar Delegate Methods
1108 /* taken under BSD-new from the PXSourceList sample project, adapted for VLC */
1109 - (BOOL)sourceList:(PXSourceList*)aSourceList isGroupAlwaysExpanded:(id)group
1110 {
1111     if ([[group identifier] isEqualToString:@"library"])
1112         return YES;
1113
1114     return NO;
1115 }
1116
1117 - (void)sourceListSelectionDidChange:(NSNotification *)notification
1118 {
1119     playlist_t * p_playlist = pl_Get(VLCIntf);
1120
1121     NSIndexSet *selectedIndexes = [o_sidebar_view selectedRowIndexes];
1122     id item = [o_sidebar_view itemAtRow:[selectedIndexes firstIndex]];
1123
1124
1125     //Set the label text to represent the new selection
1126     if ([item sdtype] > -1 && [[item identifier] length] > 0) {
1127         BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [[item identifier] UTF8String]);
1128         if (!sd_loaded)
1129             playlist_ServicesDiscoveryAdd(p_playlist, [[item identifier] UTF8String]);
1130     }
1131
1132     [o_chosen_category_lbl setStringValue:[item title]];
1133
1134     if ([[item identifier] isEqualToString:@"playlist"]) {
1135         [[[VLCMain sharedInstance] playlist] setPlaylistRoot:p_playlist->p_local_category];
1136     } else if ([[item identifier] isEqualToString:@"medialibrary"]) {
1137         [[[VLCMain sharedInstance] playlist] setPlaylistRoot:p_playlist->p_ml_category];
1138     } else {
1139         playlist_item_t * pl_item;
1140         PL_LOCK;
1141         pl_item = playlist_ChildSearchName(p_playlist->p_root, [[item untranslatedTitle] UTF8String]);
1142         PL_UNLOCK;
1143         [[[VLCMain sharedInstance] playlist] setPlaylistRoot: pl_item];
1144     }
1145
1146     PL_LOCK;
1147     if ([[[VLCMain sharedInstance] playlist] currentPlaylistRoot] != p_playlist->p_local_category || p_playlist->p_local_category->i_children > 0)
1148         [self hideDropZone];
1149     else
1150         [self showDropZone];
1151     PL_UNLOCK;
1152
1153     if ([[item identifier] isEqualToString:@"podcast{longname=\"Podcasts\"}"])
1154         [self showPodcastControls];
1155     else
1156         [self hidePodcastControls];
1157 }
1158
1159 - (NSDragOperation)sourceList:(PXSourceList *)aSourceList validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
1160 {
1161     if ([[item identifier] isEqualToString:@"playlist"] || [[item identifier] isEqualToString:@"medialibrary"]) {
1162         NSPasteboard *o_pasteboard = [info draggingPasteboard];
1163         if ([[o_pasteboard types] containsObject: @"VLCPlaylistItemPboardType"] || [[o_pasteboard types] containsObject: NSFilenamesPboardType])
1164             return NSDragOperationGeneric;
1165     }
1166     return NSDragOperationNone;
1167 }
1168
1169 - (BOOL)sourceList:(PXSourceList *)aSourceList acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
1170 {
1171     NSPasteboard *o_pasteboard = [info draggingPasteboard];
1172
1173     playlist_t * p_playlist = pl_Get(VLCIntf);
1174     playlist_item_t *p_node;
1175
1176     if ([[item identifier] isEqualToString:@"playlist"])
1177         p_node = p_playlist->p_local_category;
1178     else
1179         p_node = p_playlist->p_ml_category;
1180
1181     if ([[o_pasteboard types] containsObject: NSFilenamesPboardType]) {
1182         NSArray *o_values = [[o_pasteboard propertyListForType: NSFilenamesPboardType] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
1183         NSUInteger count = [o_values count];
1184         NSMutableArray *o_array = [NSMutableArray arrayWithCapacity:count];
1185
1186         for(NSUInteger i = 0; i < count; i++) {
1187             NSDictionary *o_dic;
1188             char *psz_uri = vlc_path2uri([[o_values objectAtIndex:i] UTF8String], NULL);
1189             if (!psz_uri)
1190                 continue;
1191
1192             o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1193
1194             free(psz_uri);
1195
1196             [o_array addObject: o_dic];
1197         }
1198
1199         [[[VLCMain sharedInstance] playlist] appendNodeArray:o_array inNode: p_node atPos:-1 enqueue:YES];
1200         return YES;
1201     }
1202     else if ([[o_pasteboard types] containsObject: @"VLCPlaylistItemPboardType"]) {
1203         NSArray * array = [[[VLCMain sharedInstance] playlist] draggedItems];
1204
1205         NSUInteger count = [array count];
1206         playlist_item_t * p_item = NULL;
1207
1208         PL_LOCK;
1209         for(NSUInteger i = 0; i < count; i++) {
1210             p_item = [[array objectAtIndex:i] pointerValue];
1211             if (!p_item) continue;
1212             playlist_NodeAddCopy(p_playlist, p_item, p_node, PLAYLIST_END);
1213         }
1214         PL_UNLOCK;
1215
1216         return YES;
1217     }
1218     return NO;
1219 }
1220
1221 - (id)sourceList:(PXSourceList *)aSourceList persistentObjectForItem:(id)item
1222 {
1223     return [item identifier];
1224 }
1225
1226 - (id)sourceList:(PXSourceList *)aSourceList itemForPersistentObject:(id)object
1227 {
1228     /* the following code assumes for sakes of simplicity that only the top level
1229      * items are allowed to have children */
1230
1231     NSArray * array = [NSArray arrayWithArray: o_sidebaritems]; // read-only arrays are noticebly faster
1232     NSUInteger count = [array count];
1233     if (count < 1)
1234         return nil;
1235
1236     for (NSUInteger x = 0; x < count; x++) {
1237         id item = [array objectAtIndex: x]; // save one objc selector call
1238         if ([[item identifier] isEqualToString:object])
1239             return item;
1240     }
1241
1242     return nil;
1243 }
1244
1245 #pragma mark -
1246 #pragma mark Podcast
1247
1248 - (IBAction)addPodcast:(id)sender
1249 {
1250     [NSApp beginSheet:o_podcast_subscribe_window modalForWindow:self modalDelegate:self didEndSelector:NULL contextInfo:nil];
1251 }
1252
1253 - (IBAction)addPodcastWindowAction:(id)sender
1254 {
1255     [o_podcast_subscribe_window orderOut:sender];
1256     [NSApp endSheet: o_podcast_subscribe_window];
1257
1258     if (sender == o_podcast_subscribe_ok_btn && [[o_podcast_subscribe_url_fld stringValue] length] > 0) {
1259         NSMutableString * podcastConf = [[NSMutableString alloc] init];
1260         if (config_GetPsz(VLCIntf, "podcast-urls") != NULL)
1261             [podcastConf appendFormat:@"%s|", config_GetPsz(VLCIntf, "podcast-urls")];
1262
1263         [podcastConf appendString: [o_podcast_subscribe_url_fld stringValue]];
1264         config_PutPsz(VLCIntf, "podcast-urls", [podcastConf UTF8String]);
1265
1266         vlc_object_t *p_obj = (vlc_object_t*)vlc_object_find_name(VLCIntf->p_libvlc, "podcast");
1267         if (p_obj) {
1268             var_SetString(p_obj, "podcast-urls", [podcastConf UTF8String]);
1269             vlc_object_release(p_obj);
1270         }
1271         [podcastConf release];
1272     }
1273 }
1274
1275 - (IBAction)removePodcast:(id)sender
1276 {
1277     if (config_GetPsz(VLCIntf, "podcast-urls") != NULL) {
1278         [o_podcast_unsubscribe_pop removeAllItems];
1279         [o_podcast_unsubscribe_pop addItemsWithTitles:[[NSString stringWithUTF8String:config_GetPsz(VLCIntf, "podcast-urls")] componentsSeparatedByString:@"|"]];
1280         [NSApp beginSheet:o_podcast_unsubscribe_window modalForWindow:self modalDelegate:self didEndSelector:NULL contextInfo:nil];
1281     }
1282 }
1283
1284 - (IBAction)removePodcastWindowAction:(id)sender
1285 {
1286     [o_podcast_unsubscribe_window orderOut:sender];
1287     [NSApp endSheet: o_podcast_unsubscribe_window];
1288
1289     if (sender == o_podcast_unsubscribe_ok_btn) {
1290         NSMutableArray * urls = [[NSMutableArray alloc] initWithArray:[[NSString stringWithUTF8String:config_GetPsz(VLCIntf, "podcast-urls")] componentsSeparatedByString:@"|"]];
1291         [urls removeObjectAtIndex: [o_podcast_unsubscribe_pop indexOfSelectedItem]];
1292         config_PutPsz(VLCIntf, "podcast-urls", [[urls componentsJoinedByString:@"|"] UTF8String]);
1293         [urls release];
1294
1295         vlc_object_t *p_obj = (vlc_object_t*)vlc_object_find_name(VLCIntf->p_libvlc, "podcast");
1296         if (p_obj) {
1297             var_SetString(p_obj, "podcast-urls", config_GetPsz(VLCIntf, "podcast-urls"));
1298             vlc_object_release(p_obj);
1299         }
1300
1301         /* reload the podcast module, since it won't update its list when removing podcasts */
1302         playlist_t * p_playlist = pl_Get(VLCIntf);
1303         if (playlist_IsServicesDiscoveryLoaded(p_playlist, "podcast{longname=\"Podcasts\"}")) {
1304             playlist_ServicesDiscoveryRemove(p_playlist, "podcast{longname=\"Podcasts\"}");
1305             playlist_ServicesDiscoveryAdd(p_playlist, "podcast{longname=\"Podcasts\"}");
1306             [o_playlist_table reloadData];
1307         }
1308
1309     }
1310 }
1311
1312 - (void)showPodcastControls
1313 {
1314     NSRect podcastViewDimensions = [o_podcast_view frame];
1315     NSRect rightSplitRect = [o_right_split_view frame];
1316     NSRect playlistTableRect = [o_playlist_table frame];
1317
1318     podcastViewDimensions.size.width = rightSplitRect.size.width;
1319     podcastViewDimensions.origin.x = podcastViewDimensions.origin.y = .0;
1320     [o_podcast_view setFrame:podcastViewDimensions];
1321
1322     playlistTableRect.origin.y = playlistTableRect.origin.y + podcastViewDimensions.size.height;
1323     playlistTableRect.size.height = playlistTableRect.size.height - podcastViewDimensions.size.height;
1324     [o_playlist_table setFrame:playlistTableRect];
1325     [o_playlist_table setNeedsDisplay:YES];
1326
1327     [o_right_split_view addSubview: o_podcast_view positioned: NSWindowAbove relativeTo: o_right_split_view];
1328     b_podcastView_displayed = YES;
1329 }
1330
1331 - (void)hidePodcastControls
1332 {
1333     if (b_podcastView_displayed) {
1334         NSRect podcastViewDimensions = [o_podcast_view frame];
1335         NSRect playlistTableRect = [o_playlist_table frame];
1336
1337         playlistTableRect.origin.y = playlistTableRect.origin.y - podcastViewDimensions.size.height;
1338         playlistTableRect.size.height = playlistTableRect.size.height + podcastViewDimensions.size.height;
1339
1340         [o_podcast_view removeFromSuperviewWithoutNeedingDisplay];
1341         [o_playlist_table setFrame: playlistTableRect];
1342         b_podcastView_displayed = NO;
1343     }
1344 }
1345
1346 @end
1347
1348 @implementation VLCDetachedVideoWindow
1349
1350 - (void)awakeFromNib
1351 {
1352     [self setAcceptsMouseMovedEvents: YES];
1353
1354     if (b_dark_interface) {
1355         [self setBackgroundColor: [NSColor clearColor]];
1356
1357         [self setOpaque: NO];
1358         [self display];
1359         [self setHasShadow:NO];
1360         [self setHasShadow:YES];
1361
1362         NSRect winrect = [self frame];
1363         CGFloat f_titleBarHeight = [o_titlebar_view frame].size.height;
1364
1365         [self setTitle: _NS("VLC media player")];
1366         [o_titlebar_view setFrame: NSMakeRect(0, winrect.size.height - f_titleBarHeight, winrect.size.width, f_titleBarHeight)];
1367         [[self contentView] addSubview: o_titlebar_view positioned: NSWindowAbove relativeTo: nil];
1368
1369         // native fs not supported with detached view yet
1370         [o_titlebar_view setFullscreenButtonHidden: YES];
1371     } else {
1372         [self setBackgroundColor: [NSColor blackColor]];
1373     }
1374
1375     NSRect videoViewRect = [[self contentView] bounds];
1376     if (b_dark_interface)
1377         videoViewRect.size.height -= [o_titlebar_view frame].size.height;
1378     CGFloat f_bottomBarHeight = [[[self controlsBar] bottomBarView] frame].size.height;
1379     videoViewRect.size.height -= f_bottomBarHeight;
1380     videoViewRect.origin.y = f_bottomBarHeight;
1381     [o_video_view setFrame: videoViewRect];
1382
1383     if (b_dark_interface) {
1384         o_color_backdrop = [[VLCColorView alloc] initWithFrame: [o_video_view frame]];
1385         [[self contentView] addSubview: o_color_backdrop positioned: NSWindowBelow relativeTo: o_video_view];
1386         [o_color_backdrop setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable];
1387
1388         [self setContentMinSize: NSMakeSize(363., f_min_video_height + [[[self controlsBar] bottomBarView] frame].size.height + [o_titlebar_view frame].size.height)];
1389     } else {
1390         [self setContentMinSize: NSMakeSize(363., f_min_video_height + [[[self controlsBar] bottomBarView] frame].size.height)];
1391     }
1392 }
1393
1394 - (void)dealloc
1395 {
1396     if (b_dark_interface)
1397         [o_color_backdrop release];
1398
1399     [super dealloc];
1400 }
1401
1402 @end