File: constrained_window_animation.mm

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (377 lines) | stat: -rw-r--r-- 12,139 bytes parent folder | download | duplicates (7)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#import "ui/base/cocoa/constrained_window/constrained_window_animation.h"

#include <stdint.h>
#include <stdlib.h>

#import "base/apple/foundation_util.h"
#include "base/files/file_path.h"
#include "base/location.h"
#include "base/native_library.h"
#include "base/notreached.h"
#include "ui/gfx/animation/tween.h"

// The window animations in this file use private APIs as described here:
// https://github.com/MarkVillacampa/undocumented-goodness/blob/master/CoreGraphics/CGSPrivate.h
// There are two important things to keep in mind when modifying this file:
// - For most operations the origin of the coordinate system is top left.
// - Perspective and shear transformations get clipped if they are bigger
//   than the window size. This does not seem to apply to scale transformations.

// Length of the animation in seconds.
const NSTimeInterval kAnimationDuration = 0.18;

// The number of pixels above the final destination to animate from.
const CGFloat kShowHideVerticalOffset = 20;

// Scale the window by this factor when animating.
const CGFloat kShowHideScaleFactor = 0.99;

// Size of the perspective effect as a factor of the window width.
const CGFloat kShowHidePerspectiveFactor = 0.04;

// Forward declare private CoreGraphics APIs used to transform windows.
extern "C" {

typedef float float32;

typedef int32_t CGSWindow;
typedef int32_t CGSConnection;

typedef struct {
  float32 x;
  float32 y;
} MeshPoint;

typedef struct {
  MeshPoint local;
  MeshPoint global;
} CGPointWarp;

CGSConnection _CGSDefaultConnection();
CGError CGSSetWindowTransform(const CGSConnection cid,
                              const CGSWindow wid,
                              CGAffineTransform transform);
CGError CGSSetWindowWarp(const CGSConnection cid,
                         const CGSWindow wid,
                         int32_t w,
                         int32_t h,
                         CGPointWarp* mesh);
CGError CGSSetWindowAlpha(const CGSConnection cid,
                          const CGSWindow wid,
                          float32 alpha);

}  // extern "C"

namespace {

struct KeyFrame {
  float value;
  float scale;
};

// Get the window location relative to the top left of the main screen.
// Most Cocoa APIs use a coordinate system where the screen origin is the
// bottom left. The various CGSSetWindow* APIs use a coordinate system where
// the screen origin is the top left.
NSPoint GetCGSWindowScreenOrigin(NSWindow* window) {
  NSArray* screens = NSScreen.screens;
  if (screens.count == 0) {
    return NSZeroPoint;
  }
  // Origin is relative to the screen with the menu bar (the screen at index 0).
  // Note, this is not the same as mainScreen which is the screen with the key
  // window.
  NSScreen* main_screen = screens[0];

  NSRect window_frame = window.frame;
  NSRect screen_frame = main_screen.frame;
  return NSMakePoint(NSMinX(window_frame),
                     NSHeight(screen_frame) - NSMaxY(window_frame));
}

// Set the transparency of the window.
void SetWindowAlpha(NSWindow* window, float alpha) {
  CGSConnection cid = _CGSDefaultConnection();
  CGSSetWindowAlpha(cid, static_cast<CGSWindow>(window.windowNumber), alpha);
}

// Scales the window and translates it so that it stays centered relative
// to its original position.
void SetWindowScale(NSWindow* window, float scale) {
  CGFloat scale_delta = 1.0 - scale;
  CGFloat cur_scale = 1.0 + scale_delta;
  CGAffineTransform transform =
      CGAffineTransformMakeScale(cur_scale, cur_scale);

  // Translate the window to keep it centered at the original location.
  NSSize window_size = window.frame.size;
  CGFloat scale_offset_x = window_size.width * (1 - cur_scale) / 2.0;
  CGFloat scale_offset_y = window_size.height * (1 - cur_scale) / 2.0;

  NSPoint origin = GetCGSWindowScreenOrigin(window);
  CGFloat new_x = -origin.x + scale_offset_x;
  CGFloat new_y = -origin.y + scale_offset_y;
  transform = CGAffineTransformTranslate(transform, new_x, new_y);

  CGSConnection cid = _CGSDefaultConnection();
  CGSSetWindowTransform(cid, static_cast<CGSWindow>(window.windowNumber),
                        transform);
}

// Unsets any window warp that may have been previously applied.
// Window warp prevents other effects such as CGSSetWindowTransform from
// being applied.
void ClearWindowWarp(NSWindow* window) {
  CGSConnection cid = _CGSDefaultConnection();
  CGSSetWindowWarp(cid, static_cast<CGSWindow>(window.windowNumber), 0, 0,
                   nullptr);
}

// Applies various transformations using a warp effect. The window is
// translated vertically by |y_offset|. The window is scaled by |scale| and
// translated so that the it remains centered relative to its original position.
// Finally, perspective is effect is applied by shrinking the top of the window.
void SetWindowWarp(NSWindow* window,
                   float y_offset,
                   float scale,
                   float perspective_offset) {
  NSRect win_rect = window.frame;
  win_rect.origin = NSZeroPoint;
  NSRect screen_rect = win_rect;
  screen_rect.origin = GetCGSWindowScreenOrigin(window);

  // Apply a vertical translate.
  screen_rect.origin.y -= y_offset;

  // Apply a scale and translate to keep the window centered.
  screen_rect.origin.x += (NSWidth(win_rect) - NSWidth(screen_rect)) / 2.0;
  screen_rect.origin.y += (NSHeight(win_rect) - NSHeight(screen_rect)) / 2.0;

  // A 2 x 2 mesh that maps each corner of the window to a location in screen
  // coordinates. Note that the origin of the coordinate system is top, left.
  CGPointWarp mesh[2][2] = {
      {{
           // Top left.
           {static_cast<float>(NSMinX(win_rect)),
            static_cast<float>(NSMinY(win_rect))},
           {static_cast<float>(NSMinX(screen_rect) + perspective_offset),
            static_cast<float>(NSMinY(screen_rect))},
       },
       {
           // Top right.
           {static_cast<float>(NSMaxX(win_rect)),
            static_cast<float>(NSMinY(win_rect))},
           {static_cast<float>(NSMaxX(screen_rect) - perspective_offset),
            static_cast<float>(NSMinY(screen_rect))},
       }},
      {{
           // Bottom left.
           {static_cast<float>(NSMinX(win_rect)),
            static_cast<float>(NSMaxY(win_rect))},
           {static_cast<float>(NSMinX(screen_rect)),
            static_cast<float>(NSMaxY(screen_rect))},
       },
       {
           // Bottom right.
           {static_cast<float>(NSMaxX(win_rect)),
            static_cast<float>(NSMaxY(win_rect))},
           {static_cast<float>(NSMaxX(screen_rect)),
            static_cast<float>(NSMaxY(screen_rect))},
       }},
  };

  CGSConnection cid = _CGSDefaultConnection();
  CGSSetWindowWarp(cid, static_cast<CGSWindow>(window.windowNumber), 2, 2,
                   &(mesh[0][0]));
}

// Sets the various effects that are a part of the Show/Hide animation.
// Value is a number between 0 and 1 where 0 means the window is completely
// hidden and 1 means the window is fully visible.
void UpdateWindowShowHideAnimationState(NSWindow* window, CGFloat value) {
  CGFloat inverse_value = 1.0 - value;

  SetWindowAlpha(window, value);
  CGFloat y_offset = kShowHideVerticalOffset * inverse_value;
  CGFloat scale = 1.0 - (1.0 - kShowHideScaleFactor) * inverse_value;
  CGFloat perspective_offset =
      (window.frame.size.width * kShowHidePerspectiveFactor) * inverse_value;

  SetWindowWarp(window, y_offset, scale, perspective_offset);
}

bool AreWindowServerEffectsDisabled() {
  // If the CHROME_HEADLESS env variable is set, this code is running in a
  // test environment. The custom constrained window animations may be
  // causing the WindowServer to crash (https://crbug.com/828031), so use the
  // simple animations.
  static bool is_headless = getenv("CHROME_HEADLESS") != nullptr;
  return is_headless;
}

}  // namespace

@interface ConstrainedWindowAnimationBase ()
// Subclasses should override these to update the window state for the current
// animation value.
- (void)setWindowStateForStart;
- (void)setWindowStateForValue:(float)value;
- (void)setWindowStateForEnd;

@property(strong) NSWindow* window;

@end

@implementation ConstrainedWindowAnimationBase

@synthesize window = _window;

- (instancetype)initWithWindow:(NSWindow*)window {
  if ((self = [self initWithDuration:kAnimationDuration
                      animationCurve:NSAnimationEaseInOut])) {
    self.window = window;
    self.animationBlockingMode = NSAnimationBlocking;
    [self setWindowStateForStart];
  }
  return self;
}

- (void)stopAnimation {
  [super stopAnimation];
  [self setWindowStateForEnd];
  if ([self.delegate respondsToSelector:@selector(animationDidEnd:)]) {
    [self.delegate animationDidEnd:self];
  }
}

- (void)setCurrentProgress:(NSAnimationProgress)progress {
  [super setCurrentProgress:progress];

  if (progress >= 1.0) {
    [self setWindowStateForEnd];

    // Starting in 10.10, the WindowServer forgets to draw the shadow on windows
    // that animate in this way on retina screens. -[NSWindow invalidateShadow]
    // doesn't fix it. Neither does toggling -setHasShadow:. But forcing an
    // update to the window size, and then undoing it, seems to fix the problem.
    // See http://crbug.com/436884.
    // TODO(tapted): Find a better fix (this is horrible).
    if (!AreWindowServerEffectsDisabled()) {
      NSRect frame = self.window.frame;
      [self.window setFrame:NSInsetRect(frame, 1, 1) display:NO animate:NO];
      [self.window setFrame:frame display:NO animate:NO];
    }
    return;
  }
  [self setWindowStateForValue:[self currentValue]];
}

- (void)setWindowStateForStart {
  // Subclasses can optionally override this method.
}

- (void)setWindowStateForValue:(float)value {
  // Subclasses must override this method.
  NOTREACHED();
}

- (void)setWindowStateForEnd {
  // Subclasses can optionally override this method.
}

@end

@implementation ConstrainedWindowAnimationShow

- (void)setWindowStateForStart {
  if (AreWindowServerEffectsDisabled()) {
    self.window.alphaValue = 0.0;
    return;
  }
  SetWindowAlpha(self.window, 0.0);
}

- (void)setWindowStateForValue:(float)value {
  if (AreWindowServerEffectsDisabled()) {
    self.window.alphaValue = value;
    return;
  }
  UpdateWindowShowHideAnimationState(self.window, value);
}

- (void)setWindowStateForEnd {
  if (AreWindowServerEffectsDisabled()) {
    self.window.alphaValue = 1.0;
    return;
  }
  SetWindowAlpha(self.window, 1.0);
  ClearWindowWarp(self.window);
}

@end

@implementation ConstrainedWindowAnimationHide

- (void)setWindowStateForValue:(float)value {
  if (AreWindowServerEffectsDisabled()) {
    self.window.alphaValue = 1.0 - value;
    return;
  }
  UpdateWindowShowHideAnimationState(self.window, 1.0 - value);
}

- (void)setWindowStateForEnd {
  if (AreWindowServerEffectsDisabled()) {
    self.window.alphaValue = 0.0;
    return;
  }
  SetWindowAlpha(self.window, 0.0);
  ClearWindowWarp(self.window);
}

@end

@implementation ConstrainedWindowAnimationPulse

// Sets the window scale based on the animation progress.
- (void)setWindowStateForValue:(float)value {
  if (AreWindowServerEffectsDisabled())
    return;

  KeyFrame frames[] = {
      {0.00, 1.0}, {0.40, 1.02}, {0.60, 1.02}, {1.00, 1.0},
  };

  CGFloat scale = 1;
  for (int i = std::size(frames) - 1; i >= 0; --i) {
    if (value >= frames[i].value) {
      CGFloat delta = frames[i + 1].value - frames[i].value;
      CGFloat frame_progress = (value - frames[i].value) / delta;
      scale = gfx::Tween::FloatValueBetween(frame_progress, frames[i].scale,
                                            frames[i + 1].scale);
      break;
    }
  }

  SetWindowScale(self.window, scale);
}

- (void)setWindowStateForEnd {
  if (AreWindowServerEffectsDisabled()) {
    NSBeep();
    return;
  }

  SetWindowScale(self.window, 1.0);
}

@end