]> git.sesse.net Git - vlc/blob - modules/gui/macosx/Windows.m
macosx: workaround for bug where window will vanish if minimized in float-on-top...
[vlc] / modules / gui / macosx / Windows.m
1 /*****************************************************************************
2  * Windows.m: MacOS X interface module
3  *****************************************************************************
4  * Copyright (C) 2012-2013 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Felix Paul Kühne <fkuehne -at- videolan -dot- org>
8  *          David Fuhrmann <david dot fuhrmann at googlemail dot com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 #import "Windows.h"
26 #import "intf.h"
27 #import "CoreInteraction.h"
28 #import "ControlsBar.h"
29 #import "VideoView.h"
30
31 /*****************************************************************************
32  * VLCWindow
33  *
34  *  Missing extension to NSWindow
35  *****************************************************************************/
36
37 @implementation VLCWindow
38
39 @synthesize hasActiveVideo=b_has_active_video;
40 @synthesize fullscreen=b_fullscreen;
41
42 - (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)styleMask
43                   backing:(NSBackingStoreType)backingType defer:(BOOL)flag
44 {
45     self = [super initWithContentRect:contentRect styleMask:styleMask backing:backingType defer:flag];
46     if (self) {
47         /* we don't want this window to be restored on relaunch */
48         if (!OSX_SNOW_LEOPARD)
49             [self setRestorable:NO];
50     }
51     return self;
52 }
53
54 - (void)setCanBecomeKeyWindow: (BOOL)canBecomeKey
55 {
56     b_isset_canBecomeKeyWindow = YES;
57     b_canBecomeKeyWindow = canBecomeKey;
58 }
59
60 - (BOOL)canBecomeKeyWindow
61 {
62     if (b_isset_canBecomeKeyWindow)
63         return b_canBecomeKeyWindow;
64
65     return [super canBecomeKeyWindow];
66 }
67
68 - (void)setCanBecomeMainWindow: (BOOL)canBecomeMain
69 {
70     b_isset_canBecomeMainWindow = YES;
71     b_canBecomeMainWindow = canBecomeMain;
72 }
73
74 - (BOOL)canBecomeMainWindow
75 {
76     if (b_isset_canBecomeMainWindow)
77         return b_canBecomeMainWindow;
78
79     return [super canBecomeMainWindow];
80 }
81
82 - (void)closeAndAnimate: (BOOL)animate
83 {
84     NSInvocation *invoc;
85
86     if (!animate) {
87         [super close];
88         return;
89     }
90
91     // TODO this callback stuff does not work and is not needed
92     invoc = [[[NSInvocation alloc] init] autorelease];
93     [invoc setSelector:@selector(close)];
94     [invoc setTarget: self];
95
96     if (![self isVisible] || [self alphaValue] == 0.0) {
97         [super close];
98         return;
99     }
100
101     [self orderOut: self animate: YES callback: invoc];
102 }
103
104 - (void)orderOut: (id)sender animate: (BOOL)animate
105 {
106     NSInvocation *invoc = [[[NSInvocation alloc] init] autorelease];
107     [invoc setSelector:@selector(orderOut:)];
108     [invoc setTarget: self];
109     [invoc setArgument: sender atIndex: 2];
110     [self orderOut: sender animate: animate callback: invoc];
111 }
112
113 - (void)orderOut: (id)sender animate: (BOOL)animate callback:(NSInvocation *)callback
114 {
115     NSViewAnimation *anim;
116     NSViewAnimation *current_anim;
117     NSMutableDictionary *dict;
118
119     if (!animate) {
120         [self orderOut: sender];
121         return;
122     }
123
124     dict = [[NSMutableDictionary alloc] initWithCapacity:2];
125
126     [dict setObject:self forKey:NSViewAnimationTargetKey];
127
128     [dict setObject:NSViewAnimationFadeOutEffect forKey:NSViewAnimationEffectKey];
129     anim = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict]];
130     [dict release];
131
132     [anim setAnimationBlockingMode:NSAnimationNonblocking];
133     [anim setDuration:0.9];
134     [anim setFrameRate:30];
135     [anim setUserInfo:callback];
136     [anim setDelegate:self];
137
138     @synchronized(self) {
139         current_anim = self->o_current_animation;
140
141         if ([[[current_anim viewAnimations] objectAtIndex:0] objectForKey: NSViewAnimationEffectKey] == NSViewAnimationFadeOutEffect && [current_anim isAnimating]) {
142             [anim release];
143         } else {
144             if (current_anim) {
145                 [current_anim stopAnimation];
146                 [anim setCurrentProgress:1.0 - [current_anim currentProgress]];
147                 [current_anim release];
148             }
149             else
150                 [anim setCurrentProgress:1.0 - [self alphaValue]];
151             self->o_current_animation = anim;
152             [anim startAnimation];
153         }
154     }
155 }
156
157 - (void)orderFront: (id)sender animate: (BOOL)animate
158 {
159     NSViewAnimation *anim;
160     NSViewAnimation *current_anim;
161     NSMutableDictionary *dict;
162
163     if (!animate) {
164         [super orderFront: sender];
165         [self setAlphaValue: 1.0];
166         return;
167     }
168
169     if (![self isVisible]) {
170         [self setAlphaValue: 0.0];
171         [super orderFront: sender];
172     }
173     else if ([self alphaValue] == 1.0) {
174         [super orderFront: self];
175         return;
176     }
177
178     dict = [[NSMutableDictionary alloc] initWithCapacity:2];
179
180     [dict setObject:self forKey:NSViewAnimationTargetKey];
181
182     [dict setObject:NSViewAnimationFadeInEffect forKey:NSViewAnimationEffectKey];
183     anim = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict]];
184     [dict release];
185
186     [anim setAnimationBlockingMode:NSAnimationNonblocking];
187     [anim setDuration:0.5];
188     [anim setFrameRate:30];
189     [anim setDelegate:self];
190
191     @synchronized(self) {
192         current_anim = self->o_current_animation;
193
194         if ([[[current_anim viewAnimations] objectAtIndex:0] objectForKey: NSViewAnimationEffectKey] == NSViewAnimationFadeInEffect && [current_anim isAnimating]) {
195             [anim release];
196         } else {
197             if (current_anim) {
198                 [current_anim stopAnimation];
199                 [anim setCurrentProgress:1.0 - [current_anim currentProgress]];
200                 [current_anim release];
201             }
202             else
203                 [anim setCurrentProgress:[self alphaValue]];
204             self->o_current_animation = anim;
205             [self orderFront: sender];
206             [anim startAnimation];
207         }
208     }
209 }
210
211 - (void)animationDidEnd:(NSAnimation*)anim
212 {
213     if ([self alphaValue] <= 0.0) {
214         NSInvocation * invoc;
215         [super orderOut: nil];
216         [self setAlphaValue: 1.0];
217         if ((invoc = [anim userInfo])) {
218             [invoc invoke];
219         }
220     }
221 }
222
223 - (VLCVoutView *)videoView
224 {
225     if ([[self contentView] class] == [VLCVoutView class])
226         return (VLCVoutView *)[self contentView];
227
228     return nil;
229 }
230
231
232 @end
233
234
235 /*****************************************************************************
236  * VLCVideoWindowCommon
237  *
238  *  Common code for main window, detached window and extra video window
239  *****************************************************************************/
240
241 @interface VLCVideoWindowCommon (Internal)
242 - (void)customZoom:(id)sender;
243 - (void)hasBecomeFullscreen;
244 - (void)leaveFullscreenAndFadeOut:(BOOL)fadeout;
245 - (void)hasEndedFullscreen;
246 @end
247
248 @implementation VLCVideoWindowCommon
249
250 @synthesize videoView=o_video_view;
251 @synthesize controlsBar=o_controls_bar;
252 @synthesize enteringFullscreenTransition=b_entering_fullscreen_transition;
253
254 #pragma mark -
255 #pragma mark Init
256
257 - (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)styleMask
258                   backing:(NSBackingStoreType)backingType defer:(BOOL)flag
259 {
260     b_dark_interface = config_GetInt(VLCIntf, "macosx-interfacestyle");
261
262     if (b_dark_interface) {
263         styleMask = NSBorderlessWindowMask;
264 #ifdef MAC_OS_X_VERSION_10_7
265         if (!OSX_SNOW_LEOPARD)
266             styleMask |= NSResizableWindowMask;
267 #endif
268     }
269
270     self = [super initWithContentRect:contentRect styleMask:styleMask
271                               backing:backingType defer:flag];
272
273     /* we want to be moveable regardless of our style */
274     [self setMovableByWindowBackground: YES];
275     [self setCanBecomeKeyWindow:YES];
276
277     o_temp_view = [[NSView alloc] init];
278     [o_temp_view setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable];
279
280     return self;
281 }
282
283 - (void)dealloc
284 {
285     [o_temp_view release];
286     [super dealloc];
287 }
288
289 - (void)awakeFromNib
290 {
291     BOOL b_nativeFullscreenMode = NO;
292 #ifdef MAC_OS_X_VERSION_10_7
293     if (!OSX_SNOW_LEOPARD)
294         b_nativeFullscreenMode = var_InheritBool(VLCIntf, "macosx-nativefullscreenmode");
295 #endif
296
297     if (b_nativeFullscreenMode) {
298         [self setCollectionBehavior: NSWindowCollectionBehaviorFullScreenPrimary];
299     } else {
300         [o_titlebar_view setFullscreenButtonHidden: YES];
301     }
302
303     [super awakeFromNib];
304 }
305
306 - (void)setTitle:(NSString *)title
307 {
308     if (!title || [title length] < 1)
309         return;
310
311     if (b_dark_interface && o_titlebar_view)
312         [o_titlebar_view setWindowTitle: title];
313
314     [super setTitle: title];
315 }
316
317 #pragma mark -
318 #pragma mark zoom / minimize / close
319
320 - (BOOL)validateMenuItem:(NSMenuItem *)menuItem
321 {
322     SEL s_menuAction = [menuItem action];
323
324     if ((s_menuAction == @selector(performClose:)) || (s_menuAction == @selector(performMiniaturize:)) || (s_menuAction == @selector(performZoom:)))
325         return YES;
326
327     return [super validateMenuItem:menuItem];
328 }
329
330 - (BOOL)windowShouldClose:(id)sender
331 {
332     return YES;
333 }
334
335 - (void)performClose:(id)sender
336 {
337     if (!([self styleMask] & NSTitledWindowMask)) {
338         [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowWillCloseNotification object:self];
339
340         [self close];
341     } else
342         [super performClose: sender];
343 }
344
345 - (void)performMiniaturize:(id)sender
346 {
347     if (!([self styleMask] & NSTitledWindowMask))
348         [self miniaturize: sender];
349     else
350         [super performMiniaturize: sender];
351 }
352
353 - (void)performZoom:(id)sender
354 {
355     if (!([self styleMask] & NSTitledWindowMask))
356         [self customZoom: sender];
357     else
358         [super performZoom: sender];
359 }
360
361 - (void)zoom:(id)sender
362 {
363     if (!([self styleMask] & NSTitledWindowMask))
364         [self customZoom: sender];
365     else
366         [super zoom: sender];
367 }
368
369 /**
370  * Given a proposed frame rectangle, return a modified version
371  * which will fit inside the screen.
372  *
373  * This method is based upon NSWindow.m, part of the GNUstep GUI Library, licensed under LGPLv2+.
374  *    Authors:  Scott Christley <scottc@net-community.com>, Venkat Ajjanagadde <venkat@ocbi.com>,
375  *              Felipe A. Rodriguez <far@ix.netcom.com>, Richard Frith-Macdonald <richard@brainstorm.co.uk>
376  *    Copyright (C) 1996 Free Software Foundation, Inc.
377  */
378 - (NSRect) customConstrainFrameRect: (NSRect)frameRect toScreen: (NSScreen*)screen
379 {
380     NSRect screenRect = [screen visibleFrame];
381     float difference;
382
383     /* Move top edge of the window inside the screen */
384     difference = NSMaxY (frameRect) - NSMaxY (screenRect);
385     if (difference > 0) {
386         frameRect.origin.y -= difference;
387     }
388
389     /* If the window is resizable, resize it (if needed) so that the
390      bottom edge is on the screen or can be on the screen when the user moves
391      the window */
392     difference = NSMaxY (screenRect) - NSMaxY (frameRect);
393     if (_styleMask & NSResizableWindowMask) {
394         float difference2;
395
396         difference2 = screenRect.origin.y - frameRect.origin.y;
397         difference2 -= difference;
398         // Take in account the space between the top of window and the top of the
399         // screen which can be used to move the bottom of the window on the screen
400         if (difference2 > 0) {
401             frameRect.size.height -= difference2;
402             frameRect.origin.y += difference2;
403         }
404
405         /* Ensure that resizing doesn't makewindow smaller than minimum */
406         difference2 = [self minSize].height - frameRect.size.height;
407         if (difference2 > 0) {
408             frameRect.size.height += difference2;
409             frameRect.origin.y -= difference2;
410         }
411     }
412
413     return frameRect;
414 }
415
416 #define DIST 3
417
418 /**
419  Zooms the receiver.   This method calls the delegate method
420  windowShouldZoom:toFrame: to determine if the window should
421  be allowed to zoom to full screen.
422  *
423  * This method is based upon NSWindow.m, part of the GNUstep GUI Library, licensed under LGPLv2+.
424  *    Authors:  Scott Christley <scottc@net-community.com>, Venkat Ajjanagadde <venkat@ocbi.com>,
425  *              Felipe A. Rodriguez <far@ix.netcom.com>, Richard Frith-Macdonald <richard@brainstorm.co.uk>
426  *    Copyright (C) 1996 Free Software Foundation, Inc.
427  */
428 - (void) customZoom: (id)sender
429 {
430     NSRect maxRect = [[self screen] visibleFrame];
431     NSRect currentFrame = [self frame];
432
433     if ([[self delegate] respondsToSelector: @selector(windowWillUseStandardFrame:defaultFrame:)]) {
434         maxRect = [[self delegate] windowWillUseStandardFrame: self defaultFrame: maxRect];
435     }
436
437     maxRect = [self customConstrainFrameRect: maxRect toScreen: [self screen]];
438
439     // Compare the new frame with the current one
440     if ((abs(NSMaxX(maxRect) - NSMaxX(currentFrame)) < DIST)
441         && (abs(NSMaxY(maxRect) - NSMaxY(currentFrame)) < DIST)
442         && (abs(NSMinX(maxRect) - NSMinX(currentFrame)) < DIST)
443         && (abs(NSMinY(maxRect) - NSMinY(currentFrame)) < DIST)) {
444         // Already in zoomed mode, reset user frame, if stored
445         if ([self frameAutosaveName] != nil) {
446             [self setFrame: previousSavedFrame display: YES animate: YES];
447             [self saveFrameUsingName: [self frameAutosaveName]];
448         }
449         return;
450     }
451
452     if ([self frameAutosaveName] != nil) {
453         [self saveFrameUsingName: [self frameAutosaveName]];
454         previousSavedFrame = [self frame];
455     }
456
457     [self setFrame: maxRect display: YES animate: YES];
458 }
459
460 #pragma mark -
461 #pragma mark Video window resizing logic
462
463 - (void)setWindowLevel:(NSInteger)i_state
464 {
465     if (var_InheritBool(VLCIntf, "video-wallpaper") || [self level] < NSNormalWindowLevel)
466         return;
467
468     if (!b_fullscreen && !b_entering_fullscreen_transition)
469         [self setLevel: i_state];
470
471     // save it for restore if window is currently minimized or in fullscreen
472     i_originalLevel = i_state;
473 }
474
475 - (NSRect)getWindowRectForProposedVideoViewSize:(NSSize)size
476 {
477     NSSize windowMinSize = [self minSize];
478     NSRect screenFrame = [[self screen] visibleFrame];
479
480     NSPoint topleftbase = NSMakePoint(0, [self frame].size.height);
481     NSPoint topleftscreen = [self convertBaseToScreen: topleftbase];
482
483     unsigned int i_width = size.width;
484     unsigned int i_height = size.height;
485     if (i_width < windowMinSize.width)
486         i_width = windowMinSize.width;
487     if (i_height < f_min_video_height)
488         i_height = f_min_video_height;
489
490     /* Calculate the window's new size */
491     NSRect new_frame;
492     new_frame.size.width = [self frame].size.width - [o_video_view frame].size.width + i_width;
493     new_frame.size.height = [self frame].size.height - [o_video_view frame].size.height + i_height;
494     new_frame.origin.x = topleftscreen.x;
495     new_frame.origin.y = topleftscreen.y - new_frame.size.height;
496
497     /* make sure the window doesn't exceed the screen size the window is on */
498     if (new_frame.size.width > screenFrame.size.width) {
499         new_frame.size.width = screenFrame.size.width;
500         new_frame.origin.x = screenFrame.origin.x;
501     }
502     if (new_frame.size.height > screenFrame.size.height) {
503         new_frame.size.height = screenFrame.size.height;
504         new_frame.origin.y = screenFrame.origin.y;
505     }
506     if (new_frame.origin.y < screenFrame.origin.y)
507         new_frame.origin.y = screenFrame.origin.y;
508
509     CGFloat right_screen_point = screenFrame.origin.x + screenFrame.size.width;
510     CGFloat right_window_point = new_frame.origin.x + new_frame.size.width;
511     if (right_window_point > right_screen_point)
512         new_frame.origin.x -= (right_window_point - right_screen_point);
513
514     return new_frame;
515 }
516
517 - (void)resizeWindow
518 {
519     if ([self fullscreen])
520         return;
521
522     NSRect window_rect = [self getWindowRectForProposedVideoViewSize:nativeVideoSize];
523     [[self animator] setFrame:window_rect display:YES];
524 }
525
526 - (void)setNativeVideoSize:(NSSize)size
527 {
528     nativeVideoSize = size;
529
530     if (var_InheritBool(VLCIntf, "macosx-video-autoresize") && !var_InheritBool(VLCIntf, "video-wallpaper"))
531         [self resizeWindow];
532 }
533
534 - (NSSize)windowWillResize:(NSWindow *)window toSize:(NSSize)proposedFrameSize
535 {
536     if (![[VLCMain sharedInstance] activeVideoPlayback] || nativeVideoSize.width == 0. || nativeVideoSize.height == 0. || window != self)
537         return proposedFrameSize;
538
539     // needed when entering lion fullscreen mode
540     if (b_entering_fullscreen_transition || [self fullscreen])
541         return proposedFrameSize;
542
543     if ([[VLCCoreInteraction sharedInstance] aspectRatioIsLocked]) {
544         NSRect videoWindowFrame = [self frame];
545         NSRect viewRect = [o_video_view convertRect:[o_video_view bounds] toView: nil];
546         NSRect contentRect = [self contentRectForFrameRect:videoWindowFrame];
547         float marginy = viewRect.origin.y + videoWindowFrame.size.height - contentRect.size.height;
548         float marginx = contentRect.size.width - viewRect.size.width;
549         if (o_titlebar_view && b_dark_interface)
550             marginy += [o_titlebar_view frame].size.height;
551
552         proposedFrameSize.height = (proposedFrameSize.width - marginx) * nativeVideoSize.height / nativeVideoSize.width + marginy;
553     }
554
555     return proposedFrameSize;
556 }
557
558 - (void)windowWillMiniaturize:(NSNotification *)notification
559 {
560     // Set level to normal as a workaround for Mavericks bug causing window
561     // to vanish from screen, see radar://15473716
562     i_originalLevel = [self level];
563     [self setLevel: NSNormalWindowLevel];
564 }
565
566 - (void)windowDidDeminiaturize:(NSNotification *)notification
567 {
568     [self setLevel: i_originalLevel];
569 }
570
571 #pragma mark -
572 #pragma mark Mouse cursor handling
573
574 //  NSTimer selectors require this function signature as per Apple's docs
575 - (void)hideMouseCursor:(NSTimer *)timer
576 {
577     [NSCursor setHiddenUntilMouseMoves: YES];
578 }
579
580 - (void)recreateHideMouseTimer
581 {
582     if (t_hide_mouse_timer != nil) {
583         [t_hide_mouse_timer invalidate];
584         [t_hide_mouse_timer release];
585     }
586
587     t_hide_mouse_timer = [NSTimer scheduledTimerWithTimeInterval:2
588                                                           target:self
589                                                         selector:@selector(hideMouseCursor:)
590                                                         userInfo:nil
591                                                          repeats:NO];
592     [t_hide_mouse_timer retain];
593 }
594
595 //  Called automatically if window's acceptsMouseMovedEvents property is true
596 - (void)mouseMoved:(NSEvent *)theEvent
597 {
598     if (b_fullscreen)
599         [self recreateHideMouseTimer];
600
601     [super mouseMoved: theEvent];
602 }
603
604 #pragma mark -
605 #pragma mark Lion native fullscreen handling
606
607 - (void)becomeKeyWindow
608 {
609     [super becomeKeyWindow];
610
611     // change fspanel state for the case when multiple windows are in fullscreen
612     if ([self hasActiveVideo] && [self fullscreen])
613         [[[VLCMainWindow sharedInstance] fsPanel] setActive:nil];
614     else
615         [[[VLCMainWindow sharedInstance] fsPanel] setNonActive:nil];
616 }
617
618 - (void)resignKeyWindow
619 {
620     [super resignKeyWindow];
621
622     [[[VLCMainWindow sharedInstance] fsPanel] setNonActive:nil];
623 }
624
625 - (void)windowWillEnterFullScreen:(NSNotification *)notification
626 {
627     // workaround, see #6668
628     [NSApp setPresentationOptions:(NSApplicationPresentationFullScreen | NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar)];
629
630     i_originalLevel = [self level];
631     // b_fullscreen and b_entering_fullscreen_transition must not be true yet
632     [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: NSNormalWindowLevel];
633     [self setLevel:NSNormalWindowLevel];
634
635     b_entering_fullscreen_transition = YES;
636
637     var_SetBool(pl_Get(VLCIntf), "fullscreen", true);
638
639     if ([self hasActiveVideo]) {
640         vout_thread_t *p_vout = getVoutForActiveWindow();
641         if (p_vout) {
642             var_SetBool(p_vout, "fullscreen", true);
643             vlc_object_release(p_vout);
644         }
645     }
646
647     if ([self hasActiveVideo])
648         [[VLCMainWindow sharedInstance] recreateHideMouseTimer];
649
650     if (b_dark_interface) {
651         [o_titlebar_view removeFromSuperviewWithoutNeedingDisplay];
652
653         NSRect winrect;
654         CGFloat f_titleBarHeight = [o_titlebar_view frame].size.height;
655         winrect = [self frame];
656
657         winrect.size.height = winrect.size.height - f_titleBarHeight;
658         [self setFrame: winrect display:NO animate:NO];
659     }
660
661     [o_video_view setFrame: [[self contentView] frame]];
662     if (![o_video_view isHidden]) {
663         [[o_controls_bar bottomBarView] setHidden: YES];
664     }
665     
666
667     [self setMovableByWindowBackground: NO];
668 }
669
670 - (void)windowDidEnterFullScreen:(NSNotification *)notification
671 {
672     // Indeed, we somehow can have an "inactive" fullscreen (but a visible window!).
673     // But this creates some problems when leaving fs over remote intfs, so activate app here.
674     [NSApp activateIgnoringOtherApps:YES];
675
676     [self setFullscreen: YES];
677     b_entering_fullscreen_transition = NO;
678
679     if ([self hasActiveVideo]) {
680         [[[VLCMainWindow sharedInstance] fsPanel] setVoutWasUpdated: self];
681         if (![o_video_view isHidden])
682             [[[VLCMainWindow sharedInstance] fsPanel] setActive: nil];
683     }
684
685     NSArray *subviews = [[self videoView] subviews];
686     NSUInteger count = [subviews count];
687
688     for (NSUInteger x = 0; x < count; x++) {
689         if ([[subviews objectAtIndex:x] respondsToSelector:@selector(reshape)])
690             [[subviews objectAtIndex:x] reshape];
691     }
692
693 }
694
695 - (void)windowWillExitFullScreen:(NSNotification *)notification
696 {
697     [self setFullscreen: NO];
698
699     var_SetBool(pl_Get(VLCIntf), "fullscreen", false);
700
701     if ([self hasActiveVideo]) {
702         vout_thread_t *p_vout = getVoutForActiveWindow();
703         if (p_vout) {
704             var_SetBool(p_vout, "fullscreen", false);
705             vlc_object_release(p_vout);
706         }
707     }
708
709     [NSCursor setHiddenUntilMouseMoves: NO];
710     [[[VLCMainWindow sharedInstance] fsPanel] setNonActive: nil];
711
712
713     if (b_dark_interface) {
714         NSRect winrect;
715         CGFloat f_titleBarHeight = [o_titlebar_view frame].size.height;
716
717         winrect = [o_video_view frame];
718         winrect.size.height -= f_titleBarHeight;
719         [o_video_view setFrame: winrect];
720
721         winrect = [self frame];
722         [o_titlebar_view setFrame: NSMakeRect(0, winrect.size.height - f_titleBarHeight,
723                                               winrect.size.width, f_titleBarHeight)];
724         [[self contentView] addSubview: o_titlebar_view];
725
726         winrect.size.height = winrect.size.height + f_titleBarHeight;
727         [self setFrame: winrect display:NO animate:NO];
728     }
729
730     NSRect videoViewFrame = [o_video_view frame];
731     videoViewFrame.origin.y += [o_controls_bar height];
732     videoViewFrame.size.height -= [o_controls_bar height];
733     [o_video_view setFrame: videoViewFrame];
734
735     if (![o_video_view isHidden]) {
736         [[o_controls_bar bottomBarView] setHidden: NO];
737     }
738
739     [self setMovableByWindowBackground: YES];
740 }
741
742 - (void)windowDidExitFullScreen:(NSNotification *)notification
743 {
744     [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: i_originalLevel];
745     [self setLevel:i_originalLevel];
746 }
747
748 #pragma mark -
749 #pragma mark Fullscreen Logic
750
751 - (void)enterFullscreen
752 {
753     NSMutableDictionary *dict1, *dict2;
754     NSScreen *screen;
755     NSRect screen_rect;
756     NSRect rect;
757     BOOL blackout_other_displays = var_InheritBool(VLCIntf, "macosx-black");
758
759     screen = [NSScreen screenWithDisplayID:(CGDirectDisplayID)var_InheritInteger(VLCIntf, "macosx-vdev")];
760
761     if (!screen) {
762         msg_Dbg(VLCIntf, "chosen screen isn't present, using current screen for fullscreen mode");
763         screen = [self screen];
764     }
765     if (!screen) {
766         msg_Dbg(VLCIntf, "Using deepest screen");
767         screen = [NSScreen deepestScreen];
768     }
769
770     screen_rect = [screen frame];
771
772     if (o_controls_bar)
773         [o_controls_bar setFullscreenState:YES];
774     [[[VLCMainWindow sharedInstance] controlsBar] setFullscreenState:YES];
775
776     [[VLCMainWindow sharedInstance] recreateHideMouseTimer];
777
778     if (blackout_other_displays)
779         [screen blackoutOtherScreens];
780
781     /* Make sure we don't see the window flashes in float-on-top mode */
782     i_originalLevel = [self level];
783     // b_fullscreen must not be true yet
784     [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: NSNormalWindowLevel];
785     [self setLevel:NSNormalWindowLevel];
786
787     /* Only create the o_fullscreen_window if we are not in the middle of the zooming animation */
788     if (!o_fullscreen_window) {
789         /* We can't change the styleMask of an already created NSWindow, so we create another window, and do eye catching stuff */
790
791         rect = [[o_video_view superview] convertRect: [o_video_view frame] toView: nil]; /* Convert to Window base coord */
792         rect.origin.x += [self frame].origin.x;
793         rect.origin.y += [self frame].origin.y;
794         o_fullscreen_window = [[VLCWindow alloc] initWithContentRect:rect styleMask: NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES];
795         [o_fullscreen_window setBackgroundColor: [NSColor blackColor]];
796         [o_fullscreen_window setCanBecomeKeyWindow: YES];
797         [o_fullscreen_window setCanBecomeMainWindow: YES];
798         [o_fullscreen_window setHasActiveVideo: YES];
799         [o_fullscreen_window setFullscreen: YES];
800
801         if (![self isVisible] || [self alphaValue] == 0.0) {
802             /* We don't animate if we are not visible, instead we
803              * simply fade the display */
804             CGDisplayFadeReservationToken token;
805
806             if (blackout_other_displays) {
807                 CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &token);
808                 CGDisplayFade(token, 0.5, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0, 0, 0, YES);
809             }
810
811             [screen setFullscreenPresentationOptions];
812
813             [o_video_view retain];
814             [[o_video_view superview] replaceSubview:o_video_view with:o_temp_view];
815             [o_temp_view setFrame:[o_video_view frame]];
816             [o_fullscreen_window setContentView:o_video_view];
817             [o_video_view release];
818
819             [o_fullscreen_window makeKeyAndOrderFront:self];
820             [o_fullscreen_window orderFront:self animate:YES];
821
822             [o_fullscreen_window setFrame:screen_rect display:YES animate:YES];
823             [o_fullscreen_window setLevel:NSNormalWindowLevel];
824
825             if (blackout_other_displays) {
826                 CGDisplayFade(token, 0.3, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0, 0, 0, NO);
827                 CGReleaseDisplayFadeReservation(token);
828             }
829
830             /* Will release the lock */
831             [self hasBecomeFullscreen];
832
833             return;
834         }
835
836         /* Make sure video view gets visible in case the playlist was visible before */
837         b_video_view_was_hidden = [o_video_view isHidden];
838         [o_video_view setHidden: NO];
839
840         /* Make sure we don't see the o_video_view disappearing of the screen during this operation */
841         NSDisableScreenUpdates();
842         [o_video_view retain];
843         [[o_video_view superview] replaceSubview:o_video_view with:o_temp_view];
844         [o_temp_view setFrame:[o_video_view frame]];
845         [o_fullscreen_window setContentView:o_video_view];
846         [o_video_view release];
847         [o_fullscreen_window makeKeyAndOrderFront:self];
848         NSEnableScreenUpdates();
849     }
850
851     /* We are in fullscreen (and no animation is running) */
852     if ([self fullscreen]) {
853         /* Make sure we are hidden */
854         [self orderOut: self];
855
856         return;
857     }
858
859     if (o_fullscreen_anim1) {
860         [o_fullscreen_anim1 stopAnimation];
861         [o_fullscreen_anim1 release];
862     }
863     if (o_fullscreen_anim2) {
864         [o_fullscreen_anim2 stopAnimation];
865         [o_fullscreen_anim2 release];
866     }
867
868     [screen setFullscreenPresentationOptions];
869
870     dict1 = [[NSMutableDictionary alloc] initWithCapacity:2];
871     dict2 = [[NSMutableDictionary alloc] initWithCapacity:3];
872
873     [dict1 setObject:self forKey:NSViewAnimationTargetKey];
874     [dict1 setObject:NSViewAnimationFadeOutEffect forKey:NSViewAnimationEffectKey];
875
876     [dict2 setObject:o_fullscreen_window forKey:NSViewAnimationTargetKey];
877     [dict2 setObject:[NSValue valueWithRect:[o_fullscreen_window frame]] forKey:NSViewAnimationStartFrameKey];
878     [dict2 setObject:[NSValue valueWithRect:screen_rect] forKey:NSViewAnimationEndFrameKey];
879
880     /* Strategy with NSAnimation allocation:
881      - Keep at most 2 animation at a time
882      - leaveFullscreen/enterFullscreen are the only responsible for releasing and alloc-ing
883      */
884     o_fullscreen_anim1 = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict1]];
885     o_fullscreen_anim2 = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict2]];
886
887     [dict1 release];
888     [dict2 release];
889
890     [o_fullscreen_anim1 setAnimationBlockingMode: NSAnimationNonblocking];
891     [o_fullscreen_anim1 setDuration: 0.3];
892     [o_fullscreen_anim1 setFrameRate: 30];
893     [o_fullscreen_anim2 setAnimationBlockingMode: NSAnimationNonblocking];
894     [o_fullscreen_anim2 setDuration: 0.2];
895     [o_fullscreen_anim2 setFrameRate: 30];
896
897     [o_fullscreen_anim2 setDelegate: self];
898     [o_fullscreen_anim2 startWhenAnimation: o_fullscreen_anim1 reachesProgress: 1.0];
899
900     [o_fullscreen_anim1 startAnimation];
901     /* fullscreenAnimation will be unlocked when animation ends */
902
903     b_entering_fullscreen_transition = YES;
904 }
905
906 - (void)hasBecomeFullscreen
907 {
908     if ([[o_video_view subviews] count] > 0)
909         [o_fullscreen_window makeFirstResponder: [[o_video_view subviews] objectAtIndex:0]];
910
911     [o_fullscreen_window makeKeyWindow];
912     [o_fullscreen_window setAcceptsMouseMovedEvents: YES];
913
914     /* tell the fspanel to move itself to front next time it's triggered */
915     [[[VLCMainWindow sharedInstance] fsPanel] setVoutWasUpdated: o_fullscreen_window];
916     [[[VLCMainWindow sharedInstance] fsPanel] setActive: nil];
917
918     if ([self isVisible])
919         [self orderOut: self];
920
921     b_entering_fullscreen_transition = NO;
922     [self setFullscreen:YES];
923 }
924
925 - (void)leaveFullscreen
926 {
927     [self leaveFullscreenAndFadeOut: NO];
928 }
929
930 - (void)leaveFullscreenAndFadeOut: (BOOL)fadeout
931 {
932     NSMutableDictionary *dict1, *dict2;
933     NSRect frame;
934     BOOL blackout_other_displays = var_InheritBool(VLCIntf, "macosx-black");
935
936     if (o_controls_bar)
937         [o_controls_bar setFullscreenState:NO];
938     [[[VLCMainWindow sharedInstance] controlsBar] setFullscreenState:NO];
939
940     /* We always try to do so */
941     [NSScreen unblackoutScreens];
942
943     [[o_video_view window] makeKeyAndOrderFront: nil];
944
945     /* Don't do anything if o_fullscreen_window is already closed */
946     if (!o_fullscreen_window) {
947         return;
948     }
949
950     if (fadeout) {
951         /* We don't animate if we are not visible, instead we
952          * simply fade the display */
953         CGDisplayFadeReservationToken token;
954
955         if (blackout_other_displays) {
956             CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &token);
957             CGDisplayFade(token, 0.3, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0, 0, 0, YES);
958         }
959
960         [[[VLCMainWindow sharedInstance] fsPanel] setNonActive: nil];
961         [[o_fullscreen_window screen] setNonFullscreenPresentationOptions];
962
963         /* Will release the lock */
964         [self hasEndedFullscreen];
965
966         /* Our window is hidden, and might be faded. We need to workaround that, so note it
967          * here */
968         b_window_is_invisible = YES;
969
970         if (blackout_other_displays) {
971             CGDisplayFade(token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0, 0, 0, NO);
972             CGReleaseDisplayFadeReservation(token);
973         }
974
975         return;
976     }
977
978     [self setAlphaValue: 0.0];
979     [self orderFront: self];
980     [[o_video_view window] orderFront: self];
981
982     [[[VLCMainWindow sharedInstance] fsPanel] setNonActive: nil];
983     [[o_fullscreen_window screen] setNonFullscreenPresentationOptions];
984
985     if (o_fullscreen_anim1) {
986         [o_fullscreen_anim1 stopAnimation];
987         [o_fullscreen_anim1 release];
988     }
989     if (o_fullscreen_anim2) {
990         [o_fullscreen_anim2 stopAnimation];
991         [o_fullscreen_anim2 release];
992     }
993
994     frame = [[o_temp_view superview] convertRect: [o_temp_view frame] toView: nil]; /* Convert to Window base coord */
995     frame.origin.x += [self frame].origin.x;
996     frame.origin.y += [self frame].origin.y;
997
998     dict2 = [[NSMutableDictionary alloc] initWithCapacity:2];
999     [dict2 setObject:self forKey:NSViewAnimationTargetKey];
1000     [dict2 setObject:NSViewAnimationFadeInEffect forKey:NSViewAnimationEffectKey];
1001
1002     o_fullscreen_anim2 = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict2]];
1003     [dict2 release];
1004
1005     [o_fullscreen_anim2 setAnimationBlockingMode: NSAnimationNonblocking];
1006     [o_fullscreen_anim2 setDuration: 0.3];
1007     [o_fullscreen_anim2 setFrameRate: 30];
1008
1009     [o_fullscreen_anim2 setDelegate: self];
1010
1011     dict1 = [[NSMutableDictionary alloc] initWithCapacity:3];
1012
1013     [dict1 setObject:o_fullscreen_window forKey:NSViewAnimationTargetKey];
1014     [dict1 setObject:[NSValue valueWithRect:[o_fullscreen_window frame]] forKey:NSViewAnimationStartFrameKey];
1015     [dict1 setObject:[NSValue valueWithRect:frame] forKey:NSViewAnimationEndFrameKey];
1016
1017     o_fullscreen_anim1 = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict1]];
1018     [dict1 release];
1019
1020     [o_fullscreen_anim1 setAnimationBlockingMode: NSAnimationNonblocking];
1021     [o_fullscreen_anim1 setDuration: 0.2];
1022     [o_fullscreen_anim1 setFrameRate: 30];
1023     [o_fullscreen_anim2 startWhenAnimation: o_fullscreen_anim1 reachesProgress: 1.0];
1024
1025     /* Make sure o_fullscreen_window is the frontmost window */
1026     [o_fullscreen_window orderFront: self];
1027
1028     [o_fullscreen_anim1 startAnimation];
1029     /* fullscreenAnimation will be unlocked when animation ends */
1030 }
1031
1032 - (void)hasEndedFullscreen
1033 {
1034     [self setFullscreen:NO];
1035
1036     /* This function is private and should be only triggered at the end of the fullscreen change animation */
1037     /* Make sure we don't see the o_video_view disappearing of the screen during this operation */
1038     NSDisableScreenUpdates();
1039     [o_video_view retain];
1040     [o_video_view removeFromSuperviewWithoutNeedingDisplay];
1041     [[o_temp_view superview] replaceSubview:o_temp_view with:o_video_view];
1042     [o_video_view release];
1043     [o_video_view setFrame:[o_temp_view frame]];
1044     if ([[o_video_view subviews] count] > 0)
1045         [self makeFirstResponder: [[o_video_view subviews] objectAtIndex:0]];
1046
1047     [o_video_view setHidden: b_video_view_was_hidden];
1048
1049     [super makeKeyAndOrderFront:self]; /* our version (in main window) contains a workaround */
1050
1051     [o_fullscreen_window orderOut: self];
1052     NSEnableScreenUpdates();
1053
1054     [o_fullscreen_window release];
1055     o_fullscreen_window = nil;
1056
1057     [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: i_originalLevel];
1058     [self setLevel:i_originalLevel];
1059
1060     [self setAlphaValue: config_GetFloat(VLCIntf, "macosx-opaqueness")];
1061
1062     // if we quit fullscreen because there is no video anymore, make sure non-embedded window is not visible
1063     if (![[VLCMain sharedInstance] activeVideoPlayback] && [self class] != [VLCMainWindow class])
1064         [self orderOut: self];
1065 }
1066
1067 - (void)animationDidEnd:(NSAnimation*)animation
1068 {
1069     NSArray *viewAnimations;
1070     if (o_makekey_anim == animation) {
1071         [o_makekey_anim release];
1072         return;
1073     }
1074     if ([animation currentValue] < 1.0)
1075         return;
1076
1077     /* Fullscreen ended or started (we are a delegate only for leaveFullscreen's/enterFullscren's anim2) */
1078     viewAnimations = [o_fullscreen_anim2 viewAnimations];
1079     if ([viewAnimations count] >=1 &&
1080         [[[viewAnimations objectAtIndex:0] objectForKey: NSViewAnimationEffectKey] isEqualToString:NSViewAnimationFadeInEffect]) {
1081         /* Fullscreen ended */
1082         [self hasEndedFullscreen];
1083     } else
1084     /* Fullscreen started */
1085         [self hasBecomeFullscreen];
1086 }
1087
1088 - (void)orderOut:(id)sender
1089 {
1090     [super orderOut:sender];
1091
1092     /*
1093      * TODO reimplement leaveFullscreenAndFadeOut:YES, or remove code
1094      * and the hack below
1095     
1096     if (![NSStringFromClass([self class]) isEqualToString:@"VLCMainWindow"]) {
1097         [self leaveFullscreenAndFadeOut:YES];
1098     }
1099      */
1100 }
1101
1102 - (void)makeKeyAndOrderFront: (id)sender
1103 {
1104     /* Hack
1105      * when we exit fullscreen and fade out, we may endup in
1106      * having a window that is faded. We can't have it fade in unless we
1107      * animate again. */
1108
1109     if (!b_window_is_invisible) {
1110         /* Make sure we don't do it too much */
1111         [super makeKeyAndOrderFront: sender];
1112         return;
1113     }
1114
1115     [super setAlphaValue:0.0f];
1116     [super makeKeyAndOrderFront: sender];
1117
1118     NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:2];
1119     [dict setObject:self forKey:NSViewAnimationTargetKey];
1120     [dict setObject:NSViewAnimationFadeInEffect forKey:NSViewAnimationEffectKey];
1121
1122     o_makekey_anim = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict]];
1123     [dict release];
1124
1125     [o_makekey_anim setAnimationBlockingMode: NSAnimationNonblocking];
1126     [o_makekey_anim setDuration: 0.1];
1127     [o_makekey_anim setFrameRate: 30];
1128     [o_makekey_anim setDelegate: self];
1129
1130     [o_makekey_anim startAnimation];
1131     b_window_is_invisible = NO;
1132
1133     /* fullscreenAnimation will be unlocked when animation ends */
1134 }
1135
1136
1137 #pragma mark -
1138 #pragma mark Accessibility stuff
1139
1140 - (NSArray *)accessibilityAttributeNames
1141 {
1142     if (!b_dark_interface || !o_titlebar_view)
1143         return [super accessibilityAttributeNames];
1144
1145     static NSMutableArray *attributes = nil;
1146     if (attributes == nil) {
1147         attributes = [[super accessibilityAttributeNames] mutableCopy];
1148         NSArray *appendAttributes = [NSArray arrayWithObjects:NSAccessibilitySubroleAttribute,
1149                                      NSAccessibilityCloseButtonAttribute,
1150                                      NSAccessibilityMinimizeButtonAttribute,
1151                                      NSAccessibilityZoomButtonAttribute, nil];
1152
1153         for(NSString *attribute in appendAttributes) {
1154             if (![attributes containsObject:attribute])
1155                 [attributes addObject:attribute];
1156         }
1157     }
1158     return attributes;
1159 }
1160
1161 - (id)accessibilityAttributeValue: (NSString*)o_attribute_name
1162 {
1163     if (b_dark_interface && o_titlebar_view) {
1164         VLCMainWindowTitleView *o_tbv = o_titlebar_view;
1165
1166         if ([o_attribute_name isEqualTo: NSAccessibilitySubroleAttribute])
1167             return NSAccessibilityStandardWindowSubrole;
1168
1169         if ([o_attribute_name isEqualTo: NSAccessibilityCloseButtonAttribute])
1170             return [[o_tbv closeButton] cell];
1171
1172         if ([o_attribute_name isEqualTo: NSAccessibilityMinimizeButtonAttribute])
1173             return [[o_tbv minimizeButton] cell];
1174
1175         if ([o_attribute_name isEqualTo: NSAccessibilityZoomButtonAttribute])
1176             return [[o_tbv zoomButton] cell];
1177     }
1178
1179     return [super accessibilityAttributeValue: o_attribute_name];
1180 }
1181
1182 @end