summaryrefslogtreecommitdiffstats
path: root/chrome/browser/ui/cocoa/browser_window_enter_fullscreen_transition.mm
blob: 7eca5ec2087b2c953a1e2a21254a7a57f1700c26 (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
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "chrome/browser/ui/cocoa/browser_window_enter_fullscreen_transition.h"

#include <QuartzCore/QuartzCore.h>

#include "base/mac/scoped_cftyperef.h"
#include "base/mac/scoped_nsobject.h"
#include "base/mac/sdk_forward_declarations.h"

namespace {

NSString* const kPrimaryWindowAnimationID = @"PrimaryWindowAnimationID";
NSString* const kSnapshotWindowAnimationID = @"SnapshotWindowAnimationID";
NSString* const kAnimationIDKey = @"AnimationIDKey";

// This class has two simultaneous animations to resize and reposition layers.
// These animations must use the same timing function, otherwise there will be
// visual discordance.
NSString* TransformAnimationTimingFunction() {
  return kCAMediaTimingFunctionEaseInEaseOut;
}

}  // namespace

@interface BrowserWindowEnterFullscreenTransition () {
  // The window which is undergoing the fullscreen transition.
  base::scoped_nsobject<NSWindow> primaryWindow_;

  // A layer that holds a snapshot of the original state of |primaryWindow_|.
  base::scoped_nsobject<CALayer> snapshotLayer_;

  // A temporary window that holds |snapshotLayer_|.
  base::scoped_nsobject<NSWindow> snapshotWindow_;

  // The frame of the |primaryWindow_| before the transition began.
  NSRect primaryWindowInitialFrame_;

  // The background color of |primaryWindow_| before the transition began.
  base::scoped_nsobject<NSColor> primaryWindowInitialBackgroundColor_;

  // Whether |primaryWindow_| was opaque before the transition began.
  BOOL primaryWindowInitialOpaque_;

  // Whether the instance is in the process of changing the size of
  // |primaryWindow_|.
  BOOL changingPrimaryWindowSize_;

  // The frame that |primaryWindow_| is expected to have after the transition
  // is finished.
  NSRect primaryWindowFinalFrame_;
}

// Takes a snapshot of |primaryWindow_| and puts it in |snapshotLayer_|.
- (void)takeSnapshot;

// Creates |snapshotWindow_| and adds |snapshotLayer_| to it.
- (void)makeAndPrepareSnapshotWindow;

// This method has several effects on |primaryWindow_|:
//  - Saves current state.
//  - Makes window transparent, with clear background.
//  - Adds NSFullScreenWindowMask style mask.
//  - Sets the size to the screen's size.
- (void)preparePrimaryWindowForAnimation;

// Applies the fullscreen animation to |snapshotLayer_|.
- (void)animateSnapshotWindowWithDuration:(CGFloat)duration;

// Applies the fullscreen animation to the root layer of |primaryWindow_|.
- (void)animatePrimaryWindowWithDuration:(CGFloat)duration;

// Override of CAAnimation delegate method.
- (void)animationDidStop:(CAAnimation*)theAnimation finished:(BOOL)flag;

// Returns the layer of the root view of |window|.
- (CALayer*)rootLayerOfWindow:(NSWindow*)window;

@end

@implementation BrowserWindowEnterFullscreenTransition

// -------------------------Public Methods----------------------------

- (instancetype)initWithWindow:(NSWindow*)window {
  DCHECK(window);
  DCHECK([self rootLayerOfWindow:window]);
  if ((self = [super init])) {
    primaryWindow_.reset([window retain]);
  }
  return self;
}

- (NSArray*)customWindowsToEnterFullScreen {
  [self takeSnapshot];
  [self makeAndPrepareSnapshotWindow];
  [self preparePrimaryWindowForAnimation];
  return @[ primaryWindow_.get(), snapshotWindow_.get() ];
}

- (void)startCustomAnimationToEnterFullScreenWithDuration:
    (NSTimeInterval)duration {
  [self animateSnapshotWindowWithDuration:duration];
  [self animatePrimaryWindowWithDuration:duration];
}

- (BOOL)shouldWindowBeUnconstrained {
  return changingPrimaryWindowSize_;
}

// -------------------------Private Methods----------------------------

- (void)takeSnapshot {
  base::ScopedCFTypeRef<CGImageRef> windowSnapshot(CGWindowListCreateImage(
      CGRectNull, kCGWindowListOptionIncludingWindow,
      [primaryWindow_ windowNumber], kCGWindowImageBoundsIgnoreFraming));
  snapshotLayer_.reset([[CALayer alloc] init]);
  [snapshotLayer_ setFrame:NSRectToCGRect([primaryWindow_ frame])];
  [snapshotLayer_ setContents:static_cast<id>(windowSnapshot.get())];
  [snapshotLayer_ setAnchorPoint:CGPointMake(0, 0)];
  CGColorRef colorRef = CGColorCreateGenericRGB(0, 0, 0, 0);
  [snapshotLayer_ setBackgroundColor:colorRef];
  CGColorRelease(colorRef);
}

- (void)makeAndPrepareSnapshotWindow {
  DCHECK(snapshotLayer_);

  snapshotWindow_.reset(
      [[NSWindow alloc] initWithContentRect:[[primaryWindow_ screen] frame]
                                  styleMask:0
                                    backing:NSBackingStoreBuffered
                                      defer:NO]);
  [[snapshotWindow_ contentView] setWantsLayer:YES];
  [snapshotWindow_ setOpaque:NO];
  [snapshotWindow_ setBackgroundColor:[NSColor clearColor]];
  [snapshotWindow_ setAnimationBehavior:NSWindowAnimationBehaviorNone];

  [snapshotWindow_ orderFront:nil];
  [[[snapshotWindow_ contentView] layer] addSublayer:snapshotLayer_];

  // Compute the frame of the snapshot layer such that the snapshot is
  // positioned exactly on top of the original position of |primaryWindow_|.
  NSRect snapshotLayerFrame =
      [snapshotWindow_ convertRectFromScreen:[primaryWindow_ frame]];
  [snapshotLayer_ setFrame:snapshotLayerFrame];
}

- (void)preparePrimaryWindowForAnimation {
  // Save initial state of |primaryWindow_|.
  primaryWindowInitialFrame_ = [primaryWindow_ frame];
  primaryWindowInitialBackgroundColor_.reset(
      [[primaryWindow_ backgroundColor] copy]);
  primaryWindowInitialOpaque_ = [primaryWindow_ isOpaque];

  primaryWindowFinalFrame_ = [[primaryWindow_ screen] frame];

  // Make |primaryWindow_| invisible. This must happen before the window is
  // resized, since resizing the window will call drawRect: and cause content
  // to flash over the entire screen.
  [primaryWindow_ setOpaque:NO];
  [primaryWindow_ setBackgroundColor:[NSColor clearColor]];
  CALayer* rootLayer = [self rootLayerOfWindow:primaryWindow_];
  rootLayer.opacity = 0;

  // As soon as the style mask includes the flag NSFullScreenWindowMask, the
  // window is expected to receive fullscreen layout. This must be set before
  // the window is resized, as that causes a relayout.
  [primaryWindow_
      setStyleMask:[primaryWindow_ styleMask] | NSFullScreenWindowMask];

  // Resize |primaryWindow_|.
  changingPrimaryWindowSize_ = YES;
  [primaryWindow_ setFrame:primaryWindowFinalFrame_ display:YES];
  changingPrimaryWindowSize_ = NO;
}

- (void)animateSnapshotWindowWithDuration:(CGFloat)duration {
  // Move the snapshot layer until it's bottom-left corner is at the
  // bottom-left corner of the screen.
  CABasicAnimation* positionAnimation =
      [CABasicAnimation animationWithKeyPath:@"position"];
  positionAnimation.toValue = [NSValue valueWithPoint:NSZeroPoint];
  positionAnimation.timingFunction = [CAMediaTimingFunction
      functionWithName:TransformAnimationTimingFunction()];

  // Expand the bounds until it covers the screen.
  NSRect finalBounds = NSMakeRect(0, 0, NSWidth(primaryWindowFinalFrame_),
                                  NSHeight(primaryWindowFinalFrame_));
  CABasicAnimation* boundsAnimation =
      [CABasicAnimation animationWithKeyPath:@"bounds"];
  boundsAnimation.toValue = [NSValue valueWithRect:finalBounds];
  boundsAnimation.timingFunction = [CAMediaTimingFunction
      functionWithName:TransformAnimationTimingFunction()];

  // Fade out the snapshot layer.
  CABasicAnimation* opacityAnimation =
      [CABasicAnimation animationWithKeyPath:@"opacity"];
  opacityAnimation.toValue = @(0.0);
  opacityAnimation.timingFunction =
      [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

  // Fill forwards, and don't remove the animation. When the animation
  // completes, the entire window will be removed.
  CAAnimationGroup* group = [CAAnimationGroup animation];
  group.removedOnCompletion = NO;
  group.fillMode = kCAFillModeForwards;
  group.animations = @[ positionAnimation, boundsAnimation, opacityAnimation ];
  group.duration = duration;
  [group setValue:kSnapshotWindowAnimationID forKey:kAnimationIDKey];
  group.delegate = self;

  [snapshotLayer_ addAnimation:group forKey:nil];
}

- (void)animatePrimaryWindowWithDuration:(CGFloat)duration {
  // As soon as the window's root layer is scaled down, the opacity should be
  // set back to 1. There are a couple of ways to do this. The easiest is to
  // just have a dummy animation as part of the same animation group.
  CABasicAnimation* opacityAnimation =
      [CABasicAnimation animationWithKeyPath:@"opacity"];
  opacityAnimation.fromValue = @(1.0);
  opacityAnimation.toValue = @(1.0);

  // The root layer's size should start scaled down to the initial size of
  // |primaryWindow_|. The animation increases the size until the root layer
  // fills the screen.
  NSRect initialFrame = primaryWindowInitialFrame_;
  NSRect endFrame = primaryWindowFinalFrame_;
  CGFloat xScale = NSWidth(initialFrame) / NSWidth(endFrame);
  CGFloat yScale = NSHeight(initialFrame) / NSHeight(endFrame);
  CATransform3D initial = CATransform3DMakeScale(xScale, yScale, 1);
  CABasicAnimation* transformAnimation =
      [CABasicAnimation animationWithKeyPath:@"transform"];
  transformAnimation.fromValue = [NSValue valueWithCATransform3D:initial];

  CALayer* root = [self rootLayerOfWindow:primaryWindow_];

  // Calculate the initial position of the root layer. This calculation is
  // agnostic of the anchorPoint.
  CGFloat layerStartPositionDeltaX = NSMidX(initialFrame) - NSMidX(endFrame);
  CGFloat layerStartPositionDeltaY = NSMidY(initialFrame) - NSMidY(endFrame);
  NSPoint layerStartPosition =
      NSMakePoint(root.position.x + layerStartPositionDeltaX,
                  root.position.y + layerStartPositionDeltaY);

  // Animate the primary window from its initial position.
  CABasicAnimation* positionAnimation =
      [CABasicAnimation animationWithKeyPath:@"position"];
  positionAnimation.fromValue = [NSValue valueWithPoint:layerStartPosition];

  CAAnimationGroup* group = [CAAnimationGroup animation];
  group.removedOnCompletion = NO;
  group.fillMode = kCAFillModeForwards;
  group.animations =
      @[ transformAnimation, opacityAnimation, positionAnimation ];
  group.timingFunction = [CAMediaTimingFunction
      functionWithName:TransformAnimationTimingFunction()];
  group.duration = duration;
  [group setValue:kPrimaryWindowAnimationID forKey:kAnimationIDKey];
  group.delegate = self;

  [root addAnimation:group forKey:kPrimaryWindowAnimationID];
}

- (void)animationDidStop:(CAAnimation*)theAnimation finished:(BOOL)flag {
  NSString* animationID = [theAnimation valueForKey:kAnimationIDKey];
  if ([animationID isEqual:kSnapshotWindowAnimationID]) {
    [snapshotWindow_ orderOut:nil];
    snapshotWindow_.reset();
    snapshotLayer_.reset();
    return;
  }

  if ([animationID isEqual:kPrimaryWindowAnimationID]) {
    [primaryWindow_ setOpaque:YES];
    [primaryWindow_ setBackgroundColor:primaryWindowInitialBackgroundColor_];
    CALayer* root = [self rootLayerOfWindow:primaryWindow_];
    root.opacity = 1;
    [root removeAnimationForKey:kPrimaryWindowAnimationID];
  }
}

- (CALayer*)rootLayerOfWindow:(NSWindow*)window {
  return [[[window contentView] superview] layer];
}

@end