VLCFSPanelController.m 15.8 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
#undef setupButton

141 142 143 144 145 146 147 148 149 150 151 152
#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) {
153
        /* We just skipped 4 "continuous" events, otherwise we are too fast */
154 155 156 157 158 159 160 161 162
        [[VLCCoreInteraction sharedInstance] forwardExtraShort];
        last_event = [NSDate timeIntervalSinceReferenceDate];
    }
}

- (IBAction)jumpBackward:(id)sender
{
    static NSTimeInterval last_event = 0;
    if (([NSDate timeIntervalSinceReferenceDate] - last_event) > 0.16) {
163
        /* We just skipped 4 "continuous" events, otherwise we are too fast */
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        [[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
{
186 187
    switch([[NSApp currentEvent] type]) {
        case NSLeftMouseUp:
188
            /* Ignore mouse up, as this is a continuous slider and
189 190 191 192 193 194 195 196 197 198 199 200 201 202
             * 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;
    }
203 204 205 206 207 208 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
    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
{
304 305 306
    if (!var_InheritBool(getIntf(), "macosx-fspanel"))
        return;

307
    [NSAnimationContext beginGrouping];
308
    [[NSAnimationContext currentContext] setDuration:0.4f];
309 310 311 312 313 314 315 316 317
    [[self.window animator] setAlphaValue:1.0f];
    [NSAnimationContext endGrouping];

    [self startAutohideTimer];
}

- (void)fadeOut
{
    [NSAnimationContext beginGrouping];
318
    [[NSAnimationContext currentContext] setDuration:0.4f];
319 320 321 322
    [[self.window animator] setAlphaValue:0.0f];
    [NSAnimationContext endGrouping];
}

323
- (void)centerPanel
324 325
{
    NSRect windowFrame = [self.window frame];
326
    windowFrame = [self contrainFrameToAssociatedVoutWindow:windowFrame];
327

328 329 330 331
    /* 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;
332

333
    [self.window setFrame:windowFrame display:YES animate:NO];
334 335
}

336
- (NSRect)contrainFrameToAssociatedVoutWindow:(NSRect)frame
337
{
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    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;
358 359 360 361 362 363 364 365 366 367
}

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

- (void)setActive
{
    [self.window orderFront:self];
368
    [self fadeIn];
369 370 371 372 373 374 375 376 377 378 379 380
}

#pragma mark -
#pragma mark Misc interactions

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

- (void)setVoutWasUpdated:(VLCWindow *)voutWindow
{
381
    _associatedVoutWindow = voutWindow;
382

383 384 385
    NSRect voutRect = voutWindow.frame;
    if (!NSEqualRects(_associatedVoutFrame, voutRect)) {
        _associatedVoutFrame = voutRect;
386 387
        [[NSUserDefaults standardUserDefaults] setObject:NSStringFromRect(_associatedVoutFrame) forKey:kAssociatedFullscreenRect];

388
        [self centerPanel];
389
    }
390

391 392 393 394 395 396 397 398 399 400 401
}

#pragma mark -
#pragma mark Autohide timer management

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

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

405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    _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
{
421
    if (!NSMouseInRect([NSEvent mouseLocation], [self.window frame], NO)) {
422 423 424 425 426 427 428 429 430
        [self fadeOut];
        [self hideMouse];
    }
    _isCounting = NO;
}

#pragma mark -
#pragma mark Helpers

431
#ifdef MAC_OS_X_VERSION_10_10
432 433 434
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"

435 436 437
/**
 Create an image mask for the NSVisualEffectView
 with rounded corners in the given rect
438

439 440 441
 This is necessary as clipping the VisualEffectView using the layers
 rounded corners is not possible when using the NSColor clearColor
 as background color.
442

443 444
 \note  The returned image will have the necessary \c capInsets and
        \c capResizingMode set.
445

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
 \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
464

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

468 469 470 471 472 473 474 475 476 477 478 479 480 481
 \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];
482 483
    [_controlsView setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantDark]];
    [self.window.contentView addSubview:_controlsView];
484
}
485
#pragma clang diagnostic pop
486
#endif
487 488 489

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

491 492
 This is necessary on macOS versions that do not support the
 NSVisualEffectView that usually is injected.
493

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

    /* Inject view in view hierarchy */
    [self.window setContentView:view];
509
    [self.window.contentView addSubview:_controlsView];
510 511 512 513 514

    /* Disable adjusting height to workaround autolayout problems */
    [_heightMaxConstraint setConstant:42.0];
    [self.window setMaxSize:NSMakeSize(4068, 80)];
    [self.window setMinSize:NSMakeSize(480, 80)];
515 516 517 518 519 520 521 522 523
}

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


@end