VLCFSPanelController.m 16 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*****************************************************************************
 * VLCFSPanelController.m: macOS fullscreen controls window controller
 *****************************************************************************
 * Copyright (C) 2006-2016 VLC authors and VideoLAN
 * $Id$
 *
 * Authors: Jérôme Decoodt <djc at videolan dot org>
 *          Felix Paul Kühne <fkuehne at videolan dot org>
 *          David Fuhrmann <david dot fuhrmann at googlemail dot com>
 *          Marvin Scholz <epirat07 at gmail 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 "VLCFSPanelController.h"
#import "VLCCoreInteraction.h"
29
#import "CompatibilityFixes.h"
30 31 32 33
#import "VLCMain.h"

@interface VLCFSPanelController () {
    BOOL _isCounting;
34 35 36 37 38

    // Only used to track changes and trigger centering of FS panel
    NSRect _associatedVoutFrame;
    // Used to ask for current constraining rect on movement
    NSWindow *_associatedVoutWindow;
39 40 41 42 43 44
}

@end

@implementation VLCFSPanelController

45 46 47 48 49 50 51 52 53 54
static NSString *kAssociatedFullscreenRect = @"VLCFullscreenAssociatedWindowRect";

+ (void)initialize
{
    NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys: NSStringFromRect(NSZeroRect), kAssociatedFullscreenRect, nil];

    [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
}


55 56 57 58 59 60
#pragma mark -
#pragma mark Initialization

- (id)init
{
    self = [super initWithWindowNibName:@"VLCFullScreenPanel"];
61 62 63 64
    if (self) {
        NSString *rectStr = [[NSUserDefaults standardUserDefaults] stringForKey:kAssociatedFullscreenRect];
        _associatedVoutFrame = NSRectFromString(rectStr);
    }
65 66 67 68 69 70 71 72 73 74
    return self;
}

- (void)windowDidLoad
{
    [super windowDidLoad];

    /* Do some window setup that is not possible in IB */
    [self.window setOpaque:NO];
    [self.window setAlphaValue:0.0f];
75
    [self.window setMovableByWindowBackground:NO];
76 77 78 79
    [self.window setLevel:NSModalPanelWindowLevel];
    [self.window setStyleMask:self.window.styleMask | NSResizableWindowMask];
    [self.window setBackgroundColor:[NSColor clearColor]];

80 81 82
    /* Set autosave name after we changed window mask to resizable */
    [self.window setFrameAutosaveName:@"VLCFullscreenControls"];

83
#ifdef MAC_OS_X_VERSION_10_10
84
    /* Inject correct background view depending on OS support */
85
    if (OSX_YOSEMITE_AND_HIGHER) {
86 87 88 89 90 91 92 93
        [self injectVisualEffectView];
    } else {
        [self injectBackgroundView];
    }
#else
    /* Compiled with old SDK, always use legacy style */
    [self injectBackgroundView];
#endif
94

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    [self setupControls];
}

#define setupButton(target, title, desc)                                              \
    [target accessibilitySetOverrideValue:title                                       \
                             forAttribute:NSAccessibilityTitleAttribute];             \
    [target accessibilitySetOverrideValue:desc                                        \
                             forAttribute:NSAccessibilityDescriptionAttribute];       \
    [target setToolTip:desc];

- (void)setupControls
{
    /* Setup translations for buttons */
    setupButton(_playPauseButton,
                _NS("Play/Pause"),
110
                _NS("Play/Pause the current media"));
111 112
    setupButton(_nextButton,
                _NS("Next"),
113
                _NS("Go to next item"));
114 115
    setupButton(_previousButton,
                _NS("Previous"),
116
                _NS("Go to the previous item"));
117 118
    setupButton(_forwardButton,
                _NS("Forward"),
119
                _NS("Seek forward"));
120 121
    setupButton(_backwardButton,
                _NS("Backward"),
122
                _NS("Seek backward"));
123 124
    setupButton(_fullscreenButton,
                _NS("Toggle Fullscreen mode"),
125
                _NS("Leave fullscreen mode"));
126 127
    setupButton(_volumeSlider,
                _NS("Volume"),
128
                _NS("Adjust the volume"));
129 130
    setupButton(_timeSlider,
                _NS("Position"),
131
                _NS("Adjust the current playback position"));
132 133

    /* Setup other controls */
134 135
    [_volumeSlider setMaxValue:[[VLCCoreInteraction sharedInstance] maxVolume]];
    [_volumeSlider setIntValue:AOUT_VOLUME_DEFAULT];
136
    [_volumeSlider setDefaultValue:AOUT_VOLUME_DEFAULT];
137 138 139 140 141 142

    /* Identifier to store the state of the remaining or total time label,
     * this is the same identifier as used for the window playback cotrols
     * so the state is shared between those.
     */
    [_remainingOrTotalTime setRemainingIdentifier:@"DisplayTimeAsTimeRemaining"];
143 144
}

145 146
#undef setupButton

147 148 149 150 151 152 153 154 155 156 157 158
#pragma mark -
#pragma mark Control Actions

- (IBAction)togglePlayPause:(id)sender
{
    [[VLCCoreInteraction sharedInstance] playOrPause];
}

- (IBAction)jumpForward:(id)sender
{
    static NSTimeInterval last_event = 0;
    if (([NSDate timeIntervalSinceReferenceDate] - last_event) > 0.16) {
159
        /* We just skipped 4 "continuous" events, otherwise we are too fast */
160 161 162 163 164 165 166 167 168
        [[VLCCoreInteraction sharedInstance] forwardExtraShort];
        last_event = [NSDate timeIntervalSinceReferenceDate];
    }
}

- (IBAction)jumpBackward:(id)sender
{
    static NSTimeInterval last_event = 0;
    if (([NSDate timeIntervalSinceReferenceDate] - last_event) > 0.16) {
169
        /* We just skipped 4 "continuous" events, otherwise we are too fast */
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
        [[VLCCoreInteraction sharedInstance] backwardExtraShort];
        last_event = [NSDate timeIntervalSinceReferenceDate];
    }
}

- (IBAction)gotoPrevious:(id)sender
{
    [[VLCCoreInteraction sharedInstance] previous];
}

- (IBAction)gotoNext:(id)sender
{
    [[VLCCoreInteraction sharedInstance] next];
}

- (IBAction)toggleFullscreen:(id)sender
{
    [[VLCCoreInteraction sharedInstance] toggleFullscreen];
}

- (IBAction)timeSliderUpdate:(id)sender
{
192 193
    switch([[NSApp currentEvent] type]) {
        case NSLeftMouseUp:
194
            /* Ignore mouse up, as this is a continuous slider and
195 196 197 198 199 200 201 202 203 204 205 206 207 208
             * when the user does a single click to a position on the slider,
             * the action is called twice, once for the mouse down and once
             * for the mouse up event. This results in two short seeks one
             * after another to the same position, which results in weird
             * audio quirks.
             */
            return;
        case NSLeftMouseDown:
        case NSLeftMouseDragged:
            break;

        default:
            return;
    }
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    input_thread_t *p_input;
    p_input = pl_CurrentInput(getIntf());

    if (p_input) {
        vlc_value_t pos;
        pos.f_float = [_timeSlider floatValue] / 10000.;
        var_Set(p_input, "position", pos);
        vlc_object_release(p_input);
    }
    [[[VLCMain sharedInstance] mainWindow] updateTimeSlider];
}

- (IBAction)volumeSliderUpdate:(id)sender
{
    [[VLCCoreInteraction sharedInstance] setVolume:[sender intValue]];
}

#pragma mark -
#pragma mark Metadata and state updates

- (void)setPlay
{
    [_playPauseButton setState:NSOffState];
}

- (void)setPause
{
    [_playPauseButton setState:NSOnState];
}

- (void)setStreamTitle:(NSString *)title
{
    [_mediaTitle setStringValue:title];
}

- (void)updatePositionAndTime
{
    input_thread_t *p_input = pl_CurrentInput(getIntf());

    /* If nothing is playing, reset times and slider */
    if (!p_input) {
        [_timeSlider setFloatValue:0.0];
        [_elapsedTime setStringValue:@""];
        [_remainingOrTotalTime setHidden:YES];
        return;
    }

    vlc_value_t pos;
    char psz_time[MSTRTIME_MAX_SIZE];

    var_Get(p_input, "position", &pos);
    float f_updated = 10000. * pos.f_float;
    [_timeSlider setFloatValue:f_updated];


    int64_t t = var_GetInteger(p_input, "time");
    mtime_t dur = input_item_GetDuration(input_GetItem(p_input));

    /* Update total duration (right field) */
    if (dur <= 0) {
        [_remainingOrTotalTime setHidden:YES];
    } else {
        [_remainingOrTotalTime setHidden:NO];

        NSString *totalTime;

        if ([_remainingOrTotalTime timeRemaining]) {
            mtime_t remaining = 0;
            if (dur > t)
                remaining = dur - t;
            totalTime = [NSString stringWithFormat:@"-%s", secstotimestr(psz_time, (remaining / 1000000))];
        } else {
            totalTime = toNSStr(secstotimestr(psz_time, (dur / 1000000)));
        }
        [_remainingOrTotalTime setStringValue:totalTime];
    }

    /* Update current position (left field) */
    NSString *playbackPosition = toNSStr(secstotimestr(psz_time, t / CLOCK_FREQ));

    [_elapsedTime setStringValue:playbackPosition];
    vlc_object_release(p_input);
}

- (void)setSeekable:(BOOL)seekable
{
    [_timeSlider setEnabled:seekable];
    [_forwardButton setEnabled:seekable];
    [_backwardButton setEnabled:seekable];
}

- (void)setVolumeLevel:(int)value
{
    [_volumeSlider setIntValue:value];
}

#pragma mark -
#pragma mark Window interactions

- (void)fadeIn
{
310 311 312
    if (!var_InheritBool(getIntf(), "macosx-fspanel"))
        return;

313
    [NSAnimationContext beginGrouping];
314
    [[NSAnimationContext currentContext] setDuration:0.4f];
315 316 317 318 319 320 321 322 323
    [[self.window animator] setAlphaValue:1.0f];
    [NSAnimationContext endGrouping];

    [self startAutohideTimer];
}

- (void)fadeOut
{
    [NSAnimationContext beginGrouping];
324
    [[NSAnimationContext currentContext] setDuration:0.4f];
325 326 327 328
    [[self.window animator] setAlphaValue:0.0f];
    [NSAnimationContext endGrouping];
}

329
- (void)centerPanel
330 331
{
    NSRect windowFrame = [self.window frame];
332
    windowFrame = [self contrainFrameToAssociatedVoutWindow:windowFrame];
333

334 335 336 337
    /* Calculate coordinates for centered position */
    NSRect limitFrame = _associatedVoutWindow.frame;
    windowFrame.origin.x = (limitFrame.size.width - windowFrame.size.width) / 2 + limitFrame.origin.x;
    windowFrame.origin.y = (limitFrame.size.height / 5) - windowFrame.size.height + limitFrame.origin.y;
338

339
    [self.window setFrame:windowFrame display:YES animate:NO];
340 341
}

342
- (NSRect)contrainFrameToAssociatedVoutWindow:(NSRect)frame
343
{
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    NSRect limitFrame = _associatedVoutWindow.frame;

    // Limit rect to limitation view
    if (frame.origin.x < limitFrame.origin.x)
        frame.origin.x = limitFrame.origin.x;
    if (frame.origin.y < limitFrame.origin.y)
        frame.origin.y = limitFrame.origin.y;

    // Limit size (could be needed after resolution changes)
    if (frame.size.height > limitFrame.size.height)
        frame.size.height = limitFrame.size.height;
    if (frame.size.width > limitFrame.size.width)
        frame.size.width = limitFrame.size.width;

    if (frame.origin.x + frame.size.width > limitFrame.origin.x + limitFrame.size.width)
        frame.origin.x = limitFrame.origin.x + limitFrame.size.width - frame.size.width;
    if (frame.origin.y + frame.size.height > limitFrame.origin.y + limitFrame.size.height)
        frame.origin.y = limitFrame.origin.y + limitFrame.size.height - frame.size.height;

    return frame;
364 365 366 367 368 369 370 371 372 373
}

- (void)setNonActive
{
    [self.window orderOut:self];
}

- (void)setActive
{
    [self.window orderFront:self];
374
    [self fadeIn];
375 376 377 378 379 380 381 382 383 384 385 386
}

#pragma mark -
#pragma mark Misc interactions

- (void)hideMouse
{
    [NSCursor setHiddenUntilMouseMoves:YES];
}

- (void)setVoutWasUpdated:(VLCWindow *)voutWindow
{
387
    _associatedVoutWindow = voutWindow;
388

389 390 391
    NSRect voutRect = voutWindow.frame;
    if (!NSEqualRects(_associatedVoutFrame, voutRect)) {
        _associatedVoutFrame = voutRect;
392 393
        [[NSUserDefaults standardUserDefaults] setObject:NSStringFromRect(_associatedVoutFrame) forKey:kAssociatedFullscreenRect];

394
        [self centerPanel];
395
    }
396

397 398 399 400 401 402 403 404 405 406 407
}

#pragma mark -
#pragma mark Autohide timer management

- (void)startAutohideTimer
{
    /* Do nothing if timer is already in place */
    if (_isCounting)
        return;

408 409 410
    /* Get timeout and make sure it is not lower than 1 second */
    int _timeToKeepVisibleInSec = MAX(var_CreateGetInteger(getIntf(), "mouse-hide-timeout") / 1000, 1);

411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
    _hideTimer = [NSTimer scheduledTimerWithTimeInterval:_timeToKeepVisibleInSec
                                                  target:self
                                                selector:@selector(autohideCallback:)
                                                userInfo:nil
                                                 repeats:NO];
    _isCounting = YES;
}

- (void)stopAutohideTimer
{
    [_hideTimer invalidate];
    _isCounting = NO;
}

- (void)autohideCallback:(NSTimer *)timer
{
427
    if (!NSMouseInRect([NSEvent mouseLocation], [self.window frame], NO)) {
428 429 430 431 432 433 434 435 436
        [self fadeOut];
        [self hideMouse];
    }
    _isCounting = NO;
}

#pragma mark -
#pragma mark Helpers

437
#ifdef MAC_OS_X_VERSION_10_10
438 439 440
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"

441 442 443
/**
 Create an image mask for the NSVisualEffectView
 with rounded corners in the given rect
444

445 446 447
 This is necessary as clipping the VisualEffectView using the layers
 rounded corners is not possible when using the NSColor clearColor
 as background color.
448

449 450
 \note  The returned image will have the necessary \c capInsets and
        \c capResizingMode set.
451

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
 \param bounds  The rect for the image size
 */
- (NSImage *)maskImageWithBounds:(NSRect)bounds
{
    static const float radius = 8.0;
    NSImage *img = [NSImage imageWithSize:bounds.size flipped:YES drawingHandler:^BOOL(NSRect dstRect) {
        NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:bounds xRadius:radius yRadius:radius];
        [[NSColor blackColor] setFill];
        [path fill];
        return YES;
    }];
    [img setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)];
    [img setResizingMode:NSImageResizingModeStretch];
    return img;
}

/**
 Injects the visual effect view in the Windows view hierarchy
470

471 472
 This is necessary as we can't use the NSVisualEffect view on
 all macOS Versions and therefore need to dynamically insert it.
473

474 475 476 477 478 479 480 481 482 483 484 485 486 487
 \warning Never call both, \c injectVisualEffectView and \c injectBackgroundView
 */
- (void)injectVisualEffectView
{
    /* Setup the view */
    NSVisualEffectView *view = [[NSVisualEffectView alloc] initWithFrame:self.window.contentView.frame];
    [view setMaskImage:[self maskImageWithBounds:self.window.contentView.bounds]];
    [view setBlendingMode:NSVisualEffectBlendingModeBehindWindow];
    [view setMaterial:NSVisualEffectMaterialDark];
    [view setState:NSVisualEffectStateActive];
    [view setAutoresizesSubviews:YES];

    /* Inject view in view hierarchy */
    [self.window setContentView:view];
488 489
    [_controlsView setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantDark]];
    [self.window.contentView addSubview:_controlsView];
490
}
491
#pragma clang diagnostic pop
492
#endif
493 494 495

/**
 Injects the standard background view in the Windows view hierarchy
496

497 498
 This is necessary on macOS versions that do not support the
 NSVisualEffectView that usually is injected.
499

500 501 502 503 504
 \warning Never call both, \c injectVisualEffectView and \c injectBackgroundView
 */
- (void)injectBackgroundView
{
    /* Setup the view */
505
    CGColorRef color = CGColorCreateGenericGray(0.0, 0.8);
506 507
    NSView *view = [[NSView alloc] initWithFrame:self.window.contentView.frame];
    [view setWantsLayer:YES];
508
    [view.layer setBackgroundColor:color];
509 510
    [view.layer setCornerRadius:8.0];
    [view setAutoresizesSubviews:YES];
511
    CGColorRelease(color);
512 513 514

    /* Inject view in view hierarchy */
    [self.window setContentView:view];
515
    [self.window.contentView addSubview:_controlsView];
516 517 518 519 520

    /* Disable adjusting height to workaround autolayout problems */
    [_heightMaxConstraint setConstant:42.0];
    [self.window setMaxSize:NSMakeSize(4068, 80)];
    [self.window setMinSize:NSMakeSize(480, 80)];
521 522 523 524 525 526 527 528 529
}

- (void)dealloc
{
    [self stopAutohideTimer];
}


@end