]> git.sesse.net Git - vlc/blob - modules/gui/macosx/MainWindow.m
macosx: don't listen to media keys if current playlist root is empty or media is...
[vlc] / modules / gui / macosx / MainWindow.m
1 /*****************************************************************************
2  * MainWindow.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2002-2013 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  *          David Fuhrmann <david dot fuhrmann at googlemail dot com>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
26  *****************************************************************************/
27
28 #import "CompatibilityFixes.h"
29 #import "MainWindow.h"
30 #import "intf.h"
31 #import "CoreInteraction.h"
32 #import "AudioEffects.h"
33 #import "MainMenu.h"
34 #import "open.h"
35 #import "controls.h" // TODO: remove me
36 #import "playlist.h"
37 #import "SideBarItem.h"
38 #import <math.h>
39 #import <vlc_playlist.h>
40 #import <vlc_url.h>
41 #import <vlc_strings.h>
42 #import <vlc_services_discovery.h>
43
44 #import "ControlsBar.h"
45 #import "VideoView.h"
46 #import "VLCVoutWindowController.h"
47
48
49 @interface VLCMainWindow (Internal)
50 - (void)resizePlaylistAfterCollapse;
51 - (void)makeSplitViewVisible;
52 - (void)makeSplitViewHidden;
53 - (void)showPodcastControls;
54 - (void)hidePodcastControls;
55 @end
56
57
58 @implementation VLCMainWindow
59
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         ![self isEvent: o_event forKey: "key-prev"] &&
127         ![self isEvent: o_event forKey: "key-next"] &&
128         ![self isEvent: o_event forKey: "key-jump+short"] &&
129         ![self isEvent: o_event forKey: "key-jump-short"]) {
130         /* We indeed want to prioritize some Cocoa key equivalent against libvlc,
131          so we perform the menu equivalent now. */
132         if ([[NSApp mainMenu] performKeyEquivalent:o_event])
133             return TRUE;
134     }
135     else
136         b_force = YES;
137
138     return [[VLCMain sharedInstance] hasDefinedShortcutKey:o_event force:b_force] ||
139            [(VLCControls *)[[VLCMain sharedInstance] controls] keyEvent:o_event];
140 }
141
142 - (void)dealloc
143 {
144     if (b_dark_interface)
145         [o_color_backdrop release];
146
147     [[NSNotificationCenter defaultCenter] removeObserver: self];
148     [o_sidebaritems release];
149
150     [super dealloc];
151 }
152
153 - (void)awakeFromNib
154 {
155     // sets lion fullscreen behaviour
156     [super awakeFromNib];
157
158     BOOL b_splitviewShouldBeHidden = NO;
159
160     /* setup the styled interface */
161     b_nativeFullscreenMode = NO;
162 #ifdef MAC_OS_X_VERSION_10_7
163     if (!OSX_SNOW_LEOPARD)
164         b_nativeFullscreenMode = var_InheritBool(VLCIntf, "macosx-nativefullscreenmode");
165 #endif
166     [self useOptimizedDrawing: YES];
167
168     [[o_search_fld cell] setPlaceholderString: _NS("Search")];
169     [[o_search_fld cell] accessibilitySetOverrideValue:_NS("Enter a term to search the playlist. Results will be selected in the table.") forAttribute:NSAccessibilityDescriptionAttribute];
170
171     [o_dropzone_btn setTitle: _NS("Open media...")];
172     [[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];
173     [o_dropzone_lbl setStringValue: _NS("Drop media here")];
174
175     [o_podcast_add_btn setTitle: _NS("Subscribe")];
176     [o_podcast_remove_btn setTitle: _NS("Unsubscribe")];
177     [o_podcast_subscribe_title_lbl setStringValue: _NS("Subscribe to a podcast")];
178     [o_podcast_subscribe_subtitle_lbl setStringValue: _NS("Enter URL of the podcast to subscribe to:")];
179     [o_podcast_subscribe_cancel_btn setTitle: _NS("Cancel")];
180     [o_podcast_subscribe_ok_btn setTitle: _NS("Subscribe")];
181     [o_podcast_unsubscribe_title_lbl setStringValue: _NS("Unsubscribe from a podcast")];
182     [o_podcast_unsubscribe_subtitle_lbl setStringValue: _NS("Select the podcast you would like to unsubscribe from:")];
183     [o_podcast_unsubscribe_ok_btn setTitle: _NS("Unsubscribe")];
184     [o_podcast_unsubscribe_cancel_btn setTitle: _NS("Cancel")];
185
186     /* interface builder action */
187     float f_threshold_height = f_min_video_height + [[o_controls_bar bottomBarView] frame].size.height;
188     if (b_dark_interface)
189         f_threshold_height += [o_titlebar_view frame].size.height;
190     if ([[self contentView] frame].size.height < f_threshold_height)
191         b_splitviewShouldBeHidden = YES;
192
193     [self setDelegate: self];
194     [self setExcludedFromWindowsMenu: YES];
195     [self setAcceptsMouseMovedEvents: YES];
196     // Set that here as IB seems to be buggy
197     if (b_dark_interface)
198         [self setContentMinSize:NSMakeSize(604., 288. + [o_titlebar_view frame].size.height)];
199     else
200         [self setContentMinSize:NSMakeSize(604., 288.)];
201
202     [self setTitle: _NS("VLC media player")];
203
204     b_dropzone_active = YES;
205     [o_dropzone_view setFrame: [o_playlist_table frame]];
206     [o_left_split_view setFrame: [o_sidebar_view frame]];
207
208     if (!OSX_SNOW_LEOPARD) {
209         /* the default small size of the search field is slightly different on Lion, let's work-around that */
210         NSRect frame;
211         frame = [o_search_fld frame];
212         frame.origin.y = frame.origin.y + 2.0;
213         frame.size.height = frame.size.height - 1.0;
214         [o_search_fld setFrame: frame];
215     }
216
217     /* create the sidebar */
218     o_sidebaritems = [[NSMutableArray alloc] init];
219     SideBarItem *libraryItem = [SideBarItem itemWithTitle:_NS("LIBRARY") identifier:@"library"];
220     SideBarItem *playlistItem = [SideBarItem itemWithTitle:_NS("Playlist") identifier:@"playlist"];
221     [playlistItem setIcon: [NSImage imageNamed:@"sidebar-playlist"]];
222     SideBarItem *medialibraryItem = [SideBarItem itemWithTitle:_NS("Media Library") identifier:@"medialibrary"];
223     [medialibraryItem setIcon: [NSImage imageNamed:@"sidebar-playlist"]];
224     SideBarItem *mycompItem = [SideBarItem itemWithTitle:_NS("MY COMPUTER") identifier:@"mycomputer"];
225     SideBarItem *devicesItem = [SideBarItem itemWithTitle:_NS("DEVICES") identifier:@"devices"];
226     SideBarItem *lanItem = [SideBarItem itemWithTitle:_NS("LOCAL NETWORK") identifier:@"localnetwork"];
227     SideBarItem *internetItem = [SideBarItem itemWithTitle:_NS("INTERNET") identifier:@"internet"];
228
229     /* SD subnodes, inspired by the Qt4 intf */
230     char **ppsz_longnames;
231     int *p_categories;
232     char **ppsz_names = vlc_sd_GetNames(pl_Get(VLCIntf), &ppsz_longnames, &p_categories);
233     if (!ppsz_names)
234         msg_Err(VLCIntf, "no sd item found"); //TODO
235     char **ppsz_name = ppsz_names, **ppsz_longname = ppsz_longnames;
236     int *p_category = p_categories;
237     NSMutableArray *internetItems = [[NSMutableArray alloc] init];
238     NSMutableArray *devicesItems = [[NSMutableArray alloc] init];
239     NSMutableArray *lanItems = [[NSMutableArray alloc] init];
240     NSMutableArray *mycompItems = [[NSMutableArray alloc] init];
241     NSString *o_identifier;
242     for (; *ppsz_name; ppsz_name++, ppsz_longname++, p_category++) {
243         o_identifier = [NSString stringWithCString: *ppsz_name encoding: NSUTF8StringEncoding];
244         switch (*p_category) {
245             case SD_CAT_INTERNET:
246                     [internetItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
247                     if (!strncmp(*ppsz_name, "podcast", 7))
248                         [[internetItems lastObject] setIcon: [NSImage imageNamed:@"sidebar-podcast"]];
249                     else
250                         [[internetItems lastObject] setIcon: [NSImage imageNamed:@"NSApplicationIcon"]];
251                     [[internetItems lastObject] setSdtype: SD_CAT_INTERNET];
252                     [[internetItems lastObject] setUntranslatedTitle: [NSString stringWithUTF8String: *ppsz_longname]];
253                 break;
254             case SD_CAT_DEVICES:
255                     [devicesItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
256                     [[devicesItems lastObject] setIcon: [NSImage imageNamed:@"NSApplicationIcon"]];
257                     [[devicesItems lastObject] setSdtype: SD_CAT_DEVICES];
258                     [[devicesItems lastObject] setUntranslatedTitle: [NSString stringWithUTF8String: *ppsz_longname]];
259                 break;
260             case SD_CAT_LAN:
261                     [lanItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
262                     [[lanItems lastObject] setIcon: [NSImage imageNamed:@"sidebar-local"]];
263                     [[lanItems lastObject] setSdtype: SD_CAT_LAN];
264                     [[lanItems lastObject] setUntranslatedTitle: [NSString stringWithUTF8String: *ppsz_longname]];
265                 break;
266             case SD_CAT_MYCOMPUTER:
267                     [mycompItems addObject: [SideBarItem itemWithTitle: _NS(*ppsz_longname) identifier: o_identifier]];
268                     if (!strncmp(*ppsz_name, "video_dir", 9))
269                         [[mycompItems lastObject] setIcon: [NSImage imageNamed:@"sidebar-movie"]];
270                     else if (!strncmp(*ppsz_name, "audio_dir", 9))
271                         [[mycompItems lastObject] setIcon: [NSImage imageNamed:@"sidebar-music"]];
272                     else if (!strncmp(*ppsz_name, "picture_dir", 11))
273                         [[mycompItems lastObject] setIcon: [NSImage imageNamed:@"sidebar-pictures"]];
274                     else
275                         [[mycompItems lastObject] setIcon: [NSImage imageNamed:@"NSApplicationIcon"]];
276                     [[mycompItems lastObject] setUntranslatedTitle: [NSString stringWithUTF8String: *ppsz_longname]];
277                     [[mycompItems lastObject] setSdtype: SD_CAT_MYCOMPUTER];
278                 break;
279             default:
280                 msg_Warn(VLCIntf, "unknown SD type found, skipping (%s)", *ppsz_name);
281                 break;
282         }
283
284         free(*ppsz_name);
285         free(*ppsz_longname);
286     }
287     [mycompItem setChildren: [NSArray arrayWithArray: mycompItems]];
288     [devicesItem setChildren: [NSArray arrayWithArray: devicesItems]];
289     [lanItem setChildren: [NSArray arrayWithArray: lanItems]];
290     [internetItem setChildren: [NSArray arrayWithArray: internetItems]];
291     [mycompItems release];
292     [devicesItems release];
293     [lanItems release];
294     [internetItems release];
295     free(ppsz_names);
296     free(ppsz_longnames);
297     free(p_categories);
298
299     [libraryItem setChildren: [NSArray arrayWithObjects: playlistItem, medialibraryItem, nil]];
300     [o_sidebaritems addObject: libraryItem];
301     if ([mycompItem hasChildren])
302         [o_sidebaritems addObject: mycompItem];
303     if ([devicesItem hasChildren])
304         [o_sidebaritems addObject: devicesItem];
305     if ([lanItem hasChildren])
306         [o_sidebaritems addObject: lanItem];
307     if ([internetItem hasChildren])
308         [o_sidebaritems addObject: internetItem];
309
310     [o_sidebar_view reloadData];
311     [o_sidebar_view selectRowIndexes:[NSIndexSet indexSetWithIndex:1] byExtendingSelection:NO];
312     [o_sidebar_view setDropItem:playlistItem dropChildIndex:NSOutlineViewDropOnItemIndex];
313     [o_sidebar_view registerForDraggedTypes:[NSArray arrayWithObjects: NSFilenamesPboardType, @"VLCPlaylistItemPboardType", nil]];
314
315     [o_sidebar_view setAutosaveName:@"mainwindow-sidebar"];
316     [(PXSourceList *)o_sidebar_view setDataSource:self];
317     [o_sidebar_view setDelegate:self];
318     [o_sidebar_view setAutosaveExpandedItems:YES];
319
320     [o_sidebar_view expandItem: libraryItem expandChildren: YES];
321
322     /* make sure we display the desired default appearance when VLC launches for the first time */
323     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
324     if (![defaults objectForKey:@"VLCFirstRun"]) {
325         [defaults setObject:[NSDate date] forKey:@"VLCFirstRun"];
326
327         NSUInteger i_sidebaritem_count = [o_sidebaritems count];
328         for (NSUInteger x = 0; x < i_sidebaritem_count; x++)
329             [o_sidebar_view expandItem: [o_sidebaritems objectAtIndex: x] expandChildren: YES];
330
331         [o_fspanel center];
332     }
333
334     if (b_dark_interface) {
335         [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(windowResizedOrMoved:) name: NSWindowDidResizeNotification object: nil];
336         [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(windowResizedOrMoved:) name: NSWindowDidMoveNotification object: nil];
337
338         [self setBackgroundColor: [NSColor clearColor]];
339         [self setOpaque: NO];
340         [self display];
341         [self setHasShadow:NO];
342         [self setHasShadow:YES];
343
344         NSRect winrect = [self frame];
345         CGFloat f_titleBarHeight = [o_titlebar_view frame].size.height;
346
347         [o_titlebar_view setFrame: NSMakeRect(0, winrect.size.height - f_titleBarHeight,
348                                               winrect.size.width, f_titleBarHeight)];
349         [[self contentView] addSubview: o_titlebar_view positioned: NSWindowAbove relativeTo: o_split_view];
350
351         if (winrect.size.height > 100) {
352             [self setFrame: winrect display:YES animate:YES];
353             previousSavedFrame = winrect;
354         }
355
356         winrect = [o_split_view frame];
357         winrect.size.height = winrect.size.height - f_titleBarHeight;
358         [o_split_view setFrame: winrect];
359         [o_video_view setFrame: winrect];
360
361         o_color_backdrop = [[VLCColorView alloc] initWithFrame: [o_split_view frame]];
362         [[self contentView] addSubview: o_color_backdrop positioned: NSWindowBelow relativeTo: o_split_view];
363         [o_color_backdrop setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable];
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(mainSplitViewDidResizeSubviews:) name: NSSplitViewDidResizeSubviewsNotification 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     // hasActiveVideo is defined for VLCVideoWindowCommon and subclasses
538     if ([obj respondsToSelector:@selector(hasActiveVideo)] && [obj hasActiveVideo]) {
539         if ([[VLCMain sharedInstance] activeVideoPlayback])
540             [[VLCCoreInteraction sharedInstance] stop];
541     }
542 }
543
544 - (void)someWindowWillMiniaturize:(NSNotification *)notification
545 {
546     if (config_GetInt(VLCIntf, "macosx-pause-minimized")) {
547         id obj = [notification object];
548
549         if ([obj class] == [VLCVideoWindowCommon class] || [obj class] == [VLCDetachedVideoWindow class] || ([obj class] == [VLCMainWindow class] && !b_nonembedded)) {
550             if ([[VLCMain sharedInstance] activeVideoPlayback])
551                 [[VLCCoreInteraction sharedInstance] pause];
552         }
553     }
554 }
555
556 #pragma mark -
557 #pragma mark Update interface and respond to foreign events
558 - (void)showDropZone
559 {
560     b_dropzone_active = YES;
561     [o_right_split_view addSubview: o_dropzone_view positioned:NSWindowAbove relativeTo:o_playlist_table];
562     [o_dropzone_view setFrame: [o_playlist_table frame]];
563     [[o_playlist_table animator] setHidden:YES];
564 }
565
566 - (void)hideDropZone
567 {
568     b_dropzone_active = NO;
569     [o_dropzone_view removeFromSuperview];
570     [[o_playlist_table animator] setHidden: NO];
571 }
572
573 - (void)hideSplitView
574 {
575     NSRect winrect = [self frame];
576     i_lastSplitViewHeight = [o_split_view frame].size.height;
577     winrect.size.height = winrect.size.height - i_lastSplitViewHeight;
578     winrect.origin.y = winrect.origin.y + i_lastSplitViewHeight;
579     [self setFrame: winrect display: YES animate: YES];
580     [self performSelector:@selector(hideDropZone) withObject:nil afterDelay:0.1];
581     if (b_dark_interface) {
582         [self setContentMinSize: NSMakeSize(604., [[o_controls_bar bottomBarView] frame].size.height + [o_titlebar_view frame].size.height)];
583         [self setContentMaxSize: NSMakeSize(FLT_MAX, [[o_controls_bar bottomBarView] frame].size.height + [o_titlebar_view frame].size.height)];
584     } else {
585         [self setContentMinSize: NSMakeSize(604., [[o_controls_bar bottomBarView] frame].size.height)];
586         [self setContentMaxSize: NSMakeSize(FLT_MAX, [[o_controls_bar bottomBarView] frame].size.height)];
587     }
588
589     b_splitview_removed = YES;
590 }
591
592 - (void)showSplitView
593 {
594     [self updateWindow];
595     if (b_dark_interface)
596         [self setContentMinSize:NSMakeSize(604., 288. + [o_titlebar_view frame].size.height)];
597     else
598         [self setContentMinSize:NSMakeSize(604., 288.)];
599     [self setContentMaxSize: NSMakeSize(FLT_MAX, FLT_MAX)];
600
601     NSRect winrect;
602     winrect = [self frame];
603     winrect.size.height = winrect.size.height + i_lastSplitViewHeight;
604     winrect.origin.y = winrect.origin.y - i_lastSplitViewHeight;
605     [self setFrame: winrect display: YES animate: YES];
606
607     [self performSelector:@selector(resizePlaylistAfterCollapse) withObject: nil afterDelay:0.75];
608
609     b_splitview_removed = NO;
610 }
611
612 - (void)updateTimeSlider
613 {
614     [o_controls_bar updateTimeSlider];
615     [o_fspanel updatePositionAndTime];
616
617     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(updateTimeSlider)];
618 }
619
620 - (void)updateName
621 {
622     input_thread_t * p_input;
623     p_input = pl_CurrentInput(VLCIntf);
624     if (p_input) {
625         NSString *aString;
626
627         if (!config_GetPsz(VLCIntf, "video-title")) {
628             char *format = var_InheritString(VLCIntf, "input-title-format");
629             char *formated = str_format_meta(pl_Get(VLCIntf), format);
630             free(format);
631             aString = [NSString stringWithUTF8String:formated];
632             free(formated);
633         } else
634             aString = [NSString stringWithUTF8String:config_GetPsz(VLCIntf, "video-title")];
635
636         char *uri = input_item_GetURI(input_GetItem(p_input));
637
638         NSURL * o_url = [NSURL URLWithString: [NSString stringWithUTF8String: uri]];
639         if ([o_url isFileURL]) {
640             [self setRepresentedURL: o_url];
641             [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
642                 [o_window setRepresentedURL:o_url];
643             }];
644         } else {
645             [self setRepresentedURL: nil];
646             [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
647                 [o_window setRepresentedURL:nil];
648             }];
649         }
650         free(uri);
651
652         if ([aString isEqualToString:@""]) {
653             if ([o_url isFileURL])
654                 aString = [[NSFileManager defaultManager] displayNameAtPath: [o_url path]];
655             else
656                 aString = [o_url absoluteString];
657         }
658
659         if ([aString length] > 0) {
660             [self setTitle: aString];
661             [[[VLCMain sharedInstance] voutController] updateWindowsUsingBlock:^(VLCVideoWindowCommon *o_window) {
662                 [o_window setTitle:aString];
663             }];
664
665             [o_fspanel setStreamTitle: aString];
666         } else {
667             [self setTitle: _NS("VLC media player")];
668             [self setRepresentedURL: nil];
669         }
670
671         vlc_object_release(p_input);
672     } else {
673         [self setTitle: _NS("VLC media player")];
674         [self setRepresentedURL: nil];
675     }
676 }
677
678 - (void)updateWindow
679 {
680     [o_controls_bar updateControls];
681     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(updateControls)];
682
683     bool b_seekable = false;
684
685     playlist_t * p_playlist = pl_Get(VLCIntf);
686     input_thread_t * p_input = playlist_CurrentInput(p_playlist);
687     if (p_input) {
688         /* seekable streams */
689         b_seekable = var_GetBool(p_input, "can-seek");
690
691         vlc_object_release(p_input);
692     }
693
694     [self updateTimeSlider];
695     if ([o_fspanel respondsToSelector:@selector(setSeekable:)])
696         [o_fspanel setSeekable: b_seekable];
697
698     PL_LOCK;
699     if ([[[VLCMain sharedInstance] playlist] currentPlaylistRoot] != p_playlist->p_local_category || p_playlist->p_local_category->i_children > 0)
700         [self hideDropZone];
701     else
702         [self showDropZone];
703     PL_UNLOCK;
704     [o_sidebar_view setNeedsDisplay:YES];
705 }
706
707 - (void)setPause
708 {
709     [o_controls_bar setPause];
710     [o_fspanel setPause];
711
712     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(setPause)];
713 }
714
715 - (void)setPlay
716 {
717     [o_controls_bar setPlay];
718     [o_fspanel setPlay];
719
720     [[[VLCMain sharedInstance] voutController] updateWindowsControlsBarWithSelector:@selector(setPlay)];
721
722 }
723
724 - (void)updateVolumeSlider
725 {
726     [[self controlsBar] updateVolumeSlider];
727     [o_fspanel setVolumeLevel: [[VLCCoreInteraction sharedInstance] volume]];
728 }
729
730 #pragma mark -
731 #pragma mark Video Output handling
732
733 - (void)setVideoplayEnabled
734 {
735     BOOL b_videoPlayback = [[VLCMain sharedInstance] activeVideoPlayback];
736
737     if (b_videoPlayback) {
738         if (!b_fullscreen)
739             frameBeforePlayback = [self frame];
740     } else {
741         if (!b_nonembedded && !b_fullscreen && frameBeforePlayback.size.width > 0 && frameBeforePlayback.size.height > 0)
742             [[self animator] setFrame:frameBeforePlayback display:YES];
743
744         // update fs button to reflect state for next startup
745         if (var_InheritBool(pl_Get(VLCIntf), "fullscreen")) {
746             [o_controls_bar setFullscreenState:YES];
747         }
748
749         [self makeFirstResponder: nil];
750         [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: NSNormalWindowLevel];
751
752         // restore alpha value to 1 for the case that macosx-opaqueness is set to < 1
753         [self setAlphaValue:1.0];
754     }
755
756     if (b_nativeFullscreenMode) {
757         if ([self hasActiveVideo] && [self fullscreen]) {
758             [[o_controls_bar bottomBarView] setHidden: b_videoPlayback];
759             [o_fspanel setActive: nil];
760         } else {
761             [[o_controls_bar bottomBarView] setHidden: NO];
762             [o_fspanel setNonActive: nil];
763         }
764     }
765 }
766
767 #pragma mark -
768 #pragma mark Lion native fullscreen handling
769 - (void)windowWillEnterFullScreen:(NSNotification *)notification
770 {
771     [super windowWillEnterFullScreen:notification];
772
773     // update split view frame after removing title bar
774     [o_split_view setFrame: [o_video_view frame]];
775 }
776
777 - (void)windowWillExitFullScreen:(NSNotification *)notification
778 {
779     [super windowWillExitFullScreen: notification];
780
781     // update split view frame after readding title bar
782     [o_split_view setFrame: [o_video_view frame]];
783 }
784 #pragma mark -
785 #pragma mark Fullscreen support
786
787 - (void)showFullscreenController
788 {
789
790     id currentWindow = [NSApp keyWindow];
791     if ([currentWindow respondsToSelector:@selector(hasActiveVideo)] && [currentWindow hasActiveVideo]) {
792         if ([currentWindow respondsToSelector:@selector(fullscreen)] && [currentWindow fullscreen]) {
793
794             if ([[VLCMain sharedInstance] activeVideoPlayback])
795                 [o_fspanel fadeIn];
796         }
797
798     }
799
800
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 split view delegate
839 - (CGFloat)splitView:(NSSplitView *)splitView constrainMaxCoordinate:(CGFloat)proposedMax ofSubviewAt:(NSInteger)dividerIndex
840 {
841     if (dividerIndex == 0)
842         return 300.;
843     else
844         return proposedMax;
845 }
846
847 - (CGFloat)splitView:(NSSplitView *)splitView constrainMinCoordinate:(CGFloat)proposedMin ofSubviewAt:(NSInteger)dividerIndex
848 {
849     if (dividerIndex == 0)
850         return 100.;
851     else
852         return proposedMin;
853 }
854
855 - (BOOL)splitView:(NSSplitView *)splitView canCollapseSubview:(NSView *)subview
856 {
857     return ([subview isEqual:o_left_split_view]);
858 }
859
860 - (BOOL)splitView:(NSSplitView *)splitView shouldAdjustSizeOfSubview:(NSView *)subview
861 {
862     if ([subview isEqual:o_left_split_view])
863         return NO;
864     return YES;
865 }
866
867 - (void)mainSplitViewDidResizeSubviews:(id)object
868 {
869     i_lastLeftSplitViewWidth = [o_left_split_view frame].size.width;
870     config_PutInt(VLCIntf, "macosx-show-sidebar", ![o_split_view isSubviewCollapsed:o_left_split_view]);
871     [[[VLCMain sharedInstance] mainMenu] updateSidebarMenuItem];
872 }
873
874 - (void)toggleLeftSubSplitView
875 {
876     [o_split_view adjustSubviews];
877     if ([o_split_view isSubviewCollapsed:o_left_split_view])
878         [o_split_view setPosition:i_lastLeftSplitViewWidth ofDividerAtIndex:0];
879     else
880         [o_split_view setPosition:[o_split_view minPossiblePositionOfDividerAtIndex:0] ofDividerAtIndex:0];
881     [[[VLCMain sharedInstance] mainMenu] updateSidebarMenuItem];
882 }
883
884 #pragma mark -
885 #pragma mark Side Bar Data handling
886 /* taken under BSD-new from the PXSourceList sample project, adapted for VLC */
887 - (NSUInteger)sourceList:(PXSourceList*)sourceList numberOfChildrenOfItem:(id)item
888 {
889     //Works the same way as the NSOutlineView data source: `nil` means a parent item
890     if (item==nil)
891         return [o_sidebaritems count];
892     else
893         return [[item children] count];
894 }
895
896
897 - (id)sourceList:(PXSourceList*)aSourceList child:(NSUInteger)index ofItem:(id)item
898 {
899     //Works the same way as the NSOutlineView data source: `nil` means a parent item
900     if (item==nil)
901         return [o_sidebaritems objectAtIndex:index];
902     else
903         return [[item children] objectAtIndex:index];
904 }
905
906
907 - (id)sourceList:(PXSourceList*)aSourceList objectValueForItem:(id)item
908 {
909     return [item title];
910 }
911
912 - (void)sourceList:(PXSourceList*)aSourceList setObjectValue:(id)object forItem:(id)item
913 {
914     [item setTitle:object];
915 }
916
917 - (BOOL)sourceList:(PXSourceList*)aSourceList isItemExpandable:(id)item
918 {
919     return [item hasChildren];
920 }
921
922
923 - (BOOL)sourceList:(PXSourceList*)aSourceList itemHasBadge:(id)item
924 {
925     if ([[item identifier] isEqualToString: @"playlist"] || [[item identifier] isEqualToString: @"medialibrary"])
926         return YES;
927
928     return [item hasBadge];
929 }
930
931
932 - (NSInteger)sourceList:(PXSourceList*)aSourceList badgeValueForItem:(id)item
933 {
934     playlist_t * p_playlist = pl_Get(VLCIntf);
935     NSInteger i_playlist_size;
936
937     if ([[item identifier] isEqualToString: @"playlist"]) {
938         PL_LOCK;
939         i_playlist_size = p_playlist->p_local_category->i_children;
940         PL_UNLOCK;
941
942         return i_playlist_size;
943     }
944     if ([[item identifier] isEqualToString: @"medialibrary"]) {
945         PL_LOCK;
946         i_playlist_size = p_playlist->p_ml_category->i_children;
947         PL_UNLOCK;
948
949         return i_playlist_size;
950     }
951
952     return [item badgeValue];
953 }
954
955
956 - (BOOL)sourceList:(PXSourceList*)aSourceList itemHasIcon:(id)item
957 {
958     return [item hasIcon];
959 }
960
961
962 - (NSImage*)sourceList:(PXSourceList*)aSourceList iconForItem:(id)item
963 {
964     return [item icon];
965 }
966
967 - (NSMenu*)sourceList:(PXSourceList*)aSourceList menuForEvent:(NSEvent*)theEvent item:(id)item
968 {
969     if ([theEvent type] == NSRightMouseDown || ([theEvent type] == NSLeftMouseDown && ([theEvent modifierFlags] & NSControlKeyMask) == NSControlKeyMask)) {
970         if (item != nil) {
971             NSMenu * m;
972             if ([item sdtype] > 0)
973             {
974                 m = [[NSMenu alloc] init];
975                 playlist_t * p_playlist = pl_Get(VLCIntf);
976                 BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [[item identifier] UTF8String]);
977                 if (!sd_loaded)
978                     [m addItemWithTitle:_NS("Enable") action:@selector(sdmenuhandler:) keyEquivalent:@""];
979                 else
980                     [m addItemWithTitle:_NS("Disable") action:@selector(sdmenuhandler:) keyEquivalent:@""];
981                 [[m itemAtIndex:0] setRepresentedObject: [item identifier]];
982             }
983             return [m autorelease];
984         }
985     }
986
987     return nil;
988 }
989
990 - (IBAction)sdmenuhandler:(id)sender
991 {
992     NSString * identifier = [sender representedObject];
993     if ([identifier length] > 0 && ![identifier isEqualToString:@"lua{sd='freebox',longname='Freebox TV'}"]) {
994         playlist_t * p_playlist = pl_Get(VLCIntf);
995         BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [identifier UTF8String]);
996
997         if (!sd_loaded)
998             playlist_ServicesDiscoveryAdd(p_playlist, [identifier UTF8String]);
999         else
1000             playlist_ServicesDiscoveryRemove(p_playlist, [identifier UTF8String]);
1001     }
1002 }
1003
1004 #pragma mark -
1005 #pragma mark Side Bar Delegate Methods
1006 /* taken under BSD-new from the PXSourceList sample project, adapted for VLC */
1007 - (BOOL)sourceList:(PXSourceList*)aSourceList isGroupAlwaysExpanded:(id)group
1008 {
1009     if ([[group identifier] isEqualToString:@"library"])
1010         return YES;
1011
1012     return NO;
1013 }
1014
1015 - (void)sourceListSelectionDidChange:(NSNotification *)notification
1016 {
1017     playlist_t * p_playlist = pl_Get(VLCIntf);
1018
1019     NSIndexSet *selectedIndexes = [o_sidebar_view selectedRowIndexes];
1020     id item = [o_sidebar_view itemAtRow:[selectedIndexes firstIndex]];
1021
1022
1023     //Set the label text to represent the new selection
1024     if ([item sdtype] > -1 && [[item identifier] length] > 0) {
1025         BOOL sd_loaded = playlist_IsServicesDiscoveryLoaded(p_playlist, [[item identifier] UTF8String]);
1026         if (!sd_loaded)
1027             playlist_ServicesDiscoveryAdd(p_playlist, [[item identifier] UTF8String]);
1028     }
1029
1030     [o_chosen_category_lbl setStringValue:[item title]];
1031
1032     if ([[item identifier] isEqualToString:@"playlist"]) {
1033         [[[VLCMain sharedInstance] playlist] setPlaylistRoot:p_playlist->p_local_category];
1034     } else if ([[item identifier] isEqualToString:@"medialibrary"]) {
1035         [[[VLCMain sharedInstance] playlist] setPlaylistRoot:p_playlist->p_ml_category];
1036     } else {
1037         playlist_item_t * pl_item;
1038         PL_LOCK;
1039         pl_item = playlist_ChildSearchName(p_playlist->p_root, [[item untranslatedTitle] UTF8String]);
1040         PL_UNLOCK;
1041         [[[VLCMain sharedInstance] playlist] setPlaylistRoot: pl_item];
1042     }
1043
1044     PL_LOCK;
1045     if ([[[VLCMain sharedInstance] playlist] currentPlaylistRoot] != p_playlist->p_local_category || p_playlist->p_local_category->i_children > 0)
1046         [self hideDropZone];
1047     else
1048         [self showDropZone];
1049     PL_UNLOCK;
1050
1051     if ([[item identifier] isEqualToString:@"podcast{longname=\"Podcasts\"}"])
1052         [self showPodcastControls];
1053     else
1054         [self hidePodcastControls];
1055
1056     [[NSNotificationCenter defaultCenter] postNotificationName: @"VLCMediaKeySupportSettingChanged"
1057                                                         object: nil
1058                                                       userInfo: nil];
1059 }
1060
1061 - (NSDragOperation)sourceList:(PXSourceList *)aSourceList validateDrop:(id <NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
1062 {
1063     if ([[item identifier] isEqualToString:@"playlist"] || [[item identifier] isEqualToString:@"medialibrary"]) {
1064         NSPasteboard *o_pasteboard = [info draggingPasteboard];
1065         if ([[o_pasteboard types] containsObject: @"VLCPlaylistItemPboardType"] || [[o_pasteboard types] containsObject: NSFilenamesPboardType])
1066             return NSDragOperationGeneric;
1067     }
1068     return NSDragOperationNone;
1069 }
1070
1071 - (BOOL)sourceList:(PXSourceList *)aSourceList acceptDrop:(id <NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
1072 {
1073     NSPasteboard *o_pasteboard = [info draggingPasteboard];
1074
1075     playlist_t * p_playlist = pl_Get(VLCIntf);
1076     playlist_item_t *p_node;
1077
1078     if ([[item identifier] isEqualToString:@"playlist"])
1079         p_node = p_playlist->p_local_category;
1080     else
1081         p_node = p_playlist->p_ml_category;
1082
1083     if ([[o_pasteboard types] containsObject: NSFilenamesPboardType]) {
1084         NSArray *o_values = [[o_pasteboard propertyListForType: NSFilenamesPboardType] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
1085         NSUInteger count = [o_values count];
1086         NSMutableArray *o_array = [NSMutableArray arrayWithCapacity:count];
1087
1088         for(NSUInteger i = 0; i < count; i++) {
1089             NSDictionary *o_dic;
1090             char *psz_uri = vlc_path2uri([[o_values objectAtIndex:i] UTF8String], NULL);
1091             if (!psz_uri)
1092                 continue;
1093
1094             o_dic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:psz_uri encoding:NSUTF8StringEncoding] forKey:@"ITEM_URL"];
1095
1096             free(psz_uri);
1097
1098             [o_array addObject: o_dic];
1099         }
1100
1101         [[[VLCMain sharedInstance] playlist] appendNodeArray:o_array inNode: p_node atPos:-1 enqueue:YES];
1102         return YES;
1103     }
1104     else if ([[o_pasteboard types] containsObject: @"VLCPlaylistItemPboardType"]) {
1105         NSArray * array = [[[VLCMain sharedInstance] playlist] draggedItems];
1106
1107         NSUInteger count = [array count];
1108         playlist_item_t * p_item = NULL;
1109
1110         PL_LOCK;
1111         for(NSUInteger i = 0; i < count; i++) {
1112             p_item = [[array objectAtIndex:i] pointerValue];
1113             if (!p_item) continue;
1114             playlist_NodeAddCopy(p_playlist, p_item, p_node, PLAYLIST_END);
1115         }
1116         PL_UNLOCK;
1117
1118         return YES;
1119     }
1120     return NO;
1121 }
1122
1123 - (id)sourceList:(PXSourceList *)aSourceList persistentObjectForItem:(id)item
1124 {
1125     return [item identifier];
1126 }
1127
1128 - (id)sourceList:(PXSourceList *)aSourceList itemForPersistentObject:(id)object
1129 {
1130     /* the following code assumes for sakes of simplicity that only the top level
1131      * items are allowed to have children */
1132
1133     NSArray * array = [NSArray arrayWithArray: o_sidebaritems]; // read-only arrays are noticebly faster
1134     NSUInteger count = [array count];
1135     if (count < 1)
1136         return nil;
1137
1138     for (NSUInteger x = 0; x < count; x++) {
1139         id item = [array objectAtIndex: x]; // save one objc selector call
1140         if ([[item identifier] isEqualToString:object])
1141             return item;
1142     }
1143
1144     return nil;
1145 }
1146
1147 #pragma mark -
1148 #pragma mark Podcast
1149
1150 - (IBAction)addPodcast:(id)sender
1151 {
1152     [NSApp beginSheet:o_podcast_subscribe_window modalForWindow:self modalDelegate:self didEndSelector:NULL contextInfo:nil];
1153 }
1154
1155 - (IBAction)addPodcastWindowAction:(id)sender
1156 {
1157     [o_podcast_subscribe_window orderOut:sender];
1158     [NSApp endSheet: o_podcast_subscribe_window];
1159
1160     if (sender == o_podcast_subscribe_ok_btn && [[o_podcast_subscribe_url_fld stringValue] length] > 0) {
1161         NSMutableString * podcastConf = [[NSMutableString alloc] init];
1162         if (config_GetPsz(VLCIntf, "podcast-urls") != NULL)
1163             [podcastConf appendFormat:@"%s|", config_GetPsz(VLCIntf, "podcast-urls")];
1164
1165         [podcastConf appendString: [o_podcast_subscribe_url_fld stringValue]];
1166         config_PutPsz(VLCIntf, "podcast-urls", [podcastConf UTF8String]);
1167
1168         vlc_object_t *p_obj = (vlc_object_t*)vlc_object_find_name(VLCIntf->p_libvlc, "podcast");
1169         if (p_obj) {
1170             var_SetString(p_obj, "podcast-urls", [podcastConf UTF8String]);
1171             vlc_object_release(p_obj);
1172         }
1173         [podcastConf release];
1174     }
1175 }
1176
1177 - (IBAction)removePodcast:(id)sender
1178 {
1179     if (config_GetPsz(VLCIntf, "podcast-urls") != NULL) {
1180         [o_podcast_unsubscribe_pop removeAllItems];
1181         [o_podcast_unsubscribe_pop addItemsWithTitles:[[NSString stringWithUTF8String:config_GetPsz(VLCIntf, "podcast-urls")] componentsSeparatedByString:@"|"]];
1182         [NSApp beginSheet:o_podcast_unsubscribe_window modalForWindow:self modalDelegate:self didEndSelector:NULL contextInfo:nil];
1183     }
1184 }
1185
1186 - (IBAction)removePodcastWindowAction:(id)sender
1187 {
1188     [o_podcast_unsubscribe_window orderOut:sender];
1189     [NSApp endSheet: o_podcast_unsubscribe_window];
1190
1191     if (sender == o_podcast_unsubscribe_ok_btn) {
1192         NSMutableArray * urls = [[NSMutableArray alloc] initWithArray:[[NSString stringWithUTF8String:config_GetPsz(VLCIntf, "podcast-urls")] componentsSeparatedByString:@"|"]];
1193         [urls removeObjectAtIndex: [o_podcast_unsubscribe_pop indexOfSelectedItem]];
1194         config_PutPsz(VLCIntf, "podcast-urls", [[urls componentsJoinedByString:@"|"] UTF8String]);
1195         [urls release];
1196
1197         vlc_object_t *p_obj = (vlc_object_t*)vlc_object_find_name(VLCIntf->p_libvlc, "podcast");
1198         if (p_obj) {
1199             var_SetString(p_obj, "podcast-urls", config_GetPsz(VLCIntf, "podcast-urls"));
1200             vlc_object_release(p_obj);
1201         }
1202
1203         /* reload the podcast module, since it won't update its list when removing podcasts */
1204         playlist_t * p_playlist = pl_Get(VLCIntf);
1205         if (playlist_IsServicesDiscoveryLoaded(p_playlist, "podcast{longname=\"Podcasts\"}")) {
1206             playlist_ServicesDiscoveryRemove(p_playlist, "podcast{longname=\"Podcasts\"}");
1207             playlist_ServicesDiscoveryAdd(p_playlist, "podcast{longname=\"Podcasts\"}");
1208             [o_playlist_table reloadData];
1209         }
1210
1211     }
1212 }
1213
1214 - (void)showPodcastControls
1215 {
1216     NSRect podcastViewDimensions = [o_podcast_view frame];
1217     NSRect rightSplitRect = [o_right_split_view frame];
1218     NSRect playlistTableRect = [o_playlist_table frame];
1219
1220     podcastViewDimensions.size.width = rightSplitRect.size.width;
1221     podcastViewDimensions.origin.x = podcastViewDimensions.origin.y = .0;
1222     [o_podcast_view setFrame:podcastViewDimensions];
1223
1224     playlistTableRect.origin.y = playlistTableRect.origin.y + podcastViewDimensions.size.height;
1225     playlistTableRect.size.height = playlistTableRect.size.height - podcastViewDimensions.size.height;
1226     [o_playlist_table setFrame:playlistTableRect];
1227     [o_playlist_table setNeedsDisplay:YES];
1228
1229     [o_right_split_view addSubview: o_podcast_view positioned: NSWindowAbove relativeTo: o_right_split_view];
1230     b_podcastView_displayed = YES;
1231 }
1232
1233 - (void)hidePodcastControls
1234 {
1235     if (b_podcastView_displayed) {
1236         NSRect podcastViewDimensions = [o_podcast_view frame];
1237         NSRect playlistTableRect = [o_playlist_table frame];
1238
1239         playlistTableRect.origin.y = playlistTableRect.origin.y - podcastViewDimensions.size.height;
1240         playlistTableRect.size.height = playlistTableRect.size.height + podcastViewDimensions.size.height;
1241
1242         [o_podcast_view removeFromSuperviewWithoutNeedingDisplay];
1243         [o_playlist_table setFrame: playlistTableRect];
1244         b_podcastView_displayed = NO;
1245     }
1246 }
1247
1248 @end
1249
1250 @implementation VLCDetachedVideoWindow
1251
1252 - (void)awakeFromNib
1253 {
1254     // sets lion fullscreen behaviour
1255     [super awakeFromNib];
1256     [self setAcceptsMouseMovedEvents: YES];
1257
1258     if (b_dark_interface) {
1259         [self setBackgroundColor: [NSColor clearColor]];
1260
1261         [self setOpaque: NO];
1262         [self display];
1263         [self setHasShadow:NO];
1264         [self setHasShadow:YES];
1265
1266         NSRect winrect = [self frame];
1267         CGFloat f_titleBarHeight = [o_titlebar_view frame].size.height;
1268
1269         [self setTitle: _NS("VLC media player")];
1270         [o_titlebar_view setFrame: NSMakeRect(0, winrect.size.height - f_titleBarHeight, winrect.size.width, f_titleBarHeight)];
1271         [[self contentView] addSubview: o_titlebar_view positioned: NSWindowAbove relativeTo: nil];
1272
1273     } else {
1274         [self setBackgroundColor: [NSColor blackColor]];
1275     }
1276
1277     NSRect videoViewRect = [[self contentView] bounds];
1278     if (b_dark_interface)
1279         videoViewRect.size.height -= [o_titlebar_view frame].size.height;
1280     CGFloat f_bottomBarHeight = [[[self controlsBar] bottomBarView] frame].size.height;
1281     videoViewRect.size.height -= f_bottomBarHeight;
1282     videoViewRect.origin.y = f_bottomBarHeight;
1283     [o_video_view setFrame: videoViewRect];
1284
1285     if (b_dark_interface) {
1286         o_color_backdrop = [[VLCColorView alloc] initWithFrame: [o_video_view frame]];
1287         [[self contentView] addSubview: o_color_backdrop positioned: NSWindowBelow relativeTo: o_video_view];
1288         [o_color_backdrop setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable];
1289
1290         [self setContentMinSize: NSMakeSize(363., f_min_video_height + [[[self controlsBar] bottomBarView] frame].size.height + [o_titlebar_view frame].size.height)];
1291     } else {
1292         [self setContentMinSize: NSMakeSize(363., f_min_video_height + [[[self controlsBar] bottomBarView] frame].size.height)];
1293     }
1294 }
1295
1296 - (void)dealloc
1297 {
1298     if (b_dark_interface)
1299         [o_color_backdrop release];
1300
1301     [super dealloc];
1302 }
1303
1304 @end