@blotch/angular-lynx-native 22.3.1 → 22.3.3

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 (123) hide show
  1. package/README.md +47 -15
  2. package/dist/android/project.d.ts +114 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +440 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +14 -2
  8. package/dist/features.d.ts +70 -0
  9. package/dist/features.d.ts.map +1 -0
  10. package/dist/features.js +115 -0
  11. package/dist/files.d.ts +24 -0
  12. package/dist/files.d.ts.map +1 -0
  13. package/dist/files.js +41 -0
  14. package/dist/generate.d.ts +34 -3
  15. package/dist/generate.d.ts.map +1 -1
  16. package/dist/generate.js +78 -19
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +16 -2
  20. package/dist/ios/build.d.ts.map +1 -1
  21. package/dist/ios/build.js +8 -2
  22. package/dist/ios/frameworks.d.ts +6 -5
  23. package/dist/ios/frameworks.d.ts.map +1 -1
  24. package/dist/ios/frameworks.js +46 -15
  25. package/dist/ios/project.d.ts +192 -11
  26. package/dist/ios/project.d.ts.map +1 -1
  27. package/dist/ios/project.js +823 -33
  28. package/dist/options.d.ts +208 -1
  29. package/dist/options.d.ts.map +1 -1
  30. package/dist/options.js +154 -0
  31. package/dist/permissions.d.ts +18 -1
  32. package/dist/permissions.d.ts.map +1 -1
  33. package/dist/permissions.js +79 -4
  34. package/dist/plugins.d.ts +245 -0
  35. package/dist/plugins.d.ts.map +1 -0
  36. package/dist/plugins.js +1244 -0
  37. package/package.json +1 -1
  38. package/templates/android/README.md +46 -5
  39. package/templates/android/angular-lynx.properties +2 -0
  40. package/templates/android/app/build.gradle.kts +78 -11
  41. package/templates/android/app/src/main/AndroidManifest.xml +19 -3
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/AngularLynxPlugins.kt +13 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/AudioRecorderModule.kt +520 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/EdgeToEdgeOverlay.kt +24 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/EngineThreadHint.kt +156 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/GeolocationModule.kt +557 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/HostElementUI.kt +331 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePickerModule.kt +143 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePipeline.kt +83 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +523 -9
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  65. package/templates/android/app/src/main/java/dev/angularlynx/shell/NetworkStatus.kt +121 -0
  66. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  67. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +35 -0
  68. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +355 -0
  69. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  70. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +7 -8
  71. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +58 -4
  72. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  73. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  74. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  75. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  76. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  77. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  78. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  79. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  80. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  81. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  82. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  83. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  84. package/templates/android/app/src/main/res/xml/share_paths.xml +7 -2
  85. package/templates/android/build.gradle.kts +1 -1
  86. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  87. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  88. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  89. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  90. package/templates/ios/App/AngularLynxPlugins.swift +22 -0
  91. package/templates/ios/App/AngularLynxVideo.h +37 -0
  92. package/templates/ios/App/AngularLynxVideo.m +435 -0
  93. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  94. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  95. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  96. package/templates/ios/App/AnimationFrameRate.swift +66 -0
  97. package/templates/ios/App/AppDelegate.swift +37 -3
  98. package/templates/ios/App/AppleSignInButton.swift +106 -0
  99. package/templates/ios/App/AppleSignInModule.swift +222 -0
  100. package/templates/ios/App/AudioRecorderModule.swift +433 -0
  101. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  102. package/templates/ios/App/BiometricsModule.swift +256 -0
  103. package/templates/ios/App/BluetoothModule.swift +1086 -0
  104. package/templates/ios/App/CalendarModule.swift +158 -0
  105. package/templates/ios/App/FilePickerModule.swift +240 -0
  106. package/templates/ios/App/GeolocationModule.swift +455 -0
  107. package/templates/ios/App/HapticsModule.swift +90 -0
  108. package/templates/ios/App/HostElementUI.swift +270 -0
  109. package/templates/ios/App/ImagePickerModule.swift +160 -1
  110. package/templates/ios/App/Info.plist +2 -0
  111. package/templates/ios/App/LynxViewController.swift +274 -9
  112. package/templates/ios/App/MotionModule.swift +430 -0
  113. package/templates/ios/App/NetworkStatus.swift +41 -0
  114. package/templates/ios/App/NfcModule.swift +346 -0
  115. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  116. package/templates/ios/App/ShareTargetModule.swift +150 -0
  117. package/templates/ios/App/ShellModule.swift +17 -0
  118. package/templates/ios/App/StoreReviewModule.swift +61 -0
  119. package/templates/ios/App/TrackingModule.swift +121 -0
  120. package/templates/ios/App/WifiModule.swift +237 -0
  121. package/templates/ios/App/XElementRegistry.swift +13 -3
  122. package/templates/ios/ShareExtension/Info.plist +42 -0
  123. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -0,0 +1,2467 @@
1
+ // `<canvas>`'s 2D context for the AngularLynx runtime: the bitmap the
2
+ // runtime's CanvasRenderingContext2D (packages/runtime/src/lib/canvas/
3
+ // canvas-2d-context.ts) draws on, with Core Graphics, the engine Safari's
4
+ // canvas drew with for years. The runtime sends its calls in batches, as the
5
+ // WebGL context does, through the AngularLynxWebGL module's `run2D`.
6
+ //
7
+ // The runtime keeps the state its getters answer and builds paths itself, in
8
+ // the canvas's pixels (arcs and rounded rectangles arrive as Bézier curves),
9
+ // so this side draws what it's told: a path filled or stroked with the
10
+ // current style, text, an image. Everything is drawn into one RGBA bitmap,
11
+ // premultiplied, rows top to bottom, the canvas's `width` by `height`; after
12
+ // each task that drew, the runtime asks for it to be shown, and a copy goes
13
+ // to the canvas's view (AngularLynxCanvasView's image layer).
14
+ //
15
+ // What the canvas spec has that Core Graphics doesn't is made here:
16
+ // - Compositing that clears what the shape doesn't cover (source-in,
17
+ // source-out, destination-in, destination-atop, copy), and shadows, draw
18
+ // the shape into a layer over the canvas first, which is then drawn over
19
+ // it with the operation and the shadow; a shadow cast from far off the
20
+ // canvas has a layer of its own there.
21
+ // - The filter (blur(), drop-shadow(), the color functions) is applied to
22
+ // that layer's pixels, before it's drawn over the canvas.
23
+ // - Conic gradients (CGContextDrawConicGradient needs iOS 17) are worked out
24
+ // a pixel at a time.
25
+ // - Text is laid out with Core Text: drawn as glyphs for a color fill (so
26
+ // emoji draw), and as the glyphs' outlines for a gradient or pattern, and
27
+ // for strokes.
28
+ //
29
+ // Everything runs on Lynx's engine thread, where the module's calls arrive;
30
+ // only showing the bitmap hops to the UI thread.
31
+
32
+ // cspell:words fabs fmod isfinite lround Roundhand
33
+
34
+ #import "AngularLynxWebGL.h"
35
+
36
+ #import <CoreText/CoreText.h>
37
+ #import <ImageIO/ImageIO.h>
38
+
39
+ #import "AngularLynxCanvas2DOps.h"
40
+
41
+ NSData *AngularLynxBytesFromWords(NSArray *words);
42
+ NSDictionary *AngularLynxEncodeImage(NSData *pixels, size_t width, size_t height,
43
+ CGBitmapInfo alphaInfo, NSString *type, double quality);
44
+
45
+ #pragma mark - Reading a batch
46
+
47
+ typedef struct {
48
+ __unsafe_unretained id *items;
49
+ NSUInteger count;
50
+ NSUInteger index;
51
+ } ALReader;
52
+
53
+ static inline id readItem(ALReader *r) {
54
+ return r->index < r->count ? r->items[r->index++] : nil;
55
+ }
56
+
57
+ static inline double readNumber(ALReader *r) {
58
+ id item = readItem(r);
59
+ return [item isKindOfClass:NSNumber.class] ? [item doubleValue] : 0;
60
+ }
61
+
62
+ static inline NSInteger readInt(ALReader *r) { return (NSInteger)readNumber(r); }
63
+
64
+ static inline NSString *readString(ALReader *r) {
65
+ id item = readItem(r);
66
+ return [item isKindOfClass:NSString.class] ? item : @"";
67
+ }
68
+
69
+ static inline NSArray *readArray(ALReader *r) {
70
+ id item = readItem(r);
71
+ return [item isKindOfClass:NSArray.class] ? item : @[];
72
+ }
73
+
74
+ static inline NSDictionary *readMap(ALReader *r) {
75
+ id item = readItem(r);
76
+ return [item isKindOfClass:NSDictionary.class] ? item : @{};
77
+ }
78
+
79
+ /// Bytes as words for the trip back, the byte count last (see fromWords in
80
+ /// network/words.ts).
81
+ static NSArray *wordsFrom(const uint8_t *bytes, NSUInteger length) {
82
+ NSUInteger wordCount = (length + 3) / 4;
83
+ NSMutableArray *words = [NSMutableArray arrayWithCapacity:wordCount + 1];
84
+ for (NSUInteger i = 0; i < wordCount; i++) {
85
+ uint32_t word = 0;
86
+ memcpy(&word, bytes + i * 4, MIN(4, length - i * 4));
87
+ [words addObject:@(word)];
88
+ }
89
+ [words addObject:@(length)];
90
+ return words;
91
+ }
92
+
93
+ /// A path from the runtime's segments (PATH_OP in canvas-2d-ops.ts): in the
94
+ /// canvas's pixels, top-left origin.
95
+ static CGMutablePathRef pathFromSegments(NSArray *segments) {
96
+ CGMutablePathRef path = CGPathCreateMutable();
97
+ NSUInteger count = segments.count;
98
+ __unsafe_unretained id *items = (__unsafe_unretained id *)malloc(sizeof(id) * MAX(count, 1));
99
+ [segments getObjects:items range:NSMakeRange(0, count)];
100
+ NSUInteger i = 0;
101
+ #define NEXT (i < count ? [items[i++] doubleValue] : 0)
102
+ while (i < count) {
103
+ NSInteger op = (NSInteger)[items[i++] doubleValue];
104
+ switch ((ALCanvas2DPathOp)op) {
105
+ case ALCanvas2DPathOpMoveTo: {
106
+ CGFloat x = NEXT, y = NEXT;
107
+ CGPathMoveToPoint(path, NULL, x, y);
108
+ break;
109
+ }
110
+ case ALCanvas2DPathOpLineTo: {
111
+ CGFloat x = NEXT, y = NEXT;
112
+ if (CGPathIsEmpty(path)) {
113
+ CGPathMoveToPoint(path, NULL, x, y);
114
+ } else {
115
+ CGPathAddLineToPoint(path, NULL, x, y);
116
+ }
117
+ break;
118
+ }
119
+ case ALCanvas2DPathOpQuadTo: {
120
+ CGFloat cx = NEXT, cy = NEXT, x = NEXT, y = NEXT;
121
+ if (CGPathIsEmpty(path)) CGPathMoveToPoint(path, NULL, cx, cy);
122
+ CGPathAddQuadCurveToPoint(path, NULL, cx, cy, x, y);
123
+ break;
124
+ }
125
+ case ALCanvas2DPathOpCubicTo: {
126
+ CGFloat ax = NEXT, ay = NEXT, bx = NEXT, by = NEXT, x = NEXT, y = NEXT;
127
+ if (CGPathIsEmpty(path)) CGPathMoveToPoint(path, NULL, ax, ay);
128
+ CGPathAddCurveToPoint(path, NULL, ax, ay, bx, by, x, y);
129
+ break;
130
+ }
131
+ case ALCanvas2DPathOpClose:
132
+ if (!CGPathIsEmpty(path)) CGPathCloseSubpath(path);
133
+ break;
134
+ default:
135
+ i = count;
136
+ }
137
+ }
138
+ #undef NEXT
139
+ free(items);
140
+ return path;
141
+ }
142
+
143
+ static BOOL invertible(CGAffineTransform t) {
144
+ CGFloat det = t.a * t.d - t.b * t.c;
145
+ return det != 0 && isfinite(det);
146
+ }
147
+
148
+ #pragma mark - State
149
+
150
+ typedef NS_ENUM(NSInteger, ALStyleKind) {
151
+ ALStyleColor,
152
+ ALStyleGradient,
153
+ ALStylePattern,
154
+ };
155
+
156
+ typedef struct {
157
+ ALStyleKind kind;
158
+ CGFloat rgba[4];
159
+ /// A pattern's image, by the runtime's id.
160
+ NSInteger objectId;
161
+ /// A pattern's transform, which crosses with the style.
162
+ CGAffineTransform transform;
163
+ } ALStyle;
164
+
165
+ @class ALCanvas2DGradient;
166
+
167
+ /// What canvas `save()` keeps. The clip is Core Graphics' own state, saved
168
+ /// with it.
169
+ @interface ALCanvas2DState : NSObject <NSCopying>
170
+ @property(nonatomic) CGAffineTransform transform;
171
+ @property(nonatomic) CGFloat globalAlpha;
172
+ @property(nonatomic) NSInteger composite;
173
+ @property(nonatomic) ALStyle fill;
174
+ @property(nonatomic) ALStyle stroke;
175
+ /// The gradients the styles paint with, which cross whole with the style.
176
+ @property(nonatomic, strong) ALCanvas2DGradient *fillGradient;
177
+ @property(nonatomic, strong) ALCanvas2DGradient *strokeGradient;
178
+ @property(nonatomic) CGFloat lineWidth;
179
+ @property(nonatomic) CGLineCap lineCap;
180
+ @property(nonatomic) CGLineJoin lineJoin;
181
+ @property(nonatomic) CGFloat miterLimit;
182
+ @property(nonatomic, copy) NSArray<NSNumber *> *lineDash;
183
+ @property(nonatomic) CGFloat lineDashOffset;
184
+ @property(nonatomic) CGFloat shadowBlur;
185
+ @property(nonatomic) CGFloat shadowOffsetX;
186
+ @property(nonatomic) CGFloat shadowOffsetY;
187
+ @property(nonatomic) CGFloat shadowR, shadowG, shadowB, shadowA;
188
+ @property(nonatomic, strong) UIFont *font;
189
+ @property(nonatomic) NSInteger textAlign;
190
+ @property(nonatomic) NSInteger textBaseline;
191
+ @property(nonatomic) BOOL rtl;
192
+ @property(nonatomic) CGFloat letterSpacing;
193
+ @property(nonatomic) BOOL smoothing;
194
+ @property(nonatomic) NSInteger smoothingQuality;
195
+ /// The filter, as its steps (see parsedFilter).
196
+ @property(nonatomic, copy) NSArray<NSNumber *> *filterSteps;
197
+ @end
198
+
199
+ @implementation ALCanvas2DState
200
+
201
+ - (instancetype)init {
202
+ if ((self = [super init])) {
203
+ _transform = CGAffineTransformIdentity;
204
+ _globalAlpha = 1;
205
+ _fill = (ALStyle){ALStyleColor, {0, 0, 0, 1}, 0, CGAffineTransformIdentity};
206
+ _stroke = (ALStyle){ALStyleColor, {0, 0, 0, 1}, 0, CGAffineTransformIdentity};
207
+ _lineWidth = 1;
208
+ _lineCap = kCGLineCapButt;
209
+ _lineJoin = kCGLineJoinMiter;
210
+ _miterLimit = 10;
211
+ _lineDash = @[];
212
+ _font = [UIFont systemFontOfSize:10];
213
+ _textAlign = 0;
214
+ _textBaseline = 3;
215
+ _smoothing = YES;
216
+ _filterSteps = @[];
217
+ }
218
+ return self;
219
+ }
220
+
221
+ - (id)copyWithZone:(NSZone *)zone {
222
+ ALCanvas2DState *copy = [[ALCanvas2DState alloc] init];
223
+ copy.transform = _transform;
224
+ copy.globalAlpha = _globalAlpha;
225
+ copy.composite = _composite;
226
+ copy.fill = _fill;
227
+ copy.stroke = _stroke;
228
+ copy.fillGradient = _fillGradient;
229
+ copy.strokeGradient = _strokeGradient;
230
+ copy.lineWidth = _lineWidth;
231
+ copy.lineCap = _lineCap;
232
+ copy.lineJoin = _lineJoin;
233
+ copy.miterLimit = _miterLimit;
234
+ copy.lineDash = _lineDash;
235
+ copy.lineDashOffset = _lineDashOffset;
236
+ copy.shadowBlur = _shadowBlur;
237
+ copy.shadowOffsetX = _shadowOffsetX;
238
+ copy.shadowOffsetY = _shadowOffsetY;
239
+ copy.shadowR = _shadowR;
240
+ copy.shadowG = _shadowG;
241
+ copy.shadowB = _shadowB;
242
+ copy.shadowA = _shadowA;
243
+ copy.font = _font;
244
+ copy.textAlign = _textAlign;
245
+ copy.textBaseline = _textBaseline;
246
+ copy.rtl = _rtl;
247
+ copy.letterSpacing = _letterSpacing;
248
+ copy.smoothing = _smoothing;
249
+ copy.smoothingQuality = _smoothingQuality;
250
+ copy.filterSteps = _filterSteps;
251
+ return copy;
252
+ }
253
+
254
+ @end
255
+
256
+ #pragma mark - Gradients and patterns
257
+
258
+ /// A CanvasGradient: linear, radial or conic, and its stops, in order.
259
+ @interface ALCanvas2DGradient : NSObject
260
+ @property(nonatomic) NSInteger type; // 0 linear, 1 radial, 2 conic
261
+ @property(nonatomic) CGFloat p0, p1, p2, p3, p4, p5;
262
+ @property(nonatomic, readonly) NSMutableArray<NSArray<NSNumber *> *> *stops;
263
+ - (nullable CGGradientRef)gradient;
264
+ - (void)colorAt:(CGFloat)t into:(CGFloat *)rgba;
265
+ @end
266
+
267
+ @implementation ALCanvas2DGradient {
268
+ CGGradientRef _gradient;
269
+ }
270
+
271
+ - (instancetype)init {
272
+ if ((self = [super init])) _stops = [NSMutableArray array];
273
+ return self;
274
+ }
275
+
276
+ - (void)dealloc {
277
+ if (_gradient) CGGradientRelease(_gradient);
278
+ }
279
+
280
+ - (void)addStop:(CGFloat)offset r:(CGFloat)r g:(CGFloat)g b:(CGFloat)b a:(CGFloat)a {
281
+ // A stop goes after the stops at the same offset, as the spec has it, so
282
+ // two at one offset make a hard edge.
283
+ NSUInteger index = _stops.count;
284
+ while (index > 0 && [_stops[index - 1][0] doubleValue] > offset) index--;
285
+ [_stops insertObject:@[ @(offset), @(r), @(g), @(b), @(a) ] atIndex:index];
286
+ if (_gradient) {
287
+ CGGradientRelease(_gradient);
288
+ _gradient = NULL;
289
+ }
290
+ }
291
+
292
+ /// The stops as a CGGradient, extended to 0 and 1 with the end colors, or
293
+ /// NULL when there are none (the gradient paints nothing).
294
+ - (CGGradientRef)gradient {
295
+ if (_gradient || _stops.count == 0) return _gradient;
296
+ NSMutableArray<NSArray<NSNumber *> *> *stops = [_stops mutableCopy];
297
+ if ([stops.firstObject[0] doubleValue] > 0) {
298
+ NSMutableArray *first = [stops.firstObject mutableCopy];
299
+ first[0] = @0;
300
+ [stops insertObject:first atIndex:0];
301
+ }
302
+ if ([stops.lastObject[0] doubleValue] < 1) {
303
+ NSMutableArray *last = [stops.lastObject mutableCopy];
304
+ last[0] = @1;
305
+ [stops addObject:last];
306
+ }
307
+ size_t count = stops.count;
308
+ CGFloat *components = malloc(sizeof(CGFloat) * count * 4);
309
+ CGFloat *locations = malloc(sizeof(CGFloat) * count);
310
+ for (size_t i = 0; i < count; i++) {
311
+ locations[i] = [stops[i][0] doubleValue];
312
+ for (size_t c = 0; c < 4; c++) {
313
+ CGFloat value = [stops[i][c + 1] doubleValue];
314
+ components[i * 4 + c] = c < 3 ? value / 255.0 : value;
315
+ }
316
+ }
317
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
318
+ _gradient = CGGradientCreateWithColorComponents(space, components, locations, count);
319
+ CGColorSpaceRelease(space);
320
+ free(components);
321
+ free(locations);
322
+ return _gradient;
323
+ }
324
+
325
+ /// The color at `t` (0 to 1), for the conic gradient, which is worked out a
326
+ /// pixel at a time: interpolated between the stops on either side, before
327
+ /// multiplying by alpha, as the spec has it. 0 to 1 each.
328
+ - (void)colorAt:(CGFloat)t into:(CGFloat *)rgba {
329
+ NSUInteger count = _stops.count;
330
+ NSArray<NSNumber *> *before = _stops.firstObject;
331
+ NSArray<NSNumber *> *after = _stops.lastObject;
332
+ for (NSUInteger i = 0; i < count; i++) {
333
+ if ([_stops[i][0] doubleValue] <= t) before = _stops[i];
334
+ if ([_stops[count - 1 - i][0] doubleValue] >= t) after = _stops[count - 1 - i];
335
+ }
336
+ CGFloat t0 = [before[0] doubleValue];
337
+ CGFloat t1 = [after[0] doubleValue];
338
+ CGFloat f = t1 > t0 ? (t - t0) / (t1 - t0) : 0;
339
+ for (int c = 0; c < 4; c++) {
340
+ CGFloat a = [before[c + 1] doubleValue];
341
+ CGFloat b = [after[c + 1] doubleValue];
342
+ CGFloat value = a + (b - a) * f;
343
+ rgba[c] = c < 3 ? value / 255.0 : value;
344
+ }
345
+ }
346
+
347
+ @end
348
+
349
+ /// A CanvasPattern: an image, how it repeats, and its own transform.
350
+ @interface ALCanvas2DPattern : NSObject
351
+ @property(nonatomic) CGImageRef image;
352
+ @property(nonatomic) NSInteger repetition; // 0 repeat, 1 repeat-x, 2 repeat-y, 3 no-repeat
353
+ @property(nonatomic) CGInterpolationQuality quality;
354
+ @end
355
+
356
+ @implementation ALCanvas2DPattern
357
+
358
+ - (void)dealloc {
359
+ CGImageRelease(_image);
360
+ }
361
+
362
+ @end
363
+
364
+ static void drawPatternCell(void *info, CGContextRef c) {
365
+ ALCanvas2DPattern *pattern = (__bridge ALCanvas2DPattern *)info;
366
+ CGFloat width = CGImageGetWidth(pattern.image);
367
+ CGFloat height = CGImageGetHeight(pattern.image);
368
+ // Pattern space is the canvas's, top-left origin, so the image is drawn
369
+ // the right way up by flipping it in its cell.
370
+ CGContextSetInterpolationQuality(c, pattern.quality);
371
+ CGContextTranslateCTM(c, 0, height);
372
+ CGContextScaleCTM(c, 1, -1);
373
+ CGContextDrawImage(c, CGRectMake(0, 0, width, height), pattern.image);
374
+ }
375
+
376
+ #pragma mark - Fonts
377
+
378
+ /// CSS's weights as UIKit's.
379
+ static UIFontWeight fontWeightFor(NSInteger weight) {
380
+ if (weight < 150) return UIFontWeightUltraLight;
381
+ if (weight < 250) return UIFontWeightThin;
382
+ if (weight < 350) return UIFontWeightLight;
383
+ if (weight < 450) return UIFontWeightRegular;
384
+ if (weight < 550) return UIFontWeightMedium;
385
+ if (weight < 650) return UIFontWeightSemibold;
386
+ if (weight < 750) return UIFontWeightBold;
387
+ if (weight < 850) return UIFontWeightHeavy;
388
+ return UIFontWeightBlack;
389
+ }
390
+
391
+ static UIFont *withItalic(UIFont *font, BOOL italic) {
392
+ if (!italic) return font;
393
+ UIFontDescriptor *descriptor =
394
+ [font.fontDescriptor fontDescriptorWithSymbolicTraits:font.fontDescriptor.symbolicTraits |
395
+ UIFontDescriptorTraitItalic];
396
+ return descriptor ? [UIFont fontWithDescriptor:descriptor size:font.pointSize] : font;
397
+ }
398
+
399
+ /// The first of the families iOS has, at the weight and style, as a
400
+ /// browser's font matching picks it. CSS's generic families are Safari's.
401
+ static UIFont *fontFor(NSString *families, NSInteger weight, BOOL italic, CGFloat size) {
402
+ UIFontWeight uiWeight = fontWeightFor(weight);
403
+ for (NSString *raw in [families componentsSeparatedByString:@"\n"]) {
404
+ NSString *family = [raw stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
405
+ NSString *lower = family.lowercaseString;
406
+ UIFont *font = nil;
407
+ if ([@[ @"sans-serif", @"system-ui", @"-apple-system", @"ui-sans-serif", @"ui-rounded" ]
408
+ containsObject:lower]) {
409
+ font = [UIFont systemFontOfSize:size weight:uiWeight];
410
+ if ([lower isEqualToString:@"ui-rounded"]) {
411
+ UIFontDescriptor *rounded =
412
+ [font.fontDescriptor fontDescriptorWithDesign:UIFontDescriptorSystemDesignRounded];
413
+ if (rounded) font = [UIFont fontWithDescriptor:rounded size:size];
414
+ }
415
+ } else if ([lower isEqualToString:@"ui-monospace"]) {
416
+ font = [UIFont monospacedSystemFontOfSize:size weight:uiWeight];
417
+ } else if ([lower isEqualToString:@"ui-serif"]) {
418
+ UIFontDescriptor *serif = [[UIFont systemFontOfSize:size weight:uiWeight].fontDescriptor
419
+ fontDescriptorWithDesign:UIFontDescriptorSystemDesignSerif];
420
+ if (serif) font = [UIFont fontWithDescriptor:serif size:size];
421
+ } else {
422
+ NSString *name = family;
423
+ if ([lower isEqualToString:@"serif"]) name = @"Times New Roman";
424
+ if ([lower isEqualToString:@"monospace"]) name = @"Courier";
425
+ if ([lower isEqualToString:@"cursive"]) name = @"Snell Roundhand";
426
+ if ([lower isEqualToString:@"fantasy"]) name = @"Papyrus";
427
+ // A family name, matched without case, then a font's own name.
428
+ NSString *match = nil;
429
+ for (NSString *installed in UIFont.familyNames) {
430
+ if ([installed caseInsensitiveCompare:name] == NSOrderedSame) {
431
+ match = installed;
432
+ break;
433
+ }
434
+ }
435
+ if (match) {
436
+ UIFontDescriptor *descriptor = [UIFontDescriptor fontDescriptorWithFontAttributes:@{
437
+ UIFontDescriptorFamilyAttribute : match,
438
+ UIFontDescriptorTraitsAttribute : @{UIFontWeightTrait : @(uiWeight)},
439
+ }];
440
+ font = [UIFont fontWithDescriptor:descriptor size:size];
441
+ } else {
442
+ font = [UIFont fontWithName:name size:size];
443
+ }
444
+ }
445
+ if (font) return withItalic(font, italic);
446
+ }
447
+ return withItalic([UIFont systemFontOfSize:size weight:uiWeight], italic);
448
+ }
449
+
450
+ #pragma mark - Filters
451
+
452
+ // The 2D context's `filter`, which the runtime parses into steps
453
+ // (packages/runtime/src/lib/canvas/css-filter.ts): a Gaussian blur, a color
454
+ // matrix, or a drop shadow, applied in order to the layer what's drawn went
455
+ // into, after its alpha and before its shadow and compositing, as the
456
+ // canvas spec has it. They
457
+ // work on the layer's bytes, premultiplied RGBA, in sRGB, which is where
458
+ // the spec has filter functions work. Android's shell runs the same steps
459
+ // the same way (CanvasFilter.kt), so the two draw alike.
460
+
461
+ /// The steps' kinds, as css-filter.ts's FILTER_STEP numbers them.
462
+ enum { ALFilterBlur = 0, ALFilterMatrix = 1, ALFilterDropShadow = 2 };
463
+
464
+ static inline uint8_t clampByte(double value) {
465
+ return value <= 0 ? 0 : value >= 255 ? 255 : (uint8_t)(value + 0.5);
466
+ }
467
+
468
+ static inline double clampUnit(double value) { return value < 0 ? 0 : value > 1 ? 1 : value; }
469
+
470
+ /// A color matrix (row by row: red, green, blue, alpha; each row's factors
471
+ /// and offset) on the colors not premultiplied, clamped, as feColorMatrix is.
472
+ static void applyColorMatrix(uint8_t *bytes, size_t pixels, const double *m) {
473
+ for (size_t i = 0; i < pixels; i++) {
474
+ uint8_t *p = bytes + i * 4;
475
+ double a = p[3] / 255.0;
476
+ double r = 0, g = 0, b = 0;
477
+ if (a > 0) {
478
+ r = p[0] / 255.0 / a;
479
+ g = p[1] / 255.0 / a;
480
+ b = p[2] / 255.0 / a;
481
+ }
482
+ double r2 = clampUnit(m[0] * r + m[1] * g + m[2] * b + m[3] * a + m[4]);
483
+ double g2 = clampUnit(m[5] * r + m[6] * g + m[7] * b + m[8] * a + m[9]);
484
+ double b2 = clampUnit(m[10] * r + m[11] * g + m[12] * b + m[13] * a + m[14]);
485
+ double a2 = clampUnit(m[15] * r + m[16] * g + m[17] * b + m[18] * a + m[19]);
486
+ p[0] = clampByte(r2 * a2 * 255);
487
+ p[1] = clampByte(g2 * a2 * 255);
488
+ p[2] = clampByte(b2 * a2 * 255);
489
+ p[3] = clampByte(a2 * 255);
490
+ }
491
+ }
492
+
493
+ /// One box blur along each row (or each column), each output the mean of
494
+ /// the `lo` bytes before it, itself and the `hi` after; transparent past the
495
+ /// edges.
496
+ static void boxPass(const uint8_t *src, uint8_t *dst, size_t width, size_t height, size_t lo,
497
+ size_t hi, BOOL horizontal) {
498
+ size_t lines = horizontal ? height : width;
499
+ size_t length = horizontal ? width : height;
500
+ size_t step = horizontal ? 4 : width * 4;
501
+ size_t lineStride = horizontal ? width * 4 : 4;
502
+ size_t size = lo + hi + 1;
503
+ for (size_t line = 0; line < lines; line++) {
504
+ const uint8_t *in = src + line * lineStride;
505
+ uint8_t *out = dst + line * lineStride;
506
+ for (size_t channel = 0; channel < 4; channel++) {
507
+ size_t sum = 0;
508
+ for (size_t i = 0; i <= hi && i < length; i++) sum += in[i * step + channel];
509
+ for (size_t x = 0; x < length; x++) {
510
+ out[x * step + channel] = (uint8_t)((sum * 2 + size) / (size * 2));
511
+ if (x + hi + 1 < length) sum += in[(x + hi + 1) * step + channel];
512
+ if (x >= lo) sum -= in[(x - lo) * step + channel];
513
+ }
514
+ }
515
+ }
516
+ }
517
+
518
+ /// One pass of a Gaussian kernel along each row (or each column).
519
+ static void kernelPass(const uint8_t *src, uint8_t *dst, size_t width, size_t height,
520
+ const double *weights, size_t radius, BOOL horizontal) {
521
+ size_t lines = horizontal ? height : width;
522
+ size_t length = horizontal ? width : height;
523
+ size_t step = horizontal ? 4 : width * 4;
524
+ size_t lineStride = horizontal ? width * 4 : 4;
525
+ for (size_t line = 0; line < lines; line++) {
526
+ const uint8_t *in = src + line * lineStride;
527
+ uint8_t *out = dst + line * lineStride;
528
+ for (size_t x = 0; x < length; x++) {
529
+ double sum[4] = {0, 0, 0, 0};
530
+ size_t from = x >= radius ? x - radius : 0;
531
+ size_t to = MIN(length - 1, x + radius);
532
+ for (size_t i = from; i <= to; i++) {
533
+ double weight = weights[(i + radius) - x];
534
+ const uint8_t *p = in + i * step;
535
+ for (int channel = 0; channel < 4; channel++) sum[channel] += p[channel] * weight;
536
+ }
537
+ for (int channel = 0; channel < 4; channel++) out[x * step + channel] = clampByte(sum[channel]);
538
+ }
539
+ }
540
+ }
541
+
542
+ /// A Gaussian blur of deviation `sigma`, as feGaussianBlur draws it: from a
543
+ /// deviation of 2, three box blurs, which the spec gives as within 3% of
544
+ /// the Gaussian (and which cost the same whatever the deviation); below it,
545
+ /// the Gaussian's own kernel, which is small there.
546
+ static void gaussianBlur(uint8_t *bytes, size_t width, size_t height, double sigma) {
547
+ if (!(sigma > 0) || width == 0 || height == 0) return;
548
+ uint8_t *scratch = malloc(width * height * 4);
549
+ if (!scratch) return;
550
+ for (int pass = 0; pass < 2; pass++) {
551
+ BOOL horizontal = pass == 0;
552
+ if (sigma >= 2) {
553
+ size_t d = (size_t)floor(sigma * 3 * sqrt(2 * M_PI) / 4 + 0.5);
554
+ if (d % 2 == 1) {
555
+ boxPass(bytes, scratch, width, height, d / 2, d / 2, horizontal);
556
+ boxPass(scratch, bytes, width, height, d / 2, d / 2, horizontal);
557
+ boxPass(bytes, scratch, width, height, d / 2, d / 2, horizontal);
558
+ } else {
559
+ // An even box is centered between two pixels: one leans left, one
560
+ // right, and the third is a pixel wider and centered.
561
+ boxPass(bytes, scratch, width, height, d / 2, d / 2 - 1, horizontal);
562
+ boxPass(scratch, bytes, width, height, d / 2 - 1, d / 2, horizontal);
563
+ boxPass(bytes, scratch, width, height, d / 2, d / 2, horizontal);
564
+ }
565
+ memcpy(bytes, scratch, width * height * 4);
566
+ } else {
567
+ size_t radius = (size_t)ceil(sigma * 3);
568
+ double weights[2 * 6 + 1];
569
+ double total = 0;
570
+ for (size_t i = 0; i <= 2 * radius; i++) {
571
+ double k = (double)i - (double)radius;
572
+ weights[i] = exp(-(k * k) / (2 * sigma * sigma));
573
+ total += weights[i];
574
+ }
575
+ for (size_t i = 0; i <= 2 * radius; i++) weights[i] /= total;
576
+ kernelPass(bytes, scratch, width, height, weights, radius, horizontal);
577
+ memcpy(bytes, scratch, width * height * 4);
578
+ }
579
+ }
580
+ free(scratch);
581
+ }
582
+
583
+ /// The shadow of what's in `bytes`: its alpha, moved by the offset (to the
584
+ /// nearest pixel), blurred by the deviation and in the color (red, green and
585
+ /// blue 0 to 255, alpha 0 to 1), as new premultiplied bytes the caller
586
+ /// frees, or NULL if they can't be made.
587
+ static uint8_t *newShadowBytes(const uint8_t *bytes, size_t width, size_t height, double dx,
588
+ double dy, double sigma, double r, double g, double b,
589
+ double a) {
590
+ size_t length = width * height * 4;
591
+ uint8_t *shadow = calloc(length, 1);
592
+ if (!shadow) return NULL;
593
+ long offsetX = lround(dx), offsetY = lround(dy);
594
+ for (size_t y = 0; y < height; y++) {
595
+ long fromY = (long)y - offsetY;
596
+ if (fromY < 0 || fromY >= (long)height) continue;
597
+ for (size_t x = 0; x < width; x++) {
598
+ long fromX = (long)x - offsetX;
599
+ if (fromX < 0 || fromX >= (long)width) continue;
600
+ shadow[(y * width + x) * 4 + 3] = bytes[((size_t)fromY * width + (size_t)fromX) * 4 + 3];
601
+ }
602
+ }
603
+ gaussianBlur(shadow, width, height, sigma);
604
+ for (size_t i = 0; i < length; i += 4) {
605
+ double shadowAlpha = shadow[i + 3] / 255.0 * a;
606
+ shadow[i] = clampByte(r * shadowAlpha);
607
+ shadow[i + 1] = clampByte(g * shadowAlpha);
608
+ shadow[i + 2] = clampByte(b * shadowAlpha);
609
+ shadow[i + 3] = clampByte(255 * shadowAlpha);
610
+ }
611
+ return shadow;
612
+ }
613
+
614
+ /// `under` drawn under `bytes`, source-over, as drop-shadow() puts its
615
+ /// shadow under what's drawn. Both are premultiplied, `pixels` long.
616
+ static void drawUnder(uint8_t *bytes, const uint8_t *under, size_t pixels) {
617
+ for (size_t i = 0; i < pixels * 4; i += 4) {
618
+ double uncovered = 1 - bytes[i + 3] / 255.0;
619
+ for (int channel = 0; channel < 4; channel++) {
620
+ bytes[i + channel] = clampByte(bytes[i + channel] + under[i + channel] * uncovered);
621
+ }
622
+ }
623
+ }
624
+
625
+ /// globalAlpha on a layer's bytes, which are premultiplied, so every
626
+ /// channel scales.
627
+ static void scaleAlpha(uint8_t *bytes, size_t pixels, double alpha) {
628
+ if (alpha >= 1) return;
629
+ for (size_t i = 0; i < pixels * 4; i++) bytes[i] = clampByte(bytes[i] * alpha);
630
+ }
631
+
632
+ /// A step of the filter: its kind and its numbers, and, for a drop shadow,
633
+ /// whether it's cast from a layer of its own when the filter reaches past
634
+ /// the layers' cap (see lastFar): one of the filter's last
635
+ /// MAX_OWN_LAYERS drop shadows moved by an offset, which parsedFilter marks.
636
+ typedef struct {
637
+ NSInteger kind;
638
+ double values[20];
639
+ BOOL castsAlone;
640
+ } ALFilterStep;
641
+
642
+ static BOOL isMovedShadow(const ALFilterStep *step);
643
+
644
+ /// The most drop shadows in one filter that can be cast from a layer of
645
+ /// their own (see lastFar): the last ones moved by an offset. Each works out
646
+ /// the steps before it twice, over the layer it goes under and over that
647
+ /// moved back by its offset, so the draws double with each one; past this,
648
+ /// the earlier ones are planned as any step is, within the layers' cap, as
649
+ /// before issue #824. Three keep a fill to eight draws.
650
+ static const NSUInteger MAX_OWN_LAYERS = 3;
651
+
652
+ /// The filter's steps, as the runtime sends them: ALFilterSteps, end to end.
653
+ static NSData *parsedFilter(NSArray<NSNumber *> *steps) {
654
+ NSUInteger count = steps.count, i = 0;
655
+ NSMutableData *parsed = [NSMutableData data];
656
+ while (i < count) {
657
+ NSInteger kind = steps[i++].integerValue;
658
+ NSUInteger arity = kind == ALFilterBlur ? 1 : kind == ALFilterMatrix ? 20 : kind == ALFilterDropShadow ? 7 : 0;
659
+ // A step it doesn't know, or one cut short, ends the list: what's after
660
+ // it would be read as the wrong numbers.
661
+ if (arity == 0 || i + arity > count) break;
662
+ ALFilterStep step = {kind, {0}, NO};
663
+ for (NSUInteger k = 0; k < arity; k++) step.values[k] = steps[i + k].doubleValue;
664
+ [parsed appendBytes:&step length:sizeof(step)];
665
+ i += arity;
666
+ }
667
+ ALFilterStep *parsedSteps = parsed.mutableBytes;
668
+ NSUInteger marked = 0;
669
+ for (NSUInteger k = parsed.length / sizeof(ALFilterStep); k > 0 && marked < MAX_OWN_LAYERS; k--) {
670
+ if (!isMovedShadow(&parsedSteps[k - 1])) continue;
671
+ parsedSteps[k - 1].castsAlone = YES;
672
+ marked++;
673
+ }
674
+ return parsed;
675
+ }
676
+
677
+ /// A step's deviation, for a blur or a drop shadow; 0 for a color matrix.
678
+ static double stepSigma(const ALFilterStep *step) {
679
+ return step->kind == ALFilterBlur ? step->values[0] : step->kind == ALFilterDropShadow ? step->values[2] : 0;
680
+ }
681
+
682
+ /// How far a step can move what's drawn, in the canvas's pixels: three
683
+ /// deviations, and a drop shadow's offset. Uncapped: -planFor:... caps the
684
+ /// layer it sizes (MAX_REACH).
685
+ static double stepReach(const ALFilterStep *step) {
686
+ if (step->kind == ALFilterBlur) return ceil(step->values[0] * 3);
687
+ if (step->kind == ALFilterDropShadow) {
688
+ return ceil(step->values[2] * 3) + ceil(MAX(fabs(step->values[0]), fabs(step->values[1])));
689
+ }
690
+ return 0;
691
+ }
692
+
693
+ /// Whether a step is a drop shadow moved by an offset.
694
+ static BOOL isMovedShadow(const ALFilterStep *step) {
695
+ return step->kind == ALFilterDropShadow && (step->values[0] != 0 || step->values[1] != 0);
696
+ }
697
+
698
+ /// One step on a layer's bytes, in a layer `scale` of whose pixels make a
699
+ /// canvas pixel: its lengths (a deviation, an offset) are in the canvas's
700
+ /// pixels, so they're scaled to the layer's.
701
+ static void applyStep(uint8_t *bytes, size_t width, size_t height, const ALFilterStep *step,
702
+ double scale) {
703
+ const double *v = step->values;
704
+ switch (step->kind) {
705
+ case ALFilterBlur:
706
+ gaussianBlur(bytes, width, height, v[0] * scale);
707
+ break;
708
+ case ALFilterMatrix:
709
+ applyColorMatrix(bytes, width * height, v);
710
+ break;
711
+ default: {
712
+ uint8_t *shadow = newShadowBytes(bytes, width, height, v[0] * scale, v[1] * scale,
713
+ v[2] * scale, v[3], v[4], v[5], v[6]);
714
+ if (!shadow) return;
715
+ drawUnder(bytes, shadow, width * height);
716
+ free(shadow);
717
+ }
718
+ }
719
+ }
720
+
721
+ /// A layer a draw goes into, over part of the canvas's pixels: from (left,
722
+ /// top), `width` by `height` of its pixels, `scale` of them to a canvas
723
+ /// pixel; `exists` is NO for none. A layer at the canvas's resolution
724
+ /// (scale 1) lies on whole pixels, so its pixels line up with the canvas's.
725
+ typedef struct {
726
+ BOOL exists;
727
+ CGFloat left, top;
728
+ size_t width, height;
729
+ CGFloat scale;
730
+ } ALLayer;
731
+
732
+ static const ALLayer NO_LAYER = {NO, 0, 0, 0, 0, 0};
733
+
734
+ static ALLayer layerOfRect(CGRect rect) {
735
+ return (ALLayer){YES, rect.origin.x, rect.origin.y, (size_t)rect.size.width,
736
+ (size_t)rect.size.height, 1};
737
+ }
738
+
739
+ /// Where a layer lies in the canvas's pixels.
740
+ static CGRect layerBounds(ALLayer layer) {
741
+ return CGRectMake(layer.left, layer.top, layer.width / layer.scale, layer.height / layer.scale);
742
+ }
743
+
744
+ /// A layer grown by `pixels` of its own on each side, which stay where they
745
+ /// were.
746
+ static ALLayer grownLayer(ALLayer layer, size_t pixels) {
747
+ return (ALLayer){YES,
748
+ layer.left - pixels / layer.scale,
749
+ layer.top - pixels / layer.scale,
750
+ layer.width + 2 * pixels,
751
+ layer.height + 2 * pixels,
752
+ layer.scale};
753
+ }
754
+
755
+ /// A layer moved by (dx, dy) canvas pixels.
756
+ static ALLayer movedLayer(ALLayer layer, double dx, double dy) {
757
+ layer.left += dx;
758
+ layer.top += dy;
759
+ return layer;
760
+ }
761
+
762
+ /// The bytes of layer `from` resampled onto layer `to`, moved by (shiftX,
763
+ /// shiftY) canvas pixels: read with bilinear filtering at the center of each
764
+ /// of `to`'s pixels, transparent past `from`'s edges, as new bytes the
765
+ /// caller frees (NULL if they can't be made). It's how a blur worked out in
766
+ /// a smaller layer is scaled up, and how a drop shadow's offset lands
767
+ /// between two pixels, which a blur that wide has no edge to show.
768
+ static uint8_t *newResampled(const uint8_t *src, ALLayer from, ALLayer to, double shiftX,
769
+ double shiftY) {
770
+ uint8_t *dst = calloc(to.width * to.height * 4, 1);
771
+ long *xs = malloc(sizeof(long) * (to.width + 1));
772
+ double *fx = malloc(sizeof(double) * (to.width + 1));
773
+ if (!dst || !xs || !fx) {
774
+ free(dst);
775
+ free(xs);
776
+ free(fx);
777
+ return NULL;
778
+ }
779
+ // Where each column's center falls in `from`, as the pixel before it and
780
+ // how far past that pixel's center it is. Clamped, so a far shift stays a
781
+ // long (and reads nothing).
782
+ for (size_t i = 0; i < to.width; i++) {
783
+ double u = (to.left + (i + 0.5) / to.scale - shiftX - from.left) * from.scale - 0.5;
784
+ u = MIN(MAX(u, -2.0), (double)from.width + 1);
785
+ xs[i] = (long)floor(u);
786
+ fx[i] = u - floor(u);
787
+ }
788
+ long w = (long)from.width, h = (long)from.height;
789
+ for (size_t j = 0; j < to.height; j++) {
790
+ double v = (to.top + (j + 0.5) / to.scale - shiftY - from.top) * from.scale - 0.5;
791
+ v = MIN(MAX(v, -2.0), (double)from.height + 1);
792
+ long y = (long)floor(v);
793
+ double wy = v - floor(v);
794
+ if (y < -1 || y >= h) continue;
795
+ for (size_t i = 0; i < to.width; i++) {
796
+ long x = xs[i];
797
+ if (x < -1 || x >= w) continue;
798
+ double wx = fx[i];
799
+ uint8_t *out = dst + (j * to.width + i) * 4;
800
+ for (int channel = 0; channel < 4; channel++) {
801
+ double corners[4] = {0, 0, 0, 0};
802
+ for (int k = 0; k < 4; k++) {
803
+ long cx = x + (k & 1), cy = y + (k >> 1);
804
+ if (cx >= 0 && cy >= 0 && cx < w && cy < h) corners[k] = src[(cy * w + cx) * 4 + channel];
805
+ }
806
+ double top = corners[0] * (1 - wx) + corners[1] * wx;
807
+ double bottom = corners[2] * (1 - wx) + corners[3] * wx;
808
+ out[channel] = clampByte(top * (1 - wy) + bottom * wy);
809
+ }
810
+ }
811
+ }
812
+ free(xs);
813
+ free(fx);
814
+ return dst;
815
+ }
816
+
817
+ #pragma mark - The context
818
+
819
+ static const CGBlendMode BLEND_MODES[] = {
820
+ kCGBlendModeNormal, kCGBlendModeSourceIn, kCGBlendModeSourceOut,
821
+ kCGBlendModeSourceAtop, kCGBlendModeDestinationOver, kCGBlendModeDestinationIn,
822
+ kCGBlendModeDestinationOut, kCGBlendModeDestinationAtop, kCGBlendModePlusLighter,
823
+ kCGBlendModeCopy, kCGBlendModeXOR, kCGBlendModeMultiply,
824
+ kCGBlendModeScreen, kCGBlendModeOverlay, kCGBlendModeDarken,
825
+ kCGBlendModeLighten, kCGBlendModeColorDodge, kCGBlendModeColorBurn,
826
+ kCGBlendModeHardLight, kCGBlendModeSoftLight, kCGBlendModeDifference,
827
+ kCGBlendModeExclusion, kCGBlendModeHue, kCGBlendModeSaturation,
828
+ kCGBlendModeColor, kCGBlendModeLuminosity,
829
+ };
830
+ static const NSInteger BLEND_MODE_COUNT = sizeof(BLEND_MODES) / sizeof(BLEND_MODES[0]);
831
+
832
+ /// The operations that clear what the shape doesn't cover: source-in,
833
+ /// source-out, destination-in, destination-atop and copy.
834
+ static BOOL isUnbounded(NSInteger composite) {
835
+ return composite == 1 || composite == 2 || composite == 5 || composite == 7 || composite == 9;
836
+ }
837
+
838
+ /// The operations that can leave a pixel less opaque than it was: those,
839
+ /// and destination-out and xor.
840
+ static BOOL reducesAlpha(NSInteger composite) {
841
+ return isUnbounded(composite) || composite == 6 || composite == 10;
842
+ }
843
+
844
+ @implementation AngularLynxCanvas2DContext {
845
+ BOOL _alpha;
846
+ size_t _width;
847
+ size_t _height;
848
+ /// The bitmap's bytes: RGBA, premultiplied, rows top to bottom.
849
+ NSMutableData *_data;
850
+ CGContextRef _cg;
851
+ /// A 1 by 1 context for working out stroke outlines.
852
+ CGContextRef _scratch;
853
+ ALCanvas2DState *_state;
854
+ NSMutableArray<ALCanvas2DState *> *_stack;
855
+ /// The gradients and patterns of every 2D context in the LynxView, by the
856
+ /// runtime's ids, so one context's can paint in another. The module holds
857
+ /// it.
858
+ NSMutableDictionary<NSNumber *, id> *_objects;
859
+ AngularLynxCanvasTarget *_target;
860
+ /// The bitmap was drawn on and not shown yet, waiting for a view.
861
+ BOOL _framePending;
862
+ }
863
+
864
+ - (instancetype)initWithCanvasId:(NSString *)canvasId
865
+ attributes:(NSDictionary *)attributes
866
+ objects:(NSMutableDictionary<NSNumber *, id> *)objects
867
+ error:(NSString **)error {
868
+ if (!(self = [super init])) return nil;
869
+ _canvasId = [canvasId copy];
870
+ _alpha = ![attributes[@"alpha"] isEqual:@NO];
871
+ _objects = objects;
872
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
873
+ _scratch = CGBitmapContextCreate(NULL, 1, 1, 8, 4, space,
874
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
875
+ CGColorSpaceRelease(space);
876
+ NSNumber *width = attributes[@"width"];
877
+ NSNumber *height = attributes[@"height"];
878
+ if (![self allocateWidth:[width isKindOfClass:NSNumber.class] ? width.unsignedIntegerValue : 300
879
+ height:[height isKindOfClass:NSNumber.class] ? height.unsignedIntegerValue
880
+ : 150]) {
881
+ *error = @"Could not allocate the canvas's bitmap";
882
+ return nil;
883
+ }
884
+ return self;
885
+ }
886
+
887
+ - (void)dealloc {
888
+ if (_cg) CGContextRelease(_cg);
889
+ if (_scratch) CGContextRelease(_scratch);
890
+ }
891
+
892
+ /// A new bitmap, cleared, with the state reset, as a canvas has when it's
893
+ /// resized or reset.
894
+ - (BOOL)allocateWidth:(size_t)width height:(size_t)height {
895
+ if (_cg) CGContextRelease(_cg);
896
+ _cg = NULL;
897
+ _width = width;
898
+ _height = height;
899
+ _state = [[ALCanvas2DState alloc] init];
900
+ _stack = [NSMutableArray array];
901
+ if (width == 0 || height == 0) {
902
+ _data = [NSMutableData data];
903
+ return YES;
904
+ }
905
+ _data = [NSMutableData dataWithLength:width * height * 4];
906
+ if (!_data) return NO;
907
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
908
+ _cg = CGBitmapContextCreate(_data.mutableBytes, width, height, 8, width * 4, space,
909
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
910
+ CGColorSpaceRelease(space);
911
+ if (!_cg) return NO;
912
+ // The canvas's top-left origin, y down: Core Graphics' is bottom-left.
913
+ CGContextTranslateCTM(_cg, 0, height);
914
+ CGContextScaleCTM(_cg, 1, -1);
915
+ // A canvas with alpha: false is opaque black until drawn on.
916
+ if (!_alpha) [self fillOpaqueBlack:CGRectMake(0, 0, width, height) path:NULL];
917
+ return YES;
918
+ }
919
+
920
+ /// What clearRect leaves on a canvas without alpha: black.
921
+ - (void)fillOpaqueBlack:(CGRect)rect path:(CGPathRef)path {
922
+ CGContextSaveGState(_cg);
923
+ CGContextSetBlendMode(_cg, kCGBlendModeCopy);
924
+ CGContextSetRGBFillColor(_cg, 0, 0, 0, 1);
925
+ if (path) {
926
+ CGContextAddPath(_cg, path);
927
+ CGContextFillPath(_cg);
928
+ } else {
929
+ CGContextFillRect(_cg, rect);
930
+ }
931
+ CGContextRestoreGState(_cg);
932
+ }
933
+
934
+ #pragma mark Showing the bitmap
935
+
936
+ - (void)attachTarget:(AngularLynxCanvasTarget *)target {
937
+ if (_target == target) return;
938
+ _target = target;
939
+ if (target) [self present];
940
+ }
941
+
942
+ - (void)targetDidLayOut:(AngularLynxCanvasTarget *)target {
943
+ if (target == _target && _framePending) [self present];
944
+ }
945
+
946
+ /// A copy of the bitmap goes to the view: drawing on goes on in the bitmap
947
+ /// while the UI thread shows the copy.
948
+ - (void)present {
949
+ AngularLynxCanvasTarget *target = _target;
950
+ if (!target || target.pixelSize.width < 1 || target.pixelSize.height < 1) {
951
+ _framePending = YES;
952
+ return;
953
+ }
954
+ _framePending = NO;
955
+ CGImageRef image = [self newImage];
956
+ BOOL opaque = !_alpha;
957
+ NSString *canvasId = _canvasId;
958
+ dispatch_async(dispatch_get_main_queue(), ^{
959
+ [target.view showImage:image opaque:opaque canvasId:canvasId];
960
+ if (image) CGImageRelease(image);
961
+ });
962
+ }
963
+
964
+ /// A copy of the bitmap as an image, or NULL when it has no pixels.
965
+ - (CGImageRef)newImage {
966
+ if (!_cg) return NULL;
967
+ NSData *copy = [_data copy];
968
+ CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)copy);
969
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
970
+ CGImageRef image = CGImageCreate(
971
+ _width, _height, 8, 32, _width * 4, space,
972
+ (_alpha ? kCGImageAlphaPremultipliedLast : kCGImageAlphaNoneSkipLast) |
973
+ kCGBitmapByteOrder32Big,
974
+ provider, NULL, false, kCGRenderingIntentDefault);
975
+ CGColorSpaceRelease(space);
976
+ CGDataProviderRelease(provider);
977
+ return image;
978
+ }
979
+
980
+ - (AngularLynxDecodedImage *)snapshot {
981
+ if (!_cg) return nil;
982
+ return [[AngularLynxDecodedImage alloc] initWithPixels:[_data copy]
983
+ width:_width
984
+ height:_height
985
+ premultiplied:YES];
986
+ }
987
+
988
+ /// After transferToImageBitmap() took the bitmap: a new one, transparent
989
+ /// black, or opaque black without alpha (premultiplied black is all zeros
990
+ /// but its alpha). Cleared byte by byte, so the clip and the state stay.
991
+ - (void)clearForTransfer {
992
+ if (!_cg) return;
993
+ uint8_t *bytes = _data.mutableBytes;
994
+ NSUInteger length = _data.length;
995
+ memset(bytes, 0, length);
996
+ if (!_alpha) {
997
+ for (NSUInteger i = 3; i < length; i += 4) bytes[i] = 255;
998
+ }
999
+ if (_target) [self present];
1000
+ }
1001
+
1002
+ - (NSDictionary *)encodeImageOfType:(NSString *)type quality:(double)quality {
1003
+ if (!_cg) return @{@"error" : @"The canvas has no pixels"};
1004
+ BOOL jpeg = [type isEqualToString:@"image/jpeg"];
1005
+ // A JPEG has no transparency: its transparent pixels come out black, as in
1006
+ // browsers, which premultiplied colors already are.
1007
+ CGBitmapInfo alphaInfo = (CGBitmapInfo)(jpeg || !_alpha ? kCGImageAlphaNoneSkipLast
1008
+ : kCGImageAlphaPremultipliedLast);
1009
+ return AngularLynxEncodeImage([_data copy], _width, _height, alphaInfo, type, quality);
1010
+ }
1011
+
1012
+ #pragma mark Running a batch
1013
+
1014
+ - (NSArray *)run:(NSArray *)commands {
1015
+ NSUInteger count = commands.count;
1016
+ __unsafe_unretained id *items = (__unsafe_unretained id *)malloc(sizeof(id) * MAX(count, 1));
1017
+ [commands getObjects:items range:NSMakeRange(0, count)];
1018
+ ALReader reader = {items, count, 0};
1019
+ ALReader *r = &reader;
1020
+ NSMutableArray *results = [NSMutableArray array];
1021
+ while (r->index < r->count) {
1022
+ NSInteger op = readInt(r);
1023
+ if (op >= 200) {
1024
+ id result = [self query:op reader:r];
1025
+ [results addObject:result ?: [NSNull null]];
1026
+ } else {
1027
+ [self command:op reader:r];
1028
+ }
1029
+ }
1030
+ free(items);
1031
+ return results;
1032
+ }
1033
+
1034
+ - (ALStyle)styleOfKind:(ALStyleKind)kind reader:(ALReader *)r {
1035
+ ALStyle style = {kind, {0, 0, 0, 1}, 0, CGAffineTransformIdentity};
1036
+ if (kind == ALStyleColor) {
1037
+ for (int i = 0; i < 4; i++) style.rgba[i] = readNumber(r);
1038
+ } else if (kind == ALStylePattern) {
1039
+ style.objectId = readInt(r);
1040
+ CGFloat a = readNumber(r), b = readNumber(r), c = readNumber(r), d = readNumber(r),
1041
+ e = readNumber(r), f = readNumber(r);
1042
+ style.transform = CGAffineTransformMake(a, b, c, d, e, f);
1043
+ }
1044
+ return style;
1045
+ }
1046
+
1047
+ /// A gradient as the runtime sends it with a style: its type, six numbers,
1048
+ /// and its stops as offset, red, green, blue, alpha.
1049
+ - (ALCanvas2DGradient *)gradientFrom:(ALReader *)r {
1050
+ ALCanvas2DGradient *gradient = [[ALCanvas2DGradient alloc] init];
1051
+ gradient.type = readInt(r);
1052
+ gradient.p0 = readNumber(r);
1053
+ gradient.p1 = readNumber(r);
1054
+ gradient.p2 = readNumber(r);
1055
+ gradient.p3 = readNumber(r);
1056
+ gradient.p4 = readNumber(r);
1057
+ gradient.p5 = readNumber(r);
1058
+ NSArray *stops = readArray(r);
1059
+ for (NSUInteger i = 0; i + 4 < stops.count; i += 5) {
1060
+ [gradient addStop:[stops[i] doubleValue]
1061
+ r:[stops[i + 1] doubleValue]
1062
+ g:[stops[i + 2] doubleValue]
1063
+ b:[stops[i + 3] doubleValue]
1064
+ a:[stops[i + 4] doubleValue]];
1065
+ }
1066
+ return gradient;
1067
+ }
1068
+
1069
+ - (void)command:(NSInteger)op reader:(ALReader *)r {
1070
+ ALCanvas2DState *s = _state;
1071
+ switch ((ALCanvas2DOp)op) {
1072
+ case ALCanvas2DOpSave:
1073
+ [_stack addObject:[s copy]];
1074
+ if (_cg) CGContextSaveGState(_cg);
1075
+ break;
1076
+ case ALCanvas2DOpRestore:
1077
+ if (_stack.count == 0) break;
1078
+ _state = _stack.lastObject;
1079
+ [_stack removeLastObject];
1080
+ if (_cg) CGContextRestoreGState(_cg);
1081
+ break;
1082
+ case ALCanvas2DOpReset:
1083
+ [self allocateWidth:_width height:_height];
1084
+ break;
1085
+ case ALCanvas2DOpResize: {
1086
+ size_t width = (size_t)MAX(0, readInt(r));
1087
+ size_t height = (size_t)MAX(0, readInt(r));
1088
+ [self allocateWidth:width height:height];
1089
+ break;
1090
+ }
1091
+ case ALCanvas2DOpPresent:
1092
+ [self present];
1093
+ break;
1094
+ case ALCanvas2DOpSetTransform: {
1095
+ CGFloat a = readNumber(r), b = readNumber(r), c = readNumber(r), d = readNumber(r),
1096
+ e = readNumber(r), f = readNumber(r);
1097
+ s.transform = CGAffineTransformMake(a, b, c, d, e, f);
1098
+ break;
1099
+ }
1100
+ case ALCanvas2DOpSetGlobalAlpha:
1101
+ s.globalAlpha = readNumber(r);
1102
+ break;
1103
+ case ALCanvas2DOpSetCompositeOperation: {
1104
+ NSInteger composite = readInt(r);
1105
+ s.composite = composite >= 0 && composite < BLEND_MODE_COUNT ? composite : 0;
1106
+ break;
1107
+ }
1108
+ case ALCanvas2DOpSetFillColor:
1109
+ s.fill = [self styleOfKind:ALStyleColor reader:r];
1110
+ break;
1111
+ case ALCanvas2DOpSetFillGradient:
1112
+ s.fill = [self styleOfKind:ALStyleGradient reader:r];
1113
+ s.fillGradient = [self gradientFrom:r];
1114
+ break;
1115
+ case ALCanvas2DOpSetFillPattern:
1116
+ s.fill = [self styleOfKind:ALStylePattern reader:r];
1117
+ break;
1118
+ case ALCanvas2DOpSetStrokeColor:
1119
+ s.stroke = [self styleOfKind:ALStyleColor reader:r];
1120
+ break;
1121
+ case ALCanvas2DOpSetStrokeGradient:
1122
+ s.stroke = [self styleOfKind:ALStyleGradient reader:r];
1123
+ s.strokeGradient = [self gradientFrom:r];
1124
+ break;
1125
+ case ALCanvas2DOpSetStrokePattern:
1126
+ s.stroke = [self styleOfKind:ALStylePattern reader:r];
1127
+ break;
1128
+ case ALCanvas2DOpSetLineWidth:
1129
+ s.lineWidth = readNumber(r);
1130
+ break;
1131
+ case ALCanvas2DOpSetLineCap: {
1132
+ NSInteger cap = readInt(r);
1133
+ s.lineCap = cap == 1 ? kCGLineCapRound : cap == 2 ? kCGLineCapSquare : kCGLineCapButt;
1134
+ break;
1135
+ }
1136
+ case ALCanvas2DOpSetLineJoin: {
1137
+ NSInteger join = readInt(r);
1138
+ s.lineJoin = join == 1 ? kCGLineJoinRound : join == 2 ? kCGLineJoinBevel : kCGLineJoinMiter;
1139
+ break;
1140
+ }
1141
+ case ALCanvas2DOpSetMiterLimit:
1142
+ s.miterLimit = readNumber(r);
1143
+ break;
1144
+ case ALCanvas2DOpSetLineDash:
1145
+ s.lineDash = readArray(r);
1146
+ s.lineDashOffset = readNumber(r);
1147
+ break;
1148
+ case ALCanvas2DOpSetShadow:
1149
+ s.shadowBlur = readNumber(r);
1150
+ s.shadowR = readNumber(r);
1151
+ s.shadowG = readNumber(r);
1152
+ s.shadowB = readNumber(r);
1153
+ s.shadowA = readNumber(r);
1154
+ s.shadowOffsetX = readNumber(r);
1155
+ s.shadowOffsetY = readNumber(r);
1156
+ break;
1157
+ case ALCanvas2DOpSetFont: {
1158
+ BOOL italic = readInt(r) != 0;
1159
+ NSInteger weight = readInt(r);
1160
+ CGFloat size = readNumber(r);
1161
+ NSString *families = readString(r);
1162
+ s.font = fontFor(families, weight, italic, MAX(size, 0.01));
1163
+ break;
1164
+ }
1165
+ case ALCanvas2DOpSetTextAlign:
1166
+ s.textAlign = readInt(r);
1167
+ break;
1168
+ case ALCanvas2DOpSetTextBaseline:
1169
+ s.textBaseline = readInt(r);
1170
+ break;
1171
+ case ALCanvas2DOpSetDirection:
1172
+ s.rtl = readInt(r) == 1;
1173
+ break;
1174
+ case ALCanvas2DOpSetLetterSpacing:
1175
+ s.letterSpacing = readNumber(r);
1176
+ break;
1177
+ case ALCanvas2DOpSetImageSmoothing:
1178
+ s.smoothing = readInt(r) != 0;
1179
+ s.smoothingQuality = readInt(r);
1180
+ break;
1181
+ case ALCanvas2DOpSetFilter:
1182
+ // Only the steps: the layers are planned from their own reach (see
1183
+ // -planFor:...).
1184
+ s.filterSteps = readArray(r);
1185
+ break;
1186
+ case ALCanvas2DOpCreatePattern: {
1187
+ NSInteger objectId = readInt(r);
1188
+ NSDictionary *source = readMap(r);
1189
+ NSInteger repetition = readInt(r);
1190
+ CGImageRef image = [self newImageFrom:source];
1191
+ if (!image) break;
1192
+ ALCanvas2DPattern *pattern = [[ALCanvas2DPattern alloc] init];
1193
+ pattern.image = image;
1194
+ pattern.repetition = repetition;
1195
+ _objects[@(objectId)] = pattern;
1196
+ break;
1197
+ }
1198
+ case ALCanvas2DOpReleaseObject:
1199
+ [_objects removeObjectForKey:@(readInt(r))];
1200
+ break;
1201
+ case ALCanvas2DOpClearPath: {
1202
+ CGMutablePathRef path = pathFromSegments(readArray(r));
1203
+ [self clearPath:path];
1204
+ CGPathRelease(path);
1205
+ break;
1206
+ }
1207
+ case ALCanvas2DOpFill: {
1208
+ CGMutablePathRef path = pathFromSegments(readArray(r));
1209
+ BOOL evenOdd = readInt(r) == 1;
1210
+ [self fillDevicePath:path evenOdd:evenOdd style:s.fill gradient:s.fillGradient];
1211
+ CGPathRelease(path);
1212
+ break;
1213
+ }
1214
+ case ALCanvas2DOpStroke: {
1215
+ CGMutablePathRef path = pathFromSegments(readArray(r));
1216
+ [self strokeDevicePath:path];
1217
+ CGPathRelease(path);
1218
+ break;
1219
+ }
1220
+ case ALCanvas2DOpClip: {
1221
+ CGMutablePathRef path = pathFromSegments(readArray(r));
1222
+ BOOL evenOdd = readInt(r) == 1;
1223
+ if (_cg) {
1224
+ CGContextBeginPath(_cg);
1225
+ CGContextAddPath(_cg, path);
1226
+ // An empty path clips everything away.
1227
+ if (CGPathIsEmpty(path)) {
1228
+ CGContextClipToRect(_cg, CGRectZero);
1229
+ } else if (evenOdd) {
1230
+ CGContextEOClip(_cg);
1231
+ } else {
1232
+ CGContextClip(_cg);
1233
+ }
1234
+ }
1235
+ CGPathRelease(path);
1236
+ break;
1237
+ }
1238
+ case ALCanvas2DOpFillText:
1239
+ case ALCanvas2DOpStrokeText: {
1240
+ NSString *text = readString(r);
1241
+ CGFloat x = readNumber(r), y = readNumber(r), maxWidth = readNumber(r);
1242
+ [self drawText:text x:x y:y maxWidth:maxWidth stroke:op == ALCanvas2DOpStrokeText];
1243
+ break;
1244
+ }
1245
+ case ALCanvas2DOpDrawImage: {
1246
+ NSDictionary *source = readMap(r);
1247
+ CGFloat sx = readNumber(r), sy = readNumber(r), sw = readNumber(r), sh = readNumber(r);
1248
+ CGFloat dx = readNumber(r), dy = readNumber(r), dw = readNumber(r), dh = readNumber(r);
1249
+ CGImageRef image = [self newImageFrom:source];
1250
+ if (image) {
1251
+ [self drawImage:image
1252
+ source:CGRectMake(sx, sy, sw, sh)
1253
+ destination:CGRectMake(dx, dy, dw, dh)];
1254
+ CGImageRelease(image);
1255
+ }
1256
+ break;
1257
+ }
1258
+ case ALCanvas2DOpPutImageData: {
1259
+ NSData *bytes = AngularLynxBytesFromWords(readArray(r));
1260
+ NSInteger width = readInt(r), height = readInt(r), x = readInt(r), y = readInt(r);
1261
+ [self putPixels:bytes width:width height:height x:x y:y];
1262
+ break;
1263
+ }
1264
+ default:
1265
+ // An unknown command can't be skipped past: the rest of the batch
1266
+ // would be read as the wrong arguments.
1267
+ r->index = r->count;
1268
+ }
1269
+ }
1270
+
1271
+ - (id)query:(NSInteger)op reader:(ALReader *)r {
1272
+ switch ((ALCanvas2DOp)op) {
1273
+ case ALCanvas2DOpMeasureText:
1274
+ return [self measureText:readString(r)];
1275
+ case ALCanvas2DOpGetImageData: {
1276
+ NSInteger x = readInt(r), y = readInt(r), width = readInt(r), height = readInt(r);
1277
+ return [self pixelsAtX:x y:y width:width height:height];
1278
+ }
1279
+ case ALCanvas2DOpIsPointInPath: {
1280
+ CGMutablePathRef path = pathFromSegments(readArray(r));
1281
+ BOOL evenOdd = readInt(r) == 1;
1282
+ CGFloat x = readNumber(r), y = readNumber(r);
1283
+ BOOL inside = CGPathContainsPoint(path, NULL, CGPointMake(x, y), evenOdd);
1284
+ CGPathRelease(path);
1285
+ return @(inside);
1286
+ }
1287
+ case ALCanvas2DOpIsPointInStroke: {
1288
+ CGMutablePathRef path = pathFromSegments(readArray(r));
1289
+ CGFloat x = readNumber(r), y = readNumber(r);
1290
+ CGPathRef outline = [self strokeOutlineOf:path];
1291
+ BOOL inside = outline && CGPathContainsPoint(outline, NULL, CGPointMake(x, y), NO);
1292
+ if (outline) CGPathRelease(outline);
1293
+ CGPathRelease(path);
1294
+ return @(inside);
1295
+ }
1296
+ default:
1297
+ r->index = r->count;
1298
+ return nil;
1299
+ }
1300
+ }
1301
+
1302
+ #pragma mark Compositing
1303
+
1304
+ - (BOOL)shadowVisible {
1305
+ ALCanvas2DState *s = _state;
1306
+ return s.shadowA > 0 && (s.shadowBlur > 0 || s.shadowOffsetX != 0 || s.shadowOffsetY != 0);
1307
+ }
1308
+
1309
+ /// The most a layer at the canvas's resolution reaches past the part of the
1310
+ /// canvas it's for, so a huge blur makes no huge layer. A blur or shadow
1311
+ /// that reaches farther goes through a smaller layer too (see
1312
+ /// -layers:count:), which this keeps about the capped layer's size.
1313
+ static const CGFloat MAX_REACH = 256;
1314
+
1315
+ /// The deviation, in a smaller layer's pixels, from which a blur is worked
1316
+ /// out there and scaled up (see isWide): a blur that wide has no detail a
1317
+ /// pixel of that layer would lose.
1318
+ static const CGFloat WIDE_SIGMA = 4;
1319
+
1320
+ /// Whether a step blurs widely enough, in a layer at `scale`, to be worked
1321
+ /// out there and scaled up: its deviation there is at least WIDE_SIGMA of
1322
+ /// the layer's pixels, so the detail the smaller layer loses is blurred
1323
+ /// away. Skia scales a wide blur down the same way.
1324
+ static BOOL isWide(const ALFilterStep *step, CGFloat scale) {
1325
+ return stepSigma(step) * scale >= WIDE_SIGMA;
1326
+ }
1327
+
1328
+ /// How far off the canvas a far drop shadow's layer can lie: 2^24 pixels,
1329
+ /// past which a float, as the canvas's pixels are on Android, no longer
1330
+ /// holds every whole pixel. Kept the same on both shells.
1331
+ static const double MAX_LAYER_OFFSET = 16777216;
1332
+
1333
+ static double reachOf(const ALFilterStep *steps, NSUInteger count) {
1334
+ double reach = 0;
1335
+ for (NSUInteger i = 0; i < count; i++) reach += stepReach(&steps[i]);
1336
+ return reach;
1337
+ }
1338
+
1339
+ /// The index of the last far drop shadow in the steps, or -1. When the
1340
+ /// steps reach past MAX_REACH, a drop shadow moved by an offset is far (up
1341
+ /// to the filter's last few, castsAlone, as each doubles the draws): it's
1342
+ /// cast from a layer of its own (-newFarShadow:...), so its offset
1343
+ /// doesn't count toward the reach the layers are planned for. Counted, an
1344
+ /// offset past the cap would leave out a shape that far off the canvas
1345
+ /// (issue #824), as the capped layer doesn't reach it, and it would lower
1346
+ /// the scale of the smaller layer a wide blur goes through, enough to keep a
1347
+ /// blur beside it at the canvas's resolution, cut short by the cap.
1348
+ static NSInteger lastFar(const ALFilterStep *steps, NSUInteger count) {
1349
+ if (!(reachOf(steps, count) > MAX_REACH)) return -1;
1350
+ for (NSUInteger i = count; i > 0; i--) {
1351
+ if (steps[i - 1].castsAlone) return (NSInteger)(i - 1);
1352
+ }
1353
+ return -1;
1354
+ }
1355
+
1356
+ /// How far the steps the layers are planned for reach: those after the last
1357
+ /// far drop shadow (lastFar).
1358
+ static double plannedReach(const ALFilterStep *steps, NSUInteger count) {
1359
+ NSUInteger first = (NSUInteger)(lastFar(steps, count) + 1);
1360
+ return reachOf(steps + first, count - first);
1361
+ }
1362
+
1363
+ /// A layer over `base` grown by `reach`, at `scale`, which keeps it about
1364
+ /// the size `base` grown by MAX_REACH is.
1365
+ static ALLayer lowLayer(ALLayer base, double reach, double scale) {
1366
+ // (side + 2 * reach) * scale, without multiplying a huge reach out.
1367
+ return (ALLayer){YES,
1368
+ base.left - reach,
1369
+ base.top - reach,
1370
+ (size_t)ceil(base.width / base.scale * scale + 2 * reach * scale),
1371
+ (size_t)ceil(base.height / base.scale * scale + 2 * reach * scale),
1372
+ scale};
1373
+ }
1374
+
1375
+ /// The layers one filtered draw (or the shadow cast from it) goes into:
1376
+ /// `full`, at the canvas's resolution, and `low`, a smaller one that reaches
1377
+ /// as far as the filter's wide blurs do (see -newRendered:...), or either
1378
+ /// alone. The shape's plan always has `full`.
1379
+ typedef struct {
1380
+ ALLayer full;
1381
+ ALLayer low;
1382
+ } ALPlan;
1383
+
1384
+ static const ALPlan NO_PLAN = {{NO, 0, 0, 0, 0, 0}, {NO, 0, 0, 0, 0, 0}};
1385
+
1386
+ /// The plan the shape is drawn into, and the one the shadow is cast from,
1387
+ /// or NO_PLAN, when it's cast from the shape's.
1388
+ typedef struct {
1389
+ ALPlan shape;
1390
+ ALPlan shadow;
1391
+ } ALLayers;
1392
+
1393
+ static CGFloat area(CGRect rect) {
1394
+ return rect.size.width * rect.size.height;
1395
+ }
1396
+
1397
+ /// The plan for a filtered draw that needs `base` (the canvas, the canvas
1398
+ /// moved back by the shadow's offset, or a layer a far drop shadow is worked
1399
+ /// out over) and the filter's reach round it, and `extra` more for the full
1400
+ /// layer (a shadow's blur, when the shadow is cast from it).
1401
+ ///
1402
+ /// The full layer is at `base`'s resolution, grown by the reach, capped at
1403
+ /// MAX_REACH of its pixels, so a huge blur makes no huge layer. Past the
1404
+ /// cap, when a step blurs widely (isWide), a low layer, scaled down by
1405
+ /// MAX_REACH over the reach, takes in the whole reach at about the size the
1406
+ /// capped layer was (issue #814), and the full layer needs to reach only as
1407
+ /// far as the steps after the last wide blur do.
1408
+ ///
1409
+ /// The reach is the steps' own, from those after the last far drop shadow
1410
+ /// (lastFar), which casts from a layer of its own. That's why the runtime
1411
+ /// sends only the steps: the whole filter's reach, which it once sent too,
1412
+ /// is too much for part of the filter and too little for a layer at another
1413
+ /// resolution.
1414
+ - (ALPlan)planFor:(ALLayer)base
1415
+ steps:(const ALFilterStep *)allSteps
1416
+ count:(NSUInteger)allCount
1417
+ extra:(CGFloat)extra {
1418
+ NSUInteger first = (NSUInteger)(lastFar(allSteps, allCount) + 1);
1419
+ const ALFilterStep *steps = allSteps + first;
1420
+ NSUInteger count = allCount - first;
1421
+ double reach = reachOf(steps, count);
1422
+ double margin = reach + extra;
1423
+ ALLayer low = NO_LAYER;
1424
+ if (reach * base.scale > MAX_REACH && isfinite(reach)) {
1425
+ double scale = MAX_REACH / reach;
1426
+ NSInteger lastWideBlur = -1;
1427
+ BOOL anyWide = NO;
1428
+ for (NSUInteger i = 0; i < count; i++) {
1429
+ if (!isWide(&steps[i], scale)) continue;
1430
+ anyWide = YES;
1431
+ if (steps[i].kind == ALFilterBlur) lastWideBlur = (NSInteger)i;
1432
+ }
1433
+ if (anyWide) {
1434
+ double after = 0;
1435
+ for (NSUInteger i = (NSUInteger)(lastWideBlur + 1); i < count; i++) {
1436
+ if (!isWide(&steps[i], scale)) after += stepReach(&steps[i]);
1437
+ }
1438
+ margin = after + extra;
1439
+ low = lowLayer(base, reach, scale);
1440
+ }
1441
+ }
1442
+ return (ALPlan){grownLayer(base, (size_t)ceil(MIN(margin * base.scale, MAX_REACH))), low};
1443
+ }
1444
+
1445
+ /// Where, in the canvas's pixels, the layers a draw goes into lie (see
1446
+ /// composite:). The shape's is the canvas grown by the filter's reach, so a
1447
+ /// shape just off the canvas still blurs onto it (see -planFor:...). With a
1448
+ /// shadow, the shadow needs the part of the shape that casts onto the
1449
+ /// canvas: the canvas moved back by the shadow's offset, grown by its blur
1450
+ /// (three of its deviations, which are half the blur) and the filter's
1451
+ /// reach.
1452
+ ///
1453
+ /// Within MAX_REACH of that, when one rectangle round both is no bigger than
1454
+ /// the two, the shape's layer grows to take that part in, and the shadow's
1455
+ /// plan is NO_PLAN. Otherwise it's a second layer: one rectangle round both
1456
+ /// would grow with the offset, and a shadow cast from far off the canvas
1457
+ /// (shadowOffsetX = 10000 and a shape at x = -10000) would make a huge
1458
+ /// layer, or, capped, cut the shape away.
1459
+ ///
1460
+ /// Past MAX_REACH, the shadow's layer is a smaller one that takes in the
1461
+ /// whole reach (issue #814): a 1000 px shadowBlur reaches 1500 px, and a
1462
+ /// layer that far round the canvas would be thousands of pixels a side.
1463
+ /// When the shadow's blur is wide at that layer's scale (WIDE_SIGMA), the
1464
+ /// shape is drawn, filtered and cast from in it, and the shadow is scaled up
1465
+ /// as it's drawn, as Skia scales a wide blur down: the detail the layer
1466
+ /// loses is blurred away. Otherwise the reach is the filter's, and the
1467
+ /// shadow's layer is planned as the shape's is, grown by the shadow's blur
1468
+ /// too.
1469
+ - (ALLayers)layers:(const ALFilterStep *)steps count:(NSUInteger)count {
1470
+ ALCanvas2DState *s = _state;
1471
+ CGRect canvas = CGRectMake(0, 0, _width, _height);
1472
+ ALPlan shape = [self planFor:layerOfRect(canvas) steps:steps count:count extra:0];
1473
+ if (![self shadowVisible]) return (ALLayers){shape, NO_PLAN};
1474
+ CGFloat blurReach = ceil(s.shadowBlur * 1.5);
1475
+ // A far drop shadow casts from a layer of its own (see -planFor:...).
1476
+ double fullReach = plannedReach(steps, count) + blurReach;
1477
+ CGRect moved = CGRectOffset(canvas, -s.shadowOffsetX, -s.shadowOffsetY);
1478
+ if (fullReach > MAX_REACH) {
1479
+ // Whole pixels, so a full layer's pixels line up with the canvas's.
1480
+ CGRect base = CGRectIntegral(moved);
1481
+ double scale = MAX_REACH / fullReach;
1482
+ if (isfinite(fullReach) && s.shadowBlur / 2 * scale >= WIDE_SIGMA) {
1483
+ return (ALLayers){shape, {NO_LAYER, lowLayer(layerOfRect(base), fullReach, scale)}};
1484
+ }
1485
+ return (ALLayers){shape, [self planFor:layerOfRect(base) steps:steps count:count extra:blurReach]};
1486
+ }
1487
+ // Within MAX_REACH, so is the filter's reach: the shape's plan is a layer
1488
+ // at the canvas's resolution alone.
1489
+ CGRect source = CGRectIntegral(CGRectInset(moved, -fullReach, -fullReach));
1490
+ CGRect shapeRect = layerBounds(shape.full);
1491
+ CGRect both = CGRectUnion(shapeRect, source);
1492
+ if (area(both) > area(shapeRect) + area(source)) {
1493
+ return (ALLayers){shape, {layerOfRect(source), NO_LAYER}};
1494
+ }
1495
+ return (ALLayers){{layerOfRect(both), NO_LAYER}, NO_PLAN};
1496
+ }
1497
+
1498
+ /// What `draw` draws into `layer`, as new bytes the caller frees (NULL if
1499
+ /// they can't be made): premultiplied RGBA, rows top to bottom, and, with a
1500
+ /// filter, through globalAlpha.
1501
+ ///
1502
+ /// The canvas spec takes what's drawn through globalAlpha first, then the
1503
+ /// filter, then casts the shadow and composites, outside the clip until then
1504
+ /// (since whatwg/html#10674): so a drop-shadow() shows through a see-through
1505
+ /// shape. Without a filter, the alpha goes on as the layer's drawn, which
1506
+ /// comes to the same.
1507
+ - (uint8_t *)newDrawn:(ALLayer)layer draw:(void (^)(CGContextRef c))draw {
1508
+ size_t width = layer.width, height = layer.height;
1509
+ if (width == 0 || height == 0) return NULL;
1510
+ uint8_t *bytes = calloc(width * height * 4, 1);
1511
+ if (!bytes) return NULL;
1512
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1513
+ CGContextRef c = CGBitmapContextCreate(bytes, width, height, 8, width * 4, space,
1514
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
1515
+ CGColorSpaceRelease(space);
1516
+ if (!c) {
1517
+ free(bytes);
1518
+ return NULL;
1519
+ }
1520
+ // The canvas's flip, and the layer's place in its pixels, worked out
1521
+ // first in doubles: a small layer's left can be far off the canvas.
1522
+ CGContextTranslateCTM(c, 0, height);
1523
+ CGContextScaleCTM(c, 1, -1);
1524
+ CGContextTranslateCTM(c, -layer.left * layer.scale, -layer.top * layer.scale);
1525
+ if (layer.scale != 1) CGContextScaleCTM(c, layer.scale, layer.scale);
1526
+ draw(c);
1527
+ CGContextRelease(c);
1528
+ if (_state.filterSteps.count > 0) scaleAlpha(bytes, width * height, _state.globalAlpha);
1529
+ return bytes;
1530
+ }
1531
+
1532
+ /// What `draw` draws through the filter's steps, as `plan` has it: new
1533
+ /// bytes (which the caller frees, NULL if they can't be made) over its
1534
+ /// `full` layer, or over its `low` one when it has only that.
1535
+ ///
1536
+ /// With both, the low layer is drawn too, and the steps whose deviation is
1537
+ /// wide enough there (isWide) are worked out in it and scaled up onto the
1538
+ /// full one (newResampled): a wide blur replaces the full layer (so the
1539
+ /// steps before it are worked out only in the low one), and a wide drop
1540
+ /// shadow's shadow goes under it. The other steps are applied in both. So
1541
+ /// whatever the wide steps bring onto the canvas from past the full layer's
1542
+ /// reach comes from the low one, which reaches as far as the steps do, and
1543
+ /// the rest keeps the full layer's resolution.
1544
+ ///
1545
+ /// A far drop shadow (lastFar) is cast from a layer of its own (see
1546
+ /// -newFarShadow:...), so the plan is for the steps after the last one, and
1547
+ /// the steps up to it are worked out over each of the plan's layers in
1548
+ /// place of what `draw` draws there.
1549
+ - (uint8_t *)newRendered:(ALPlan)plan
1550
+ steps:(const ALFilterStep *)allSteps
1551
+ count:(NSUInteger)allCount
1552
+ draw:(void (^)(CGContextRef c))draw {
1553
+ NSInteger far = lastFar(allSteps, allCount);
1554
+ const ALFilterStep *steps = allSteps + (far + 1);
1555
+ NSUInteger count = allCount - (NSUInteger)(far + 1);
1556
+ uint8_t * (^source)(ALLayer) = ^uint8_t *(ALLayer layer) {
1557
+ if (far < 0) return [self newDrawn:layer draw:draw];
1558
+ return [self newFarShadow:layer steps:allSteps count:(NSUInteger)far + 1 draw:draw];
1559
+ };
1560
+ ALLayer full = plan.full, low = plan.low;
1561
+ if (!full.exists || !low.exists) {
1562
+ ALLayer only = full.exists ? full : low;
1563
+ if (!only.exists) return NULL;
1564
+ uint8_t *bytes = source(only);
1565
+ if (!bytes) return NULL;
1566
+ for (NSUInteger i = 0; i < count; i++) {
1567
+ applyStep(bytes, only.width, only.height, &steps[i], only.scale);
1568
+ }
1569
+ return bytes;
1570
+ }
1571
+ NSInteger lastWide = -1, lastWideBlur = -1;
1572
+ for (NSUInteger i = 0; i < count; i++) {
1573
+ if (!isWide(&steps[i], low.scale)) continue;
1574
+ lastWide = (NSInteger)i;
1575
+ if (steps[i].kind == ALFilterBlur) lastWideBlur = (NSInteger)i;
1576
+ }
1577
+ uint8_t *lowBytes = source(low);
1578
+ if (!lowBytes) return NULL;
1579
+ uint8_t *fullBytes = NULL;
1580
+ if (lastWideBlur < 0) {
1581
+ fullBytes = source(full);
1582
+ if (!fullBytes) {
1583
+ free(lowBytes);
1584
+ return NULL;
1585
+ }
1586
+ }
1587
+ BOOL failed = NO;
1588
+ for (NSUInteger i = 0; i < count && !failed; i++) {
1589
+ const ALFilterStep *step = &steps[i];
1590
+ if (!isWide(step, low.scale)) {
1591
+ // The low layer is read only up to the last wide step.
1592
+ if ((NSInteger)i < lastWide) applyStep(lowBytes, low.width, low.height, step, low.scale);
1593
+ if (fullBytes) applyStep(fullBytes, full.width, full.height, step, full.scale);
1594
+ } else if (step->kind == ALFilterBlur) {
1595
+ applyStep(lowBytes, low.width, low.height, step, low.scale);
1596
+ if ((NSInteger)i == lastWideBlur) {
1597
+ fullBytes = newResampled(lowBytes, low, full, 0, 0);
1598
+ failed = !fullBytes;
1599
+ }
1600
+ } else {
1601
+ // The shadow is cast unmoved, then moved as it's resampled onto each
1602
+ // layer, so its offset needn't be whole pixels of the low one.
1603
+ const double *v = step->values;
1604
+ uint8_t *cast = newShadowBytes(lowBytes, low.width, low.height, 0, 0, v[2] * low.scale,
1605
+ v[3], v[4], v[5], v[6]);
1606
+ if (!cast) {
1607
+ failed = YES;
1608
+ break;
1609
+ }
1610
+ if (fullBytes) {
1611
+ uint8_t *moved = newResampled(cast, low, full, v[0], v[1]);
1612
+ if (moved) drawUnder(fullBytes, moved, full.width * full.height);
1613
+ failed = !moved;
1614
+ free(moved);
1615
+ }
1616
+ if (!failed && (NSInteger)i < lastWide) {
1617
+ uint8_t *moved = newResampled(cast, low, low, v[0], v[1]);
1618
+ if (moved) drawUnder(lowBytes, moved, low.width * low.height);
1619
+ failed = !moved;
1620
+ free(moved);
1621
+ }
1622
+ free(cast);
1623
+ }
1624
+ }
1625
+ free(lowBytes);
1626
+ if (failed) {
1627
+ free(fullBytes);
1628
+ return NULL;
1629
+ }
1630
+ return fullBytes;
1631
+ }
1632
+
1633
+ /// What `draw` draws through the alpha and the steps, which end with a far
1634
+ /// drop shadow (lastFar), over `layer`, as new bytes the caller frees (NULL
1635
+ /// if they can't be made): the steps before it, worked out over the layer,
1636
+ /// with the shadow under them, cast from those steps worked out over the
1637
+ /// layer moved back by the shadow's offset. That layer takes in the shape
1638
+ /// the shadow is cast from however far off the canvas it lies, and it's the
1639
+ /// size `layer` is, as the canvas shadow casts from a layer of its own (see
1640
+ /// -layers:count:).
1641
+ ///
1642
+ /// The shadow's own blur goes on there as a blur step after the others, so
1643
+ /// a wide one is worked out in a smaller layer as any blur is (see
1644
+ /// -planFor:...), and the shadow is the alpha that leaves, in its color: a
1645
+ /// blur blurs each channel alike, so that's the alpha blurred, as
1646
+ /// newShadowBytes casts it. The offset isn't rounded: the moved layer
1647
+ /// needn't lie on whole pixels, as only its bytes are used, each landing on
1648
+ /// the pixel of `layer` it's moved onto, so a fractional offset draws the
1649
+ /// shape between pixels there, as it lands on the canvas. A wide shadow's
1650
+ /// offset, resampled from the smaller layer, kept its fraction before this
1651
+ /// too.
1652
+ - (uint8_t *)newFarShadow:(ALLayer)layer
1653
+ steps:(const ALFilterStep *)steps
1654
+ count:(NSUInteger)count
1655
+ draw:(void (^)(CGContextRef c))draw {
1656
+ NSUInteger before = count - 1;
1657
+ const double *v = steps[before].values;
1658
+ uint8_t *shape = [self newOver:layer steps:steps count:before draw:draw];
1659
+ if (!shape) return NULL;
1660
+ // Past where a shadow's layer can lie, the canvas's pixels place no shape
1661
+ // the shadow could be cast from.
1662
+ if (fabs(v[0]) > MAX_LAYER_OFFSET || fabs(v[1]) > MAX_LAYER_OFFSET) return shape;
1663
+ // The steps before the shadow, then its blur.
1664
+ ALFilterStep *blurred = malloc(sizeof(ALFilterStep) * count);
1665
+ if (!blurred) {
1666
+ free(shape);
1667
+ return NULL;
1668
+ }
1669
+ memcpy(blurred, steps, sizeof(ALFilterStep) * before);
1670
+ blurred[before] = (ALFilterStep){ALFilterBlur, {v[2]}, NO};
1671
+ uint8_t *cast = [self newOver:movedLayer(layer, -v[0], -v[1]) steps:blurred count:count draw:draw];
1672
+ free(blurred);
1673
+ uint8_t *shadow = cast ? newShadowBytes(cast, layer.width, layer.height, 0, 0, 0, v[3], v[4],
1674
+ v[5], v[6])
1675
+ : NULL;
1676
+ free(cast);
1677
+ if (!shadow) {
1678
+ free(shape);
1679
+ return NULL;
1680
+ }
1681
+ drawUnder(shape, shadow, layer.width * layer.height);
1682
+ free(shadow);
1683
+ return shape;
1684
+ }
1685
+
1686
+ /// What `draw` draws through the alpha and the steps over `layer`, as new
1687
+ /// bytes the caller frees (NULL if they can't be made): planned round it as
1688
+ /// any filtered draw is (-planFor:...), and resampled down to it. The plan's
1689
+ /// full layer lies on its pixels, so that copies them.
1690
+ - (uint8_t *)newOver:(ALLayer)layer
1691
+ steps:(const ALFilterStep *)steps
1692
+ count:(NSUInteger)count
1693
+ draw:(void (^)(CGContextRef c))draw {
1694
+ if (count == 0) return [self newDrawn:layer draw:draw];
1695
+ ALPlan plan = [self planFor:layer steps:steps count:count extra:0];
1696
+ uint8_t *bytes = [self newRendered:plan steps:steps count:count draw:draw];
1697
+ if (!bytes) return NULL;
1698
+ if (plan.full.width == layer.width && plan.full.height == layer.height) return bytes;
1699
+ uint8_t *cut = newResampled(bytes, plan.full, layer, 0, 0);
1700
+ free(bytes);
1701
+ return cut;
1702
+ }
1703
+
1704
+ /// Premultiplied RGBA bytes, rows top to bottom, as an image.
1705
+ static CGImageRef newImageOfBytes(const uint8_t *bytes, size_t width,
1706
+ size_t height) CF_RETURNS_RETAINED {
1707
+ CFDataRef data = CFDataCreate(NULL, bytes, (CFIndex)(width * height * 4));
1708
+ if (!data) return NULL;
1709
+ CGDataProviderRef provider = CGDataProviderCreateWithCFData(data);
1710
+ CFRelease(data);
1711
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1712
+ CGImageRef image =
1713
+ CGImageCreate(width, height, 8, 32, width * 4, space,
1714
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big, provider, NULL,
1715
+ false, kCGRenderingIntentDefault);
1716
+ CGColorSpaceRelease(space);
1717
+ CGDataProviderRelease(provider);
1718
+ return image;
1719
+ }
1720
+
1721
+ /// What `draw` draws through the plan's layer at the canvas's resolution,
1722
+ /// as an image over that layer. NULL if the layer can't be made.
1723
+ - (CGImageRef)newLayerImage:(ALPlan)plan
1724
+ steps:(const ALFilterStep *)steps
1725
+ count:(NSUInteger)count
1726
+ draw:(void (^)(CGContextRef c))draw CF_RETURNS_RETAINED {
1727
+ uint8_t *bytes = [self newRendered:plan steps:steps count:count draw:draw];
1728
+ if (!bytes) return NULL;
1729
+ CGImageRef image = newImageOfBytes(bytes, plan.full.width, plan.full.height);
1730
+ free(bytes);
1731
+ return image;
1732
+ }
1733
+
1734
+ static CGRect bitmapRect(CGRect rect, size_t height);
1735
+
1736
+ /// The shadow a plan with only a smaller layer casts, as an image the
1737
+ /// canvas's size: cast in that layer, blurred by the shadow's deviation at
1738
+ /// its scale (newShadowBytes, as drop-shadow() is), and scaled up onto the
1739
+ /// canvas, moved by the shadow's offset. Core Graphics' own shadow would
1740
+ /// blur the layer scaled up, at the canvas's resolution. NULL if a layer
1741
+ /// can't be made.
1742
+ - (CGImageRef)newScaledShadowOf:(ALPlan)plan
1743
+ steps:(const ALFilterStep *)steps
1744
+ count:(NSUInteger)count
1745
+ draw:(void (^)(CGContextRef c))draw CF_RETURNS_RETAINED {
1746
+ ALCanvas2DState *s = _state;
1747
+ ALLayer low = plan.low;
1748
+ uint8_t *bytes = [self newRendered:plan steps:steps count:count draw:draw];
1749
+ if (!bytes) return NULL;
1750
+ uint8_t *shadow = newShadowBytes(bytes, low.width, low.height, 0, 0,
1751
+ s.shadowBlur / 2 * low.scale, s.shadowR, s.shadowG,
1752
+ s.shadowB, s.shadowA);
1753
+ free(bytes);
1754
+ if (!shadow) return NULL;
1755
+ CGImageRef image = newImageOfBytes(shadow, low.width, low.height);
1756
+ free(shadow);
1757
+ if (!image) return NULL;
1758
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1759
+ CGContextRef bitmap =
1760
+ CGBitmapContextCreate(NULL, _width, _height, 8, _width * 4, space,
1761
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
1762
+ CGColorSpaceRelease(space);
1763
+ if (!bitmap) {
1764
+ CGImageRelease(image);
1765
+ return NULL;
1766
+ }
1767
+ CGContextSetInterpolationQuality(bitmap, kCGInterpolationHigh);
1768
+ CGRect bounds = CGRectOffset(layerBounds(low), s.shadowOffsetX, s.shadowOffsetY);
1769
+ CGContextDrawImage(bitmap, bitmapRect(bounds, _height), image);
1770
+ CGImageRelease(image);
1771
+ CGImageRef cast = CGBitmapContextCreateImage(bitmap);
1772
+ CGContextRelease(bitmap);
1773
+ return cast;
1774
+ }
1775
+
1776
+ /// The part of the canvas's pixels a context draws on: the canvas, or a
1777
+ /// layer's area, from the context's own size and transform.
1778
+ static CGRect drawableRect(CGContextRef c) {
1779
+ CGRect device =
1780
+ CGRectMake(0, 0, CGBitmapContextGetWidth(c), CGBitmapContextGetHeight(c));
1781
+ return CGRectApplyAffineTransform(device, CGAffineTransformInvert(CGContextGetCTM(c)));
1782
+ }
1783
+
1784
+ /// A rectangle of the canvas's pixels (y down) in the bitmap's own space
1785
+ /// (y up), for a canvas `height` pixels tall.
1786
+ static CGRect bitmapRect(CGRect rect, size_t height) {
1787
+ return CGRectMake(rect.origin.x, (CGFloat)height - CGRectGetMaxY(rect), rect.size.width,
1788
+ rect.size.height);
1789
+ }
1790
+
1791
+ /// Draws with the state's alpha, compositing and shadow. `draw` draws in a
1792
+ /// context whose space is the canvas's pixels, with nothing else set.
1793
+ ///
1794
+ /// Core Graphics draws an operation like source-in only where the shape
1795
+ /// covers, and a shadow for each thing drawn; the canvas spec composites
1796
+ /// the whole canvas, and the shadow of the shape as a whole. So for those,
1797
+ /// the shape is drawn into a transparent layer over the canvas (see
1798
+ /// -layers), which is drawn over it with the operation and the shadow. A
1799
+ /// filter works on pixels, so it needs the layer too: it's applied to the
1800
+ /// layer first.
1801
+ - (void)composite:(void (^)(CGContextRef c))draw {
1802
+ if (!_cg) return;
1803
+ ALCanvas2DState *s = _state;
1804
+ CGContextRef c = _cg;
1805
+ BOOL shadow = [self shadowVisible];
1806
+ BOOL filtered = s.filterSteps.count > 0;
1807
+ if (!shadow && !filtered && !isUnbounded(s.composite)) {
1808
+ CGContextSaveGState(c);
1809
+ CGContextSetAlpha(c, s.globalAlpha);
1810
+ CGContextSetBlendMode(c, BLEND_MODES[s.composite]);
1811
+ draw(c);
1812
+ CGContextRestoreGState(c);
1813
+ [self keepOpaque];
1814
+ return;
1815
+ }
1816
+ NSData *parsed = parsedFilter(s.filterSteps);
1817
+ const ALFilterStep *steps = parsed.bytes;
1818
+ NSUInteger count = parsed.length / sizeof(ALFilterStep);
1819
+ ALLayers layers = [self layers:steps count:count];
1820
+ CGImageRef image = [self newLayerImage:layers.shape steps:steps count:count draw:draw];
1821
+ if (!image) return;
1822
+ CGRect shapeRect = layerBounds(layers.shape.full);
1823
+ // The shadow's own layer at the canvas's resolution, or a smaller one
1824
+ // alone, whose shadow is scaled up (see -layers:count:).
1825
+ BOOL scaledShadow = !layers.shadow.full.exists && layers.shadow.low.exists;
1826
+ CGImageRef shadowImage = NULL;
1827
+ CGRect shadowRect = CGRectNull;
1828
+ if (layers.shadow.full.exists) {
1829
+ shadowRect = layerBounds(layers.shadow.full);
1830
+ shadowImage = [self newLayerImage:layers.shadow steps:steps count:count draw:draw];
1831
+ if (!shadowImage) {
1832
+ CGImageRelease(image);
1833
+ return;
1834
+ }
1835
+ }
1836
+ // The spec composites the shadow, then the shape, each over the whole
1837
+ // clip with the operation (its drawing model's steps 6 and 7). With an
1838
+ // operation like source-in, Core Graphics composites only the shape, and
1839
+ // drops the shadow's step, so for those the shadow is cast alone into an
1840
+ // image of its own, and the two are drawn one after the other. So is one
1841
+ // scaled up from a smaller layer, which Core Graphics doesn't cast.
1842
+ CGImageRef cast = NULL;
1843
+ if (shadow && (isUnbounded(s.composite) || scaledShadow)) {
1844
+ if (scaledShadow) {
1845
+ cast = [self newScaledShadowOf:layers.shadow steps:steps count:count draw:draw];
1846
+ } else {
1847
+ cast = shadowImage ? [self newShadowOf:shadowImage rect:shadowRect]
1848
+ : [self newShadowOf:image rect:shapeRect];
1849
+ }
1850
+ // A layer that can't be made drops the draw, as the shape's does.
1851
+ if (!cast) {
1852
+ CGImageRelease(shadowImage);
1853
+ CGImageRelease(image);
1854
+ return;
1855
+ }
1856
+ }
1857
+ CGContextSaveGState(c);
1858
+ CGContextSetAlpha(c, filtered ? 1 : s.globalAlpha);
1859
+ CGContextSetBlendMode(c, BLEND_MODES[s.composite]);
1860
+ // Otherwise Core Graphics casts the shadow as the layer's drawn.
1861
+ if (shadow && !cast) [self setShadow:c movedBy:0];
1862
+ // The layers' images are drawn in the bitmap's own space, where their rows
1863
+ // already lie top to bottom.
1864
+ CGContextScaleCTM(c, 1, -1);
1865
+ CGContextTranslateCTM(c, 0, -(CGFloat)_height);
1866
+ if (cast) {
1867
+ CGContextDrawImage(c, CGRectMake(0, 0, _width, _height), cast);
1868
+ } else if (shadowImage) {
1869
+ // Only the shadow's layer's shadow is drawn: the layer is moved left off
1870
+ // the bitmap, and the shadow's offset right by as much, which Core
1871
+ // Graphics casts to the same pixels (it casts the shadow of what's drawn
1872
+ // off the bitmap). Then the shape's layer is drawn without one, as the
1873
+ // spec composites the shadow, then the shape.
1874
+ CGFloat away = MAX(0, CGRectGetMaxX(shadowRect));
1875
+ [self setShadow:c movedBy:away];
1876
+ CGContextDrawImage(c, CGRectOffset(bitmapRect(shadowRect, _height), -away, 0), shadowImage);
1877
+ CGContextSetShadowWithColor(c, CGSizeZero, 0, NULL);
1878
+ }
1879
+ CGContextDrawImage(c, bitmapRect(shapeRect, _height), image);
1880
+ CGContextRestoreGState(c);
1881
+ CGImageRelease(cast);
1882
+ CGImageRelease(shadowImage);
1883
+ CGImageRelease(image);
1884
+ [self keepOpaque];
1885
+ }
1886
+
1887
+ /// Sets the state's shadow on `c`, a context whose own space is the
1888
+ /// canvas's pixels (or a layer's), y up, moved `dx` pixels further right.
1889
+ - (void)setShadow:(CGContextRef)c movedBy:(CGFloat)dx {
1890
+ ALCanvas2DState *s = _state;
1891
+ CGColorRef color = CGColorCreateSRGB(s.shadowR / 255, s.shadowG / 255, s.shadowB / 255,
1892
+ s.shadowA);
1893
+ // A shadow's offset is in the bitmap's own space, y up, whatever the
1894
+ // transform, as the canvas's is in its pixels, y down. Its blur is twice
1895
+ // the Gaussian's deviation, as the canvas's is.
1896
+ CGContextSetShadowWithColor(c, CGSizeMake(s.shadowOffsetX + dx, -s.shadowOffsetY),
1897
+ s.shadowBlur, color);
1898
+ CGColorRelease(color);
1899
+ }
1900
+
1901
+ /// The shadow `image`, a layer over `rect` of the canvas's pixels, casts,
1902
+ /// alone, as an image the canvas's size. The layer is moved left off the
1903
+ /// bitmap, and its shadow right by as much, so only the shadow lands, with
1904
+ /// Core Graphics' blur, as an operation like source-over casts it. NULL if
1905
+ /// the bitmap can't be made.
1906
+ - (CGImageRef)newShadowOf:(CGImageRef)image rect:(CGRect)rect CF_RETURNS_RETAINED {
1907
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
1908
+ CGContextRef bitmap =
1909
+ CGBitmapContextCreate(NULL, _width, _height, 8, _width * 4, space,
1910
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
1911
+ CGColorSpaceRelease(space);
1912
+ if (!bitmap) return NULL;
1913
+ CGFloat away = MAX(0, CGRectGetMaxX(rect));
1914
+ [self setShadow:bitmap movedBy:away];
1915
+ CGContextDrawImage(bitmap, CGRectOffset(bitmapRect(rect, _height), -away, 0), image);
1916
+ CGImageRef shadow = CGBitmapContextCreateImage(bitmap);
1917
+ CGContextRelease(bitmap);
1918
+ return shadow;
1919
+ }
1920
+
1921
+ /// An opaque canvas stays opaque: what an operation like copy or
1922
+ /// destination-out left see-through is put over black, as a browser keeps a
1923
+ /// canvas made with alpha: false. It's done on the bytes, as premultiplied
1924
+ /// colors are already over black: drawing black under them would be
1925
+ /// antialiased at the clip's edge, and leave those pixels see-through.
1926
+ - (void)keepOpaque {
1927
+ if (_alpha || !reducesAlpha(_state.composite) || !_cg) return;
1928
+ uint8_t *bytes = _data.mutableBytes;
1929
+ NSUInteger length = _data.length;
1930
+ for (NSUInteger i = 3; i < length; i += 4) bytes[i] = 255;
1931
+ }
1932
+
1933
+ #pragma mark Shapes
1934
+
1935
+ /// Fills a path in the canvas's pixels with a style, which is in the space
1936
+ /// of the current transform.
1937
+ - (void)fillDevicePath:(CGPathRef)path
1938
+ evenOdd:(BOOL)evenOdd
1939
+ style:(ALStyle)style
1940
+ gradient:(ALCanvas2DGradient *)styleGradient {
1941
+ if (CGPathIsEmpty(path)) return;
1942
+ CGAffineTransform transform = _state.transform;
1943
+ if (style.kind == ALStyleColor) {
1944
+ CGFloat r = style.rgba[0] / 255, g = style.rgba[1] / 255, b = style.rgba[2] / 255,
1945
+ a = style.rgba[3];
1946
+ [self composite:^(CGContextRef c) {
1947
+ CGContextSetRGBFillColor(c, r, g, b, a);
1948
+ CGContextAddPath(c, path);
1949
+ if (evenOdd) {
1950
+ CGContextEOFillPath(c);
1951
+ } else {
1952
+ CGContextFillPath(c);
1953
+ }
1954
+ }];
1955
+ return;
1956
+ }
1957
+ id object = style.kind == ALStyleGradient ? styleGradient : _objects[@(style.objectId)];
1958
+ if ([object isKindOfClass:ALCanvas2DGradient.class]) {
1959
+ ALCanvas2DGradient *gradient = object;
1960
+ if (gradient.stops.count == 0) return;
1961
+ __weak typeof(self) weakSelf = self;
1962
+ [self composite:^(CGContextRef c) {
1963
+ CGContextAddPath(c, path);
1964
+ if (evenOdd) {
1965
+ CGContextEOClip(c);
1966
+ } else {
1967
+ CGContextClip(c);
1968
+ }
1969
+ [weakSelf paintGradient:gradient in:c transform:transform];
1970
+ }];
1971
+ return;
1972
+ }
1973
+ if ([object isKindOfClass:ALCanvas2DPattern.class]) {
1974
+ ALCanvas2DPattern *pattern = object;
1975
+ pattern.quality = [self interpolationQuality];
1976
+ CGFloat width = CGImageGetWidth(pattern.image);
1977
+ CGFloat height = CGImageGetHeight(pattern.image);
1978
+ NSInteger repetition = pattern.repetition;
1979
+ CGAffineTransform patternTransform = CGAffineTransformConcat(style.transform, transform);
1980
+ [self composite:^(CGContextRef c) {
1981
+ // Pattern space maps to the bitmap's own space (y up), past the
1982
+ // canvas's flip: the pattern's transform, then the canvas's, then the
1983
+ // context's own, which is the canvas's flip, or the flip of a layer
1984
+ // (for a filter or a shadow) and its place in the canvas's pixels.
1985
+ CGAffineTransform matrix = CGAffineTransformConcat(patternTransform, CGContextGetCTM(c));
1986
+ // A step longer than the bitmap reaches in pattern space repeats
1987
+ // nothing: no-repeat, and the other axis of repeat-x or repeat-y. The
1988
+ // bitmap's corners are taken back into pattern space to find how far
1989
+ // that is.
1990
+ CGFloat once = 1;
1991
+ if (invertible(matrix)) {
1992
+ CGAffineTransform back = CGAffineTransformInvert(matrix);
1993
+ CGRect reach = CGRectApplyAffineTransform(
1994
+ CGRectMake(0, 0, CGBitmapContextGetWidth(c), CGBitmapContextGetHeight(c)), back);
1995
+ once = 2 * MAX(MAX(fabs(CGRectGetMinX(reach)), fabs(CGRectGetMaxX(reach))),
1996
+ MAX(fabs(CGRectGetMinY(reach)), fabs(CGRectGetMaxY(reach)))) +
1997
+ width + height + 1;
1998
+ }
1999
+ CGFloat xStep = repetition == 0 || repetition == 1 ? width : once;
2000
+ CGFloat yStep = repetition == 0 || repetition == 2 ? height : once;
2001
+ CGPatternCallbacks callbacks = {0, drawPatternCell, NULL};
2002
+ CGPatternRef cg = CGPatternCreate((__bridge void *)pattern, CGRectMake(0, 0, width, height),
2003
+ matrix, xStep, yStep, kCGPatternTilingConstantSpacing,
2004
+ true, &callbacks);
2005
+ CGColorSpaceRef space = CGColorSpaceCreatePattern(NULL);
2006
+ CGContextSetFillColorSpace(c, space);
2007
+ CGColorSpaceRelease(space);
2008
+ CGFloat alpha = 1;
2009
+ CGContextSetFillPattern(c, cg, &alpha);
2010
+ CGContextAddPath(c, path);
2011
+ if (evenOdd) {
2012
+ CGContextEOFillPath(c);
2013
+ } else {
2014
+ CGContextFillPath(c);
2015
+ }
2016
+ CGPatternRelease(cg);
2017
+ }];
2018
+ }
2019
+ }
2020
+
2021
+ - (void)paintGradient:(ALCanvas2DGradient *)gradient
2022
+ in:(CGContextRef)c
2023
+ transform:(CGAffineTransform)transform {
2024
+ CGGradientRef cg = gradient.gradient;
2025
+ if (!cg) return;
2026
+ CGGradientDrawingOptions extend =
2027
+ kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation;
2028
+ switch (gradient.type) {
2029
+ case 0: {
2030
+ // A gradient of no length paints nothing.
2031
+ if (gradient.p0 == gradient.p2 && gradient.p1 == gradient.p3) return;
2032
+ CGContextConcatCTM(c, transform);
2033
+ CGContextDrawLinearGradient(c, cg, CGPointMake(gradient.p0, gradient.p1),
2034
+ CGPointMake(gradient.p2, gradient.p3), extend);
2035
+ break;
2036
+ }
2037
+ case 1: {
2038
+ if (gradient.p0 == gradient.p3 && gradient.p1 == gradient.p4 &&
2039
+ gradient.p2 == gradient.p5) {
2040
+ return;
2041
+ }
2042
+ CGContextConcatCTM(c, transform);
2043
+ CGContextDrawRadialGradient(c, cg, CGPointMake(gradient.p0, gradient.p1), gradient.p2,
2044
+ CGPointMake(gradient.p3, gradient.p4), gradient.p5, extend);
2045
+ break;
2046
+ }
2047
+ default:
2048
+ [self paintConicGradient:gradient in:c transform:transform];
2049
+ }
2050
+ }
2051
+
2052
+ /// A conic gradient, a pixel at a time over what the clip leaves: the color
2053
+ /// at each pixel's angle around the center, clockwise from the start angle,
2054
+ /// in the gradient's space.
2055
+ - (void)paintConicGradient:(ALCanvas2DGradient *)gradient
2056
+ in:(CGContextRef)c
2057
+ transform:(CGAffineTransform)transform {
2058
+ if (!invertible(transform)) return;
2059
+ CGAffineTransform inverse = CGAffineTransformInvert(transform);
2060
+ // What the context draws on: the canvas, or the bigger layer of a filter
2061
+ // or a shadow, whose pixels past the canvas can still reach it.
2062
+ CGRect bounds =
2063
+ CGRectIntegral(CGRectIntersection(CGContextGetClipBoundingBox(c), drawableRect(c)));
2064
+ if (CGRectIsEmpty(bounds)) return;
2065
+ // A pixel of the context's own, which in the smaller layer of a wide blur
2066
+ // or shadow (issue #814) is several of the canvas's: the gradient is
2067
+ // worked out at that density, not over every canvas pixel the layer
2068
+ // reaches.
2069
+ CGAffineTransform ctm = CGContextGetCTM(c);
2070
+ CGFloat density = MIN(1, sqrt(ctm.a * ctm.a + ctm.b * ctm.b));
2071
+ if (!(density > 0)) return;
2072
+ size_t width = (size_t)ceil(bounds.size.width * density);
2073
+ size_t height = (size_t)ceil(bounds.size.height * density);
2074
+ if (width == 0 || height == 0) return;
2075
+ // The image is drawn over `bounds`, so each of its pixels covers this much
2076
+ // of the canvas: sampled at those pixels' centers, not at 1 / density,
2077
+ // which rounding the size up would leave apart from where they're drawn.
2078
+ // At density 1 the bounds are whole pixels, and a step is one.
2079
+ CGFloat stepX = bounds.size.width / width, stepY = bounds.size.height / height;
2080
+ NSMutableData *pixels = [NSMutableData dataWithLength:width * height * 4];
2081
+ uint8_t *p = pixels.mutableBytes;
2082
+ // 256 colors around the circle, as the stops give them.
2083
+ uint8_t table[256][4];
2084
+ for (int i = 0; i < 256; i++) {
2085
+ CGFloat rgba[4];
2086
+ [gradient colorAt:i / 255.0 into:rgba];
2087
+ table[i][3] = (uint8_t)lround(rgba[3] * 255);
2088
+ for (int k = 0; k < 3; k++) table[i][k] = (uint8_t)lround(rgba[k] * rgba[3] * 255);
2089
+ }
2090
+ CGFloat start = gradient.p0, cx = gradient.p1, cy = gradient.p2;
2091
+ for (size_t y = 0; y < height; y++) {
2092
+ for (size_t x = 0; x < width; x++) {
2093
+ CGPoint point = CGPointApplyAffineTransform(
2094
+ CGPointMake(bounds.origin.x + (x + 0.5) * stepX, bounds.origin.y + (y + 0.5) * stepY),
2095
+ inverse);
2096
+ CGFloat angle = atan2(point.y - cy, point.x - cx) - start;
2097
+ CGFloat t = fmod(angle / (2 * M_PI), 1);
2098
+ if (t < 0) t += 1;
2099
+ const uint8_t *color = table[(int)lround(t * 255)];
2100
+ memcpy(p + (y * width + x) * 4, color, 4);
2101
+ }
2102
+ }
2103
+ CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)pixels);
2104
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
2105
+ CGImageRef image =
2106
+ CGImageCreate(width, height, 8, 32, width * 4, space,
2107
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big, provider, NULL,
2108
+ false, kCGRenderingIntentDefault);
2109
+ CGColorSpaceRelease(space);
2110
+ CGDataProviderRelease(provider);
2111
+ // Drawn upright in the canvas's flipped space.
2112
+ CGContextTranslateCTM(c, bounds.origin.x, bounds.origin.y + bounds.size.height);
2113
+ CGContextScaleCTM(c, 1, -1);
2114
+ CGContextDrawImage(c, CGRectMake(0, 0, bounds.size.width, bounds.size.height), image);
2115
+ CGImageRelease(image);
2116
+ }
2117
+
2118
+ /// The outline a stroke of the path (in the canvas's pixels) fills, in the
2119
+ /// canvas's pixels. The line's width, dashes and joins are in the space of
2120
+ /// the current transform, so the path is taken back into it to be stroked.
2121
+ - (CGPathRef)strokeOutlineOf:(CGPathRef)devicePath {
2122
+ ALCanvas2DState *s = _state;
2123
+ CGAffineTransform transform = s.transform;
2124
+ if (!invertible(transform) || CGPathIsEmpty(devicePath)) return NULL;
2125
+ CGAffineTransform inverse = CGAffineTransformInvert(transform);
2126
+ CGPathRef userPath = CGPathCreateCopyByTransformingPath(devicePath, &inverse);
2127
+ CGContextRef c = _scratch;
2128
+ CGContextSaveGState(c);
2129
+ CGContextSetLineWidth(c, s.lineWidth);
2130
+ CGContextSetLineCap(c, s.lineCap);
2131
+ CGContextSetLineJoin(c, s.lineJoin);
2132
+ CGContextSetMiterLimit(c, s.miterLimit);
2133
+ NSUInteger dashCount = s.lineDash.count;
2134
+ if (dashCount > 0) {
2135
+ CGFloat *lengths = malloc(sizeof(CGFloat) * dashCount);
2136
+ for (NSUInteger i = 0; i < dashCount; i++) lengths[i] = s.lineDash[i].doubleValue;
2137
+ CGContextSetLineDash(c, s.lineDashOffset, lengths, dashCount);
2138
+ free(lengths);
2139
+ }
2140
+ CGContextBeginPath(c);
2141
+ CGContextAddPath(c, userPath);
2142
+ CGContextReplacePathWithStrokedPath(c);
2143
+ CGPathRef outline = CGContextIsPathEmpty(c) ? NULL : CGContextCopyPath(c);
2144
+ CGContextBeginPath(c);
2145
+ CGContextRestoreGState(c);
2146
+ CGPathRelease(userPath);
2147
+ if (!outline) return NULL;
2148
+ CGPathRef device = CGPathCreateCopyByTransformingPath(outline, &transform);
2149
+ CGPathRelease(outline);
2150
+ return device;
2151
+ }
2152
+
2153
+ - (void)strokeDevicePath:(CGPathRef)path {
2154
+ CGPathRef outline = [self strokeOutlineOf:path];
2155
+ if (!outline) return;
2156
+ [self fillDevicePath:outline evenOdd:NO style:_state.stroke gradient:_state.strokeGradient];
2157
+ CGPathRelease(outline);
2158
+ }
2159
+
2160
+ - (void)clearPath:(CGPathRef)path {
2161
+ if (!_cg || CGPathIsEmpty(path)) return;
2162
+ if (!_alpha) {
2163
+ [self fillOpaqueBlack:CGRectZero path:path];
2164
+ return;
2165
+ }
2166
+ // Not touched by alpha, compositing or shadows, as the spec has it; the
2167
+ // clip still applies.
2168
+ CGContextSaveGState(_cg);
2169
+ CGContextSetBlendMode(_cg, kCGBlendModeClear);
2170
+ CGContextAddPath(_cg, path);
2171
+ CGContextFillPath(_cg);
2172
+ CGContextRestoreGState(_cg);
2173
+ }
2174
+
2175
+ #pragma mark Images
2176
+
2177
+ - (CGInterpolationQuality)interpolationQuality {
2178
+ if (!_state.smoothing) return kCGInterpolationNone;
2179
+ switch (_state.smoothingQuality) {
2180
+ case 2:
2181
+ return kCGInterpolationHigh;
2182
+ case 1:
2183
+ return kCGInterpolationMedium;
2184
+ default:
2185
+ return kCGInterpolationLow;
2186
+ }
2187
+ }
2188
+
2189
+ /// An image source (see #imageSource in canvas-2d-context.ts): a decoded
2190
+ /// image by id, or a canvas by its id, as it is now.
2191
+ - (CGImageRef)newImageFrom:(NSDictionary *)source {
2192
+ if (source[@"blank"]) {
2193
+ // A canvas without a context: a transparent image of its size.
2194
+ NSInteger width = [source[@"width"] integerValue];
2195
+ NSInteger height = [source[@"height"] integerValue];
2196
+ if (width < 1 || height < 1) return NULL;
2197
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
2198
+ CGContextRef blank = CGBitmapContextCreate(NULL, width, height, 8, width * 4, space,
2199
+ kCGImageAlphaPremultipliedLast |
2200
+ kCGBitmapByteOrder32Big);
2201
+ CGColorSpaceRelease(space);
2202
+ if (!blank) return NULL;
2203
+ CGImageRef image = CGBitmapContextCreateImage(blank);
2204
+ CGContextRelease(blank);
2205
+ return image;
2206
+ }
2207
+ AngularLynxDecodedImage *decoded = nil;
2208
+ NSString *canvasId = source[@"canvas"];
2209
+ if ([canvasId isKindOfClass:NSString.class]) {
2210
+ decoded = [canvasId isEqualToString:_canvasId]
2211
+ ? [self snapshot]
2212
+ : [[AngularLynxCanvasRegistry contextForCanvasId:canvasId] snapshot];
2213
+ } else if ([source[@"image"] isKindOfClass:NSNumber.class]) {
2214
+ decoded = [AngularLynxDecodedImage imageWithId:[source[@"image"] integerValue]];
2215
+ }
2216
+ if (!decoded || decoded.width < 1 || decoded.height < 1) return NULL;
2217
+ CGDataProviderRef provider =
2218
+ CGDataProviderCreateWithCFData((__bridge CFDataRef)decoded.pixels);
2219
+ CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
2220
+ CGImageRef image = CGImageCreate(
2221
+ decoded.width, decoded.height, 8, 32, decoded.width * 4, space,
2222
+ (decoded.premultiplied ? kCGImageAlphaPremultipliedLast : kCGImageAlphaLast) |
2223
+ kCGBitmapByteOrder32Big,
2224
+ provider, NULL, false, kCGRenderingIntentDefault);
2225
+ CGColorSpaceRelease(space);
2226
+ CGDataProviderRelease(provider);
2227
+ return image;
2228
+ }
2229
+
2230
+ /// drawImage: the source rectangle of the image drawn in the destination
2231
+ /// rectangle, in the space of the current transform. The whole image is
2232
+ /// drawn, placed so the source lands on the destination, and clipped to the
2233
+ /// destination, so a source between pixels is drawn where it falls.
2234
+ - (void)drawImage:(CGImageRef)image source:(CGRect)src destination:(CGRect)dst {
2235
+ CGAffineTransform transform = _state.transform;
2236
+ CGFloat scaleX = dst.size.width / src.size.width;
2237
+ CGFloat scaleY = dst.size.height / src.size.height;
2238
+ CGRect whole = CGRectMake(dst.origin.x - src.origin.x * scaleX,
2239
+ dst.origin.y - src.origin.y * scaleY,
2240
+ CGImageGetWidth(image) * scaleX, CGImageGetHeight(image) * scaleY);
2241
+ CGInterpolationQuality quality = [self interpolationQuality];
2242
+ CGImageRetain(image);
2243
+ [self composite:^(CGContextRef c) {
2244
+ CGContextConcatCTM(c, transform);
2245
+ CGContextClipToRect(c, dst);
2246
+ CGContextSetInterpolationQuality(c, quality);
2247
+ // Drawn upright in the canvas's flipped space.
2248
+ CGContextTranslateCTM(c, whole.origin.x, whole.origin.y + whole.size.height);
2249
+ CGContextScaleCTM(c, 1, -1);
2250
+ CGContextDrawImage(c, CGRectMake(0, 0, whole.size.width, whole.size.height), image);
2251
+ }];
2252
+ CGImageRelease(image);
2253
+ }
2254
+
2255
+ #pragma mark Pixels
2256
+
2257
+ /// getImageData: the rectangle's pixels, not premultiplied, rows top to
2258
+ /// bottom; transparent black outside the canvas.
2259
+ - (NSArray *)pixelsAtX:(NSInteger)x y:(NSInteger)y width:(NSInteger)width height:(NSInteger)height {
2260
+ if (width <= 0 || height <= 0) return wordsFrom(NULL, 0);
2261
+ NSMutableData *out = [NSMutableData dataWithLength:(NSUInteger)(width * height * 4)];
2262
+ if (!out) return wordsFrom(NULL, 0);
2263
+ uint8_t *o = out.mutableBytes;
2264
+ const uint8_t *bitmap = _data.bytes;
2265
+ for (NSInteger row = 0; row < height; row++) {
2266
+ NSInteger sy = y + row;
2267
+ if (sy < 0 || sy >= (NSInteger)_height || !_cg) continue;
2268
+ for (NSInteger column = 0; column < width; column++) {
2269
+ NSInteger sx = x + column;
2270
+ if (sx < 0 || sx >= (NSInteger)_width) continue;
2271
+ const uint8_t *p = bitmap + (sy * _width + sx) * 4;
2272
+ uint8_t *q = o + (row * width + column) * 4;
2273
+ uint8_t alpha = _alpha ? p[3] : 255;
2274
+ q[3] = alpha;
2275
+ if (alpha == 0) continue;
2276
+ for (int c = 0; c < 3; c++) {
2277
+ q[c] = alpha == 255 ? p[c] : (uint8_t)MIN(255, (p[c] * 255 + alpha / 2) / alpha);
2278
+ }
2279
+ }
2280
+ }
2281
+ return wordsFrom(o, out.length);
2282
+ }
2283
+
2284
+ /// putImageData: straight RGBA written into the bitmap as it is, whatever
2285
+ /// the transform, clip and compositing.
2286
+ - (void)putPixels:(NSData *)bytes
2287
+ width:(NSInteger)width
2288
+ height:(NSInteger)height
2289
+ x:(NSInteger)x
2290
+ y:(NSInteger)y {
2291
+ if (!_cg || (NSInteger)bytes.length < width * height * 4) return;
2292
+ const uint8_t *in = bytes.bytes;
2293
+ uint8_t *bitmap = _data.mutableBytes;
2294
+ for (NSInteger row = 0; row < height; row++) {
2295
+ NSInteger dy = y + row;
2296
+ if (dy < 0 || dy >= (NSInteger)_height) continue;
2297
+ for (NSInteger column = 0; column < width; column++) {
2298
+ NSInteger dx = x + column;
2299
+ if (dx < 0 || dx >= (NSInteger)_width) continue;
2300
+ const uint8_t *p = in + (row * width + column) * 4;
2301
+ uint8_t *q = bitmap + (dy * _width + dx) * 4;
2302
+ uint8_t alpha = _alpha ? p[3] : 255;
2303
+ for (int c = 0; c < 3; c++) q[c] = (uint8_t)((p[c] * alpha + 127) / 255);
2304
+ q[3] = alpha;
2305
+ }
2306
+ }
2307
+ }
2308
+
2309
+ #pragma mark Text
2310
+
2311
+ /// The text laid out as one line in the current font.
2312
+ - (CTLineRef)newLineFor:(NSString *)text {
2313
+ ALCanvas2DState *s = _state;
2314
+ NSMutableDictionary *attributes = [@{
2315
+ (__bridge NSString *)kCTFontAttributeName : s.font,
2316
+ (__bridge NSString *)kCTForegroundColorFromContextAttributeName : @YES,
2317
+ } mutableCopy];
2318
+ if (s.letterSpacing != 0) {
2319
+ attributes[(__bridge NSString *)kCTKernAttributeName] = @(s.letterSpacing);
2320
+ }
2321
+ CTWritingDirection direction =
2322
+ s.rtl ? kCTWritingDirectionRightToLeft : kCTWritingDirectionLeftToRight;
2323
+ CTParagraphStyleSetting setting = {kCTParagraphStyleSpecifierBaseWritingDirection,
2324
+ sizeof(direction), &direction};
2325
+ CTParagraphStyleRef paragraph = CTParagraphStyleCreate(&setting, 1);
2326
+ attributes[(__bridge NSString *)kCTParagraphStyleAttributeName] = (__bridge id)paragraph;
2327
+ CFRelease(paragraph);
2328
+ NSAttributedString *string = [[NSAttributedString alloc] initWithString:text
2329
+ attributes:attributes];
2330
+ return CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)string);
2331
+ }
2332
+
2333
+ /// Where the line starts from the anchor, for textAlign, as a multiple of
2334
+ /// its width.
2335
+ - (CGFloat)alignmentOffsetForWidth:(CGFloat)width {
2336
+ BOOL rtl = _state.rtl;
2337
+ switch (_state.textAlign) {
2338
+ case 1: // end
2339
+ return rtl ? 0 : -width;
2340
+ case 2: // left
2341
+ return 0;
2342
+ case 3: // right
2343
+ return -width;
2344
+ case 4: // center
2345
+ return -width / 2;
2346
+ default: // start
2347
+ return rtl ? -width : 0;
2348
+ }
2349
+ }
2350
+
2351
+ /// How far above the alphabetic baseline the anchor is, for textBaseline,
2352
+ /// from the font's metrics, as Chrome works it out.
2353
+ - (CGFloat)baselineHeight {
2354
+ CTFontRef font = (__bridge CTFontRef)_state.font;
2355
+ CGFloat ascent = CTFontGetAscent(font);
2356
+ CGFloat descent = CTFontGetDescent(font);
2357
+ switch (_state.textBaseline) {
2358
+ case 0: // top
2359
+ return ascent;
2360
+ case 1: // hanging
2361
+ return ascent * 0.8;
2362
+ case 2: // middle
2363
+ return (ascent - descent) / 2;
2364
+ case 4: // ideographic
2365
+ case 5: // bottom
2366
+ return -descent;
2367
+ default: // alphabetic
2368
+ return 0;
2369
+ }
2370
+ }
2371
+
2372
+ - (void)drawText:(NSString *)text
2373
+ x:(CGFloat)x
2374
+ y:(CGFloat)y
2375
+ maxWidth:(CGFloat)maxWidth
2376
+ stroke:(BOOL)stroke {
2377
+ if (!_cg || text.length == 0 || _state.font.pointSize <= 0.01) return;
2378
+ CTLineRef line = [self newLineFor:text];
2379
+ CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL);
2380
+ // Text wider than maxWidth is squeezed to fit, as the spec allows.
2381
+ CGFloat scaleX = maxWidth > 0 && width > maxWidth ? maxWidth / width : 1;
2382
+ CGFloat originX = x + [self alignmentOffsetForWidth:width] * scaleX;
2383
+ CGFloat baseline = y + [self baselineHeight];
2384
+ ALStyle style = stroke ? _state.stroke : _state.fill;
2385
+ CGAffineTransform transform = _state.transform;
2386
+ if (!stroke && style.kind == ALStyleColor) {
2387
+ // Drawn as glyphs, so color glyphs (emoji) draw too.
2388
+ CGFloat r = style.rgba[0] / 255, g = style.rgba[1] / 255, b = style.rgba[2] / 255,
2389
+ a = style.rgba[3];
2390
+ [self composite:^(CGContextRef c) {
2391
+ CGContextConcatCTM(c, transform);
2392
+ CGContextTranslateCTM(c, originX, baseline);
2393
+ // Core Text draws y up.
2394
+ CGContextScaleCTM(c, scaleX, -1);
2395
+ CGContextSetTextMatrix(c, CGAffineTransformIdentity);
2396
+ CGContextSetTextPosition(c, 0, 0);
2397
+ CGContextSetRGBFillColor(c, r, g, b, a);
2398
+ CTLineDraw(line, c);
2399
+ }];
2400
+ CFRelease(line);
2401
+ return;
2402
+ }
2403
+ // The glyphs' outlines, in the canvas's pixels, filled or stroked as a
2404
+ // path is.
2405
+ CGMutablePathRef glyphs = CGPathCreateMutable();
2406
+ CFArrayRef runs = CTLineGetGlyphRuns(line);
2407
+ for (CFIndex i = 0; i < CFArrayGetCount(runs); i++) {
2408
+ CTRunRef run = CFArrayGetValueAtIndex(runs, i);
2409
+ CTFontRef font = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);
2410
+ CFIndex count = CTRunGetGlyphCount(run);
2411
+ CGGlyph *glyphIds = malloc(sizeof(CGGlyph) * MAX(count, 1));
2412
+ CGPoint *positions = malloc(sizeof(CGPoint) * MAX(count, 1));
2413
+ CTRunGetGlyphs(run, CFRangeMake(0, count), glyphIds);
2414
+ CTRunGetPositions(run, CFRangeMake(0, count), positions);
2415
+ for (CFIndex g = 0; g < count; g++) {
2416
+ CGAffineTransform place = CGAffineTransformMake(
2417
+ scaleX, 0, 0, -1, originX + positions[g].x * scaleX, baseline - positions[g].y);
2418
+ CGPathRef outline = CTFontCreatePathForGlyph(font, glyphIds[g], &place);
2419
+ if (outline) {
2420
+ CGPathAddPath(glyphs, NULL, outline);
2421
+ CGPathRelease(outline);
2422
+ }
2423
+ }
2424
+ free(glyphIds);
2425
+ free(positions);
2426
+ }
2427
+ CFRelease(line);
2428
+ CGPathRef device = CGPathCreateCopyByTransformingPath(glyphs, &transform);
2429
+ CGPathRelease(glyphs);
2430
+ if (stroke) {
2431
+ [self strokeDevicePath:device];
2432
+ } else {
2433
+ [self fillDevicePath:device evenOdd:NO style:style gradient:_state.fillGradient];
2434
+ }
2435
+ CGPathRelease(device);
2436
+ }
2437
+
2438
+ /// measureText: TextMetrics' numbers, in order (see LynxTextMetrics),
2439
+ /// measured from the anchor textAlign and textBaseline put it at.
2440
+ - (NSArray *)measureText:(NSString *)text {
2441
+ CTLineRef line = [self newLineFor:text];
2442
+ CGFloat width = CTLineGetTypographicBounds(line, NULL, NULL, NULL);
2443
+ CGRect glyphs = text.length > 0 ? CTLineGetBoundsWithOptions(line, kCTLineBoundsUseGlyphPathBounds)
2444
+ : CGRectZero;
2445
+ CFRelease(line);
2446
+ CTFontRef font = (__bridge CTFontRef)_state.font;
2447
+ CGFloat ascent = CTFontGetAscent(font);
2448
+ CGFloat descent = CTFontGetDescent(font);
2449
+ CGFloat offset = [self alignmentOffsetForWidth:width];
2450
+ CGFloat anchor = [self baselineHeight];
2451
+ return @[
2452
+ @(width),
2453
+ @(-(offset + CGRectGetMinX(glyphs))),
2454
+ @(offset + CGRectGetMaxX(glyphs)),
2455
+ @(ascent - anchor),
2456
+ @(descent + anchor),
2457
+ @(CGRectGetMaxY(glyphs) - anchor),
2458
+ @(-CGRectGetMinY(glyphs) + anchor),
2459
+ @(ascent - anchor),
2460
+ @(descent + anchor),
2461
+ @(ascent * 0.8 - anchor),
2462
+ @(-anchor),
2463
+ @(-descent - anchor),
2464
+ ];
2465
+ }
2466
+
2467
+ @end