summaryrefslogtreecommitdiffstats
path: root/macosx/HBPreviewController.m
blob: 1db48cdcd5e4f79bb86cbd749190941847d9eefa (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
/* $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 "HBQTKitPlayer.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 (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] objectForKey:@"HBPreviewWindowCenter"];
    if (centerString.length)
    {
        NSPoint center = NSPointFromString(centerString);
        self.windowCenterPoint = center;
        [self.window HB_resizeToBestSizeForViewSize:NSMakeSize(MIN_WIDTH, MIN_HEIGHT) center:self.windowCenterPoint 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((MIN_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;

        // adjust the preview slider length
        self.pictureHUD.pictureCount = generator.imagesCount;
        [self switchStateToHUD:self.pictureHUD];
    }
    else
    {
        self.previewView.image = nil;
        self.currentHUD.view.hidden = YES;
        self.window.title = NSLocalizedString(@"Preview", nil);
    }
}

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

- (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];
}

- (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, update the preview window
        // to the new situation
        if (self.generator)
        {
            [self reloadPreviews];
        }
    }
}

#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];
}

- (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)", nil), scale * 100.0];
        }
        else
        {
            [scaleString appendString:NSLocalizedString(@"(Actual size)", nil)];
        }

        if (self.previewView.fitToView == YES)
        {
            [scaleString appendString:NSLocalizedString(@" Scaled To Screen", nil)];
        }

        // 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 - %@ %@", nil),
                             self.generator.info, scaleString];
    }
}

#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 *huds = [@[self.pictureHUD, self.encodingHUD, self.playerHUD] mutableCopy];
    [huds removeObject:hud];
    for (NSViewController *controller in huds) {
        controller.view.hidden = YES;
    }
    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];
}

/**
 * Adjusts the window to draw the current picture (fPicture) adjusting its size as
 * necessary to display as much of the picture as possible.
 */
- (void)displayPreviewAtIndex:(NSUInteger)idx
{
    if (!self.generator)
    {
        return;
    }

    if (self.window.isVisible)
    {
        CGImageRef fPreviewImage = [self.generator copyImageAtIndex:idx shouldCache:YES];
        [self.previewView setImage:fPreviewImage];
        CFRelease(fPreviewImage);
    }

    if (self.previewView.fitToView == NO && !(self.window.styleMask & NSFullScreenWindowMask))
    {
        // Get the optimal view size for the image
        NSSize imageScaledSize = [self.generator imageSize];

        // Scale the window to the image size
        NSSize windowSize = [self.previewView optimalViewSizeForImageSize:imageScaledSize minSize:NSMakeSize(MIN_WIDTH, MIN_HEIGHT)];
        [self.window HB_resizeToBestSizeForViewSize:windowSize center:self.windowCenterPoint animate:self.window.isVisible];
    }

    [self updateSizeLabels];
}

- (void)toggleScaleToScreen
{
    if (self.previewView.fitToView == YES)
    {
        self.previewView.fitToView = NO;
        [self displayPreviewAtIndex:self.pictureHUD.selectedIndex];
    }
    else
    {
        self.previewView.fitToView = YES;
        if (!(self.window.styleMask & NSFullScreenWindowMask))
        {
            [self.window setFrame:self.window.screen.visibleFrame display:YES animate:YES];
        }
    }
}

- (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 alertWithMessageText:NSLocalizedString(@"HandBrake can't open the preview.", nil)
                                     defaultButton:NSLocalizedString(@"Open in external player", nil)
                                   alternateButton:NSLocalizedString(@"Cancel", nil)
                                       otherButton:nil
                         informativeTextWithFormat:NSLocalizedString(@"HandBrake can't playback this combination of video/audio/container format. Do you want to open it in an external player?", nil)];

    [alert beginSheetModalForWindow:self.window modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:(void *)CFBridgingRetain(fileURL)];
}

- (void)alertDidEnd:(NSAlert *)alert
         returnCode:(NSInteger)returnCode
        contextInfo:(void *)contextInfo
{
    NSURL *fileURL = CFBridgingRelease(contextInfo);
    if (returnCode == NSModalResponseOK)
    {
        [[NSWorkspace sharedWorkspace] openURL:fileURL];
    }
}

- (void)setUpPlaybackOfURL:(NSURL *)fileURL;
{
    if (self.player.isPlayable && self.currentHUD == self.encodingHUD)
    {
        [self switchStateToHUD:self.playerHUD];
    }
    else
    {
        [self showAlert:fileURL];
        [self switchStateToHUD:self.pictureHUD];
    }
}

- (void)didCreateMovieAtURL:(NSURL *)fileURL
{
    if (fileURL)
    {
        self.player = [[HBAVPlayer alloc] initWithURL:fileURL];

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

                dispatch_async(dispatch_get_main_queue(), ^{
                    [self setUpPlaybackOfURL:fileURL];
                });

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

#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.window.contentView.layer insertSublayer:playerLayer atIndex:1];

    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.currentHUD HB_keyDown:event] == NO)
    {
        [super keyDown:event];
    }
}

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

@end