summaryrefslogtreecommitdiffstats
path: root/macosx/HBPreviewController.m
blob: 586d7bb10d809e205743624d34e6a38d4320b741 (plain)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
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
/* $Id: HBPreviewController.m $

 This file is part of the HandBrake source code.
 Homepage: <http://handbrake.fr/>.
 It may be used under the terms of the GNU General Public License. */

#import "HBPreviewController.h"
#import "HBPreviewGenerator.h"
#import "HBPictureController.h"

#import "HBController.h"
#import "HBPreviewView.h"

#import "HBPlayer.h"
#import "HBAVPlayer.h"

#import "HBPictureHUDController.h"
#import "HBEncodingProgressHUDController.h"
#import "HBPlayerHUDController.h"

#import "NSWindow+HBAdditions.h"

#define ANIMATION_DUR 0.15
#define HUD_FADEOUT_TIME 4.0

// Make min width and height of preview window large enough for hud.
#define MIN_WIDTH 480.0
#define MIN_HEIGHT 360.0

@interface HBPreviewController () <HBPreviewGeneratorDelegate, HBPictureHUDControllerDelegate, HBEncodingProgressHUDControllerDelegate, HBPlayerHUDControllerDelegate>

@property (nonatomic, readonly) HBPictureHUDController *pictureHUD;
@property (nonatomic, readonly) HBEncodingProgressHUDController *encodingHUD;
@property (nonatomic, readonly) HBPlayerHUDController *playerHUD;

@property (nonatomic, readwrite) NSViewController<HBHUD> *currentHUD;

@property (nonatomic) NSTimer *hudTimer;
@property (nonatomic) BOOL mouseInWindow;

@property (nonatomic) id<HBPlayer> player;

@property (nonatomic) HBPictureController *pictureSettingsWindow;

@property (nonatomic) NSPoint windowCenterPoint;
@property (nonatomic, weak) IBOutlet HBPreviewView *previewView;

@end

@implementation HBPreviewController

- (instancetype)init
{
    self = [super initWithWindowNibName:@"PicturePreview"];
	return self;
}

- (void)windowDidLoad
{
    [self.window.contentView setWantsLayer:YES];

    // Read the window center position
    // We need the center and we can't use the
    // standard NSWindow autosave because we change
    // the window size at startup.
    NSString *centerString = [NSUserDefaults.standardUserDefaults stringForKey:@"HBPreviewWindowCenter"];
    if (centerString.length)
    {
        NSPoint center = NSPointFromString(centerString);
        self.windowCenterPoint = center;
        [self.window HB_resizeToBestSizeForViewSize:NSMakeSize(MIN_WIDTH, MIN_HEIGHT) keepInScreenRect:YES centerPoint:center animate:NO];
    }
    else
    {
        self.windowCenterPoint = [self.window HB_centerPoint];
    }

    self.window.excludedFromWindowsMenu = YES;
    self.window.acceptsMouseMovedEvents = YES;

    _pictureHUD = [[HBPictureHUDController alloc] init];
    self.pictureHUD.delegate = self;
    _encodingHUD = [[HBEncodingProgressHUDController alloc] init];
    self.encodingHUD.delegate = self;
    _playerHUD = [[HBPlayerHUDController alloc] init];
    self.playerHUD.delegate = self;

    [self.window.contentView addSubview:self.pictureHUD.view];
    [self.window.contentView addSubview:self.encodingHUD.view];
    [self.window.contentView addSubview:self.playerHUD.view];

    // Relocate our hud origins.
    CGPoint origin = CGPointMake(floor((self.window.frame.size.width - _pictureHUD.view.bounds.size.width) / 2), MIN_HEIGHT / 10);

    [self.pictureHUD.view setFrameOrigin:origin];
    [self.encodingHUD.view setFrameOrigin:origin];
    [self.playerHUD.view setFrameOrigin:origin];

    self.currentHUD = self.pictureHUD;
    self.currentHUD.view.hidden = YES;

    NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:self.window.contentView.frame
                                                                 options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingInVisibleRect | NSTrackingActiveAlways
                                                                   owner:self
                                                                userInfo:nil];
    [self.window.contentView addTrackingArea:trackingArea];
}

- (void)dealloc
{
    [_hudTimer invalidate];
    _generator.delegate = nil;
    [_generator cancel];
}

- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
    SEL action = menuItem.action;

    if (action == @selector(selectPresetFromMenu:))
    {
        return [self.documentController validateMenuItem:menuItem];
    }

    return YES;
}

- (IBAction)selectDefaultPreset:(id)sender
{
    [self.documentController selectDefaultPreset:sender];
}

- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window
{
    return self.documentController.window.undoManager;
}

- (IBAction)selectPresetFromMenu:(id)sender
{
    [self.documentController selectPresetFromMenu:sender];
}

- (void)setPicture:(HBPicture *)picture
{
    _picture = picture;
    self.pictureSettingsWindow.picture = _picture;
}

- (void)setGenerator:(HBPreviewGenerator *)generator
{
    if (_generator)
    {
        _generator.delegate = nil;
        [_generator cancel];
    }

    _generator = generator;

    if (generator)
    {
        generator.delegate = self;
        self.pictureHUD.generator = generator;
    }
    else
    {
        self.previewView.image = nil;
        self.window.title = NSLocalizedString(@"Preview", @"Preview -> window title");
        self.pictureHUD.generator = nil;
    }

    [self switchStateToHUD:self.pictureHUD];

    if (generator)
    {
        [self resizeToOptimalSize];
    }
}

- (void)reloadPreviews
{
    if (self.generator)
    {
        [self.generator cancel];
        [self switchStateToHUD:self.pictureHUD];
        [self resizeToOptimalSize];
    }
}

- (void)showWindow:(id)sender
{
    [super showWindow:sender];

    if (self.currentHUD == self.pictureHUD)
    {
        [self reloadPreviews];
    }
}

- (void)windowWillClose:(NSNotification *)aNotification
{
    if (self.currentHUD == self.encodingHUD)
    {
        [self cancelEncoding];
    }
    else if (self.currentHUD == self.playerHUD)
    {
        [self.player pause];
    }

    [self.pictureSettingsWindow close];
    [self.generator purgeImageCache];
}

#pragma mark - Window sizing

- (void)resizeToOptimalSize
{
    if (!(self.window.styleMask & NSWindowStyleMaskFullScreen))
    {
        if (self.previewView.fitToView)
        {
            [self.window setFrame:self.window.screen.visibleFrame display:YES animate:YES];
        }
        else
        {
            // Get the optimal view size for the image
            NSSize windowSize = [self.previewView optimalViewSizeForImageSize:self.generator.imageSize
                                                                      minSize:NSMakeSize(MIN_WIDTH, MIN_HEIGHT)
                                                                  scaleFactor:self.window.backingScaleFactor];
            // Scale the window to the image size
            [self.window HB_resizeToBestSizeForViewSize:windowSize keepInScreenRect:YES centerPoint:NSZeroPoint animate:self.window.isVisible];
        }
    }

    [self updateSizeLabels];
}

- (void)windowDidChangeBackingProperties:(NSNotification *)notification
{
    NSWindow *theWindow = (NSWindow *)notification.object;

    CGFloat newBackingScaleFactor = theWindow.backingScaleFactor;
    CGFloat oldBackingScaleFactor = [notification.userInfo[NSBackingPropertyOldScaleFactorKey] doubleValue];

    if (newBackingScaleFactor != oldBackingScaleFactor)
    {
        // Scale factor changed, resize the preview window
        if (self.generator)
        {
            [self resizeToOptimalSize];
        }
    }
}

#pragma mark - Window sizing

- (void)windowDidMove:(NSNotification *)notification
{
    if (self.previewView.fitToView == NO)
    {
        self.windowCenterPoint = [self.window HB_centerPoint];
        [NSUserDefaults.standardUserDefaults setObject:NSStringFromPoint(self.windowCenterPoint) forKey:@"HBPreviewWindowCenter"];
    }
}

- (void)windowDidResize:(NSNotification *)notification
{
    [self updateSizeLabels];
    if (self.currentHUD == self.playerHUD)
    {
        [CATransaction begin];
        CATransaction.disableActions = YES;
        self.player.layer.frame = self.previewView.pictureFrame;
        [CATransaction commit];
    }
}

- (void)updateSizeLabels
{
    if (self.generator)
    {
        CGFloat scale = self.previewView.scale;

        NSMutableString *scaleString = [NSMutableString string];
        if (scale * 100.0 != 100)
        {
            [scaleString appendFormat:NSLocalizedString(@"(%.0f%% actual size)", @"Preview -> size info label"), floor(scale * 100.0)];
        }
        else
        {
            [scaleString appendString:NSLocalizedString(@"(Actual size)", @"Preview -> size info label")];
        }

        if (self.previewView.fitToView == YES)
        {
            [scaleString appendString:NSLocalizedString(@" Scaled To Screen", @"Preview -> size info label")];
        }

        // Set the info fields in the hud controller
        self.pictureHUD.info = self.generator.info;
        self.pictureHUD.scale = scaleString;

        // Set the info field in the window title bar
        self.window.title = [NSString stringWithFormat:NSLocalizedString(@"Preview - %@ %@", @"Preview -> window title format"),
                             self.generator.info, scaleString];
    }
}

- (void)toggleScaleToScreen
{
    self.previewView.fitToView = !self.previewView.fitToView;
    [self resizeToOptimalSize];
}

#pragma mark - Hud State

/**
 * Switch the preview controller to one of his hud mode:
 * This methods is the only way to change the mode, do not try otherwise.
 * @param hud NSViewController<HBHUD> the hud to show
 */
- (void)switchStateToHUD:(NSViewController<HBHUD> *)hud
{
    if (self.currentHUD == self.playerHUD)
    {
        [self exitPlayerState];
    }

    if (hud == self.pictureHUD)
    {
        [self enterPictureState];
    }
    else if (hud == self.encodingHUD)
    {
        [self enterEncodingState];
    }
    else if (hud == self.playerHUD)
    {
        [self enterPlayerState];
    }

    // Show the current hud
    NSMutableArray<NSViewController<HBHUD> *> *huds = [@[self.pictureHUD, self.encodingHUD, self.playerHUD] mutableCopy];
    [huds removeObject:hud];
    for (NSViewController *controller in huds)
    {
        controller.view.hidden = YES;
    }

    if (self.generator)
    {
        hud.view.hidden = NO;
        hud.view.layer.opacity = 1.0;
    }

    [self.window makeFirstResponder:hud.view];
    [self startHudTimer];
    self.currentHUD = hud;
}

#pragma mark - HUD Control Overlay

- (void)mouseEntered:(NSEvent *)theEvent
{
    if (self.generator)
    {
        NSView *hud = self.currentHUD.view;

        [self showHudWithAnimation:hud];
        [self startHudTimer];
    }
    self.mouseInWindow = YES;
}

- (void)mouseExited:(NSEvent *)theEvent
{
    [self hudTimerFired:nil];
    self.mouseInWindow = NO;
}

- (void)mouseMoved:(NSEvent *)theEvent
{
    [super mouseMoved:theEvent];

    // Test for mouse location to show/hide hud controls
    if (self.generator && self.mouseInWindow)
    {
        NSView *hud = self.currentHUD.view;
        NSPoint mouseLoc = theEvent.locationInWindow;

        if (NSPointInRect(mouseLoc, hud.frame))
        {
            [self stopHudTimer];
        }
        else
        {
            [self showHudWithAnimation:hud];
            [self startHudTimer];
        }
	}
}

- (void)showHudWithAnimation:(NSView *)hud
{
    // The standard view animator doesn't play
    // nicely with the Yosemite visual effects yet.
    // So let's do the fade ourself.
    if (hud.layer.opacity == 0 || hud.isHidden)
    {
        [hud setHidden:NO];

        [CATransaction begin];
        CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
        fadeInAnimation.fromValue = @([hud.layer.presentationLayer opacity]);
        fadeInAnimation.toValue = @(1.0);
        fadeInAnimation.beginTime = 0.0;
        fadeInAnimation.duration = ANIMATION_DUR;

        [hud.layer addAnimation:fadeInAnimation forKey:nil];
        [hud.layer setOpacity:1];

        [CATransaction commit];
    }
}

- (void)hideHudWithAnimation:(NSView *)hud
{
    if (hud.layer.opacity != 0)
    {
        [CATransaction begin];
        CABasicAnimation *fadeOutAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
        fadeOutAnimation.fromValue = @([hud.layer.presentationLayer opacity]);
        fadeOutAnimation.toValue = @(0.0);
        fadeOutAnimation.beginTime = 0.0;
        fadeOutAnimation.duration = ANIMATION_DUR;

        [hud.layer addAnimation:fadeOutAnimation forKey:nil];
        [hud.layer setOpacity:0];

        [CATransaction commit];
    }
}

- (void)startHudTimer
{
	if (self.hudTimer)
    {
        [self.hudTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:HUD_FADEOUT_TIME]];
	}
    else
    {
        self.hudTimer = [NSTimer scheduledTimerWithTimeInterval:HUD_FADEOUT_TIME target:self selector:@selector(hudTimerFired:)
                                                       userInfo:nil repeats:YES];
    }
}

- (void)stopHudTimer
{
    [self.hudTimer invalidate];
    self.hudTimer = nil;
}

- (void)hudTimerFired:(NSTimer *)theTimer
{
    if (self.currentHUD.canBeHidden)
    {
        [self hideHudWithAnimation:self.currentHUD.view];
    }
    [self stopHudTimer];
}

#pragma mark - Still previews mode

- (void)enterPictureState
{
    [self displayPreviewAtIndex:self.pictureHUD.selectedIndex];
}

- (void)displayPreviewAtIndex:(NSUInteger)idx
{
    if (self.generator && self.window.isVisible)
    {
        CGImageRef image = [self.generator copyImageAtIndex:idx shouldCache:YES];
        self.previewView.image = image;
        CFRelease(image);
    }
}

- (void)showPictureSettings
{
    if (self.pictureSettingsWindow == nil)
    {
        self.pictureSettingsWindow = [[HBPictureController alloc] init];
        self.pictureSettingsWindow.previewController = self;
    }

    self.pictureSettingsWindow.picture = self.picture;
    [self.pictureSettingsWindow showWindow:self];
}

#pragma mark - Encoding mode

- (void)enterEncodingState
{
    self.encodingHUD.progress = 0;
}

- (void)cancelEncoding
{
    [self.generator cancel];
}

- (void)createMoviePreviewWithPictureIndex:(NSUInteger)index duration:(NSUInteger)duration
{
    if ([self.generator createMovieAsyncWithImageAtIndex:index duration:duration])
    {
        [self switchStateToHUD:self.encodingHUD];
    }
}

- (void)updateProgress:(double)progress info:(NSString *)progressInfo
{
    self.encodingHUD.progress = progress;
    self.encodingHUD.info = progressInfo;
}

- (void)didCancelMovieCreation
{
    [self switchStateToHUD:self.pictureHUD];
}

- (void)showAlert:(NSURL *)fileURL
{
    NSAlert *alert = [[NSAlert alloc] init];
    alert.messageText = NSLocalizedString(@"HandBrake can't open the preview.", @"Preview -> live preview alert message");
    alert.informativeText = NSLocalizedString(@"HandBrake can't playback this combination of video/audio/container format. Do you want to open it in an external player?", @"Preview -> live preview alert informative text");
    [alert addButtonWithTitle:NSLocalizedString(@"Open in external player", @"Preview -> live preview alert default button")];
    [alert addButtonWithTitle:NSLocalizedString(@"Cancel", @"Preview -> live preview alert alternate button")];

    [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode)
    {
        if (returnCode == NSAlertFirstButtonReturn)
        {
            [[NSWorkspace sharedWorkspace] openURL:fileURL];
        }
    }];
}

- (void)setUpPlaybackOfURL:(NSURL *)fileURL playerClass:(Class)class
{
    NSArray<Class> *availablePlayerClasses = @[[HBAVPlayer class]];

    self.player = [[class alloc] initWithURL:fileURL];

    if (self.player)
    {
        [self.player loadPlayableValueAsynchronouslyWithCompletionHandler:^{

            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.player.isPlayable && self.currentHUD == self.encodingHUD)
                {
                    [self switchStateToHUD:self.playerHUD];
                }
                else
                {
                    // Try to open the preview with the next player class.
                    NSUInteger idx = [availablePlayerClasses indexOfObject:class];
                    if (idx != NSNotFound && (idx + 1) < availablePlayerClasses.count)
                    {
                        Class nextPlayer = availablePlayerClasses[idx + 1];
                        [self setUpPlaybackOfURL:fileURL playerClass:nextPlayer];
                    }
                    else
                    {
                        [self showAlert:fileURL];
                        [self switchStateToHUD:self.pictureHUD];
                    }
                }
            });

        }];
    }
    else
    {
        [self showAlert:fileURL];
        [self switchStateToHUD:self.pictureHUD];
    }
}

- (void)didCreateMovieAtURL:(NSURL *)fileURL
{
    [self setUpPlaybackOfURL:fileURL playerClass:[HBAVPlayer class]];
}

#pragma mark - Player mode

- (void)enterPlayerState
{
    // Scale the layer to the picture player size
    CALayer *playerLayer = self.player.layer;
    playerLayer.frame = self.previewView.pictureFrame;

    [self.previewView.layer insertSublayer:playerLayer atIndex:10];
    self.playerHUD.player = self.player;
}

- (void)exitPlayerState
{
    self.playerHUD.player = nil;
    [self.player pause];
    [self.player.layer removeFromSuperlayer];
    self.player = nil;
}

- (void)stopPlayer
{
    [self switchStateToHUD:self.pictureHUD];
}

#pragma mark - Scroll

- (void)keyDown:(NSEvent *)event
{
    if (self.generator && [self.currentHUD HB_keyDown:event] == NO)
    {
        [super keyDown:event];
    }
}

- (void)scrollWheel:(NSEvent *)event
{
    if (self.generator && [self.currentHUD HB_scrollWheel:event] == NO)
    {
        [super scrollWheel:event];
    }
}

@end