Windows.m 38 KB
Newer Older
1 2 3
/*****************************************************************************
 * Windows.m: MacOS X interface module
 *****************************************************************************
4
 * Copyright (C) 2012-2014 VLC authors and VideoLAN
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 * $Id$
 *
 * Authors: Felix Paul Kühne <fkuehne -at- videolan -dot- org>
 *          David Fuhrmann <david dot fuhrmann at googlemail dot com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#import "Windows.h"
26
#import "VLCMain.h"
27
#import "VLCCoreInteraction.h"
28
#import "VLCControlsBarCommon.h"
29
#import "VLCVoutView.h"
30
#import "CompatibilityFixes.h"
31 32 33 34 35 36 37

/*****************************************************************************
 * VLCWindow
 *
 *  Missing extension to NSWindow
 *****************************************************************************/

38 39 40 41 42 43 44 45 46 47
@interface VLCWindow()
{
    BOOL b_canBecomeKeyWindow;
    BOOL b_isset_canBecomeKeyWindow;
    BOOL b_canBecomeMainWindow;
    BOOL b_isset_canBecomeMainWindow;
}
@end

@implementation VLCWindow
48

49 50 51 52 53 54
- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)styleMask
                  backing:(NSBackingStoreType)backingType defer:(BOOL)flag
{
    self = [super initWithContentRect:contentRect styleMask:styleMask backing:backingType defer:flag];
    if (self) {
        /* we don't want this window to be restored on relaunch */
55
        [self setRestorable:NO];
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    }
    return self;
}

- (void)setCanBecomeKeyWindow: (BOOL)canBecomeKey
{
    b_isset_canBecomeKeyWindow = YES;
    b_canBecomeKeyWindow = canBecomeKey;
}

- (BOOL)canBecomeKeyWindow
{
    if (b_isset_canBecomeKeyWindow)
        return b_canBecomeKeyWindow;

    return [super canBecomeKeyWindow];
}

- (void)setCanBecomeMainWindow: (BOOL)canBecomeMain
{
    b_isset_canBecomeMainWindow = YES;
    b_canBecomeMainWindow = canBecomeMain;
}

- (BOOL)canBecomeMainWindow
{
    if (b_isset_canBecomeMainWindow)
        return b_canBecomeMainWindow;

    return [super canBecomeMainWindow];
}

88
- (void)closeAndAnimate:(BOOL)animate
89
{
90
    // No animation, just close
91 92 93 94 95
    if (!animate) {
        [super close];
        return;
    }

96 97 98 99 100 101 102 103 104
    // Animate window alpha value
    [self setAlphaValue:1.0];
    __unsafe_unretained typeof(self) this = self;
    [NSAnimationContext runAnimationGroup:^(NSAnimationContext *context){
        [[NSAnimationContext currentContext] setDuration:0.9];
        [[this animator] setAlphaValue:0.0];
    } completionHandler:^{
        [this close];
    }];
105 106
}

107
- (void)orderOut:(id)sender animate:(BOOL)animate
108 109
{
    if (!animate) {
110
        [super orderOut:sender];
111 112 113
        return;
    }

114 115 116
    if ([self alphaValue] == 0.0) {
        [super orderOut:self];
        return;
117
    }
118 119 120 121 122 123 124
    __unsafe_unretained typeof(self) this = self;
    [NSAnimationContext runAnimationGroup:^(NSAnimationContext *context){
        [[NSAnimationContext currentContext] setDuration:0.5];
        [[this animator] setAlphaValue:0.0];
    } completionHandler:^{
        [this orderOut:self];
    }];
125 126
}

127
- (void)orderFront:(id)sender animate:(BOOL)animate
128 129
{
    if (!animate) {
130 131
        [super orderFront:sender];
        [self setAlphaValue:1.0];
132 133 134 135
        return;
    }

    if (![self isVisible]) {
136 137 138 139
        [self setAlphaValue:0.0];
        [super orderFront:sender];
    } else if ([self alphaValue] == 1.0) {
        [super orderFront:self];
140 141 142
        return;
    }

143 144 145 146
    [NSAnimationContext beginGrouping];
    [[NSAnimationContext currentContext] setDuration:0.5];
    [[self animator] setAlphaValue:1.0];
    [NSAnimationContext endGrouping];
147 148
}

149 150
- (VLCVoutView *)videoView
{
151 152
    NSArray *o_subViews = [[self contentView] subviews];
    if ([o_subViews count] > 0) {
153
        id o_vout_view = [o_subViews firstObject];
154 155 156 157

        if ([o_vout_view class] == [VLCVoutView class])
            return (VLCVoutView *)o_vout_view;
    }
158 159 160 161

    return nil;
}

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
- (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
{
    if (!screen)
        screen = [self screen];
    NSRect screenRect = [screen frame];
    NSRect constrainedRect = [super constrainFrameRect:frameRect toScreen:screen];

    /*
     * Ugly workaround!
     * With Mavericks, there is a nasty bug resulting in grey bars on top in fullscreen mode.
     * It looks like this is enforced by the os because the window is in the way for the menu bar.
     *
     * According to the documentation, this constraining can be changed by overwriting this
     * method. But in this situation, even the received frameRect is already contrained with the
     * menu bars height substracted. This case is detected here, and the full height is
     * enforced again.
     *
     * See #9469 and radar://15583566
     */

    BOOL b_inFullscreen = [self fullscreen] || ([self respondsToSelector:@selector(inFullscreenTransition)] && [(VLCVideoWindowCommon *)self inFullscreenTransition]);

184
    if((OSX_MAVERICKS) && b_inFullscreen && constrainedRect.size.width == screenRect.size.width
185
          && constrainedRect.size.height != screenRect.size.height
186
          && fabs(screenRect.size.height - constrainedRect.size.height) <= 25.) {
187

188
        msg_Dbg(getIntf(), "Contrain window height %.1f to screen height %.1f",
189 190 191 192 193 194
                constrainedRect.size.height, screenRect.size.height);
        constrainedRect.size.height = screenRect.size.height;
    }

    return constrainedRect;
}
195

196 197 198 199 200 201 202 203
@end

/*****************************************************************************
 * VLCVideoWindowCommon
 *
 *  Common code for main window, detached window and extra video window
 *****************************************************************************/

204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
@interface VLCVideoWindowCommon()
{
    // variables for fullscreen handling
    VLCVideoWindowCommon *o_current_video_window;
    VLCWindow       * o_fullscreen_window;
    NSViewAnimation * o_fullscreen_anim1;
    NSViewAnimation * o_fullscreen_anim2;
    NSView          * o_temp_view;

    NSInteger i_originalLevel;

    BOOL b_video_view_was_hidden;

    NSTimer *t_hide_mouse_timer;

    NSRect frameBeforeLionFullscreen;
}

222 223 224 225 226
- (void)customZoom:(id)sender;
- (void)hasBecomeFullscreen;
- (void)hasEndedFullscreen;
@end

227 228
@implementation VLCVideoWindowCommon

229 230 231
#pragma mark -
#pragma mark Init

232 233 234
- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)styleMask
                  backing:(NSBackingStoreType)backingType defer:(BOOL)flag
{
235
    _darkInterface = config_GetInt(getIntf(), "macosx-interfacestyle");
236

237
    if (_darkInterface) {
238
        styleMask = NSBorderlessWindowMask | NSResizableWindowMask;
239 240 241 242 243 244 245
    }

    self = [super initWithContentRect:contentRect styleMask:styleMask
                              backing:backingType defer:flag];

    /* we want to be moveable regardless of our style */
    [self setMovableByWindowBackground: YES];
246
    [self setCanBecomeKeyWindow:YES];
247

248 249 250
    o_temp_view = [[NSView alloc] init];
    [o_temp_view setAutoresizingMask:NSViewHeightSizable | NSViewWidthSizable];

251 252 253
    return self;
}

254 255
- (void)awakeFromNib
{
256
    BOOL b_nativeFullscreenMode = var_InheritBool(getIntf(), "macosx-nativefullscreenmode");
257 258 259

    if (b_nativeFullscreenMode) {
        [self setCollectionBehavior: NSWindowCollectionBehaviorFullScreenPrimary];
260
    } else if (OSX_EL_CAPITAN || OSX_SIERRA) {
261 262
        // Native fullscreen seems to be default on El Capitan, this disables it explicitely
        [self setCollectionBehavior: NSWindowCollectionBehaviorFullScreenAuxiliary];
263 264 265 266 267
    }

    [super awakeFromNib];
}

268 269
- (void)setTitle:(NSString *)title
{
270 271 272
    if (!title || [title length] < 1)
        return;

273 274
    if (_darkInterface && self.titlebarView)
        [self.titlebarView setWindowTitle: title];
275 276 277 278 279 280 281

    [super setTitle: title];
}

#pragma mark -
#pragma mark zoom / minimize / close

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
    SEL s_menuAction = [menuItem action];

    if ((s_menuAction == @selector(performClose:)) || (s_menuAction == @selector(performMiniaturize:)) || (s_menuAction == @selector(performZoom:)))
        return YES;

    return [super validateMenuItem:menuItem];
}

- (BOOL)windowShouldClose:(id)sender
{
    return YES;
}

- (void)performClose:(id)sender
{
    if (!([self styleMask] & NSTitledWindowMask)) {
        [[NSNotificationCenter defaultCenter] postNotificationName:NSWindowWillCloseNotification object:self];

302
        [self close];
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    } else
        [super performClose: sender];
}

- (void)performMiniaturize:(id)sender
{
    if (!([self styleMask] & NSTitledWindowMask))
        [self miniaturize: sender];
    else
        [super performMiniaturize: sender];
}

- (void)performZoom:(id)sender
{
    if (!([self styleMask] & NSTitledWindowMask))
        [self customZoom: sender];
    else
        [super performZoom: sender];
}

- (void)zoom:(id)sender
{
    if (!([self styleMask] & NSTitledWindowMask))
        [self customZoom: sender];
    else
        [super zoom: sender];
}

/**
 * Given a proposed frame rectangle, return a modified version
 * which will fit inside the screen.
 *
 * This method is based upon NSWindow.m, part of the GNUstep GUI Library, licensed under LGPLv2+.
 *    Authors:  Scott Christley <scottc@net-community.com>, Venkat Ajjanagadde <venkat@ocbi.com>,
 *              Felipe A. Rodriguez <far@ix.netcom.com>, Richard Frith-Macdonald <richard@brainstorm.co.uk>
 *    Copyright (C) 1996 Free Software Foundation, Inc.
 */
- (NSRect) customConstrainFrameRect: (NSRect)frameRect toScreen: (NSScreen*)screen
{
    NSRect screenRect = [screen visibleFrame];
343
    CGFloat difference;
344 345 346 347 348 349 350 351 352 353 354 355

    /* Move top edge of the window inside the screen */
    difference = NSMaxY (frameRect) - NSMaxY (screenRect);
    if (difference > 0) {
        frameRect.origin.y -= difference;
    }

    /* If the window is resizable, resize it (if needed) so that the
     bottom edge is on the screen or can be on the screen when the user moves
     the window */
    difference = NSMaxY (screenRect) - NSMaxY (frameRect);
    if (_styleMask & NSResizableWindowMask) {
356
        CGFloat difference2;
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401

        difference2 = screenRect.origin.y - frameRect.origin.y;
        difference2 -= difference;
        // Take in account the space between the top of window and the top of the
        // screen which can be used to move the bottom of the window on the screen
        if (difference2 > 0) {
            frameRect.size.height -= difference2;
            frameRect.origin.y += difference2;
        }

        /* Ensure that resizing doesn't makewindow smaller than minimum */
        difference2 = [self minSize].height - frameRect.size.height;
        if (difference2 > 0) {
            frameRect.size.height += difference2;
            frameRect.origin.y -= difference2;
        }
    }

    return frameRect;
}

#define DIST 3

/**
 Zooms the receiver.   This method calls the delegate method
 windowShouldZoom:toFrame: to determine if the window should
 be allowed to zoom to full screen.
 *
 * This method is based upon NSWindow.m, part of the GNUstep GUI Library, licensed under LGPLv2+.
 *    Authors:  Scott Christley <scottc@net-community.com>, Venkat Ajjanagadde <venkat@ocbi.com>,
 *              Felipe A. Rodriguez <far@ix.netcom.com>, Richard Frith-Macdonald <richard@brainstorm.co.uk>
 *    Copyright (C) 1996 Free Software Foundation, Inc.
 */
- (void) customZoom: (id)sender
{
    NSRect maxRect = [[self screen] visibleFrame];
    NSRect currentFrame = [self frame];

    if ([[self delegate] respondsToSelector: @selector(windowWillUseStandardFrame:defaultFrame:)]) {
        maxRect = [[self delegate] windowWillUseStandardFrame: self defaultFrame: maxRect];
    }

    maxRect = [self customConstrainFrameRect: maxRect toScreen: [self screen]];

    // Compare the new frame with the current one
402 403 404 405
    if ((fabs(NSMaxX(maxRect) - NSMaxX(currentFrame)) < DIST)
        && (fabs(NSMaxY(maxRect) - NSMaxY(currentFrame)) < DIST)
        && (fabs(NSMinX(maxRect) - NSMinX(currentFrame)) < DIST)
        && (fabs(NSMinY(maxRect) - NSMinY(currentFrame)) < DIST)) {
406 407
        // Already in zoomed mode, reset user frame, if stored
        if ([self frameAutosaveName] != nil) {
408
            [self setFrame: self.previousSavedFrame display: YES animate: YES];
409 410 411 412 413 414 415
            [self saveFrameUsingName: [self frameAutosaveName]];
        }
        return;
    }

    if ([self frameAutosaveName] != nil) {
        [self saveFrameUsingName: [self frameAutosaveName]];
416
        self.previousSavedFrame = [self frame];
417 418 419 420 421
    }

    [self setFrame: maxRect display: YES animate: YES];
}

422 423 424
#pragma mark -
#pragma mark Video window resizing logic

425 426
- (void)setWindowLevel:(NSInteger)i_state
{
427
    if (var_InheritBool(getIntf(), "video-wallpaper") || [self level] < NSNormalWindowLevel)
428 429
        return;

430
    if (!self.fullscreen && !_inFullscreenTransition)
431
        [self setLevel: i_state];
432 433 434

    // save it for restore if window is currently minimized or in fullscreen
    i_originalLevel = i_state;
435 436
}

437
- (NSRect)getWindowRectForProposedVideoViewSize:(NSSize)size
438 439 440 441
{
    NSSize windowMinSize = [self minSize];
    NSRect screenFrame = [[self screen] visibleFrame];

442 443
    NSRect topleftbase = NSMakeRect(0, [self frame].size.height, 0, 0);
    NSPoint topleftscreen = [self convertRectToScreen: topleftbase].origin;
444

445 446 447 448 449 450
    CGFloat f_width = size.width;
    CGFloat f_height = size.height;
    if (f_width < windowMinSize.width)
        f_width = windowMinSize.width;
    if (f_height < f_min_video_height)
        f_height = f_min_video_height;
451 452 453

    /* Calculate the window's new size */
    NSRect new_frame;
454 455
    new_frame.size.width = [self frame].size.width - [_videoView frame].size.width + f_width;
    new_frame.size.height = [self frame].size.height - [_videoView frame].size.height + f_height;
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
    new_frame.origin.x = topleftscreen.x;
    new_frame.origin.y = topleftscreen.y - new_frame.size.height;

    /* make sure the window doesn't exceed the screen size the window is on */
    if (new_frame.size.width > screenFrame.size.width) {
        new_frame.size.width = screenFrame.size.width;
        new_frame.origin.x = screenFrame.origin.x;
    }
    if (new_frame.size.height > screenFrame.size.height) {
        new_frame.size.height = screenFrame.size.height;
        new_frame.origin.y = screenFrame.origin.y;
    }
    if (new_frame.origin.y < screenFrame.origin.y)
        new_frame.origin.y = screenFrame.origin.y;

    CGFloat right_screen_point = screenFrame.origin.x + screenFrame.size.width;
    CGFloat right_window_point = new_frame.origin.x + new_frame.size.width;
    if (right_window_point > right_screen_point)
        new_frame.origin.x -= (right_window_point - right_screen_point);

476 477 478 479 480
    return new_frame;
}

- (void)resizeWindow
{
481 482
    // VOUT_WINDOW_SET_SIZE is triggered when exiting fullscreen. This event is ignored here
    // to avoid interference with the animation.
483
    if ([self fullscreen] || _inFullscreenTransition)
484 485
        return;

486
    NSRect window_rect = [self getWindowRectForProposedVideoViewSize:self.nativeVideoSize];
487
    [[self animator] setFrame:window_rect display:YES];
488 489 490 491
}

- (void)setNativeVideoSize:(NSSize)size
{
492
    _nativeVideoSize = size;
493

494
    if (var_InheritBool(getIntf(), "macosx-video-autoresize") && !var_InheritBool(getIntf(), "video-wallpaper"))
495 496 497 498 499
        [self resizeWindow];
}

- (NSSize)windowWillResize:(NSWindow *)window toSize:(NSSize)proposedFrameSize
{
500
    if (![[VLCMain sharedInstance] activeVideoPlayback] || self.nativeVideoSize.width == 0. || self.nativeVideoSize.height == 0. || window != self)
501 502 503
        return proposedFrameSize;

    // needed when entering lion fullscreen mode
504
    if (_inFullscreenTransition || [self fullscreen])
505 506
        return proposedFrameSize;

507
    if ([_videoView isHidden])
508 509
        return proposedFrameSize;

510 511
    if ([[VLCCoreInteraction sharedInstance] aspectRatioIsLocked]) {
        NSRect videoWindowFrame = [self frame];
512
        NSRect viewRect = [_videoView convertRect:[_videoView bounds] toView: nil];
513
        NSRect contentRect = [self contentRectForFrameRect:videoWindowFrame];
514 515
        CGFloat marginy = viewRect.origin.y + videoWindowFrame.size.height - contentRect.size.height;
        CGFloat marginx = contentRect.size.width - viewRect.size.width;
516 517
        if (self.titlebarView && _darkInterface)
            marginy += [self.titlebarView frame].size.height;
518

519
        proposedFrameSize.height = (proposedFrameSize.width - marginx) * self.nativeVideoSize.height / self.nativeVideoSize.width + marginy;
520 521 522 523 524
    }

    return proposedFrameSize;
}

525 526 527 528 529 530 531 532 533 534 535 536
- (void)windowWillMiniaturize:(NSNotification *)notification
{
    // Set level to normal as a workaround for Mavericks bug causing window
    // to vanish from screen, see radar://15473716
    i_originalLevel = [self level];
    [self setLevel: NSNormalWindowLevel];
}

- (void)windowDidDeminiaturize:(NSNotification *)notification
{
    [self setLevel: i_originalLevel];
}
537

538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
#pragma mark -
#pragma mark Mouse cursor handling

//  NSTimer selectors require this function signature as per Apple's docs
- (void)hideMouseCursor:(NSTimer *)timer
{
    [NSCursor setHiddenUntilMouseMoves: YES];
}

- (void)recreateHideMouseTimer
{
    if (t_hide_mouse_timer != nil) {
        [t_hide_mouse_timer invalidate];
    }

    t_hide_mouse_timer = [NSTimer scheduledTimerWithTimeInterval:2
                                                          target:self
                                                        selector:@selector(hideMouseCursor:)
                                                        userInfo:nil
                                                         repeats:NO];
}

//  Called automatically if window's acceptsMouseMovedEvents property is true
- (void)mouseMoved:(NSEvent *)theEvent
{
563
    if (self.fullscreen)
564
        [self recreateHideMouseTimer];
565
    if (self.hasActiveVideo && [self isKeyWindow]) {
566 567 568 569 570 571 572 573
        if (NSPointInRect([theEvent locationInWindow],
                          [[self videoView] convertRect:[[self videoView] bounds]
                                                 toView:nil])) {
            [self recreateHideMouseTimer];
        } else {
            [t_hide_mouse_timer invalidate];
        }
    }
574 575 576 577

    [super mouseMoved: theEvent];
}

578 579 580 581 582 583
#pragma mark -
#pragma mark Key events

- (void)flagsChanged:(NSEvent *)theEvent
{
    BOOL b_alt_pressed = ([theEvent modifierFlags] & NSAlternateKeyMask) != 0;
584
    [self.titlebarView informModifierPressed: b_alt_pressed];
585 586 587 588

    [super flagsChanged:theEvent];
}

589 590
#pragma mark -
#pragma mark Lion native fullscreen handling
591 592 593 594 595 596 597

- (void)becomeKeyWindow
{
    [super becomeKeyWindow];

    // change fspanel state for the case when multiple windows are in fullscreen
    if ([self hasActiveVideo] && [self fullscreen])
598
        [[[[VLCMain sharedInstance] mainWindow] fspanel] setActive];
599
    else
600
        [[[[VLCMain sharedInstance] mainWindow] fspanel] setNonActive];
601 602
}

603 604 605 606
- (void)resignKeyWindow
{
    [super resignKeyWindow];

607
    [[[[VLCMain sharedInstance] mainWindow] fspanel] setNonActive];
608 609
}

610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
-(NSArray*)customWindowsToEnterFullScreenForWindow:(NSWindow *)window
{
    if (window == self) {
        return [NSArray arrayWithObject:window];
    }

    return nil;
}

- (NSArray*)customWindowsToExitFullScreenForWindow:(NSWindow*)window
{
    if (window == self) {
        return [NSArray arrayWithObject:window];
    }

    return nil;
}

- (void)window:window startCustomAnimationToEnterFullScreenWithDuration:(NSTimeInterval)duration
{
    [window setStyleMask:([window styleMask] | NSFullScreenWindowMask)];

    NSScreen *screen = [window screen];
    NSRect screenFrame = [screen frame];

    [NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
        [context setDuration:0.5 * duration];
        [[window animator] setFrame:screenFrame display:YES];
    } completionHandler:nil];
}

- (void)window:window startCustomAnimationToExitFullScreenWithDuration:(NSTimeInterval)duration
{
    [window setStyleMask:([window styleMask] & ~NSFullScreenWindowMask)];
    [[window animator] setFrame:frameBeforeLionFullscreen display:YES animate:YES];

    [NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
        [context setDuration:0.5 * duration];
        [[window animator] setFrame:frameBeforeLionFullscreen display:YES animate:YES];
    } completionHandler:nil];
}

652 653
- (void)windowWillEnterFullScreen:(NSNotification *)notification
{
654
    _windowShouldExitFullscreenWhenFinished = [[VLCMain sharedInstance] activeVideoPlayback];
655

656
    NSInteger i_currLevel = [self level];
657
    // self.fullscreen and _inFullscreenTransition must not be true yet
658 659
    [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: NSNormalWindowLevel];
    [self setLevel:NSNormalWindowLevel];
660
    i_originalLevel = i_currLevel;
661

662
    _inFullscreenTransition = YES;
663

664
    var_SetBool(pl_Get(getIntf()), "fullscreen", true);
665

666 667
    frameBeforeLionFullscreen = [self frame];

668 669 670 671 672 673
    if ([self hasActiveVideo]) {
        vout_thread_t *p_vout = getVoutForActiveWindow();
        if (p_vout) {
            var_SetBool(p_vout, "fullscreen", true);
            vlc_object_release(p_vout);
        }
674 675
    }

676
    if ([self hasActiveVideo])
677
        [[[VLCMain sharedInstance] mainWindow] recreateHideMouseTimer];
678

679
    if (_darkInterface) {
680
        [self.titlebarView removeFromSuperviewWithoutNeedingDisplay];
681 682

        NSRect winrect;
683
        CGFloat f_titleBarHeight = [self.titlebarView frame].size.height;
684 685 686 687 688 689
        winrect = [self frame];

        winrect.size.height = winrect.size.height - f_titleBarHeight;
        [self setFrame: winrect display:NO animate:NO];
    }

690 691 692
    [_videoView setFrame: [[self contentView] frame]];
    if (![_videoView isHidden]) {
        [[self.controlsBar bottomBarView] setHidden: YES];
693
    }
694 695 696 697 698 699 700 701 702 703

    [self setMovableByWindowBackground: NO];
}

- (void)windowDidEnterFullScreen:(NSNotification *)notification
{
    // Indeed, we somehow can have an "inactive" fullscreen (but a visible window!).
    // But this creates some problems when leaving fs over remote intfs, so activate app here.
    [NSApp activateIgnoringOtherApps:YES];

704
    [self setFullscreen: YES];
705
    _inFullscreenTransition = NO;
706

707
    if ([self hasActiveVideo]) {
708
        [[[[VLCMain sharedInstance] mainWindow] fspanel] setVoutWasUpdated:self];
709
        if (![_videoView isHidden])
710
            [[[[VLCMain sharedInstance] mainWindow] fspanel] setActive];
711
    }
712 713 714 715 716

    NSArray *subviews = [[self videoView] subviews];
    NSUInteger count = [subviews count];

    for (NSUInteger x = 0; x < count; x++) {
717 718
        if ([[subviews objectAtIndex:x] respondsToSelector:@selector(reshape)])
            [[subviews objectAtIndex:x] reshape];
719 720 721 722 723
    }
}

- (void)windowWillExitFullScreen:(NSNotification *)notification
{
724
    _inFullscreenTransition = YES;
725 726
    [self setFullscreen: NO];

727
    if ([self hasActiveVideo]) {
728
        var_SetBool(pl_Get(getIntf()), "fullscreen", false);
729

730 731 732 733 734
        vout_thread_t *p_vout = getVoutForActiveWindow();
        if (p_vout) {
            var_SetBool(p_vout, "fullscreen", false);
            vlc_object_release(p_vout);
        }
735 736 737
    }

    [NSCursor setHiddenUntilMouseMoves: NO];
738
    [[[[VLCMain sharedInstance] mainWindow] fspanel] setNonActive];
739

740

741
    if (_darkInterface) {
742
        NSRect winrect;
743
        CGFloat f_titleBarHeight = [self.titlebarView frame].size.height;
744

745
        winrect = [_videoView frame];
746
        winrect.size.height -= f_titleBarHeight;
747
        [_videoView setFrame: winrect];
748 749

        winrect = [self frame];
750
        [self.titlebarView setFrame: NSMakeRect(0, winrect.size.height - f_titleBarHeight,
751
                                              winrect.size.width, f_titleBarHeight)];
752
        [[self contentView] addSubview: self.titlebarView];
753 754 755 756 757

        winrect.size.height = winrect.size.height + f_titleBarHeight;
        [self setFrame: winrect display:NO animate:NO];
    }

758 759 760 761
    NSRect videoViewFrame = [_videoView frame];
    videoViewFrame.origin.y += [self.controlsBar height];
    videoViewFrame.size.height -= [self.controlsBar height];
    [_videoView setFrame: videoViewFrame];
762

763 764
    if (![_videoView isHidden]) {
        [[self.controlsBar bottomBarView] setHidden: NO];
765
    }
766

767 768 769
    [self setMovableByWindowBackground: YES];
}

770 771
- (void)windowDidExitFullScreen:(NSNotification *)notification
{
772
    _inFullscreenTransition = NO;
773

774 775 776 777
    [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: i_originalLevel];
    [self setLevel:i_originalLevel];
}

778 779 780
#pragma mark -
#pragma mark Fullscreen Logic

781
- (void)enterFullscreenWithAnimation:(BOOL)b_animation
782 783 784 785 786
{
    NSMutableDictionary *dict1, *dict2;
    NSScreen *screen;
    NSRect screen_rect;
    NSRect rect;
787
    BOOL blackout_other_displays = var_InheritBool(getIntf(), "macosx-black");
788

789
    screen = [NSScreen screenWithDisplayID:(CGDirectDisplayID)var_InheritInteger(getIntf(), "macosx-vdev")];
790 791

    if (!screen) {
792
        msg_Dbg(getIntf(), "chosen screen isn't present, using current screen for fullscreen mode");
793 794 795
        screen = [self screen];
    }
    if (!screen) {
796
        msg_Dbg(getIntf(), "Using deepest screen");
797 798 799 800 801
        screen = [NSScreen deepestScreen];
    }

    screen_rect = [screen frame];

802 803
    if (self.controlsBar)
        [self.controlsBar setFullscreenState:YES];
804
    [[[[VLCMain sharedInstance] mainWindow] controlsBar] setFullscreenState:YES];
805

806
    [[[VLCMain sharedInstance] mainWindow] recreateHideMouseTimer];
807 808 809 810 811

    if (blackout_other_displays)
        [screen blackoutOtherScreens];

    /* Make sure we don't see the window flashes in float-on-top mode */
812
    NSInteger i_currLevel = [self level];
813
    // self.fullscreen must not be true yet
814
    [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: NSNormalWindowLevel];
815
    [self setLevel:NSNormalWindowLevel];
816
    i_originalLevel = i_currLevel; // would be overwritten by previous call
817 818 819 820 821

    /* Only create the o_fullscreen_window if we are not in the middle of the zooming animation */
    if (!o_fullscreen_window) {
        /* We can't change the styleMask of an already created NSWindow, so we create another window, and do eye catching stuff */

822
        rect = [[_videoView superview] convertRect: [_videoView frame] toView: nil]; /* Convert to Window base coord */
823 824 825 826 827 828
        rect.origin.x += [self frame].origin.x;
        rect.origin.y += [self frame].origin.y;
        o_fullscreen_window = [[VLCWindow alloc] initWithContentRect:rect styleMask: NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:YES];
        [o_fullscreen_window setBackgroundColor: [NSColor blackColor]];
        [o_fullscreen_window setCanBecomeKeyWindow: YES];
        [o_fullscreen_window setCanBecomeMainWindow: YES];
829 830
        [o_fullscreen_window setHasActiveVideo: YES];
        [o_fullscreen_window setFullscreen: YES];
831

832
        /* Make sure video view gets visible in case the playlist was visible before */
833 834
        b_video_view_was_hidden = [_videoView isHidden];
        [_videoView setHidden: NO];
835 836

        if (!b_animation) {
837 838 839 840 841 842 843 844 845
            /* We don't animate if we are not visible, instead we
             * simply fade the display */
            CGDisplayFadeReservationToken token;

            if (blackout_other_displays) {
                CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &token);
                CGDisplayFade(token, 0.5, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0, 0, 0, YES);
            }

846
            NSDisableScreenUpdates();
847 848 849 850
            [[_videoView superview] replaceSubview:_videoView with:o_temp_view];
            [o_temp_view setFrame:[_videoView frame]];
            [[o_fullscreen_window contentView] addSubview:_videoView];
            [_videoView setFrame: [[o_fullscreen_window contentView] frame]];
851 852 853 854 855
            NSEnableScreenUpdates();

            [screen setFullscreenPresentationOptions];

            [o_fullscreen_window setFrame:screen_rect display:YES animate:NO];
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871

            [o_fullscreen_window orderFront:self animate:YES];

            [o_fullscreen_window setLevel:NSNormalWindowLevel];

            if (blackout_other_displays) {
                CGDisplayFade(token, 0.3, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0, 0, 0, NO);
                CGReleaseDisplayFadeReservation(token);
            }

            /* Will release the lock */
            [self hasBecomeFullscreen];

            return;
        }

872
        /* Make sure we don't see the _videoView disappearing of the screen during this operation */
873
        NSDisableScreenUpdates();
874 875 876 877
        [[_videoView superview] replaceSubview:_videoView with:o_temp_view];
        [o_temp_view setFrame:[_videoView frame]];
        [[o_fullscreen_window contentView] addSubview:_videoView];
        [_videoView setFrame: [[o_fullscreen_window contentView] frame]];
878 879 880 881 882
        [o_fullscreen_window makeKeyAndOrderFront:self];
        NSEnableScreenUpdates();
    }

    /* We are in fullscreen (and no animation is running) */
883
    if ([self fullscreen]) {
884 885 886 887 888 889 890 891 892 893 894 895 896
        /* Make sure we are hidden */
        [self orderOut: self];

        return;
    }

    if (o_fullscreen_anim1) {
        [o_fullscreen_anim1 stopAnimation];
    }
    if (o_fullscreen_anim2) {
        [o_fullscreen_anim2 stopAnimation];
    }

897
    [screen setFullscreenPresentationOptions];
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912

    dict1 = [[NSMutableDictionary alloc] initWithCapacity:2];
    dict2 = [[NSMutableDictionary alloc] initWithCapacity:3];

    [dict1 setObject:self forKey:NSViewAnimationTargetKey];
    [dict1 setObject:NSViewAnimationFadeOutEffect forKey:NSViewAnimationEffectKey];

    [dict2 setObject:o_fullscreen_window forKey:NSViewAnimationTargetKey];
    [dict2 setObject:[NSValue valueWithRect:[o_fullscreen_window frame]] forKey:NSViewAnimationStartFrameKey];
    [dict2 setObject:[NSValue valueWithRect:screen_rect] forKey:NSViewAnimationEndFrameKey];

    /* Strategy with NSAnimation allocation:
     - Keep at most 2 animation at a time
     - leaveFullscreen/enterFullscreen are the only responsible for releasing and alloc-ing
     */
913 914
    o_fullscreen_anim1 = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict1]];
    o_fullscreen_anim2 = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict2]];
915 916 917 918 919 920 921 922 923 924 925 926 927

    [o_fullscreen_anim1 setAnimationBlockingMode: NSAnimationNonblocking];
    [o_fullscreen_anim1 setDuration: 0.3];
    [o_fullscreen_anim1 setFrameRate: 30];
    [o_fullscreen_anim2 setAnimationBlockingMode: NSAnimationNonblocking];
    [o_fullscreen_anim2 setDuration: 0.2];
    [o_fullscreen_anim2 setFrameRate: 30];

    [o_fullscreen_anim2 setDelegate: self];
    [o_fullscreen_anim2 startWhenAnimation: o_fullscreen_anim1 reachesProgress: 1.0];

    [o_fullscreen_anim1 startAnimation];
    /* fullscreenAnimation will be unlocked when animation ends */
928

929
    _inFullscreenTransition = YES;
930 931 932 933
}

- (void)hasBecomeFullscreen
{
934
    if ([[_videoView subviews] count] > 0)
935
        [o_fullscreen_window makeFirstResponder: [[_videoView subviews] firstObject]];
936 937 938 939 940

    [o_fullscreen_window makeKeyWindow];
    [o_fullscreen_window setAcceptsMouseMovedEvents: YES];

    /* tell the fspanel to move itself to front next time it's triggered */
941 942
    [[[[VLCMain sharedInstance] mainWindow] fspanel] setVoutWasUpdated:o_fullscreen_window];
    [[[[VLCMain sharedInstance] mainWindow] fspanel] setActive];
943 944 945 946

    if ([self isVisible])
        [self orderOut: self];

947
    _inFullscreenTransition = NO;
948
    [self setFullscreen:YES];
949 950
}

951
- (void)leaveFullscreenWithAnimation:(BOOL)b_animation
952 953 954
{
    NSMutableDictionary *dict1, *dict2;
    NSRect frame;
955
    BOOL blackout_other_displays = var_InheritBool(getIntf(), "macosx-black");
956

957 958
    if (self.controlsBar)
        [self.controlsBar setFullscreenState:NO];
959
    [[[[VLCMain sharedInstance] mainWindow] controlsBar] setFullscreenState:NO];
960 961 962 963

    /* We always try to do so */
    [NSScreen unblackoutScreens];

964
    [[_videoView window] makeKeyAndOrderFront: nil];
965 966 967 968 969 970

    /* Don't do anything if o_fullscreen_window is already closed */
    if (!o_fullscreen_window) {
        return;
    }

971
    [[[[VLCMain sharedInstance] mainWindow] fspanel] setNonActive];
972 973 974 975 976 977 978 979 980 981 982
    [[o_fullscreen_window screen] setNonFullscreenPresentationOptions];

    if (o_fullscreen_anim1) {
        [o_fullscreen_anim1 stopAnimation];
        o_fullscreen_anim1 = nil;
    }
    if (o_fullscreen_anim2) {
        [o_fullscreen_anim2 stopAnimation];
        o_fullscreen_anim2 = nil;
    }

983
    _inFullscreenTransition = YES;
984 985
    [self setFullscreen:NO];

986
    if (!b_animation) {
987 988 989 990 991 992 993 994 995
        /* We don't animate if we are not visible, instead we
         * simply fade the display */
        CGDisplayFadeReservationToken token;

        if (blackout_other_displays) {
            CGAcquireDisplayFadeReservation(kCGMaxDisplayReservationInterval, &token);
            CGDisplayFade(token, 0.3, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0, 0, 0, YES);
        }

996 997
        [self setAlphaValue:1.0];
        [self orderFront: self];
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011

        /* Will release the lock */
        [self hasEndedFullscreen];

        if (blackout_other_displays) {
            CGDisplayFade(token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0, 0, 0, NO);
            CGReleaseDisplayFadeReservation(token);
        }

        return;
    }

    [self setAlphaValue: 0.0];
    [self orderFront: self];
1012
    [[_videoView window] orderFront: self];
1013 1014 1015 1016 1017 1018 1019 1020 1021

    frame = [[o_temp_view superview] convertRect: [o_temp_view frame] toView: nil]; /* Convert to Window base coord */
    frame.origin.x += [self frame].origin.x;
    frame.origin.y += [self frame].origin.y;

    dict2 = [[NSMutableDictionary alloc] initWithCapacity:2];
    [dict2 setObject:self forKey:NSViewAnimationTargetKey];
    [dict2 setObject:NSViewAnimationFadeInEffect forKey:NSViewAnimationEffectKey];

1022
    o_fullscreen_anim2 = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict2]];
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035

    [o_fullscreen_anim2 setAnimationBlockingMode: NSAnimationNonblocking];
    [o_fullscreen_anim2 setDuration: 0.3];
    [o_fullscreen_anim2 setFrameRate: 30];

    [o_fullscreen_anim2 setDelegate: self];

    dict1 = [[NSMutableDictionary alloc] initWithCapacity:3];

    [dict1 setObject:o_fullscreen_window forKey:NSViewAnimationTargetKey];
    [dict1 setObject:[NSValue valueWithRect:[o_fullscreen_window frame]] forKey:NSViewAnimationStartFrameKey];
    [dict1 setObject:[NSValue valueWithRect:frame] forKey:NSViewAnimationEndFrameKey];

1036
    o_fullscreen_anim1 = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:dict1]];
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

    [o_fullscreen_anim1 setAnimationBlockingMode: NSAnimationNonblocking];
    [o_fullscreen_anim1 setDuration: 0.2];
    [o_fullscreen_anim1 setFrameRate: 30];
    [o_fullscreen_anim2 startWhenAnimation: o_fullscreen_anim1 reachesProgress: 1.0];

    /* Make sure o_fullscreen_window is the frontmost window */
    [o_fullscreen_window orderFront: self];

    [o_fullscreen_anim1 startAnimation];
    /* fullscreenAnimation will be unlocked when animation ends */
}

- (void)hasEndedFullscreen
{
1052
    _inFullscreenTransition = NO;
1053

1054
    /* This function is private and should be only triggered at the end of the fullscreen change animation */
1055
    /* Make sure we don't see the _videoView disappearing of the screen during this operation */
1056
    NSDisableScreenUpdates();
1057 1058 1059 1060
    [_videoView removeFromSuperviewWithoutNeedingDisplay];
    [[o_temp_view superview] replaceSubview:o_temp_view with:_videoView];
    [_videoView setFrame:[o_temp_view frame]];
    if ([[_videoView subviews] count] > 0)
1061
        [self makeFirstResponder: [[_videoView subviews] firstObject]];
1062

1063
    [_videoView setHidden: b_video_view_was_hidden];
1064

1065
    [self makeKeyAndOrderFront:self];
1066 1067 1068 1069 1070

    [o_fullscreen_window orderOut: self];
    NSEnableScreenUpdates();

    o_fullscreen_window = nil;
1071

1072
    [[[VLCMain sharedInstance] voutController] updateWindowLevelForHelperWindows: i_originalLevel];
1073
    [self setLevel:i_originalLevel];
1074

1075
    [self setAlphaValue: config_GetFloat(getIntf(), "macosx-opaqueness")];
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
}

- (void)animationDidEnd:(NSAnimation*)animation
{
    NSArray *viewAnimations;
    if ([animation currentValue] < 1.0)
        return;

    /* Fullscreen ended or started (we are a delegate only for leaveFullscreen's/enterFullscren's anim2) */
    viewAnimations = [o_fullscreen_anim2 viewAnimations];
    if ([viewAnimations count] >=1 &&
1087
        [[[viewAnimations firstObject] objectForKey: NSViewAnimationEffectKey] isEqualToString:NSViewAnimationFadeInEffect]) {
1088 1089 1090 1091 1092 1093 1094
        /* Fullscreen ended */
        [self hasEndedFullscreen];
    } else
    /* Fullscreen started */
        [self hasBecomeFullscreen];
}

1095 1096
#pragma mark -
#pragma mark Accessibility stuff
1097

1098 1099
- (NSArray *)accessibilityAttributeNames
{
1100
    if (!_darkInterface || !self.titlebarView)
1101 1102 1103 1104 1105
        return [super accessibilityAttributeNames];

    static NSMutableArray *attributes = nil;
    if (attributes == nil) {
        attributes = [[super accessibilityAttributeNames] mutableCopy];
1106 1107 1108 1109
        NSArray *appendAttributes = [NSArray arrayWithObjects:NSAccessibilitySubroleAttribute,
                                     NSAccessibilityCloseButtonAttribute,
                                     NSAccessibilityMinimizeButtonAttribute,
                                     NSAccessibilityZoomButtonAttribute, nil];
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120

        for(NSString *attribute in appendAttributes) {
            if (![attributes containsObject:attribute])
                [attributes addObject:attribute];
        }
    }
    return attributes;
}

- (id)accessibilityAttributeValue: (NSString*)o_attribute_name
{
1121 1122
    if (_darkInterface && self.titlebarView) {
        VLCMainWindowTitleView *o_tbv = self.titlebarView;
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138

        if ([o_attribute_name isEqualTo: NSAccessibilitySubroleAttribute])
            return NSAccessibilityStandardWindowSubrole;

        if ([o_attribute_name isEqualTo: NSAccessibilityCloseButtonAttribute])
            return [[o_tbv closeButton] cell];

        if ([o_attribute_name isEqualTo: NSAccessibilityMinimizeButtonAttribute])
            return [[o_tbv minimizeButton] cell];

        if ([o_attribute_name isEqualTo: NSAccessibilityZoomButtonAttribute])
            return [[o_tbv zoomButton] cell];
    }

    return [super accessibilityAttributeValue: o_attribute_name];
}
1139 1140

@end