@g9tm/lynxcontrols-native 2.6.19 → 2.7.1

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 (61) hide show
  1. package/README.md +40 -1
  2. package/android/build.gradle.kts +7 -0
  3. package/android/src/main/java/com/g9lynx/g9native/G9HostModule.kt +20 -0
  4. package/android/src/main/java/com/g9lynx/g9native/G9NativeImages.kt +16 -0
  5. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasModel.kt +2 -2
  6. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasPaths.kt +7 -26
  7. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasView.kt +9 -4
  8. package/android/src/main/java/com/g9lynx/g9native/generated/G9HostModuleSpec.java +3 -0
  9. package/android/src/main/java/com/g9lynx/g9native/generated/G9ImageModuleSpec.java +27 -0
  10. package/android/src/main/java/com/g9lynx/g9native/image/G9HostTypeface.kt +49 -0
  11. package/android/src/main/java/com/g9lynx/g9native/image/G9ImageDraw.kt +222 -0
  12. package/android/src/main/java/com/g9lynx/g9native/image/G9ImageModule.kt +54 -0
  13. package/android/src/main/java/com/g9lynx/g9native/image/G9ImageProcessor.kt +464 -0
  14. package/android/src/main/java/com/g9lynx/g9native/image/core/G9HostFont.kt +28 -0
  15. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageBudget.kt +54 -0
  16. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageColor.kt +48 -0
  17. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageError.kt +19 -0
  18. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageExifTags.kt +61 -0
  19. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageFiles.kt +99 -0
  20. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageGeometry.kt +150 -0
  21. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageJson.kt +200 -0
  22. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageQuality.kt +65 -0
  23. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageRedaction.kt +77 -0
  24. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageService.kt +102 -0
  25. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageSniff.kt +63 -0
  26. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageSpec.kt +237 -0
  27. package/catalog/catalog.json +161 -1
  28. package/catalog/index.md +1 -1
  29. package/dist/.tsbuildinfo +1 -1
  30. package/dist/image.d.ts +219 -0
  31. package/dist/image.d.ts.map +1 -0
  32. package/dist/image.js +116 -0
  33. package/dist/image.js.map +1 -0
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +1 -0
  37. package/dist/protocol.d.ts +17 -0
  38. package/dist/protocol.d.ts.map +1 -1
  39. package/dist/services.d.ts.map +1 -1
  40. package/dist/services.js +12 -0
  41. package/dist/services.js.map +1 -1
  42. package/generated/G9HostModule.ts +1 -0
  43. package/generated/G9ImageModule.ts +64 -0
  44. package/ios/Tests/G9NativeTestSuite.h +8 -0
  45. package/ios/Tests/G9NativeTestSuite.m +350 -0
  46. package/ios/Tests/G9NativeTests.m +16 -0
  47. package/ios/g9lynx-native-swift.podspec +1 -1
  48. package/ios/g9lynx-native.podspec +5 -4
  49. package/ios/src/G9HostModule.m +10 -0
  50. package/ios/src/G9ImageModule.h +30 -0
  51. package/ios/src/G9ImageModule.m +986 -0
  52. package/ios/src/core/G9ImageCore.h +201 -0
  53. package/ios/src/core/G9ImageCore.m +1039 -0
  54. package/ios/src/generated/G9HostModuleSpec.h +1 -0
  55. package/ios/src/generated/G9ImageModuleSpec.h +16 -0
  56. package/ios/src/generated/G9ImageModuleSpec.m +2 -0
  57. package/ios/swift/canvas/G9LCCanvasCore.swift +3 -2
  58. package/ios/swift/canvas/G9LCCanvasView.swift +15 -4
  59. package/ios/swift/shared/G9LCFonts.swift +18 -2
  60. package/package.json +4 -4
  61. package/types/platform-native-module.d.ts +23 -0
@@ -0,0 +1,1039 @@
1
+ #import "G9ImageCore.h"
2
+ #include <math.h>
3
+ #include <stdlib.h>
4
+
5
+ NSString *const G9ImageErrorInvalidArgument = @"invalid-argument";
6
+ NSString *const G9ImageErrorNotFound = @"not-found";
7
+ NSString *const G9ImageErrorDecode = @"decode";
8
+ NSString *const G9ImageErrorMemory = @"memory";
9
+ NSString *const G9ImageErrorIO = @"io";
10
+ NSString *const G9ImageErrorCancelled = @"cancelled";
11
+ NSString *const G9ImageErrorUnsupported = @"unsupported";
12
+
13
+ // The largest output side (the shared defaults: whole numbers 1..20000).
14
+ static const double G9ImageMaxSide = 20000;
15
+ // maxBytes scaling gives up once the shorter side would drop below this.
16
+ static const NSInteger G9ImageMinScaledSide = 16;
17
+
18
+ G9ImageAffine G9ImageAffineIdentity(void) {
19
+ G9ImageAffine m = {1, 0, 0, 1, 0, 0};
20
+ return m;
21
+ }
22
+
23
+ G9ImageAffine G9ImageAffineConcat(G9ImageAffine outer, G9ImageAffine inner) {
24
+ G9ImageAffine m;
25
+ m.a = outer.a * inner.a + outer.c * inner.b;
26
+ m.b = outer.b * inner.a + outer.d * inner.b;
27
+ m.c = outer.a * inner.c + outer.c * inner.d;
28
+ m.d = outer.b * inner.c + outer.d * inner.d;
29
+ m.e = outer.a * inner.e + outer.c * inner.f + outer.e;
30
+ m.f = outer.b * inner.e + outer.d * inner.f + outer.f;
31
+ return m;
32
+ }
33
+
34
+ G9ImageAffine G9ImageAffineInvert(G9ImageAffine m, BOOL *ok) {
35
+ double det = m.a * m.d - m.b * m.c;
36
+ if (!isfinite(det) || fabs(det) < 1e-12) {
37
+ if (ok) *ok = NO;
38
+ return G9ImageAffineIdentity();
39
+ }
40
+ G9ImageAffine r;
41
+ r.a = m.d / det;
42
+ r.b = -m.b / det;
43
+ r.c = -m.c / det;
44
+ r.d = m.a / det;
45
+ r.e = (m.c * m.f - m.d * m.e) / det;
46
+ r.f = (m.b * m.e - m.a * m.f) / det;
47
+ if (ok) *ok = YES;
48
+ return r;
49
+ }
50
+
51
+ void G9ImageAffineApply(G9ImageAffine m, double x, double y, double *outX, double *outY) {
52
+ *outX = m.a * x + m.c * y + m.e;
53
+ *outY = m.b * x + m.d * y + m.f;
54
+ }
55
+
56
+ static double G9Clamp(double v, double lo, double hi) {
57
+ return v < lo ? lo : (v > hi ? hi : v);
58
+ }
59
+
60
+ static BOOL G9IsNumber(id value) {
61
+ return [value isKindOfClass:[NSNumber class]] && isfinite([value doubleValue]);
62
+ }
63
+
64
+ static NSNumber *G9Double(double v) {
65
+ return [NSNumber numberWithDouble:v];
66
+ }
67
+
68
+ static NSNumber *G9Integer(long long v) {
69
+ return [NSNumber numberWithLongLong:v];
70
+ }
71
+
72
+ static NSNumber *G9Bool(BOOL v) {
73
+ return [NSNumber numberWithBool:v];
74
+ }
75
+
76
+ /** Absent and JSON null read alike. */
77
+ static id G9Field(NSDictionary *d, NSString *key) {
78
+ id value = [d objectForKey:key];
79
+ return value == [NSNull null] ? nil : value;
80
+ }
81
+
82
+ static BOOL G9Fail(NSString **message, NSString *text) {
83
+ if (message) *message = text;
84
+ return NO;
85
+ }
86
+
87
+ @implementation G9ImageCore
88
+
89
+ #pragma mark - orientation and boxes
90
+
91
+ + (NSInteger)normalizedOrientation:(NSInteger)orientation {
92
+ return orientation >= 1 && orientation <= 8 ? orientation : 1;
93
+ }
94
+
95
+ + (BOOL)orientationSwapsAxes:(NSInteger)orientation {
96
+ NSInteger o = [self normalizedOrientation:orientation];
97
+ return o >= 5;
98
+ }
99
+
100
+ + (void)orientedSizeForRawWidth:(double)rawWidth
101
+ rawHeight:(double)rawHeight
102
+ orientation:(NSInteger)orientation
103
+ width:(double *)width
104
+ height:(double *)height {
105
+ BOOL swap = [self orientationSwapsAxes:orientation];
106
+ *width = swap ? rawHeight : rawWidth;
107
+ *height = swap ? rawWidth : rawHeight;
108
+ }
109
+
110
+ + (G9ImageAffine)orientedToRawForOrientation:(NSInteger)orientation rawWidth:(double)w rawHeight:(double)h {
111
+ // EXIF: how the stored rows and columns are turned for display. Inverse maps, displayed (x, y) → stored (rx, ry).
112
+ G9ImageAffine m = {0, 0, 0, 0, 0, 0};
113
+ switch ([self normalizedOrientation:orientation]) {
114
+ case 2: m.a = -1; m.d = 1; m.e = w; break; // mirrored: rx = W − x
115
+ case 3: m.a = -1; m.d = -1; m.e = w; m.f = h; break; // 180°
116
+ case 4: m.a = 1; m.d = -1; m.f = h; break; // flipped: ry = H − y
117
+ case 5: m.c = 1; m.b = 1; break; // transpose: rx = y, ry = x
118
+ case 6: m.c = 1; m.b = -1; m.f = h; break; // 90° CW to display: rx = y, ry = H − x
119
+ case 7: m.c = -1; m.e = w; m.b = -1; m.f = h; break; // transverse: rx = W − y, ry = H − x
120
+ case 8: m.c = -1; m.e = w; m.b = 1; break; // 90° CCW to display: rx = W − y, ry = x
121
+ default: m.a = 1; m.d = 1; break;
122
+ }
123
+ return m;
124
+ }
125
+
126
+ + (G9ImageBox)rawBoxForOutputWidth:(double)width
127
+ height:(double)height
128
+ matrix:(G9ImageAffine)matrix
129
+ orientation:(NSInteger)orientation
130
+ rawWidth:(double)rawWidth
131
+ rawHeight:(double)rawHeight
132
+ margin:(double)margin {
133
+ G9ImageBox empty = {0, 0, 0, 0};
134
+ double ow, oh;
135
+ [self orientedSizeForRawWidth:rawWidth rawHeight:rawHeight orientation:orientation width:&ow height:&oh];
136
+ double xs[4] = {0, width, 0, width}, ys[4] = {0, 0, height, height};
137
+ double minX = INFINITY, minY = INFINITY, maxX = -INFINITY, maxY = -INFINITY;
138
+ for (int i = 0; i < 4; i++) {
139
+ double x, y;
140
+ G9ImageAffineApply(matrix, xs[i], ys[i], &x, &y);
141
+ minX = fmin(minX, x), maxX = fmax(maxX, x), minY = fmin(minY, y), maxY = fmax(maxY, y);
142
+ }
143
+ if (!isfinite(minX) || !isfinite(maxX) || !isfinite(minY) || !isfinite(maxY)) return empty;
144
+ minX = G9Clamp(minX - margin, 0, ow), maxX = G9Clamp(maxX + margin, 0, ow);
145
+ minY = G9Clamp(minY - margin, 0, oh), maxY = G9Clamp(maxY + margin, 0, oh);
146
+ if (maxX <= minX || maxY <= minY) return empty;
147
+ G9ImageAffine toRaw = [self orientedToRawForOrientation:orientation rawWidth:rawWidth rawHeight:rawHeight];
148
+ double bx[4] = {minX, maxX, minX, maxX}, by[4] = {minY, minY, maxY, maxY};
149
+ double rMinX = INFINITY, rMinY = INFINITY, rMaxX = -INFINITY, rMaxY = -INFINITY;
150
+ for (int i = 0; i < 4; i++) {
151
+ double x, y;
152
+ G9ImageAffineApply(toRaw, bx[i], by[i], &x, &y);
153
+ rMinX = fmin(rMinX, x), rMaxX = fmax(rMaxX, x), rMinY = fmin(rMinY, y), rMaxY = fmax(rMaxY, y);
154
+ }
155
+ rMinX = G9Clamp(floor(rMinX + 1e-9), 0, rawWidth), rMaxX = G9Clamp(ceil(rMaxX - 1e-9), 0, rawWidth);
156
+ rMinY = G9Clamp(floor(rMinY + 1e-9), 0, rawHeight), rMaxY = G9Clamp(ceil(rMaxY - 1e-9), 0, rawHeight);
157
+ if (rMaxX <= rMinX || rMaxY <= rMinY) return empty;
158
+ G9ImageBox box = {rMinX, rMinY, rMaxX - rMinX, rMaxY - rMinY};
159
+ return box;
160
+ }
161
+
162
+ + (double)sourcePixelsPerOutputPixel:(G9ImageAffine)m {
163
+ double first = hypot(m.a, m.b), second = hypot(m.c, m.d);
164
+ double v = fmin(first, second);
165
+ return isfinite(v) ? v : 1;
166
+ }
167
+
168
+ + (NSInteger)subsampleForSourcePerOutput:(double)sourcePerOutput {
169
+ if (!isfinite(sourcePerOutput)) return 1;
170
+ if (sourcePerOutput >= 8) return 8;
171
+ if (sourcePerOutput >= 4) return 4;
172
+ if (sourcePerOutput >= 2) return 2;
173
+ return 1;
174
+ }
175
+
176
+ + (NSInteger)previewMaxPixelForMaxSide:(NSInteger)maxSide width:(double)width height:(double)height {
177
+ double longest = fmax(width, height);
178
+ double side = maxSide > 0 ? fmin((double)maxSide, longest) : longest;
179
+ return (NSInteger)fmax(1, floor(side));
180
+ }
181
+
182
+ #pragma mark - encoding
183
+
184
+ + (NSInteger)qualityFloorForQuality:(NSInteger)quality {
185
+ return quality < 30 ? (quality < 0 ? 0 : quality) : 30;
186
+ }
187
+
188
+ + (NSInteger)qualityForMaxBytes:(long long)maxBytes
189
+ start:(NSInteger)start
190
+ floor:(NSInteger)floor
191
+ encoder:(id<G9ImageQualityEncoder>)encoder
192
+ attempts:(NSInteger *)attempts {
193
+ NSInteger count = 0;
194
+ if (floor > start) floor = start;
195
+ long long size = [encoder byteCountAtQuality:start];
196
+ count++;
197
+ NSInteger best = -1;
198
+ if (size >= 0 && size <= maxBytes) {
199
+ best = start;
200
+ } else {
201
+ NSInteger lo = floor, hi = start - 1;
202
+ while (lo <= hi) {
203
+ NSInteger mid = lo + (hi - lo) / 2;
204
+ long long bytes = [encoder byteCountAtQuality:mid];
205
+ count++;
206
+ if (bytes >= 0 && bytes <= maxBytes) {
207
+ best = mid;
208
+ lo = mid + 1;
209
+ } else {
210
+ hi = mid - 1;
211
+ }
212
+ }
213
+ }
214
+ if (attempts) *attempts = count;
215
+ return best;
216
+ }
217
+
218
+ + (BOOL)canScaleWidth:(NSInteger)width height:(NSInteger)height {
219
+ NSInteger w = [self scaledDimension:width], h = [self scaledDimension:height];
220
+ return (w < h ? w : h) >= G9ImageMinScaledSide;
221
+ }
222
+
223
+ + (double)lineHeightForSize:(double)size {
224
+ return 1.25 * size;
225
+ }
226
+
227
+ + (NSInteger)scaledDimension:(NSInteger)value {
228
+ NSInteger v = (NSInteger)llround((double)value * 0.85);
229
+ return v < 1 ? 1 : v;
230
+ }
231
+
232
+ + (NSString *)outputFormatForRequested:(NSString *)requested
233
+ sourceMime:(NSString *)sourceMime
234
+ hasAlpha:(BOOL)hasAlpha
235
+ webpEncodable:(BOOL)webpEncodable {
236
+ if ([requested isEqualToString:@"png"]) return @"png";
237
+ if ([requested isEqualToString:@"webp"]) return webpEncodable ? @"webp" : @"jpeg";
238
+ if ([requested isEqualToString:@"source"]) {
239
+ NSString *source = [self formatForMime:sourceMime];
240
+ if ([source isEqualToString:@"jpeg"] || [source isEqualToString:@"png"]) return source;
241
+ if ([source isEqualToString:@"webp"] && webpEncodable) return @"webp";
242
+ if ([source isEqualToString:@"heic"]) return @"jpeg";
243
+ return hasAlpha ? @"png" : @"jpeg";
244
+ }
245
+ return @"jpeg";
246
+ }
247
+
248
+ + (BOOL)formatHasAlpha:(NSString *)format {
249
+ return [format isEqualToString:@"png"] || [format isEqualToString:@"webp"];
250
+ }
251
+
252
+ + (NSString *)mimeForFormat:(NSString *)format {
253
+ if ([format isEqualToString:@"jpeg"]) return @"image/jpeg";
254
+ if ([format isEqualToString:@"png"]) return @"image/png";
255
+ if ([format isEqualToString:@"webp"]) return @"image/webp";
256
+ if ([format isEqualToString:@"heic"]) return @"image/heic";
257
+ if ([format isEqualToString:@"gif"]) return @"image/gif";
258
+ if ([format isEqualToString:@"tiff"]) return @"image/tiff";
259
+ if ([format isEqualToString:@"bmp"]) return @"image/bmp";
260
+ return @"application/octet-stream";
261
+ }
262
+
263
+ + (NSString *)extensionForFormat:(NSString *)format {
264
+ if ([format isEqualToString:@"jpeg"]) return @"jpg";
265
+ if ([format isEqualToString:@"png"] || [format isEqualToString:@"webp"] || [format isEqualToString:@"heic"] ||
266
+ [format isEqualToString:@"gif"] || [format isEqualToString:@"tiff"] || [format isEqualToString:@"bmp"])
267
+ return format;
268
+ return @"img";
269
+ }
270
+
271
+ + (NSString *)mimeForTypeIdentifier:(NSString *)type {
272
+ if (type == nil) return @"application/octet-stream";
273
+ if ([type isEqualToString:@"public.jpeg"]) return @"image/jpeg";
274
+ if ([type isEqualToString:@"public.png"]) return @"image/png";
275
+ if ([type isEqualToString:@"org.webmproject.webp"]) return @"image/webp";
276
+ if ([type isEqualToString:@"public.heic"] || [type isEqualToString:@"public.heif"] ||
277
+ [type isEqualToString:@"public.heics"])
278
+ return @"image/heic";
279
+ if ([type isEqualToString:@"com.compuserve.gif"]) return @"image/gif";
280
+ if ([type isEqualToString:@"public.tiff"]) return @"image/tiff";
281
+ if ([type isEqualToString:@"com.microsoft.bmp"]) return @"image/bmp";
282
+ return @"application/octet-stream";
283
+ }
284
+
285
+ + (NSString *)formatForMime:(NSString *)mime {
286
+ if (mime == nil) return nil;
287
+ if ([mime isEqualToString:@"image/jpeg"]) return @"jpeg";
288
+ if ([mime isEqualToString:@"image/png"]) return @"png";
289
+ if ([mime isEqualToString:@"image/webp"]) return @"webp";
290
+ if ([mime isEqualToString:@"image/heic"] || [mime isEqualToString:@"image/heif"]) return @"heic";
291
+ if ([mime isEqualToString:@"image/gif"]) return @"gif";
292
+ if ([mime isEqualToString:@"image/tiff"]) return @"tiff";
293
+ if ([mime isEqualToString:@"image/bmp"]) return @"bmp";
294
+ return nil;
295
+ }
296
+
297
+ #pragma mark - redactions and text
298
+
299
+ + (double)pixelateBlockForStrength:(double)strength width:(double)width height:(double)height {
300
+ double s = isfinite(strength) ? G9Clamp(strength, 0, 1) : 0.5;
301
+ return fmax(4, s * 0.08 * fmin(width, height));
302
+ }
303
+
304
+ + (double)blurRadiusForStrength:(double)strength width:(double)width height:(double)height {
305
+ double s = isfinite(strength) ? G9Clamp(strength, 0, 1) : 0.5;
306
+ return fmax(2, s * 0.05 * fmin(width, height));
307
+ }
308
+
309
+ + (double)fontWeightTraitForWeight:(double)weight {
310
+ // UIFontWeight: ultraLight … black.
311
+ static const double traits[9] = {-0.8, -0.6, -0.4, 0, 0.23, 0.3, 0.4, 0.56, 0.62};
312
+ double w = isfinite(weight) ? G9Clamp(weight, 100, 900) : 400;
313
+ int index = (int)lround(w / 100.0) - 1;
314
+ if (index < 0) index = 0;
315
+ if (index > 8) index = 8;
316
+ return traits[index];
317
+ }
318
+
319
+ #pragma mark - names and paths
320
+
321
+ + (NSString *)defaultNameForEpochMs:(long long)epochMs random:(uint32_t)random {
322
+ return [NSString stringWithFormat:@"g9photo-%lld-%04x", epochMs, (unsigned)(random & 0xFFFF)];
323
+ }
324
+
325
+ + (BOOL)isUsableName:(NSString *)name {
326
+ if (![name isKindOfClass:[NSString class]] || [name length] == 0) return NO;
327
+ if ([name isEqualToString:@"."] || [name isEqualToString:@".."]) return NO;
328
+ NSCharacterSet *bad = [NSCharacterSet characterSetWithCharactersInString:@"/\\"];
329
+ if ([name rangeOfCharacterFromSet:bad].location != NSNotFound) return NO;
330
+ unichar nul = 0;
331
+ return [name rangeOfString:[NSString stringWithCharacters:&nul length:1]].location == NSNotFound;
332
+ }
333
+
334
+ + (NSString *)uniquePathInDirectory:(NSString *)directory base:(NSString *)base extension:(NSString *)extension {
335
+ NSFileManager *fm = [NSFileManager defaultManager];
336
+ NSString *path = [directory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", base, extension]];
337
+ for (NSInteger i = 1; [fm fileExistsAtPath:path]; i++) {
338
+ path = [directory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%ld.%@", base, (long)i, extension]];
339
+ }
340
+ return path;
341
+ }
342
+
343
+ + (NSString *)filePathFromString:(NSString *)value {
344
+ if (![value isKindOfClass:[NSString class]]) return nil;
345
+ NSString *text = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
346
+ if ([text length] == 0) return nil;
347
+ if ([[text lowercaseString] hasPrefix:@"file://"]) {
348
+ NSString *rest = [text substringFromIndex:7];
349
+ // file://localhost/path and file:///path
350
+ if ([[rest lowercaseString] hasPrefix:@"localhost/"]) rest = [rest substringFromIndex:9];
351
+ if (![rest hasPrefix:@"/"]) return nil;
352
+ NSString *decoded = [rest stringByRemovingPercentEncoding];
353
+ return [decoded length] ? decoded : nil;
354
+ }
355
+ if ([text rangeOfString:@"://"].location != NSNotFound) return nil;
356
+ return text;
357
+ }
358
+
359
+ #pragma mark - colours
360
+
361
+ static int G9HexValue(unichar c) {
362
+ if (c >= '0' && c <= '9') return c - '0';
363
+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
364
+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
365
+ return -1;
366
+ }
367
+
368
+ static BOOL G9ParseNumber(NSString *text, double *out) {
369
+ const char *raw = [text UTF8String];
370
+ if (raw == NULL || *raw == 0) return NO;
371
+ char *end = NULL;
372
+ double v = strtod(raw, &end);
373
+ if (end == raw || *end != 0 || !isfinite(v)) return NO;
374
+ *out = v;
375
+ return YES;
376
+ }
377
+
378
+ /** A channel 0..255 (or a percentage) → 0..1, rounded to a byte like the Swift and Kotlin parsers. */
379
+ static BOOL G9Channel(NSString *text, BOOL alpha, double *out) {
380
+ double v;
381
+ if ([text hasSuffix:@"%"]) {
382
+ if (!G9ParseNumber([text substringToIndex:[text length] - 1], &v)) return NO;
383
+ *out = round(G9Clamp(v, 0, 100) / 100 * 255) / 255;
384
+ return YES;
385
+ }
386
+ if (!G9ParseNumber(text, &v)) return NO;
387
+ *out = alpha ? round(G9Clamp(v, 0, 1) * 255) / 255 : round(G9Clamp(v, 0, 255)) / 255;
388
+ return YES;
389
+ }
390
+
391
+ + (BOOL)parseColor:(NSString *)value rgba:(double *)rgba {
392
+ if (![value isKindOfClass:[NSString class]]) return NO;
393
+ NSString *text = [[value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] lowercaseString];
394
+ if ([text length] == 0) return NO;
395
+ if ([text hasPrefix:@"#"]) {
396
+ NSUInteger n = [text length] - 1;
397
+ int v[8];
398
+ if (n != 3 && n != 4 && n != 6 && n != 8) return NO;
399
+ for (NSUInteger i = 0; i < n; i++) {
400
+ v[i] = G9HexValue([text characterAtIndex:i + 1]);
401
+ if (v[i] < 0) return NO;
402
+ }
403
+ if (n <= 4) {
404
+ for (NSUInteger i = 0; i < 4; i++) rgba[i] = i < n ? v[i] * 17 / 255.0 : 1;
405
+ } else {
406
+ for (NSUInteger i = 0; i < 4; i++) rgba[i] = i * 2 < n ? (v[i * 2] * 16 + v[i * 2 + 1]) / 255.0 : 1;
407
+ }
408
+ return YES;
409
+ }
410
+ if ([text hasPrefix:@"rgb("] || [text hasPrefix:@"rgba("]) {
411
+ if (![text hasSuffix:@")"]) return NO;
412
+ NSRange open = [text rangeOfString:@"("];
413
+ NSString *inner = [text substringWithRange:NSMakeRange(open.location + 1, [text length] - open.location - 2)];
414
+ inner = [inner stringByReplacingOccurrencesOfString:@"/" withString:@" / "];
415
+ NSArray *raw = [inner componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]];
416
+ NSMutableArray *parts = [NSMutableArray array];
417
+ for (NSString *p in raw) {
418
+ NSString *t = [p stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
419
+ if ([t length] && ![t isEqualToString:@"/"]) [parts addObject:t];
420
+ }
421
+ if ([parts count] != 3 && [parts count] != 4) return NO;
422
+ double out[4] = {0, 0, 0, 1};
423
+ for (NSUInteger i = 0; i < [parts count]; i++) {
424
+ if (!G9Channel([parts objectAtIndex:i], i == 3, &out[i])) return NO;
425
+ }
426
+ for (int i = 0; i < 4; i++) rgba[i] = out[i];
427
+ return YES;
428
+ }
429
+ if ([text isEqualToString:@"transparent"]) {
430
+ rgba[0] = rgba[1] = rgba[2] = rgba[3] = 0;
431
+ return YES;
432
+ }
433
+ if ([text isEqualToString:@"black"] || [text isEqualToString:@"white"]) {
434
+ double c = [text isEqualToString:@"white"] ? 1 : 0;
435
+ rgba[0] = rgba[1] = rgba[2] = c;
436
+ rgba[3] = 1;
437
+ return YES;
438
+ }
439
+ return NO;
440
+ }
441
+
442
+ #pragma mark - SVG path data
443
+
444
+ static BOOL G9IsLetter(unichar c) {
445
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
446
+ }
447
+
448
+ static void G9AddSegment(NSMutableData *out, int op, double p0, double p1, double p2, double p3, double p4, double p5) {
449
+ G9PathSegment s;
450
+ s.op = op;
451
+ s.p[0] = p0, s.p[1] = p1, s.p[2] = p2, s.p[3] = p3, s.p[4] = p4, s.p[5] = p5;
452
+ [out appendBytes:&s length:sizeof(s)];
453
+ }
454
+
455
+ + (NSData *)pathSegmentsFromData:(NSString *)d {
456
+ NSMutableData *out = [NSMutableData data];
457
+ if (![d isKindOfClass:[NSString class]]) return out;
458
+ // Tokens: command letters and numbers (the same tokenizer as G9LCSvgPath.parse and G9CanvasPaths).
459
+ NSMutableArray *tokens = [NSMutableArray array];
460
+ NSMutableString *number = [NSMutableString string];
461
+ unichar previous = ' ';
462
+ NSUInteger length = [d length];
463
+ for (NSUInteger i = 0; i < length; i++) {
464
+ unichar c = [d characterAtIndex:i];
465
+ BOOL hasDot = [number rangeOfString:@"."].location != NSNotFound;
466
+ BOOL hasExp = [number rangeOfString:@"e"].location != NSNotFound || [number rangeOfString:@"E"].location != NSNotFound;
467
+ if (G9IsLetter(c) && c != 'e' && c != 'E') {
468
+ if ([number length]) [tokens addObject:[NSString stringWithString:number]];
469
+ [number setString:@""];
470
+ [tokens addObject:[NSString stringWithCharacters:&c length:1]];
471
+ } else if (c == '-' && !(previous == 'e' || previous == 'E')) {
472
+ if ([number length]) [tokens addObject:[NSString stringWithString:number]];
473
+ [number setString:@"-"];
474
+ } else if (c == '.' && hasDot && !hasExp) {
475
+ if ([number length]) [tokens addObject:[NSString stringWithString:number]];
476
+ [number setString:@"."];
477
+ } else if (c == ',' || c == ' ' || c == '\n' || c == '\t' || c == '\r') {
478
+ if ([number length]) [tokens addObject:[NSString stringWithString:number]];
479
+ [number setString:@""];
480
+ } else {
481
+ [number appendString:[NSString stringWithCharacters:&c length:1]];
482
+ }
483
+ previous = c;
484
+ }
485
+ if ([number length]) [tokens addObject:[NSString stringWithString:number]];
486
+
487
+ NSUInteger count = [tokens count], index = 0;
488
+ unichar command = 'M';
489
+ double cx = 0, cy = 0, sx = 0, sy = 0;
490
+ double lcx = 0, lcy = 0, lqx = 0, lqy = 0;
491
+ BOOL hasCubic = NO, hasQuad = NO;
492
+ double v[6];
493
+ while (index < count) {
494
+ NSString *token = [tokens objectAtIndex:index];
495
+ unichar first = [token characterAtIndex:0];
496
+ if (G9IsLetter(first)) {
497
+ command = first;
498
+ index++;
499
+ if (command == 'Z' || command == 'z') {
500
+ G9AddSegment(out, G9PathClose, 0, 0, 0, 0, 0, 0);
501
+ cx = sx, cy = sy;
502
+ hasCubic = hasQuad = NO;
503
+ continue;
504
+ }
505
+ }
506
+ BOOL relative = command >= 'a' && command <= 'z';
507
+ double bx = relative ? cx : 0, by = relative ? cy : 0;
508
+ unichar upper = relative ? (unichar)(command - 32) : command;
509
+ int need;
510
+ switch (upper) {
511
+ case 'M': case 'L': case 'T': need = 2; break;
512
+ case 'H': case 'V': need = 1; break;
513
+ case 'C': need = 6; break;
514
+ case 'S': case 'Q': need = 4; break;
515
+ default: need = 0; break;
516
+ }
517
+ if (need == 0) {
518
+ // Unknown command (arcs): skip its numbers.
519
+ index++;
520
+ continue;
521
+ }
522
+ for (int k = 0; k < need; k++) {
523
+ double n;
524
+ if (index >= count || !G9ParseNumber([tokens objectAtIndex:index], &n)) return out;
525
+ v[k] = n;
526
+ index++;
527
+ }
528
+ switch (upper) {
529
+ case 'M':
530
+ cx = bx + v[0], cy = by + v[1];
531
+ G9AddSegment(out, G9PathMove, cx, cy, 0, 0, 0, 0);
532
+ sx = cx, sy = cy;
533
+ command = relative ? 'l' : 'L'; // further pairs are line-tos
534
+ hasCubic = hasQuad = NO;
535
+ break;
536
+ case 'L':
537
+ cx = bx + v[0], cy = by + v[1];
538
+ G9AddSegment(out, G9PathLine, cx, cy, 0, 0, 0, 0);
539
+ hasCubic = hasQuad = NO;
540
+ break;
541
+ case 'H':
542
+ cx = bx + v[0];
543
+ G9AddSegment(out, G9PathLine, cx, cy, 0, 0, 0, 0);
544
+ hasCubic = hasQuad = NO;
545
+ break;
546
+ case 'V':
547
+ cy = by + v[0];
548
+ G9AddSegment(out, G9PathLine, cx, cy, 0, 0, 0, 0);
549
+ hasCubic = hasQuad = NO;
550
+ break;
551
+ case 'C': {
552
+ double x1 = bx + v[0], y1 = by + v[1], x2 = bx + v[2], y2 = by + v[3];
553
+ cx = bx + v[4], cy = by + v[5];
554
+ G9AddSegment(out, G9PathCubic, x1, y1, x2, y2, cx, cy);
555
+ lcx = x2, lcy = y2, hasCubic = YES, hasQuad = NO;
556
+ break;
557
+ }
558
+ case 'S': {
559
+ double x1 = hasCubic ? 2 * cx - lcx : cx, y1 = hasCubic ? 2 * cy - lcy : cy;
560
+ double x2 = bx + v[0], y2 = by + v[1];
561
+ cx = bx + v[2], cy = by + v[3];
562
+ G9AddSegment(out, G9PathCubic, x1, y1, x2, y2, cx, cy);
563
+ lcx = x2, lcy = y2, hasCubic = YES, hasQuad = NO;
564
+ break;
565
+ }
566
+ case 'Q': {
567
+ double qx = bx + v[0], qy = by + v[1];
568
+ cx = bx + v[2], cy = by + v[3];
569
+ G9AddSegment(out, G9PathQuad, qx, qy, cx, cy, 0, 0);
570
+ lqx = qx, lqy = qy, hasQuad = YES, hasCubic = NO;
571
+ break;
572
+ }
573
+ case 'T': {
574
+ double qx = hasQuad ? 2 * cx - lqx : cx, qy = hasQuad ? 2 * cy - lqy : cy;
575
+ cx = bx + v[0], cy = by + v[1];
576
+ G9AddSegment(out, G9PathQuad, qx, qy, cx, cy, 0, 0);
577
+ lqx = qx, lqy = qy, hasQuad = YES, hasCubic = NO;
578
+ break;
579
+ }
580
+ }
581
+ }
582
+ return out;
583
+ }
584
+
585
+ #pragma mark - metadata
586
+
587
+ + (NSDictionary *)outputMetadataFromSourceProperties:(NSDictionary *)properties {
588
+ NSMutableDictionary *out = [NSMutableDictionary dictionary];
589
+ NSNumber *one = [NSNumber numberWithInt:1];
590
+ if ([properties isKindOfClass:[NSDictionary class]]) {
591
+ // The ImageIO key strings (kCGImagePropertyExifDictionary = "{Exif}", …; G9ImageModuleTests checks they agree).
592
+ NSArray *dictionaries = [NSArray arrayWithObjects:@"{Exif}", @"{ExifAux}", @"{GPS}", @"{TIFF}", @"{IPTC}", nil];
593
+ for (NSString *key in dictionaries) {
594
+ id value = [properties objectForKey:key];
595
+ if ([value isKindOfClass:[NSDictionary class]]) [out setObject:[value mutableCopy] forKey:key];
596
+ }
597
+ NSArray *scalars = [NSArray arrayWithObjects:@"DPIWidth", @"DPIHeight", nil];
598
+ for (NSString *key in scalars) {
599
+ id value = [properties objectForKey:key];
600
+ if (value != nil) [out setObject:value forKey:key];
601
+ }
602
+ }
603
+ NSMutableDictionary *exif = [out objectForKey:@"{Exif}"];
604
+ if (exif != nil) {
605
+ [exif removeObjectForKey:@"PixelXDimension"];
606
+ [exif removeObjectForKey:@"PixelYDimension"];
607
+ [exif removeObjectForKey:@"SubjectArea"];
608
+ }
609
+ NSMutableDictionary *tiff = [out objectForKey:@"{TIFF}"];
610
+ if (tiff != nil) [tiff setObject:one forKey:@"Orientation"];
611
+ [out setObject:one forKey:@"Orientation"];
612
+ return out;
613
+ }
614
+
615
+ #pragma mark - JSON
616
+
617
+ + (id)objectFromJSON:(NSString *)json {
618
+ if (![json isKindOfClass:[NSString class]]) return nil;
619
+ NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
620
+ if (data == nil) return nil;
621
+ return [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
622
+ }
623
+
624
+ static NSString *G9JSONText(id object) {
625
+ NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:NULL];
626
+ return data ? [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] : nil;
627
+ }
628
+
629
+ + (NSString *)okReply:(id)value {
630
+ NSMutableDictionary *reply = [NSMutableDictionary dictionary];
631
+ [reply setObject:G9Bool(YES) forKey:@"ok"];
632
+ [reply setObject:value ?: [NSDictionary dictionary] forKey:@"value"];
633
+ NSString *text = G9JSONText(reply);
634
+ return text ?: [self failReply:G9ImageErrorIO message:@"The result could not be written as JSON."];
635
+ }
636
+
637
+ + (NSString *)failReply:(NSString *)code message:(NSString *)message {
638
+ NSMutableDictionary *error = [NSMutableDictionary dictionary];
639
+ [error setObject:code forKey:@"code"];
640
+ [error setObject:message ?: @"" forKey:@"message"];
641
+ NSMutableDictionary *reply = [NSMutableDictionary dictionary];
642
+ [reply setObject:G9Bool(NO) forKey:@"ok"];
643
+ [reply setObject:error forKey:@"error"];
644
+ return G9JSONText(reply) ?: @"{\"ok\":false,\"error\":{\"code\":\"io\",\"message\":\"\"}}";
645
+ }
646
+
647
+ static NSString *G9PathArgument(NSDictionary *args, NSString *key, NSString **message) {
648
+ id raw = G9Field(args, key);
649
+ if (![raw isKindOfClass:[NSString class]] || [raw length] == 0) {
650
+ G9Fail(message, [NSString stringWithFormat:@"`%@` must be a file path or a file:// URI.", key]);
651
+ return nil;
652
+ }
653
+ NSString *path = [G9ImageCore filePathFromString:raw];
654
+ if (path == nil) G9Fail(message, [NSString stringWithFormat:@"`%@` must be a plain path or a file:// URI on iOS.", key]);
655
+ return path;
656
+ }
657
+
658
+ + (NSDictionary *)validateProbeArguments:(id)args message:(NSString **)message {
659
+ if (![args isKindOfClass:[NSDictionary class]]) return G9Fail(message, @"The argument must be a JSON object."), nil;
660
+ NSString *path = G9PathArgument(args, @"path", message);
661
+ if (path == nil) return nil;
662
+ return [NSDictionary dictionaryWithObject:path forKey:@"path"];
663
+ }
664
+
665
+ + (NSDictionary *)validatePreviewArguments:(id)args message:(NSString **)message {
666
+ if (![args isKindOfClass:[NSDictionary class]]) return G9Fail(message, @"The argument must be a JSON object."), nil;
667
+ NSString *path = G9PathArgument(args, @"path", message);
668
+ if (path == nil) return nil;
669
+ id maxSide = G9Field(args, @"maxSide");
670
+ if (!G9IsNumber(maxSide) || [maxSide doubleValue] < 1) return G9Fail(message, @"`maxSide` must be a number ≥ 1."), nil;
671
+ NSMutableDictionary *out = [NSMutableDictionary dictionary];
672
+ [out setObject:path forKey:@"path"];
673
+ [out setObject:G9Integer((long long)floor([maxSide doubleValue])) forKey:@"maxSide"];
674
+ id dir = G9Field(args, @"dir");
675
+ if (dir != nil) {
676
+ NSString *d = [dir isKindOfClass:[NSString class]] ? [self filePathFromString:dir] : nil;
677
+ if (d == nil) return G9Fail(message, @"`dir` must be a folder path or null."), nil;
678
+ [out setObject:d forKey:@"dir"];
679
+ }
680
+ return out;
681
+ }
682
+
683
+ + (NSDictionary *)validateCancelArguments:(id)args message:(NSString **)message {
684
+ if (![args isKindOfClass:[NSDictionary class]]) return G9Fail(message, @"The argument must be a JSON object."), nil;
685
+ id token = G9Field(args, @"token");
686
+ if (![token isKindOfClass:[NSString class]] || [token length] == 0) return G9Fail(message, @"`token` must be a non-empty string."), nil;
687
+ return [NSDictionary dictionaryWithObject:token forKey:@"token"];
688
+ }
689
+
690
+ /** A number field: absent → `fallback`; present must be finite (clamped to [lo, hi] when `clamp`, else rejected). */
691
+ static BOOL G9NumberField(NSDictionary *d, NSString *key, double fallback, double lo, double hi, BOOL clamp, double *out,
692
+ NSString *where, NSString **message) {
693
+ id value = G9Field(d, key);
694
+ if (value == nil) {
695
+ *out = fallback;
696
+ return YES;
697
+ }
698
+ if (!G9IsNumber(value)) return G9Fail(message, [NSString stringWithFormat:@"%@`%@` must be a number.", where, key]);
699
+ double v = [value doubleValue];
700
+ if (v < lo || v > hi) {
701
+ if (!clamp) return G9Fail(message, [NSString stringWithFormat:@"%@`%@` is out of range.", where, key]);
702
+ v = G9Clamp(v, lo, hi);
703
+ }
704
+ *out = v;
705
+ return YES;
706
+ }
707
+
708
+ static BOOL G9RequiredNumber(NSDictionary *d, NSString *key, double *out, NSString *where, NSString **message) {
709
+ id value = G9Field(d, key);
710
+ if (!G9IsNumber(value)) return G9Fail(message, [NSString stringWithFormat:@"%@`%@` must be a number.", where, key]);
711
+ *out = [value doubleValue];
712
+ return YES;
713
+ }
714
+
715
+ static BOOL G9BoolField(NSDictionary *d, NSString *key, BOOL fallback, BOOL *out, NSString *where, NSString **message) {
716
+ id value = G9Field(d, key);
717
+ if (value == nil) {
718
+ *out = fallback;
719
+ return YES;
720
+ }
721
+ if (![value isKindOfClass:[NSNumber class]]) return G9Fail(message, [NSString stringWithFormat:@"%@`%@` must be true or false.", where, key]);
722
+ *out = [value boolValue];
723
+ return YES;
724
+ }
725
+
726
+ /** A colour field: absent → nil (and YES); present must parse. */
727
+ static BOOL G9ColorField(NSDictionary *d, NSString *key, NSString **out, NSString *where, NSString **message) {
728
+ id value = G9Field(d, key);
729
+ *out = nil;
730
+ if (value == nil) return YES;
731
+ double rgba[4];
732
+ if (![value isKindOfClass:[NSString class]] || ![G9ImageCore parseColor:value rgba:rgba])
733
+ return G9Fail(message, [NSString stringWithFormat:@"%@`%@` is not a colour.", where, key]);
734
+ *out = value;
735
+ return YES;
736
+ }
737
+
738
+ static BOOL G9ChoiceField(NSDictionary *d, NSString *key, NSArray *choices, NSString **out, NSString *where, NSString **message) {
739
+ id value = G9Field(d, key);
740
+ if (value == nil) {
741
+ *out = [choices objectAtIndex:0];
742
+ return YES;
743
+ }
744
+ if (![value isKindOfClass:[NSString class]] || ![choices containsObject:value])
745
+ return G9Fail(message, [NSString stringWithFormat:@"%@`%@` must be one of %@.", where, key, [choices componentsJoinedByString:@", "]]);
746
+ *out = value;
747
+ return YES;
748
+ }
749
+
750
+ /** Six finite numbers, or absent (the identity). */
751
+ static NSArray *G9MatrixField(NSDictionary *d, NSString *key, NSString *where, NSString **message) {
752
+ id value = G9Field(d, key);
753
+ if (value == nil) {
754
+ return [NSArray arrayWithObjects:G9Double(1), G9Double(0), G9Double(0), G9Double(1), G9Double(0), G9Double(0), nil];
755
+ }
756
+ if (![value isKindOfClass:[NSArray class]] || [value count] != 6) {
757
+ G9Fail(message, [NSString stringWithFormat:@"%@`%@` must be six numbers [a, b, c, d, e, f].", where, key]);
758
+ return nil;
759
+ }
760
+ for (id n in value) {
761
+ if (!G9IsNumber(n)) {
762
+ G9Fail(message, [NSString stringWithFormat:@"%@`%@` must be six finite numbers.", where, key]);
763
+ return nil;
764
+ }
765
+ }
766
+ return value;
767
+ }
768
+
769
+ static NSDictionary *G9Redaction(id raw, NSUInteger i, NSString **message) {
770
+ NSString *where = [NSString stringWithFormat:@"redact[%lu]: ", (unsigned long)i];
771
+ if (![raw isKindOfClass:[NSDictionary class]]) {
772
+ G9Fail(message, [where stringByAppendingString:@"must be an object."]);
773
+ return nil;
774
+ }
775
+ double x, y, w, h, angle, strength;
776
+ NSString *mode;
777
+ if (!G9RequiredNumber(raw, @"x", &x, where, message) || !G9RequiredNumber(raw, @"y", &y, where, message) ||
778
+ !G9RequiredNumber(raw, @"width", &w, where, message) || !G9RequiredNumber(raw, @"height", &h, where, message) ||
779
+ !G9NumberField(raw, @"angle", 0, -1e9, 1e9, NO, &angle, where, message) ||
780
+ !G9NumberField(raw, @"strength", 0.5, 0, 1, YES, &strength, where, message) ||
781
+ !G9ChoiceField(raw, @"mode", [NSArray arrayWithObjects:@"pixelate", @"blur", nil], &mode, where, message))
782
+ return nil;
783
+ if (w <= 0 || h <= 0) {
784
+ G9Fail(message, [where stringByAppendingString:@"`width` and `height` must be > 0."]);
785
+ return nil;
786
+ }
787
+ NSMutableDictionary *out = [NSMutableDictionary dictionary];
788
+ [out setObject:G9Double(x) forKey:@"x"];
789
+ [out setObject:G9Double(y) forKey:@"y"];
790
+ [out setObject:G9Double(w) forKey:@"width"];
791
+ [out setObject:G9Double(h) forKey:@"height"];
792
+ [out setObject:G9Double(angle) forKey:@"angle"];
793
+ [out setObject:mode forKey:@"mode"];
794
+ [out setObject:G9Double(strength) forKey:@"strength"];
795
+ return out;
796
+ }
797
+
798
+ static NSDictionary *G9Overlay(id raw, NSUInteger i, NSString **message) {
799
+ NSString *where = [NSString stringWithFormat:@"overlay[%lu]: ", (unsigned long)i];
800
+ if (![raw isKindOfClass:[NSDictionary class]]) {
801
+ G9Fail(message, [where stringByAppendingString:@"must be an object."]);
802
+ return nil;
803
+ }
804
+ id k = G9Field(raw, @"k");
805
+ NSMutableDictionary *out = [NSMutableDictionary dictionary];
806
+ double opacity;
807
+ if (!G9NumberField(raw, @"opacity", 1, 0, 1, YES, &opacity, where, message)) return nil;
808
+ [out setObject:G9Double(opacity) forKey:@"opacity"];
809
+ if ([k isEqual:@"path"]) {
810
+ id d = G9Field(raw, @"d");
811
+ if (![d isKindOfClass:[NSString class]]) {
812
+ G9Fail(message, [where stringByAppendingString:@"`d` must be SVG path data."]);
813
+ return nil;
814
+ }
815
+ NSString *stroke, *fill, *cap, *join;
816
+ double width;
817
+ if (!G9ColorField(raw, @"stroke", &stroke, where, message) || !G9ColorField(raw, @"fill", &fill, where, message) ||
818
+ !G9NumberField(raw, @"width", 1, 0, 1e6, NO, &width, where, message) ||
819
+ !G9ChoiceField(raw, @"cap", [NSArray arrayWithObjects:@"butt", @"round", @"square", nil], &cap, where, message) ||
820
+ !G9ChoiceField(raw, @"join", [NSArray arrayWithObjects:@"miter", @"round", @"bevel", nil], &join, where, message))
821
+ return nil;
822
+ NSArray *transform = G9MatrixField(raw, @"transform", where, message);
823
+ if (transform == nil) return nil;
824
+ id dash = G9Field(raw, @"dash");
825
+ if (dash != nil) {
826
+ BOOL good = [dash isKindOfClass:[NSArray class]];
827
+ if (good) {
828
+ for (id n in dash) good = good && G9IsNumber(n) && [n doubleValue] >= 0;
829
+ }
830
+ if (!good) {
831
+ G9Fail(message, [where stringByAppendingString:@"`dash` must be an array of numbers ≥ 0."]);
832
+ return nil;
833
+ }
834
+ [out setObject:dash forKey:@"dash"];
835
+ }
836
+ [out setObject:@"path" forKey:@"k"];
837
+ [out setObject:d forKey:@"d"];
838
+ if (stroke) [out setObject:stroke forKey:@"stroke"];
839
+ if (fill) [out setObject:fill forKey:@"fill"];
840
+ [out setObject:G9Double(width) forKey:@"width"];
841
+ [out setObject:cap forKey:@"cap"];
842
+ [out setObject:join forKey:@"join"];
843
+ [out setObject:transform forKey:@"transform"];
844
+ return out;
845
+ }
846
+ if ([k isEqual:@"text"]) {
847
+ id text = G9Field(raw, @"text");
848
+ if (![text isKindOfClass:[NSString class]]) {
849
+ G9Fail(message, [where stringByAppendingString:@"`text` must be a string."]);
850
+ return nil;
851
+ }
852
+ double x, y, angle, size, padding, radius, weight, maxWidth;
853
+ NSString *color, *background, *align;
854
+ BOOL rtl;
855
+ if (!G9RequiredNumber(raw, @"x", &x, where, message) || !G9RequiredNumber(raw, @"y", &y, where, message) ||
856
+ !G9NumberField(raw, @"angle", 0, -1e9, 1e9, NO, &angle, where, message) ||
857
+ !G9NumberField(raw, @"size", 32, 0.01, 1e5, NO, &size, where, message) ||
858
+ !G9NumberField(raw, @"padding", 0, 0, 1e5, YES, &padding, where, message) ||
859
+ !G9NumberField(raw, @"radius", 0, 0, 1e5, YES, &radius, where, message) ||
860
+ !G9NumberField(raw, @"weight", 400, 1, 1000, YES, &weight, where, message) ||
861
+ !G9NumberField(raw, @"maxWidth", 0, 0, 1e6, YES, &maxWidth, where, message) ||
862
+ !G9ColorField(raw, @"color", &color, where, message) ||
863
+ !G9ColorField(raw, @"background", &background, where, message) ||
864
+ !G9ChoiceField(raw, @"align", [NSArray arrayWithObjects:@"center", @"left", @"right", @"start", @"end", nil], &align, where, message) ||
865
+ !G9BoolField(raw, @"rtl", NO, &rtl, where, message))
866
+ return nil;
867
+ id font = G9Field(raw, @"font");
868
+ if (font != nil && ![font isKindOfClass:[NSString class]]) {
869
+ G9Fail(message, [where stringByAppendingString:@"`font` must be a string."]);
870
+ return nil;
871
+ }
872
+ [out setObject:@"text" forKey:@"k"];
873
+ [out setObject:text forKey:@"text"];
874
+ [out setObject:G9Double(x) forKey:@"x"];
875
+ [out setObject:G9Double(y) forKey:@"y"];
876
+ [out setObject:G9Double(angle) forKey:@"angle"];
877
+ [out setObject:G9Double(size) forKey:@"size"];
878
+ [out setObject:color ?: @"#000000" forKey:@"color"];
879
+ if (background) [out setObject:background forKey:@"background"];
880
+ [out setObject:G9Double(padding) forKey:@"padding"];
881
+ [out setObject:G9Double(radius) forKey:@"radius"];
882
+ [out setObject:font ?: @"" forKey:@"font"];
883
+ [out setObject:G9Double(weight) forKey:@"weight"];
884
+ [out setObject:align forKey:@"align"];
885
+ [out setObject:G9Bool(rtl) forKey:@"rtl"];
886
+ [out setObject:G9Double(maxWidth) forKey:@"maxWidth"];
887
+ return out;
888
+ }
889
+ G9Fail(message, [where stringByAppendingString:@"`k` must be \"path\" or \"text\"."]);
890
+ return nil;
891
+ }
892
+
893
+ + (NSDictionary *)validateProcessSpec:(id)spec message:(NSString **)message {
894
+ if (![spec isKindOfClass:[NSDictionary class]]) return G9Fail(message, @"The spec must be a JSON object."), nil;
895
+ NSString *where = @"";
896
+ NSMutableDictionary *out = [NSMutableDictionary dictionary];
897
+ id token = G9Field(spec, @"token");
898
+ if (token != nil) {
899
+ if (![token isKindOfClass:[NSString class]]) return G9Fail(message, @"`token` must be a string."), nil;
900
+ if ([token length]) [out setObject:token forKey:@"token"];
901
+ }
902
+ NSString *path = G9PathArgument(spec, @"path", message);
903
+ if (path == nil) return nil;
904
+ [out setObject:path forKey:@"path"];
905
+
906
+ BOOL passthrough, circle, keep;
907
+ if (!G9BoolField(spec, @"passthrough", NO, &passthrough, where, message) ||
908
+ !G9BoolField(spec, @"circle", NO, &circle, where, message) ||
909
+ !G9BoolField(spec, @"keepMetadata", NO, &keep, where, message))
910
+ return nil;
911
+ [out setObject:G9Bool(passthrough) forKey:@"passthrough"];
912
+ [out setObject:G9Bool(circle) forKey:@"circle"];
913
+ [out setObject:G9Bool(keep) forKey:@"keepMetadata"];
914
+
915
+ id dir = G9Field(spec, @"dir");
916
+ if (dir != nil) {
917
+ NSString *d = [dir isKindOfClass:[NSString class]] ? [self filePathFromString:dir] : nil;
918
+ if (d == nil) return G9Fail(message, @"`dir` must be a folder path or null."), nil;
919
+ [out setObject:d forKey:@"dir"];
920
+ }
921
+ id name = G9Field(spec, @"name");
922
+ if (name != nil) {
923
+ if (![self isUsableName:name]) return G9Fail(message, @"`name` must be a file name without a folder or extension."), nil;
924
+ [out setObject:name forKey:@"name"];
925
+ }
926
+ NSString *format;
927
+ if (!G9ChoiceField(spec, @"format", [NSArray arrayWithObjects:@"jpeg", @"png", @"webp", @"source", nil], &format, where, message))
928
+ return nil;
929
+ [out setObject:format forKey:@"format"];
930
+ if (passthrough) return out; // nothing else is read: the bytes are copied as they are
931
+
932
+ double width, height, quality, maxBytes;
933
+ if (!G9RequiredNumber(spec, @"width", &width, where, message) || !G9RequiredNumber(spec, @"height", &height, where, message))
934
+ return nil;
935
+ if (width != floor(width) || height != floor(height) || width < 1 || height < 1 || width > G9ImageMaxSide ||
936
+ height > G9ImageMaxSide)
937
+ return G9Fail(message, @"`width` and `height` must be whole numbers from 1 to 20000."), nil;
938
+ [out setObject:G9Integer((long long)width) forKey:@"width"];
939
+ [out setObject:G9Integer((long long)height) forKey:@"height"];
940
+ if (!G9NumberField(spec, @"quality", 90, 0, 100, NO, &quality, where, message) ||
941
+ !G9NumberField(spec, @"maxBytes", 0, 0, 1e15, NO, &maxBytes, where, message))
942
+ return nil;
943
+ [out setObject:G9Integer(llround(quality)) forKey:@"quality"];
944
+ [out setObject:G9Integer((long long)floor(maxBytes)) forKey:@"maxBytes"];
945
+
946
+ NSArray *matrix = G9MatrixField(spec, @"matrix", where, message);
947
+ if (matrix == nil) return nil;
948
+ BOOL invertible = NO;
949
+ G9ImageAffineInvert([self affineFromArray:matrix], &invertible);
950
+ if (!invertible) return G9Fail(message, @"`matrix` must be invertible."), nil;
951
+ [out setObject:matrix forKey:@"matrix"];
952
+
953
+ NSString *background;
954
+ if (!G9ColorField(spec, @"background", &background, where, message)) return nil;
955
+ if (background) [out setObject:background forKey:@"background"];
956
+
957
+ id redact = G9Field(spec, @"redact");
958
+ NSMutableArray *regions = [NSMutableArray array];
959
+ if (redact != nil) {
960
+ if (![redact isKindOfClass:[NSArray class]]) return G9Fail(message, @"`redact` must be an array."), nil;
961
+ for (NSUInteger i = 0; i < [redact count]; i++) {
962
+ NSDictionary *r = G9Redaction([redact objectAtIndex:i], i, message);
963
+ if (r == nil) return nil;
964
+ [regions addObject:r];
965
+ }
966
+ }
967
+ [out setObject:regions forKey:@"redact"];
968
+
969
+ id overlay = G9Field(spec, @"overlay");
970
+ NSMutableArray *ops = [NSMutableArray array];
971
+ if (overlay != nil) {
972
+ if (![overlay isKindOfClass:[NSArray class]]) return G9Fail(message, @"`overlay` must be an array."), nil;
973
+ for (NSUInteger i = 0; i < [overlay count]; i++) {
974
+ NSDictionary *op = G9Overlay([overlay objectAtIndex:i], i, message);
975
+ if (op == nil) return nil;
976
+ [ops addObject:op];
977
+ }
978
+ }
979
+ [out setObject:ops forKey:@"overlay"];
980
+ return out;
981
+ }
982
+
983
+ + (G9ImageAffine)affineFromArray:(NSArray *)values {
984
+ if (![values isKindOfClass:[NSArray class]] || [values count] != 6) return G9ImageAffineIdentity();
985
+ G9ImageAffine m;
986
+ m.a = [[values objectAtIndex:0] doubleValue];
987
+ m.b = [[values objectAtIndex:1] doubleValue];
988
+ m.c = [[values objectAtIndex:2] doubleValue];
989
+ m.d = [[values objectAtIndex:3] doubleValue];
990
+ m.e = [[values objectAtIndex:4] doubleValue];
991
+ m.f = [[values objectAtIndex:5] doubleValue];
992
+ return m;
993
+ }
994
+
995
+ @end
996
+
997
+ @implementation G9ImageCancelRegistry
998
+
999
+ - (instancetype)init {
1000
+ if ((self = [super init])) {
1001
+ _pending = [[NSMutableSet alloc] init];
1002
+ _cancelled = [[NSMutableSet alloc] init];
1003
+ }
1004
+ return self;
1005
+ }
1006
+
1007
+ - (void)begin:(NSString *)token {
1008
+ if ([token length] == 0) return;
1009
+ @synchronized(self) {
1010
+ [_pending addObject:token];
1011
+ [_cancelled removeObject:token];
1012
+ }
1013
+ }
1014
+
1015
+ - (BOOL)cancel:(NSString *)token {
1016
+ if ([token length] == 0) return NO;
1017
+ @synchronized(self) {
1018
+ if (![_pending containsObject:token]) return NO;
1019
+ [_cancelled addObject:token];
1020
+ return YES;
1021
+ }
1022
+ }
1023
+
1024
+ - (BOOL)isCancelled:(NSString *)token {
1025
+ if ([token length] == 0) return NO;
1026
+ @synchronized(self) {
1027
+ return [_cancelled containsObject:token];
1028
+ }
1029
+ }
1030
+
1031
+ - (void)end:(NSString *)token {
1032
+ if ([token length] == 0) return;
1033
+ @synchronized(self) {
1034
+ [_pending removeObject:token];
1035
+ [_cancelled removeObject:token];
1036
+ }
1037
+ }
1038
+
1039
+ @end