@blotch/angular-lynx-native 22.2.25 → 22.2.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +15 -11
  2. package/dist/android/project.d.ts +13 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +40 -11
  5. package/dist/app-links.d.ts +53 -0
  6. package/dist/app-links.d.ts.map +1 -0
  7. package/dist/app-links.js +115 -0
  8. package/dist/generate.d.ts +1 -1
  9. package/dist/generate.js +8 -2
  10. package/dist/index.d.ts +3 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +23 -0
  13. package/dist/ios/build.d.ts.map +1 -1
  14. package/dist/ios/build.js +5 -0
  15. package/dist/ios/project.d.ts +16 -2
  16. package/dist/ios/project.d.ts.map +1 -1
  17. package/dist/ios/project.js +57 -6
  18. package/dist/options.d.ts +68 -1
  19. package/dist/options.d.ts.map +1 -1
  20. package/dist/options.js +70 -0
  21. package/dist/permissions.d.ts.map +1 -1
  22. package/dist/permissions.js +7 -0
  23. package/dist/png.d.ts +5 -0
  24. package/dist/png.d.ts.map +1 -1
  25. package/dist/png.js +19 -5
  26. package/dist/splash.d.ts +70 -0
  27. package/dist/splash.d.ts.map +1 -0
  28. package/dist/splash.js +239 -0
  29. package/package.json +1 -1
  30. package/templates/android/README.md +11 -2
  31. package/templates/android/app/build.gradle.kts +19 -9
  32. package/templates/android/app/proguard-rules.pro +67 -55
  33. package/templates/android/app/src/debug/java/dev/angularlynx/shell/DevServer.kt +6 -0
  34. package/templates/android/app/src/main/AndroidManifest.xml +3 -1
  35. package/templates/android/app/src/main/java/dev/angularlynx/shell/AssetsModule.kt +2 -1
  36. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +16 -3
  37. package/templates/android/app/src/main/java/dev/angularlynx/shell/LinkingModule.kt +42 -0
  38. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +96 -7
  39. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +15 -0
  40. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +24 -0
  41. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +15 -4
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +10 -1
  43. package/templates/android/app/src/main/res/values/colors.xml +3 -2
  44. package/templates/android/app/src/main/res/values/splash.xml +9 -0
  45. package/templates/android/app/src/main/res/values/themes.xml +14 -0
  46. package/templates/android/app/src/release/java/dev/angularlynx/shell/DevServer.kt +2 -0
  47. package/templates/android/build.gradle.kts +1 -1
  48. package/templates/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  49. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  50. package/templates/android/gradlew.bat +41 -11
  51. package/templates/ios/App/AngularLynxWebGL.h +34 -6
  52. package/templates/ios/App/AngularLynxWebGL.m +58 -23
  53. package/templates/ios/App/AngularLynxWebGLContext.m +104 -26
  54. package/templates/ios/App/AnimationFrameRate.swift +214 -0
  55. package/templates/ios/App/AppDelegate.swift +48 -0
  56. package/templates/ios/App/AssetsModule.swift +3 -1
  57. package/templates/ios/App/DevServer.swift +3 -0
  58. package/templates/ios/App/Info.plist +12 -5
  59. package/templates/ios/App/LinkingModule.swift +62 -1
  60. package/templates/ios/App/LynxViewController.swift +30 -6
  61. package/templates/ios/App/ShellModule.swift +40 -1
  62. package/templates/ios/App/SplashScreen.swift +71 -0
@@ -9,6 +9,14 @@
9
9
  // (`enableMTSModule`). The runtime batches the calls into one `run` per frame;
10
10
  // see packages/runtime/src/lib/canvas/webgl-bridge.ts for the protocol.
11
11
  //
12
+ // Lynx's main thread is its engine thread, which the shell runs off the UI
13
+ // thread (LynxViewController's thread strategy), and the module's calls
14
+ // arrive there. So every GL call is made there: an EGL context is current on
15
+ // one thread at a time, and the context keeps it current between batches.
16
+ // The canvas's view lives on the UI thread, and hands the context what it
17
+ // draws into (AngularLynxCanvasTarget) through Lynx's runOnTasmThread:, so
18
+ // the registry and the contexts are the engine thread's alone.
19
+ //
12
20
  // The OpenGL ES 3.0 is ANGLE's, on Metal (libEGL and libGLESv2, prebuilt
13
21
  // with Lynx's frameworks by scripts/build-angle-ios-frameworks.sh), rather
14
22
  // than iOS's own OpenGL ES. Apple deprecated that in iOS 12, and the
@@ -18,18 +26,37 @@
18
26
  // 3.00, is WebGL2's, so three.js's shaders compile as they are.
19
27
 
20
28
  #import <Foundation/Foundation.h>
29
+ #import <Lynx/LynxContext.h>
21
30
  #import <Lynx/LynxModule.h>
22
31
  #import <Lynx/LynxUI.h>
32
+ #import <QuartzCore/QuartzCore.h>
23
33
  #import <UIKit/UIKit.h>
24
34
 
25
35
  NS_ASSUME_NONNULL_BEGIN
26
36
 
27
37
  @class AngularLynxCanvasView;
28
38
 
39
+ /// What a canvas's view gives its context to show frames in: the view's
40
+ /// CAMetalLayer, which the context makes its window surface on, and the
41
+ /// layer's size in pixels. The context reads it on the engine thread, where
42
+ /// a UIView mustn't be touched, nor released for the last time.
43
+ @interface AngularLynxCanvasTarget : NSObject
44
+ @property(nonatomic, readonly) CAMetalLayer *layer;
45
+ /// The layer's size in pixels as the view was last laid out: written on the
46
+ /// UI thread, read on the engine thread.
47
+ @property(atomic) CGSize pixelSize;
48
+ /// The view, for the UI thread alone (the context sets its opacity there).
49
+ @property(nonatomic, weak, readonly, nullable) AngularLynxCanvasView *view;
50
+ @end
51
+
29
52
  /// The drawing surface: a view backed by a CAMetalLayer, which the context
30
53
  /// copies each finished frame into (an EGL window surface on the layer).
31
54
  @interface AngularLynxCanvasView : UIView
32
55
  @property(nonatomic, copy, nullable) NSString *canvasId;
56
+ /// The LynxView's context, whose engine thread the view hands its target to
57
+ /// (runOnTasmThread:). The canvas element sets it before the canvas id.
58
+ @property(nonatomic, weak, nullable) LynxContext *lynxContext;
59
+ @property(nonatomic, readonly) AngularLynxCanvasTarget *target;
33
60
  @end
34
61
 
35
62
  /// The `canvas` element. Its `canvas-id` attribute, which the runtime sets,
@@ -63,24 +90,25 @@ NS_ASSUME_NONNULL_BEGIN
63
90
  - (NSDictionary *)encodeImageOfType:(NSString *)type
64
91
  quality:(double)quality
65
92
  premultiplied:(BOOL)premultiplied;
66
- /// Shows frames in this view, or nowhere while it's nil.
67
- - (void)attachView:(nullable AngularLynxCanvasView *)view;
93
+ /// Shows frames in this canvas's target, or nowhere while it's nil.
94
+ - (void)attachTarget:(nullable AngularLynxCanvasTarget *)target;
68
95
  /// The view was laid out: a frame that waited for it to have a size is shown.
69
- - (void)viewDidLayOut:(AngularLynxCanvasView *)view;
96
+ - (void)targetDidLayOut:(AngularLynxCanvasTarget *)target;
70
97
  - (void)destroy;
71
98
  @end
72
99
 
73
100
  /// Pairs canvases with contexts by canvas id: either can come first, as the
74
101
  /// runtime may make the context before Lynx has made the element's view.
102
+ /// Engine thread only, as the contexts are.
75
103
  @interface AngularLynxCanvasRegistry : NSObject
76
- + (void)setView:(nullable AngularLynxCanvasView *)view forCanvasId:(NSString *)canvasId;
77
- + (nullable AngularLynxCanvasView *)viewForCanvasId:(NSString *)canvasId;
104
+ + (void)setTarget:(nullable AngularLynxCanvasTarget *)target forCanvasId:(NSString *)canvasId;
105
+ + (nullable AngularLynxCanvasTarget *)targetForCanvasId:(NSString *)canvasId;
78
106
  + (void)setContext:(nullable AngularLynxWebGLContext *)context forCanvasId:(NSString *)canvasId;
79
107
  + (nullable AngularLynxWebGLContext *)contextForCanvasId:(NSString *)canvasId;
80
108
  @end
81
109
 
82
110
  /// The `AngularLynxWebGL` module. Registered on the LynxView's config, and
83
- /// called from the main thread.
111
+ /// called from Lynx's main thread, on its engine thread.
84
112
  @interface AngularLynxWebGLModule : NSObject <LynxModule>
85
113
  @end
86
114
 
@@ -8,8 +8,8 @@
8
8
 
9
9
  @implementation AngularLynxCanvasRegistry
10
10
 
11
- // Weak both ways: the view belongs to Lynx, the context to the module.
12
- static NSMapTable<NSString *, AngularLynxCanvasView *> *views(void) {
11
+ // Weak both ways: the target belongs to its view, the context to the module.
12
+ static NSMapTable<NSString *, AngularLynxCanvasTarget *> *targets(void) {
13
13
  static NSMapTable *table;
14
14
  static dispatch_once_t once;
15
15
  dispatch_once(&once, ^{
@@ -27,23 +27,23 @@ static NSMapTable<NSString *, AngularLynxWebGLContext *> *contexts(void) {
27
27
  return table;
28
28
  }
29
29
 
30
- + (void)setView:(AngularLynxCanvasView *)view forCanvasId:(NSString *)canvasId {
31
- if (view) {
32
- [views() setObject:view forKey:canvasId];
30
+ + (void)setTarget:(AngularLynxCanvasTarget *)target forCanvasId:(NSString *)canvasId {
31
+ if (target) {
32
+ [targets() setObject:target forKey:canvasId];
33
33
  } else {
34
- [views() removeObjectForKey:canvasId];
34
+ [targets() removeObjectForKey:canvasId];
35
35
  }
36
- [[contexts() objectForKey:canvasId] attachView:view];
36
+ [[contexts() objectForKey:canvasId] attachTarget:target];
37
37
  }
38
38
 
39
- + (AngularLynxCanvasView *)viewForCanvasId:(NSString *)canvasId {
40
- return [views() objectForKey:canvasId];
39
+ + (AngularLynxCanvasTarget *)targetForCanvasId:(NSString *)canvasId {
40
+ return [targets() objectForKey:canvasId];
41
41
  }
42
42
 
43
43
  + (void)setContext:(AngularLynxWebGLContext *)context forCanvasId:(NSString *)canvasId {
44
44
  if (context) {
45
45
  [contexts() setObject:context forKey:canvasId];
46
- [context attachView:[views() objectForKey:canvasId]];
46
+ [context attachTarget:[targets() objectForKey:canvasId]];
47
47
  } else {
48
48
  [contexts() removeObjectForKey:canvasId];
49
49
  }
@@ -289,6 +289,18 @@ static AngularLynxDecodedImage *decodeImage(NSData *bytes, NSDictionary *options
289
289
 
290
290
  #pragma mark - Canvas
291
291
 
292
+ @implementation AngularLynxCanvasTarget
293
+
294
+ - (instancetype)initWithView:(AngularLynxCanvasView *)view {
295
+ if ((self = [super init])) {
296
+ _layer = (CAMetalLayer *)view.layer;
297
+ _view = view;
298
+ }
299
+ return self;
300
+ }
301
+
302
+ @end
303
+
292
304
  @implementation AngularLynxCanvasView
293
305
 
294
306
  + (Class)layerClass {
@@ -305,40 +317,62 @@ static AngularLynxDecodedImage *decodeImage(NSData *bytes, NSDictionary *options
305
317
  self.contentScaleFactor = UIScreen.mainScreen.scale;
306
318
  // Lynx dispatches touches itself, from the LynxView.
307
319
  self.userInteractionEnabled = NO;
320
+ _target = [[AngularLynxCanvasTarget alloc] initWithView:self];
308
321
  }
309
322
  return self;
310
323
  }
311
324
 
325
+ /// Runs `block` on Lynx's engine thread, where the module's calls arrive and
326
+ /// every GL call is made: next on it, or at once when this is it (it's the UI
327
+ /// thread under Lynx's default thread strategy). Nothing runs once the
328
+ /// LynxView has gone, nor do its contexts.
329
+ - (void)onEngineThread:(dispatch_block_t)block {
330
+ [_lynxContext runOnTasmThread:block];
331
+ }
332
+
312
333
  // A frame drawn before Lynx gave the view a size waits for one (see
313
334
  // present). An app that draws only when something changes, such as a photo
314
335
  // editor drawing its photo once, would otherwise show nothing until it drew
315
336
  // again; one drawing every frame never noticed.
316
337
  - (void)layoutSubviews {
317
338
  [super layoutSubviews];
318
- if (_canvasId) {
319
- [[AngularLynxCanvasRegistry contextForCanvasId:_canvasId] viewDidLayOut:self];
320
- }
339
+ // ANGLE sizes the layer's next drawable from its bounds and scale, as here.
340
+ CGSize size = self.bounds.size;
341
+ CGFloat scale = self.layer.contentsScale;
342
+ _target.pixelSize = CGSizeMake(floor(size.width * scale), floor(size.height * scale));
343
+ NSString *canvasId = _canvasId;
344
+ AngularLynxCanvasTarget *target = _target;
345
+ if (!canvasId) return;
346
+ [self onEngineThread:^{
347
+ [[AngularLynxCanvasRegistry contextForCanvasId:canvasId] targetDidLayOut:target];
348
+ }];
321
349
  }
322
350
 
323
351
  - (void)setCanvasId:(NSString *)canvasId {
324
352
  if ([_canvasId isEqualToString:canvasId]) return;
325
- if (_canvasId && [AngularLynxCanvasRegistry viewForCanvasId:_canvasId] == self) {
326
- [AngularLynxCanvasRegistry setView:nil forCanvasId:_canvasId];
327
- }
353
+ NSString *old = _canvasId;
328
354
  _canvasId = [canvasId copy];
329
- if (_canvasId) [AngularLynxCanvasRegistry setView:self forCanvasId:_canvasId];
355
+ NSString *new = _canvasId;
356
+ AngularLynxCanvasTarget *target = _target;
357
+ [self onEngineThread:^{
358
+ if (old && [AngularLynxCanvasRegistry targetForCanvasId:old] == target) {
359
+ [AngularLynxCanvasRegistry setTarget:nil forCanvasId:old];
360
+ }
361
+ if (new) [AngularLynxCanvasRegistry setTarget:target forCanvasId:new];
362
+ }];
330
363
  }
331
364
 
332
365
  - (void)dealloc {
333
- // The registry holds the view weakly; a context still showing frames in it
334
- // stops.
366
+ // The context holds the target, and its layer, while it shows frames in
367
+ // it; it lets go here.
335
368
  NSString *canvasId = _canvasId;
369
+ AngularLynxCanvasTarget *target = _target;
336
370
  if (canvasId) {
337
- dispatch_async(dispatch_get_main_queue(), ^{
338
- if (![AngularLynxCanvasRegistry viewForCanvasId:canvasId]) {
339
- [[AngularLynxCanvasRegistry contextForCanvasId:canvasId] attachView:nil];
371
+ [_lynxContext runOnTasmThread:^{
372
+ if ([AngularLynxCanvasRegistry targetForCanvasId:canvasId] == target) {
373
+ [AngularLynxCanvasRegistry setTarget:nil forCanvasId:canvasId];
340
374
  }
341
- });
375
+ }];
342
376
  }
343
377
  }
344
378
 
@@ -351,6 +385,7 @@ static AngularLynxDecodedImage *decodeImage(NSData *bytes, NSDictionary *options
351
385
  }
352
386
 
353
387
  LYNX_PROP_SETTER("canvas-id", setCanvasId, NSString *) {
388
+ self.view.lynxContext = self.context.lynxContext;
354
389
  self.view.canvasId = requestReset || ![value isKindOfClass:NSString.class] ? nil : value;
355
390
  }
356
391
 
@@ -185,7 +185,7 @@ static NSUInteger componentsOf(GLenum format) {
185
185
 
186
186
  // The view's layer, as a window surface each frame is copied into. Made
187
187
  // when a frame is first shown in the view, as the surface's framebuffer 0.
188
- __weak AngularLynxCanvasView *_view;
188
+ AngularLynxCanvasTarget *_target;
189
189
  EGLSurface _surface;
190
190
  /// A frame was finished before there was a view to show it in.
191
191
  BOOL _framePending;
@@ -195,6 +195,11 @@ static NSUInteger componentsOf(GLenum format) {
195
195
  GLuint _readFramebuffer;
196
196
  GLuint _renderbuffer;
197
197
 
198
+ /// The errors taken off GL, which a read does to learn whether the read
199
+ /// itself failed, in the order GL gave them. getError reports them. GL
200
+ /// keeps one flag for each code, and so does the set.
201
+ NSMutableOrderedSet<NSNumber *> *_heldErrors;
202
+
198
203
  // The runtime's object ids, to GL names (ids are never reused).
199
204
  GLuint *_names;
200
205
  NSUInteger _namesCapacity;
@@ -254,6 +259,7 @@ static NSUInteger componentsOf(GLenum format) {
254
259
  _stencil = [attributes[@"stencil"] isEqual:@YES];
255
260
  _preserveDrawingBuffer = [attributes[@"preserveDrawingBuffer"] isEqual:@YES];
256
261
  _syncs = [NSMutableDictionary dictionary];
262
+ _heldErrors = [NSMutableOrderedSet orderedSet];
257
263
  _namesCapacity = 256;
258
264
  _names = calloc(_namesCapacity, sizeof(GLuint));
259
265
 
@@ -420,41 +426,45 @@ static NSUInteger componentsOf(GLenum format) {
420
426
  glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _drawFramebuffer);
421
427
  }
422
428
 
423
- - (void)attachView:(AngularLynxCanvasView *)view {
424
- // A view that went away has already turned _view (weak) to nil, but its
425
- // layer lives on in the surface until the surface is let go of here.
426
- if (_view == view && (view || _surface == EGL_NO_SURFACE)) return;
429
+ - (void)attachTarget:(AngularLynxCanvasTarget *)target {
430
+ if (_target == target) return;
431
+ // The surface holds the old target's layer until it's let go of here.
427
432
  [self releaseSurface];
428
- _view = view;
429
- if (view) {
430
- view.layer.opaque = !_alpha;
431
- view.opaque = !_alpha;
433
+ _target = target;
434
+ if (target) {
435
+ // The view's opacity is the UI thread's to set.
436
+ BOOL opaque = !_alpha;
437
+ dispatch_async(dispatch_get_main_queue(), ^{
438
+ AngularLynxCanvasView *view = target.view;
439
+ view.layer.opaque = opaque;
440
+ view.opaque = opaque;
441
+ });
432
442
  if (_framePending) [self present];
433
443
  }
434
444
  }
435
445
 
436
- - (void)viewDidLayOut:(AngularLynxCanvasView *)view {
437
- if (view == _view && _framePending) [self present];
446
+ - (void)targetDidLayOut:(AngularLynxCanvasTarget *)target {
447
+ if (target == _target && _framePending) [self present];
438
448
  }
439
449
 
440
450
  /// Shows the finished frame: copies the default framebuffer (resolving it
441
451
  /// when it's multisampled) into the view's layer, scaled to its size, and
442
452
  /// presents it. Without a laid-out view, the frame waits for one.
443
453
  - (void)present {
444
- AngularLynxCanvasView *view = _view;
445
- CGSize size = view.bounds.size;
446
- // ANGLE sizes the layer's next drawable from its bounds and scale, as
447
- // here, when the blit below first draws to it.
448
- CGFloat scale = view.layer.contentsScale;
449
- GLint layerWidth = (GLint)(size.width * scale);
450
- GLint layerHeight = (GLint)(size.height * scale);
451
- if (!view || layerWidth < 1 || layerHeight < 1) {
454
+ AngularLynxCanvasTarget *target = _target;
455
+ // The layer's size as the view was last laid out: ANGLE sizes the layer's
456
+ // next drawable from its bounds and scale, as the view measured it, when
457
+ // the blit below first draws to it.
458
+ CGSize size = target.pixelSize;
459
+ GLint layerWidth = (GLint)size.width;
460
+ GLint layerHeight = (GLint)size.height;
461
+ if (!target || layerWidth < 1 || layerHeight < 1) {
452
462
  _framePending = YES;
453
463
  return;
454
464
  }
455
465
  if (_surface == EGL_NO_SURFACE) {
456
- _surface = eglCreateWindowSurface(_display, _config, (__bridge EGLNativeWindowType)view.layer,
457
- NULL);
466
+ _surface = eglCreateWindowSurface(_display, _config,
467
+ (__bridge EGLNativeWindowType)target.layer, NULL);
458
468
  if (_surface == EGL_NO_SURFACE) {
459
469
  NSLog(@"[AngularLynxWebGL] No window surface for the canvas (EGL error 0x%x)", eglGetError());
460
470
  _framePending = YES;
@@ -663,6 +673,24 @@ static NSUInteger componentsOf(GLenum format) {
663
673
  return @{@"base64" : [file base64EncodedStringWithOptions:0], @"type" : type};
664
674
  }
665
675
 
676
+ #pragma mark - Errors
677
+
678
+ /// Moves every error GL has recorded into _heldErrors, and answers whether
679
+ /// there were any. GL records several at once, one for each code, and
680
+ /// glGetError takes one off a call, so only a loop leaves GL with none.
681
+ - (BOOL)holdErrors {
682
+ BOOL any = NO;
683
+ // GL has eight error codes, so eight calls empty it. The count is there so
684
+ // a GL that answers an error to every call can't hang the engine thread.
685
+ for (int i = 0; i < 8; i++) {
686
+ GLenum error = glGetError();
687
+ if (error == GL_NO_ERROR) break;
688
+ [_heldErrors addObject:@(error)];
689
+ any = YES;
690
+ }
691
+ return any;
692
+ }
693
+
666
694
  #pragma mark - Objects
667
695
 
668
696
  - (GLuint)nameOf:(GLuint)objectId {
@@ -2145,8 +2173,16 @@ static BOOL isUnsignedUniform(GLenum type) {
2145
2173
  switch ((ALWebGLOp)op) {
2146
2174
  case ALWebGLOpGetParameter:
2147
2175
  return [self parameter:nextEnum(r)];
2148
- case ALWebGLOpGetError:
2149
- return @(glGetError());
2176
+ case ALWebGLOpGetError: {
2177
+ // The errors a read held come first, and GL's own after them. Taking
2178
+ // GL's too reports a code once when a call raised it again after a
2179
+ // read held it, as GL would have with its one flag.
2180
+ [self holdErrors];
2181
+ NSNumber *error = _heldErrors.firstObject;
2182
+ if (!error) return @(GL_NO_ERROR);
2183
+ [_heldErrors removeObjectAtIndex:0];
2184
+ return error;
2185
+ }
2150
2186
  case ALWebGLOpShaderInfo: {
2151
2187
  GLuint shader = [self nameOf:nextUInt(r)];
2152
2188
  GLint compiled = GL_FALSE;
@@ -2377,11 +2413,53 @@ static BOOL isUnsignedUniform(GLenum type) {
2377
2413
  GLsizei width = nextInt(r), height = nextInt(r);
2378
2414
  GLenum format = nextEnum(r), type = nextEnum(r);
2379
2415
  NSUInteger length = (NSUInteger)MAX(0, nextNumber(r));
2380
- NSMutableData *data = [NSMutableData dataWithLength:(length + 3) / 4 * 4];
2416
+ // Read into a pixel pack buffer and mapped, rather than straight into
2417
+ // memory, as encodeImageOfType: does: ANGLE on Metal is slow at the
2418
+ // read into memory. In the Simulator that took a whole readPixels() of
2419
+ // a 2048 by 1365 canvas from about 418 ms to 342 (the rest is the
2420
+ // trip back as numbers), and one of 256 by 256 from 23 to 13. The
2421
+ // app's pack alignment, row length and
2422
+ // skips lay the pixels out in a buffer just as they do in memory, so
2423
+ // they stay as the app set them, and `length` (the runtime's count of
2424
+ // what they need) is the buffer's size.
2425
+ //
2426
+ // A failed read writes nothing, and WebGL leaves the app's array alone
2427
+ // then. Into memory that was a zeroed array; a buffer holds whatever
2428
+ // it was given. So GL's error tells: the errors from before the read
2429
+ // are held for getError, and one after it means the read failed and
2430
+ // answers nil, which the runtime takes as nothing read. Every earlier
2431
+ // error is taken, not one: a second one left on GL would be found
2432
+ // after the read, and a read that worked would answer nil.
2433
+ [self holdErrors];
2434
+ // The runtime sends this only while no pack buffer is bound (an app
2435
+ // reading into one sends ReadPixelsToBuffer), but the binding is put
2436
+ // back whatever it was.
2437
+ GLint packBuffer = 0;
2438
+ glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &packBuffer);
2439
+ GLuint pack = 0;
2440
+ glGenBuffers(1, &pack);
2441
+ glBindBuffer(GL_PIXEL_PACK_BUFFER, pack);
2442
+ glBufferData(GL_PIXEL_PACK_BUFFER, (GLsizeiptr)length, NULL, GL_STREAM_READ);
2381
2443
  BOOL resolved = [self beginRead];
2382
- glReadPixels(x, y, width, height, format, type, data.mutableBytes);
2444
+ glReadPixels(x, y, width, height, format, type, 0);
2383
2445
  [self endRead:resolved];
2384
- return wordsFromBytes(data.bytes, length);
2446
+ // The read's own error is held with the rest, for getError, and
2447
+ // leaves the answer nil.
2448
+ BOOL read = ![self holdErrors];
2449
+ NSArray *result = nil;
2450
+ if (read && length == 0) {
2451
+ result = wordsFromBytes(NULL, 0);
2452
+ } else if (read) {
2453
+ const void *mapped =
2454
+ glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, (GLsizeiptr)length, GL_MAP_READ_BIT);
2455
+ if (mapped) {
2456
+ result = wordsFromBytes(mapped, length);
2457
+ glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
2458
+ }
2459
+ }
2460
+ glDeleteBuffers(1, &pack);
2461
+ glBindBuffer(GL_PIXEL_PACK_BUFFER, (GLuint)packBuffer);
2462
+ return result;
2385
2463
  }
2386
2464
  case ALWebGLOpGetBufferSubData: {
2387
2465
  GLenum target = nextEnum(r);
@@ -0,0 +1,214 @@
1
+ import Foundation
2
+ import ObjectiveC
3
+ import QuartzCore
4
+
5
+ /// Asks iOS to run the app's Core Animation transitions at up to 120 fps on a
6
+ /// ProMotion iPhone.
7
+ ///
8
+ /// An element with `enable-new-animator="false"` hands its CSS transitions and
9
+ /// `@keyframes` to Core Animation, as `<lynx-stack-outlet>`'s pages and
10
+ /// `ui-bottom-sheet` do. Lynx makes those animations without a
11
+ /// `preferredFrameRateRange`, and iOS runs an animation that asks for no rate at
12
+ /// 60 fps: `CADisableMinimumFrameDurationOnPhone` in Info.plist only lets the
13
+ /// app ask for more. On an iPhone 14 Pro a stack push ran at a steady 60 fps
14
+ /// while the Home Screen's own animations ran at 120.
15
+ ///
16
+ /// Lynx adds its animations in many places (a transition, a keyframe
17
+ /// animation, and their copies on the element's background and border layers),
18
+ /// and they all go through `CALayer.add(_:forKey:)`, so the shell asks there,
19
+ /// for every animation added in the app: UIKit's in the shell's own views too.
20
+ /// With it, the push ran at 120 fps while it moved fast, then slower as it
21
+ /// eased to a stop, as the Home Screen's animations do.
22
+ ///
23
+ /// It leaves alone an animation that asks for a rate of its own, and a loop
24
+ /// that never ends, such as a spinner or a pulse: nobody follows those with
25
+ /// their eye, so they keep the system's rate, and the battery that saves.
26
+ enum AnimationFrameRate {
27
+ /// The range Apple's ProMotion guidance gives fast motion: 120 fps, and no
28
+ /// lower than 80.
29
+ static let fastMotion = CAFrameRateRange(minimum: 80, maximum: 120, preferred: 120)
30
+
31
+ /// The most repeats a finite animation has. Lynx writes CSS's `infinite` as
32
+ /// 10⁹ iterations (half that with `alternate`), and UIKit's loops repeat
33
+ /// forever (`.infinity`), so anything above this is a loop.
34
+ static let loopRepeatCount: Float = 1_000
35
+
36
+ /// Whether the shell asks for `fastMotion` on this animation.
37
+ static func asksForFastMotion(_ animation: CAAnimation) -> Bool {
38
+ // The default range, {0, 0, 0}, is an animation that asks for nothing.
39
+ animation.preferredFrameRateRange.maximum == 0
40
+ && animation.repeatCount <= loopRepeatCount
41
+ && animation.repeatDuration.isFinite
42
+ }
43
+
44
+ /// Swaps in `CALayer`'s replacement `add(_:forKey:)`, and has Lynx's own
45
+ /// animator's rate asked for from the main thread (see `LynxAnimatorFrameRate`).
46
+ /// Call it once, before the first LynxView exists.
47
+ static func install() {
48
+ _ = swapped
49
+ LynxAnimatorFrameRate.install()
50
+ }
51
+
52
+ /// A static's initializer runs once, however often `install()` is called:
53
+ /// swapping twice would put CALayer's own method back.
54
+ private static let swapped: Void = {
55
+ guard
56
+ let original = class_getInstanceMethod(
57
+ CALayer.self, #selector(CALayer.add(_:forKey:))),
58
+ let replacement = class_getInstanceMethod(
59
+ CALayer.self, #selector(CALayer.angularLynx_add(_:forKey:)))
60
+ else { return }
61
+ method_exchangeImplementations(original, replacement)
62
+ }()
63
+ }
64
+
65
+ /// Asks iOS, from the main thread, for the rate Lynx's own animator asks for,
66
+ /// while that animator runs.
67
+ ///
68
+ /// Lynx works out each frame of an element's CSS transitions and `animate()`
69
+ /// itself (every element without `enable-new-animator="false"`), from a
70
+ /// `CADisplayLink` in its `LynxVSyncPulse`. The build's `preferredFps: 'high'`
71
+ /// has Lynx ask that link for up to 120 fps. But the link is made on the thread
72
+ /// that first asks it for a frame, and the shell runs Lynx's engine off the
73
+ /// main thread (`MostOnTASM`), so it lives on the engine thread, and iOS doesn't
74
+ /// raise the display's rate for a display link there. On an iPhone 14 Pro a
75
+ /// transition on Lynx's animator drew a frame every 16.7 ms while the same one
76
+ /// in Core Animation drew one every 8.3 ms. With a display link on the main
77
+ /// thread asking for the same range, it drew one every 8.3 ms too: the engine
78
+ /// already ticked that fast, and only the display held it back.
79
+ ///
80
+ /// So the shell swaps in its own `requestPulse`, which Lynx calls on the engine
81
+ /// thread for each frame it wants, and while those frames come from a link that
82
+ /// asks for more than 60 fps, a display link on the main thread asks for the
83
+ /// same range. It pauses once Lynx has asked for no frame for a few frames, so
84
+ /// a screen with nothing moving keeps the system's rate. A `preferredFps` of
85
+ /// `'auto'` or `'low'` leaves Lynx's link asking for nothing, so nothing is
86
+ /// asked for here either.
87
+ final class LynxAnimatorFrameRate: NSObject {
88
+ static let shared = LynxAnimatorFrameRate()
89
+
90
+ /// How long the main thread keeps asking after Lynx's last frame request: a
91
+ /// few frames, so a frame Angular's work delays doesn't drop the rate between
92
+ /// two of an animation's frames.
93
+ static let linger: CFTimeInterval = 0.1
94
+
95
+ /// The highest rate a display link asks for before the main thread asks too:
96
+ /// what an app gets without asking.
97
+ static let defaultMaximum: Float = 60
98
+
99
+ /// Guards what both threads read: the engine thread writes the request, the
100
+ /// main thread reads it on its own frames.
101
+ private let lock = NSLock()
102
+ private var lastRequest: CFTimeInterval = 0
103
+ private var range = CAFrameRateRange.default
104
+ /// Whether the main thread's link runs, or is about to.
105
+ private var asking = false
106
+ /// The main thread's link. Only the main thread touches it.
107
+ private var link: CADisplayLink?
108
+
109
+ /// Swaps `LynxVSyncPulse`'s `requestPulse` for one that also asks from the
110
+ /// main thread. Does nothing if Lynx no longer has that class or method.
111
+ static func install() {
112
+ _ = swapped
113
+ }
114
+
115
+ private static let swapped: Void = {
116
+ let selector = NSSelectorFromString("requestPulse")
117
+ let replacementSelector = #selector(NSObject.angularLynx_requestPulse)
118
+ guard
119
+ let pulse = NSClassFromString("LynxVSyncPulse"),
120
+ let original = class_getInstanceMethod(pulse, selector),
121
+ let replacement = class_getInstanceMethod(NSObject.self, replacementSelector),
122
+ // Added to LynxVSyncPulse itself, so the swap changes only its methods,
123
+ // not NSObject's.
124
+ class_addMethod(
125
+ pulse, replacementSelector, method_getImplementation(replacement),
126
+ method_getTypeEncoding(replacement)),
127
+ let added = class_getInstanceMethod(pulse, replacementSelector)
128
+ else { return }
129
+ method_exchangeImplementations(original, added)
130
+ }()
131
+
132
+ /// Whether a link's range asks for more than an app gets by default.
133
+ static func asksForHighRate(_ range: CAFrameRateRange) -> Bool {
134
+ max(range.maximum, range.preferred ?? 0) > defaultMaximum
135
+ }
136
+
137
+ /// Called on the engine thread for each frame Lynx asks its link for.
138
+ func lynxRequestedFrame(_ range: CAFrameRateRange) {
139
+ lock.lock()
140
+ lastRequest = CACurrentMediaTime()
141
+ self.range = range
142
+ let start = !asking
143
+ asking = true
144
+ lock.unlock()
145
+ if start {
146
+ DispatchQueue.main.async { self.resume() }
147
+ }
148
+ }
149
+
150
+ private func resume() {
151
+ let link: CADisplayLink
152
+ if let existing = self.link {
153
+ link = existing
154
+ } else {
155
+ link = CADisplayLink(target: self, selector: #selector(tick(_:)))
156
+ link.add(to: .main, forMode: .common)
157
+ self.link = link
158
+ }
159
+ lock.lock()
160
+ let range = self.range
161
+ lock.unlock()
162
+ link.preferredFrameRateRange = range
163
+ link.isPaused = false
164
+ }
165
+
166
+ @objc private func tick(_ link: CADisplayLink) {
167
+ lock.lock()
168
+ let idle = link.timestamp - lastRequest > Self.linger
169
+ if idle {
170
+ // A request after this unlock finds `asking` false and resumes the link
171
+ // on a later turn of the main thread, after this pause.
172
+ asking = false
173
+ }
174
+ lock.unlock()
175
+ if idle {
176
+ link.isPaused = true
177
+ }
178
+ }
179
+ }
180
+
181
+ extension NSObject {
182
+ /// Takes the place of `LynxVSyncPulse`'s `requestPulse` once
183
+ /// `LynxAnimatorFrameRate.install()` has run, so `self` is a `LynxVSyncPulse`.
184
+ @objc fileprivate func angularLynx_requestPulse() {
185
+ // The implementations are swapped, so this runs Lynx's own requestPulse.
186
+ angularLynx_requestPulse()
187
+ let getter = NSSelectorFromString("displayLink")
188
+ guard responds(to: getter),
189
+ let link = perform(getter)?.takeUnretainedValue() as? CADisplayLink,
190
+ LynxAnimatorFrameRate.asksForHighRate(link.preferredFrameRateRange)
191
+ else { return }
192
+ LynxAnimatorFrameRate.shared.lynxRequestedFrame(link.preferredFrameRateRange)
193
+ }
194
+ }
195
+
196
+ extension CALayer {
197
+ /// Takes the place of `add(_:forKey:)` once `AnimationFrameRate.install()`
198
+ /// has run.
199
+ @objc fileprivate func angularLynx_add(_ animation: CAAnimation, forKey key: String?) {
200
+ // The implementations are swapped, so each `angularLynx_add` call below
201
+ // runs CALayer's own `add(_:forKey:)`.
202
+ guard AnimationFrameRate.asksForFastMotion(animation),
203
+ // Core Animation adds a copy of the animation anyway. The one passed in
204
+ // may be one a layer handed back from `animation(forKey:)`, which mustn't
205
+ // be changed, so the rate goes on a copy of our own.
206
+ let fast = animation.copy() as? CAAnimation
207
+ else {
208
+ angularLynx_add(animation, forKey: key)
209
+ return
210
+ }
211
+ fast.preferredFrameRateRange = AnimationFrameRate.fastMotion
212
+ angularLynx_add(fast, forKey: key)
213
+ }
214
+ }