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