@g9tm/lynxcontrols-native 2.6.18 → 2.7.0

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 (53) 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/G9NativeImages.kt +16 -0
  4. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasModel.kt +2 -2
  5. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasPaths.kt +7 -26
  6. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasView.kt +9 -4
  7. package/android/src/main/java/com/g9lynx/g9native/generated/G9ImageModuleSpec.java +27 -0
  8. package/android/src/main/java/com/g9lynx/g9native/image/G9HostTypeface.kt +49 -0
  9. package/android/src/main/java/com/g9lynx/g9native/image/G9ImageDraw.kt +222 -0
  10. package/android/src/main/java/com/g9lynx/g9native/image/G9ImageModule.kt +54 -0
  11. package/android/src/main/java/com/g9lynx/g9native/image/G9ImageProcessor.kt +464 -0
  12. package/android/src/main/java/com/g9lynx/g9native/image/core/G9HostFont.kt +28 -0
  13. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageBudget.kt +54 -0
  14. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageColor.kt +48 -0
  15. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageError.kt +19 -0
  16. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageExifTags.kt +61 -0
  17. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageFiles.kt +99 -0
  18. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageGeometry.kt +150 -0
  19. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageJson.kt +200 -0
  20. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageQuality.kt +65 -0
  21. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageRedaction.kt +77 -0
  22. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageService.kt +102 -0
  23. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageSniff.kt +63 -0
  24. package/android/src/main/java/com/g9lynx/g9native/image/core/G9ImageSpec.kt +237 -0
  25. package/catalog/catalog.json +161 -1
  26. package/catalog/index.md +1 -1
  27. package/dist/.tsbuildinfo +1 -1
  28. package/dist/image.d.ts +219 -0
  29. package/dist/image.d.ts.map +1 -0
  30. package/dist/image.js +116 -0
  31. package/dist/image.js.map +1 -0
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +1 -0
  35. package/dist/protocol.d.ts +12 -0
  36. package/dist/protocol.d.ts.map +1 -1
  37. package/generated/G9ImageModule.ts +64 -0
  38. package/ios/Tests/G9NativeTestSuite.h +8 -0
  39. package/ios/Tests/G9NativeTestSuite.m +350 -0
  40. package/ios/Tests/G9NativeTests.m +16 -0
  41. package/ios/g9lynx-native-swift.podspec +1 -1
  42. package/ios/g9lynx-native.podspec +5 -4
  43. package/ios/src/G9ImageModule.h +30 -0
  44. package/ios/src/G9ImageModule.m +986 -0
  45. package/ios/src/core/G9ImageCore.h +201 -0
  46. package/ios/src/core/G9ImageCore.m +1039 -0
  47. package/ios/src/generated/G9ImageModuleSpec.h +16 -0
  48. package/ios/src/generated/G9ImageModuleSpec.m +2 -0
  49. package/ios/swift/canvas/G9LCCanvasCore.swift +3 -2
  50. package/ios/swift/canvas/G9LCCanvasView.swift +15 -4
  51. package/ios/swift/shared/G9LCFonts.swift +18 -2
  52. package/package.json +4 -4
  53. package/types/platform-native-module.d.ts +18 -0
@@ -0,0 +1,986 @@
1
+ #import "G9ImageModule.h"
2
+ #import <CoreGraphics/CoreGraphics.h>
3
+ #import <CoreImage/CoreImage.h>
4
+ #import <CoreText/CoreText.h>
5
+ #import <ImageIO/ImageIO.h>
6
+ #import <objc/message.h>
7
+ #import "core/G9ImageCore.h"
8
+
9
+ typedef void (^G9ImageReply)(NSString *json);
10
+
11
+ static NSString *const G9ImageErrorDomain = @"g9.image";
12
+
13
+ static NSError *G9ImageError(NSString *code, NSString *message) {
14
+ return [NSError errorWithDomain:G9ImageErrorDomain
15
+ code:1
16
+ userInfo:@{@"code" : code, NSLocalizedDescriptionKey : message ?: @""}];
17
+ }
18
+
19
+ static NSString *G9ImageReplyForError(NSError *error) {
20
+ NSString *code = error.userInfo[@"code"] ?: G9ImageErrorIO;
21
+ return [G9ImageCore failReply:code message:error.localizedDescription];
22
+ }
23
+
24
+ static CGAffineTransform G9CG(G9ImageAffine m) {
25
+ return CGAffineTransformMake(m.a, m.b, m.c, m.d, m.e, m.f);
26
+ }
27
+
28
+ static G9ImageAffine G9Scale(double sx, double sy) {
29
+ G9ImageAffine m = {sx, 0, 0, sy, 0, 0};
30
+ return m;
31
+ }
32
+
33
+ static CGColorSpaceRef G9SRGB(void) {
34
+ static CGColorSpaceRef space;
35
+ static dispatch_once_t once;
36
+ dispatch_once(&once, ^{
37
+ space = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
38
+ });
39
+ return space;
40
+ }
41
+
42
+ /** A CSS colour as an sRGB CGColor (+1), or NULL. */
43
+ static CGColorRef G9CreateColor(NSString *css) {
44
+ double rgba[4];
45
+ if (![G9ImageCore parseColor:css rgba:rgba]) return NULL;
46
+ CGFloat components[4] = {rgba[0], rgba[1], rgba[2], rgba[3]};
47
+ return CGColorCreate(G9SRGB(), components);
48
+ }
49
+
50
+ static void G9Fill(CGContextRef ctx, NSString *css, CGRect rect) {
51
+ CGColorRef color = G9CreateColor(css);
52
+ if (!color) return;
53
+ CGContextSetFillColorWithColor(ctx, color);
54
+ CGContextFillRect(ctx, rect);
55
+ CGColorRelease(color);
56
+ }
57
+
58
+ /** An 8-bit sRGB RGBA canvas (premultiplied), cleared; NULL when the memory is not there. */
59
+ static CGContextRef G9CreateCanvas(size_t width, size_t height) {
60
+ if (width == 0 || height == 0) return NULL;
61
+ CGContextRef ctx = CGBitmapContextCreate(NULL, width, height, 8, 0, G9SRGB(),
62
+ kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
63
+ if (ctx) CGContextClearRect(ctx, CGRectMake(0, 0, width, height));
64
+ return ctx;
65
+ }
66
+
67
+ #pragma mark - The source
68
+
69
+ /** An opened picture: its ImageIO source and what probe answers. */
70
+ @interface G9ImageSource : NSObject
71
+ @property(nonatomic) CGImageSourceRef source;
72
+ @property(nonatomic, copy) NSString *path;
73
+ @property(nonatomic, copy) NSDictionary *properties;
74
+ @property(nonatomic) double rawWidth;
75
+ @property(nonatomic) double rawHeight;
76
+ @property(nonatomic) NSInteger orientation;
77
+ @property(nonatomic, copy) NSString *mime;
78
+ @property(nonatomic) long long bytes;
79
+ @property(nonatomic) BOOL hasAlpha;
80
+ + (nullable instancetype)open:(NSString *)path error:(NSError **)error;
81
+ /** The size a person sees (the orientation applied). */
82
+ - (double)width;
83
+ - (double)height;
84
+ @end
85
+
86
+ @implementation G9ImageSource
87
+
88
+ - (void)dealloc {
89
+ if (_source) CFRelease(_source);
90
+ }
91
+
92
+ + (nullable instancetype)open:(NSString *)path error:(NSError **)error {
93
+ BOOL directory = NO;
94
+ if (![NSFileManager.defaultManager fileExistsAtPath:path isDirectory:&directory] || directory) {
95
+ if (error) *error = G9ImageError(G9ImageErrorNotFound, [NSString stringWithFormat:@"No file at %@.", path]);
96
+ return nil;
97
+ }
98
+ NSDictionary *options = @{(id)kCGImageSourceShouldCache : @(NO)};
99
+ CGImageSourceRef source = CGImageSourceCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path], (__bridge CFDictionaryRef)options);
100
+ if (!source || CGImageSourceGetCount(source) == 0) {
101
+ if (source) CFRelease(source);
102
+ if (error) *error = G9ImageError(G9ImageErrorDecode, @"The file is not a picture ImageIO can read.");
103
+ return nil;
104
+ }
105
+ G9ImageSource *s = [[G9ImageSource alloc] init];
106
+ s.source = source;
107
+ s.path = path;
108
+ s.properties = CFBridgingRelease(CGImageSourceCopyPropertiesAtIndex(source, 0, (__bridge CFDictionaryRef)options)) ?: @{};
109
+ NSNumber *w = s.properties[(id)kCGImagePropertyPixelWidth], *h = s.properties[(id)kCGImagePropertyPixelHeight];
110
+ if (w == nil || h == nil) {
111
+ // No size in the header: a lazily created image knows it without decoding.
112
+ CGImageRef image = CGImageSourceCreateImageAtIndex(source, 0, (__bridge CFDictionaryRef)options);
113
+ if (image) {
114
+ w = @(CGImageGetWidth(image));
115
+ h = @(CGImageGetHeight(image));
116
+ CGImageRelease(image);
117
+ }
118
+ }
119
+ if (w.doubleValue < 1 || h.doubleValue < 1) {
120
+ if (error) *error = G9ImageError(G9ImageErrorDecode, @"The picture has no size.");
121
+ return nil;
122
+ }
123
+ s.rawWidth = w.doubleValue;
124
+ s.rawHeight = h.doubleValue;
125
+ s.orientation = [G9ImageCore normalizedOrientation:[s.properties[(id)kCGImagePropertyOrientation] integerValue]];
126
+ s.mime = [G9ImageCore mimeForTypeIdentifier:(__bridge NSString *)CGImageSourceGetType(source)];
127
+ s.hasAlpha = [s.properties[(id)kCGImagePropertyHasAlpha] boolValue];
128
+ s.bytes = [[NSFileManager.defaultManager attributesOfItemAtPath:path error:NULL] fileSize];
129
+ return s;
130
+ }
131
+
132
+ - (double)width {
133
+ double w, h;
134
+ [G9ImageCore orientedSizeForRawWidth:_rawWidth rawHeight:_rawHeight orientation:_orientation width:&w height:&h];
135
+ return w;
136
+ }
137
+
138
+ - (double)height {
139
+ double w, h;
140
+ [G9ImageCore orientedSizeForRawWidth:_rawWidth rawHeight:_rawHeight orientation:_orientation width:&w height:&h];
141
+ return h;
142
+ }
143
+
144
+ @end
145
+
146
+ #pragma mark - Encoding
147
+
148
+ static BOOL G9WebPEncodable(void) {
149
+ static BOOL encodable;
150
+ static dispatch_once_t once;
151
+ dispatch_once(&once, ^{
152
+ NSArray *types = CFBridgingRelease(CGImageDestinationCopyTypeIdentifiers());
153
+ encodable = [types containsObject:@"org.webmproject.webp"];
154
+ });
155
+ return encodable;
156
+ }
157
+
158
+ static NSString *G9TypeForFormat(NSString *format) {
159
+ if ([format isEqualToString:@"png"]) return @"public.png";
160
+ if ([format isEqualToString:@"webp"]) return @"org.webmproject.webp";
161
+ return @"public.jpeg";
162
+ }
163
+
164
+ /** One encoding at a quality (0..100, lossy formats) with the metadata (nil = none), or nil. */
165
+ static NSData *G9Encode(CGImageRef image, NSString *format, NSInteger quality, NSDictionary *metadata) {
166
+ NSMutableData *data = [NSMutableData data];
167
+ CGImageDestinationRef destination =
168
+ CGImageDestinationCreateWithData((__bridge CFMutableDataRef)data, (__bridge CFStringRef)G9TypeForFormat(format), 1, NULL);
169
+ if (!destination) return nil;
170
+ NSMutableDictionary *properties = metadata ? [metadata mutableCopy] : [NSMutableDictionary dictionary];
171
+ if (![format isEqualToString:@"png"]) properties[(id)kCGImageDestinationLossyCompressionQuality] = @(quality / 100.0);
172
+ CGImageDestinationAddImage(destination, image, (__bridge CFDictionaryRef)properties);
173
+ BOOL ok = CGImageDestinationFinalize(destination);
174
+ CFRelease(destination);
175
+ return ok ? data : nil;
176
+ }
177
+
178
+ /** The quality search's encoder: encodes once per quality and keeps the bytes for the winner. */
179
+ @interface G9ImageEncodings : NSObject <G9ImageQualityEncoder>
180
+ @property(nonatomic) CGImageRef image;
181
+ @property(nonatomic, copy) NSString *format;
182
+ @property(nonatomic, copy, nullable) NSDictionary *metadata;
183
+ @property(nonatomic, strong) NSMutableDictionary<NSNumber *, NSData *> *results;
184
+ @end
185
+
186
+ @implementation G9ImageEncodings
187
+
188
+ - (long long)byteCountAtQuality:(NSInteger)quality {
189
+ if (!_results) _results = [NSMutableDictionary dictionary];
190
+ NSData *data = _results[@(quality)];
191
+ if (!data) {
192
+ data = G9Encode(_image, _format, quality, _metadata);
193
+ if (!data) return -1;
194
+ _results[@(quality)] = data;
195
+ }
196
+ return (long long)data.length;
197
+ }
198
+
199
+ @end
200
+
201
+ #pragma mark - Fonts
202
+
203
+ static UIFont * (^G9TextFontProvider)(CGFloat, CGFloat);
204
+
205
+ /** The host's text font: G9LCFonts.textFont through the Swift bridge, else the provider, else the system font. */
206
+ static UIFont *G9HostTextFont(CGFloat size, CGFloat weight) {
207
+ Class bridge = NSClassFromString(@"G9LCFontsBridge");
208
+ SEL selector = NSSelectorFromString(@"textFontWithSize:weight:");
209
+ if ([bridge respondsToSelector:selector]) {
210
+ UIFont *(*call)(id, SEL, CGFloat, CGFloat) = (UIFont * (*)(id, SEL, CGFloat, CGFloat)) objc_msgSend;
211
+ UIFont *font = call(bridge, selector, size, weight);
212
+ if (font) return font;
213
+ }
214
+ UIFont * (^provider)(CGFloat, CGFloat);
215
+ @synchronized([G9ImageModule class]) {
216
+ provider = G9TextFontProvider;
217
+ }
218
+ if (provider) {
219
+ UIFont *font = provider(size, weight);
220
+ if (font) return font;
221
+ }
222
+ return [UIFont systemFontOfSize:size weight:(UIFontWeight)[G9ImageCore fontWeightTraitForWeight:weight]];
223
+ }
224
+
225
+ /** `fonts/<name>.ttf|otf` or `<name>.ttf|otf` in the app bundle, registered once: its PostScript name, or nil. */
226
+ static NSString *G9BundledFontName(NSString *name) {
227
+ static NSMutableDictionary<NSString *, id> *cache;
228
+ static dispatch_once_t once;
229
+ dispatch_once(&once, ^{
230
+ cache = [NSMutableDictionary dictionary];
231
+ });
232
+ @synchronized(cache) {
233
+ id known = cache[name];
234
+ if (known) return known == [NSNull null] ? nil : known;
235
+ NSURL *url = nil;
236
+ for (NSString *ext in @[ @"ttf", @"otf" ]) {
237
+ url = [NSBundle.mainBundle URLForResource:name withExtension:ext subdirectory:@"fonts"]
238
+ ?: [NSBundle.mainBundle URLForResource:name withExtension:ext];
239
+ if (url) break;
240
+ }
241
+ NSString *postScript = nil;
242
+ if (url) {
243
+ CTFontManagerRegisterFontsForURL((__bridge CFURLRef)url, kCTFontManagerScopeProcess, NULL);
244
+ NSArray *descriptors = CFBridgingRelease(CTFontManagerCreateFontDescriptorsFromURL((__bridge CFURLRef)url));
245
+ if (descriptors.count) {
246
+ postScript = CFBridgingRelease(CTFontDescriptorCopyAttribute((__bridge CTFontDescriptorRef)descriptors.firstObject, kCTFontNameAttribute));
247
+ }
248
+ }
249
+ cache[name] = postScript ?: [NSNull null];
250
+ return postScript;
251
+ }
252
+ }
253
+
254
+ /** `font`: "" = the host's text font; else a bundled font file, a family (at the weight) or a PostScript/full name. */
255
+ static CTFontRef G9CreateFont(NSString *name, CGFloat size, CGFloat weight) {
256
+ if (name.length) {
257
+ NSString *bundled = G9BundledFontName(name);
258
+ if (bundled) return CTFontCreateWithName((__bridge CFStringRef)bundled, size, NULL);
259
+ NSDictionary *traits = @{(id)kCTFontWeightTrait : @([G9ImageCore fontWeightTraitForWeight:weight])};
260
+ NSDictionary *attributes = @{(id)kCTFontFamilyNameAttribute : name, (id)kCTFontTraitsAttribute : traits};
261
+ CTFontDescriptorRef wanted = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attributes);
262
+ NSSet *mandatory = [NSSet setWithObject:(id)kCTFontFamilyNameAttribute];
263
+ CTFontDescriptorRef match = CTFontDescriptorCreateMatchingFontDescriptor(wanted, (__bridge CFSetRef)mandatory);
264
+ CFRelease(wanted);
265
+ if (match) {
266
+ CTFontRef font = CTFontCreateWithFontDescriptor(match, size, NULL);
267
+ CFRelease(match);
268
+ if (font) return font;
269
+ }
270
+ // A PostScript or full name: Core Text falls back to another font when it does not know it, so check the answer.
271
+ CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)name, size, NULL);
272
+ if (font) {
273
+ NSString *postScript = CFBridgingRelease(CTFontCopyPostScriptName(font));
274
+ NSString *full = CFBridgingRelease(CTFontCopyFullName(font));
275
+ if ([postScript caseInsensitiveCompare:name] == NSOrderedSame || [full caseInsensitiveCompare:name] == NSOrderedSame) return font;
276
+ CFRelease(font);
277
+ }
278
+ }
279
+ return (CTFontRef)CFBridgingRetain(G9HostTextFont(size, weight));
280
+ }
281
+
282
+ #pragma mark - Drawing
283
+
284
+ /** Draws `image` (its own pixel space) through `transform` (image px → current user space), upright. */
285
+ static void G9DrawImage(CGContextRef ctx, CGImageRef image, CGAffineTransform transform) {
286
+ CGFloat w = CGImageGetWidth(image), h = CGImageGetHeight(image);
287
+ CGContextSaveGState(ctx);
288
+ CGContextConcatCTM(ctx, transform);
289
+ CGContextTranslateCTM(ctx, 0, h);
290
+ CGContextScaleCTM(ctx, 1, -1);
291
+ CGContextDrawImage(ctx, CGRectMake(0, 0, w, h), image);
292
+ CGContextRestoreGState(ctx);
293
+ }
294
+
295
+ /** One privacy region (OUTPUT px; the current CTM maps them to the canvas through `sx`, `sy`). */
296
+ static void G9Redact(CGContextRef ctx, NSDictionary *r, double specW, double specH, double sx, double sy, size_t outW,
297
+ size_t outH, CIContext *ci) {
298
+ CGRect rect = CGRectMake([r[@"x"] doubleValue], [r[@"y"] doubleValue], [r[@"width"] doubleValue], [r[@"height"] doubleValue]);
299
+ CGFloat cx = CGRectGetMidX(rect), cy = CGRectGetMidY(rect);
300
+ CGAffineTransform turn = CGAffineTransformMakeTranslation(cx, cy);
301
+ turn = CGAffineTransformRotate(turn, [r[@"angle"] doubleValue] * M_PI / 180.0);
302
+ turn = CGAffineTransformTranslate(turn, -cx, -cy);
303
+ CGPathRef shape = CGPathCreateWithRect(rect, &turn);
304
+ CGRect device = CGRectApplyAffineTransform(CGPathGetBoundingBox(shape), CGAffineTransformMakeScale(sx, sy));
305
+ device = CGRectIntersection(CGRectIntegral(device), CGRectMake(0, 0, outW, outH));
306
+ if (CGRectIsEmpty(device)) {
307
+ CGPathRelease(shape);
308
+ return;
309
+ }
310
+ double scale = MIN(sx, sy), strength = [r[@"strength"] doubleValue];
311
+ CGImageRef snapshot = CGBitmapContextCreateImage(ctx);
312
+ if (!snapshot) {
313
+ CGPathRelease(shape);
314
+ return;
315
+ }
316
+ CIImage *input = [CIImage imageWithCGImage:snapshot];
317
+ // Core Image counts y from the bottom.
318
+ CGRect ciBox = CGRectMake(device.origin.x, outH - CGRectGetMaxY(device), device.size.width, device.size.height);
319
+ CIImage *output = nil;
320
+ if ([r[@"mode"] isEqualToString:@"blur"]) {
321
+ double radius = [G9ImageCore blurRadiusForStrength:strength width:specW height:specH] * scale;
322
+ CGRect around = CGRectIntersection(CGRectInset(ciBox, -3 * radius, -3 * radius), input.extent);
323
+ CIFilter *blur = [CIFilter filterWithName:@"CIGaussianBlur"];
324
+ [blur setValue:[[input imageByCroppingToRect:around] imageByClampingToExtent] forKey:kCIInputImageKey];
325
+ [blur setValue:@(radius) forKey:kCIInputRadiusKey];
326
+ output = [blur.outputImage imageByCroppingToRect:ciBox];
327
+ } else {
328
+ double block = [G9ImageCore pixelateBlockForStrength:strength width:specW height:specH] * scale;
329
+ CIFilter *pixellate = [CIFilter filterWithName:@"CIPixellate"];
330
+ [pixellate setValue:[input imageByClampingToExtent] forKey:kCIInputImageKey];
331
+ [pixellate setValue:@(block) forKey:kCIInputScaleKey];
332
+ // The blocks line up with the region's centre.
333
+ [pixellate setValue:[CIVector vectorWithX:cx * sx Y:outH - cy * sy] forKey:kCIInputCenterKey];
334
+ output = [pixellate.outputImage imageByCroppingToRect:ciBox];
335
+ }
336
+ CGImageRef patch = output ? [ci createCGImage:output fromRect:ciBox format:kCIFormatRGBA8 colorSpace:G9SRGB()] : NULL;
337
+ CGImageRelease(snapshot);
338
+ if (patch) {
339
+ CGContextSaveGState(ctx);
340
+ CGContextAddPath(ctx, shape);
341
+ CGContextClip(ctx);
342
+ CGAffineTransform place = CGAffineTransformMake(1 / sx, 0, 0, 1 / sy, device.origin.x / sx, device.origin.y / sy);
343
+ CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
344
+ G9DrawImage(ctx, patch, place);
345
+ CGContextRestoreGState(ctx);
346
+ CGImageRelease(patch);
347
+ }
348
+ CGPathRelease(shape);
349
+ }
350
+
351
+ static CGPathRef G9CreatePath(NSString *d) {
352
+ NSData *data = [G9ImageCore pathSegmentsFromData:d];
353
+ const G9PathSegment *segments = data.bytes;
354
+ NSUInteger count = data.length / sizeof(G9PathSegment);
355
+ CGMutablePathRef path = CGPathCreateMutable();
356
+ for (NSUInteger i = 0; i < count; i++) {
357
+ const double *p = segments[i].p;
358
+ BOOL empty = CGPathIsEmpty(path);
359
+ switch (segments[i].op) {
360
+ case G9PathMove:
361
+ CGPathMoveToPoint(path, NULL, p[0], p[1]);
362
+ break;
363
+ case G9PathLine:
364
+ if (empty) CGPathMoveToPoint(path, NULL, 0, 0);
365
+ CGPathAddLineToPoint(path, NULL, p[0], p[1]);
366
+ break;
367
+ case G9PathCubic:
368
+ if (empty) CGPathMoveToPoint(path, NULL, 0, 0);
369
+ CGPathAddCurveToPoint(path, NULL, p[0], p[1], p[2], p[3], p[4], p[5]);
370
+ break;
371
+ case G9PathQuad:
372
+ if (empty) CGPathMoveToPoint(path, NULL, 0, 0);
373
+ CGPathAddQuadCurveToPoint(path, NULL, p[0], p[1], p[2], p[3]);
374
+ break;
375
+ case G9PathClose:
376
+ if (!empty) CGPathCloseSubpath(path);
377
+ break;
378
+ }
379
+ }
380
+ return path;
381
+ }
382
+
383
+ static void G9DrawPathOp(CGContextRef ctx, NSDictionary *op) {
384
+ CGPathRef path = G9CreatePath(op[@"d"]);
385
+ if (CGPathIsEmpty(path)) {
386
+ CGPathRelease(path);
387
+ return;
388
+ }
389
+ double opacity = [op[@"opacity"] doubleValue];
390
+ CGContextSaveGState(ctx);
391
+ CGContextConcatCTM(ctx, G9CG([G9ImageCore affineFromArray:op[@"transform"]]));
392
+ CGContextSetAlpha(ctx, opacity);
393
+ // One layer, so a stroke over its own fill is not doubled by the opacity.
394
+ CGContextBeginTransparencyLayer(ctx, NULL);
395
+ CGColorRef fill = G9CreateColor(op[@"fill"]);
396
+ if (fill) {
397
+ CGContextAddPath(ctx, path);
398
+ CGContextSetFillColorWithColor(ctx, fill);
399
+ CGContextFillPath(ctx);
400
+ CGColorRelease(fill);
401
+ }
402
+ CGColorRef stroke = G9CreateColor(op[@"stroke"]);
403
+ double width = [op[@"width"] doubleValue];
404
+ if (stroke && width > 0) {
405
+ CGContextAddPath(ctx, path);
406
+ CGContextSetStrokeColorWithColor(ctx, stroke);
407
+ CGContextSetLineWidth(ctx, width);
408
+ NSString *cap = op[@"cap"], *join = op[@"join"];
409
+ CGContextSetLineCap(ctx, [cap isEqualToString:@"round"] ? kCGLineCapRound : [cap isEqualToString:@"square"] ? kCGLineCapSquare : kCGLineCapButt);
410
+ CGContextSetLineJoin(ctx, [join isEqualToString:@"round"] ? kCGLineJoinRound : [join isEqualToString:@"bevel"] ? kCGLineJoinBevel : kCGLineJoinMiter);
411
+ NSArray *dash = op[@"dash"];
412
+ if (dash.count) {
413
+ CGFloat *lengths = calloc(dash.count, sizeof(CGFloat));
414
+ CGFloat total = 0;
415
+ for (NSUInteger i = 0; i < dash.count; i++) total += (lengths[i] = [dash[i] doubleValue]);
416
+ if (total > 0) CGContextSetLineDash(ctx, 0, lengths, dash.count);
417
+ free(lengths);
418
+ }
419
+ CGContextStrokePath(ctx);
420
+ }
421
+ if (stroke) CGColorRelease(stroke);
422
+ CGContextEndTransparencyLayer(ctx);
423
+ CGContextRestoreGState(ctx);
424
+ CGPathRelease(path);
425
+ }
426
+
427
+ /** A text block centred at (x, y), turned `angle` degrees about its centre, on a rounded background with padding. */
428
+ static void G9DrawTextOp(CGContextRef ctx, NSDictionary *op) {
429
+ NSString *text = op[@"text"];
430
+ if (text.length == 0) return;
431
+ CGFloat size = [op[@"size"] doubleValue], padding = [op[@"padding"] doubleValue], radius = [op[@"radius"] doubleValue];
432
+ CGFloat maxWidth = [op[@"maxWidth"] doubleValue];
433
+ BOOL rtl = [op[@"rtl"] boolValue];
434
+ NSString *align = op[@"align"];
435
+ CTTextAlignment alignment = kCTTextAlignmentCenter;
436
+ if ([align isEqualToString:@"left"]) alignment = kCTTextAlignmentLeft;
437
+ else if ([align isEqualToString:@"right"]) alignment = kCTTextAlignmentRight;
438
+ else if ([align isEqualToString:@"start"]) alignment = rtl ? kCTTextAlignmentRight : kCTTextAlignmentLeft;
439
+ else if ([align isEqualToString:@"end"]) alignment = rtl ? kCTTextAlignmentLeft : kCTTextAlignmentRight;
440
+ CTWritingDirection direction = rtl ? kCTWritingDirectionRightToLeft : kCTWritingDirectionLeftToRight;
441
+ // Every line is 1.25 × size tall (the shared default), the glyphs centred in it like CSS line-height.
442
+ CGFloat lineHeight = [G9ImageCore lineHeightForSize:size];
443
+ CTParagraphStyleSetting settings[4] = {
444
+ {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment},
445
+ {kCTParagraphStyleSpecifierBaseWritingDirection, sizeof(direction), &direction},
446
+ {kCTParagraphStyleSpecifierMinimumLineHeight, sizeof(lineHeight), &lineHeight},
447
+ {kCTParagraphStyleSpecifierMaximumLineHeight, sizeof(lineHeight), &lineHeight},
448
+ };
449
+ CTParagraphStyleRef paragraph = CTParagraphStyleCreate(settings, 4);
450
+ CTFontRef font = G9CreateFont(op[@"font"], size, [op[@"weight"] doubleValue]);
451
+ CGFloat baselineOffset = (lineHeight - (CTFontGetAscent(font) + CTFontGetDescent(font))) / 2;
452
+ CGColorRef color = G9CreateColor(op[@"color"]);
453
+ NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
454
+ attributes[(id)kCTFontAttributeName] = (__bridge id)font;
455
+ attributes[(id)kCTParagraphStyleAttributeName] = (__bridge id)paragraph;
456
+ attributes[(id)kCTBaselineOffsetAttributeName] = @(baselineOffset);
457
+ if (color) attributes[(id)kCTForegroundColorAttributeName] = (__bridge id)color;
458
+ // Core Text shapes Arabic script (joining, ligatures) and orders the runs by the bidi algorithm from this direction.
459
+ NSAttributedString *string = [[NSAttributedString alloc] initWithString:text attributes:attributes];
460
+ CTFramesetterRef setter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)string);
461
+ CGSize limit = CGSizeMake(maxWidth > 0 ? maxWidth : CGFLOAT_MAX, CGFLOAT_MAX);
462
+ CGSize fit = CTFramesetterSuggestFrameSizeWithConstraints(setter, CFRangeMake(0, 0), NULL, limit, NULL);
463
+ CGFloat tw = ceil(fit.width), th = ceil(fit.height);
464
+ CGFloat bw = tw + 2 * padding, bh = th + 2 * padding;
465
+
466
+ CGContextSaveGState(ctx);
467
+ CGContextTranslateCTM(ctx, [op[@"x"] doubleValue], [op[@"y"] doubleValue]);
468
+ CGContextRotateCTM(ctx, [op[@"angle"] doubleValue] * M_PI / 180.0);
469
+ CGContextSetAlpha(ctx, [op[@"opacity"] doubleValue]);
470
+ CGContextBeginTransparencyLayer(ctx, NULL);
471
+ CGColorRef background = G9CreateColor(op[@"background"]);
472
+ if (background) {
473
+ CGRect box = CGRectMake(-bw / 2, -bh / 2, bw, bh);
474
+ CGFloat rx = MIN(radius, bw / 2), ry = MIN(radius, bh / 2);
475
+ CGPathRef rounded = CGPathCreateWithRoundedRect(box, rx, ry, NULL);
476
+ CGContextAddPath(ctx, rounded);
477
+ CGContextSetFillColorWithColor(ctx, background);
478
+ CGContextFillPath(ctx);
479
+ CGPathRelease(rounded);
480
+ CGColorRelease(background);
481
+ }
482
+ // Core Text draws y-up: from the text box's bottom-left corner.
483
+ CGContextTranslateCTM(ctx, -tw / 2, th / 2);
484
+ CGContextScaleCTM(ctx, 1, -1);
485
+ CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
486
+ CGPathRef framePath = CGPathCreateWithRect(CGRectMake(0, 0, tw, th), NULL);
487
+ CTFrameRef frame = CTFramesetterCreateFrame(setter, CFRangeMake(0, 0), framePath, NULL);
488
+ CTFrameDraw(frame, ctx);
489
+ CFRelease(frame);
490
+ CGPathRelease(framePath);
491
+ CGContextEndTransparencyLayer(ctx);
492
+ CGContextRestoreGState(ctx);
493
+
494
+ CFRelease(setter);
495
+ if (color) CGColorRelease(color);
496
+ CFRelease(font);
497
+ CFRelease(paragraph);
498
+ }
499
+
500
+ #pragma mark - The service
501
+
502
+ @interface G9ImageService : NSObject
503
+ @property(nonatomic, readonly) dispatch_queue_t queue;
504
+ @property(nonatomic, readonly) G9ImageCancelRegistry *tokens;
505
+ + (instancetype)shared;
506
+ - (nullable NSDictionary *)probe:(NSDictionary *)args error:(NSError **)error;
507
+ - (nullable NSDictionary *)preview:(NSDictionary *)args error:(NSError **)error;
508
+ - (nullable NSDictionary *)process:(NSDictionary *)spec error:(NSError **)error;
509
+ @end
510
+
511
+ @implementation G9ImageService {
512
+ CIContext *_ci;
513
+ }
514
+
515
+ + (instancetype)shared {
516
+ static G9ImageService *service;
517
+ static dispatch_once_t once;
518
+ dispatch_once(&once, ^{
519
+ service = [[G9ImageService alloc] init];
520
+ });
521
+ return service;
522
+ }
523
+
524
+ - (instancetype)init {
525
+ if ((self = [super init])) {
526
+ _queue = dispatch_queue_create("g9.image", DISPATCH_QUEUE_SERIAL);
527
+ _tokens = [[G9ImageCancelRegistry alloc] init];
528
+ }
529
+ return self;
530
+ }
531
+
532
+ /** Core Image for the redactions (used on the serial queue only), sRGB in and out. */
533
+ - (CIContext *)ci {
534
+ if (!_ci) {
535
+ _ci = [CIContext contextWithOptions:@{
536
+ kCIContextWorkingColorSpace : (__bridge id)G9SRGB(),
537
+ kCIContextOutputColorSpace : (__bridge id)G9SRGB(),
538
+ }];
539
+ }
540
+ return _ci;
541
+ }
542
+
543
+ - (NSString *)directoryFor:(nullable NSString *)dir error:(NSError **)error {
544
+ NSString *folder = dir;
545
+ if (folder.length == 0) {
546
+ NSString *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject ?: NSTemporaryDirectory();
547
+ folder = [caches stringByAppendingPathComponent:@"g9photo"];
548
+ }
549
+ NSError *e = nil;
550
+ if (![NSFileManager.defaultManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:&e]) {
551
+ if (error) *error = G9ImageError(G9ImageErrorIO, e.localizedDescription ?: @"The folder could not be created.");
552
+ return nil;
553
+ }
554
+ return folder;
555
+ }
556
+
557
+ - (NSString *)baseName:(nullable NSString *)name {
558
+ if (name.length) return name;
559
+ long long now = (long long)([NSDate date].timeIntervalSince1970 * 1000);
560
+ return [G9ImageCore defaultNameForEpochMs:now random:arc4random()];
561
+ }
562
+
563
+ - (BOOL)write:(NSData *)data to:(NSString *)path error:(NSError **)error {
564
+ NSError *e = nil;
565
+ if ([data writeToFile:path options:NSDataWritingAtomic error:&e]) return YES;
566
+ if (error) *error = G9ImageError(G9ImageErrorIO, e.localizedDescription ?: @"The file could not be written.");
567
+ return NO;
568
+ }
569
+
570
+ #pragma mark probe / preview
571
+
572
+ - (NSDictionary *)probe:(NSDictionary *)args error:(NSError **)error {
573
+ G9ImageSource *s = [G9ImageSource open:args[@"path"] error:error];
574
+ if (!s) return nil;
575
+ return @{
576
+ @"width" : @((long long)s.width),
577
+ @"height" : @((long long)s.height),
578
+ @"orientation" : @(s.orientation),
579
+ @"mime" : s.mime,
580
+ @"bytes" : @(s.bytes),
581
+ @"hasAlpha" : @(s.hasAlpha),
582
+ };
583
+ }
584
+
585
+ - (NSDictionary *)preview:(NSDictionary *)args error:(NSError **)error {
586
+ G9ImageSource *s = [G9ImageSource open:args[@"path"] error:error];
587
+ if (!s) return nil;
588
+ NSInteger maxPixel = [G9ImageCore previewMaxPixelForMaxSide:[args[@"maxSide"] integerValue] width:s.width height:s.height];
589
+ NSDictionary *options = @{
590
+ (id)kCGImageSourceCreateThumbnailFromImageAlways : @(YES),
591
+ (id)kCGImageSourceCreateThumbnailWithTransform : @(YES),
592
+ (id)kCGImageSourceThumbnailMaxPixelSize : @(maxPixel),
593
+ (id)kCGImageSourceShouldCacheImmediately : @(YES),
594
+ };
595
+ CGImageRef thumb = CGImageSourceCreateThumbnailAtIndex(s.source, 0, (__bridge CFDictionaryRef)options);
596
+ if (!thumb) {
597
+ if (error) *error = G9ImageError(G9ImageErrorDecode, @"The picture could not be decoded.");
598
+ return nil;
599
+ }
600
+ // Redrawn into sRGB (a Display P3 HEIC thumbnail stays in its own space otherwise).
601
+ size_t w = CGImageGetWidth(thumb), h = CGImageGetHeight(thumb);
602
+ CGContextRef ctx = G9CreateCanvas(w, h);
603
+ if (!ctx) {
604
+ CGImageRelease(thumb);
605
+ if (error) *error = G9ImageError(G9ImageErrorMemory, @"Not enough memory for the preview.");
606
+ return nil;
607
+ }
608
+ if (!s.hasAlpha) G9Fill(ctx, @"#ffffff", CGRectMake(0, 0, w, h));
609
+ CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
610
+ CGContextDrawImage(ctx, CGRectMake(0, 0, w, h), thumb);
611
+ CGImageRelease(thumb);
612
+ CGImageRef image = CGBitmapContextCreateImage(ctx);
613
+ CGContextRelease(ctx);
614
+ NSString *format = s.hasAlpha ? @"png" : @"jpeg";
615
+ NSData *data = image ? G9Encode(image, format, 85, nil) : nil;
616
+ CGImageRelease(image);
617
+ if (!data) {
618
+ if (error) *error = G9ImageError(G9ImageErrorIO, @"The preview could not be encoded.");
619
+ return nil;
620
+ }
621
+ NSString *folder = [self directoryFor:args[@"dir"] error:error];
622
+ if (!folder) return nil;
623
+ NSString *path = [G9ImageCore uniquePathInDirectory:folder base:[self baseName:nil] extension:[G9ImageCore extensionForFormat:format]];
624
+ if (![self write:data to:path error:error]) return nil;
625
+ return @{
626
+ @"path" : path,
627
+ @"width" : @(w),
628
+ @"height" : @(h),
629
+ @"sourceWidth" : @((long long)s.width),
630
+ @"sourceHeight" : @((long long)s.height),
631
+ };
632
+ }
633
+
634
+ #pragma mark process
635
+
636
+ - (BOOL)cancelled:(nullable NSString *)token error:(NSError **)error {
637
+ if (![self.tokens isCancelled:token]) return NO;
638
+ if (error) *error = G9ImageError(G9ImageErrorCancelled, @"Cancelled.");
639
+ return YES;
640
+ }
641
+
642
+ /**
643
+ * Pipeline steps 2–5 at `outW` × `outH` (the spec's own size, or smaller after a maxBytes or memory step: the spec's
644
+ * coordinates are scaled onto it). Returns a +1 image, or NULL with `error`.
645
+ */
646
+ - (CGImageRef)render:(G9ImageSource *)s
647
+ spec:(NSDictionary *)spec
648
+ width:(size_t)outW
649
+ height:(size_t)outH
650
+ alpha:(BOOL)alpha
651
+ error:(NSError **)error {
652
+ double specW = [spec[@"width"] doubleValue], specH = [spec[@"height"] doubleValue];
653
+ double sx = outW / specW, sy = outH / specH;
654
+ // canvas px → oriented source px
655
+ G9ImageAffine toOriented = G9ImageAffineConcat([G9ImageCore affineFromArray:spec[@"matrix"]], G9Scale(1 / sx, 1 / sy));
656
+ G9ImageBox box = [G9ImageCore rawBoxForOutputWidth:outW
657
+ height:outH
658
+ matrix:toOriented
659
+ orientation:s.orientation
660
+ rawWidth:s.rawWidth
661
+ rawHeight:s.rawHeight
662
+ margin:2];
663
+ CGContextRef ctx = G9CreateCanvas(outW, outH);
664
+ if (!ctx) {
665
+ if (error) *error = G9ImageError(G9ImageErrorMemory, @"Not enough memory for the output.");
666
+ return NULL;
667
+ }
668
+ CGRect canvas = CGRectMake(0, 0, outW, outH);
669
+ // y down from the top-left, like the contract's pixels
670
+ CGContextTranslateCTM(ctx, 0, outH);
671
+ CGContextScaleCTM(ctx, 1, -1);
672
+ NSString *background = spec[@"background"];
673
+ if (background) G9Fill(ctx, background, canvas);
674
+ else if (!alpha) G9Fill(ctx, @"#ffffff", canvas);
675
+
676
+ if (box.width > 0 && box.height > 0) {
677
+ NSInteger sample = [G9ImageCore subsampleForSourcePerOutput:[G9ImageCore sourcePixelsPerOutputPixel:toOriented]];
678
+ NSMutableDictionary *options = [@{(id)kCGImageSourceShouldCache : @(NO)} mutableCopy];
679
+ if (sample > 1) options[(id)kCGImageSourceSubsampleFactor] = @(sample);
680
+ CGImageRef full = CGImageSourceCreateImageAtIndex(s.source, 0, (__bridge CFDictionaryRef)options);
681
+ if (!full) {
682
+ CGContextRelease(ctx);
683
+ if (error) *error = G9ImageError(G9ImageErrorDecode, @"The picture could not be decoded.");
684
+ return NULL;
685
+ }
686
+ // ImageIO subsamples only some formats: measure what came back.
687
+ double fw = CGImageGetWidth(full), fh = CGImageGetHeight(full);
688
+ double kx = fw / s.rawWidth, ky = fh / s.rawHeight;
689
+ double rx = floor(box.x * kx), ry = floor(box.y * ky);
690
+ double rw = MIN(fw, ceil((box.x + box.width) * kx)) - rx, rh = MIN(fh, ceil((box.y + box.height) * ky)) - ry;
691
+ CGImageRef region = (rx == 0 && ry == 0 && rw == fw && rh == fh) ? CGImageRetain(full)
692
+ : CGImageCreateWithImageInRect(full, CGRectMake(rx, ry, rw, rh));
693
+ CGImageRelease(full);
694
+ if (!region) {
695
+ CGContextRelease(ctx);
696
+ if (error) *error = G9ImageError(G9ImageErrorDecode, @"The picture's region could not be decoded.");
697
+ return NULL;
698
+ }
699
+ // region px → raw px → oriented px → canvas px: the orientation applied once, inside this one matrix.
700
+ G9ImageAffine regionToRaw = {1 / kx, 0, 0, 1 / ky, rx / kx, ry / ky};
701
+ G9ImageAffine rawToOriented = G9ImageAffineInvert(
702
+ [G9ImageCore orientedToRawForOrientation:s.orientation rawWidth:s.rawWidth rawHeight:s.rawHeight], NULL);
703
+ G9ImageAffine orientedToCanvas = G9ImageAffineInvert(toOriented, NULL);
704
+ G9ImageAffine total = G9ImageAffineConcat(orientedToCanvas, G9ImageAffineConcat(rawToOriented, regionToRaw));
705
+ CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
706
+ G9DrawImage(ctx, region, G9CG(total));
707
+ CGImageRelease(region);
708
+ }
709
+
710
+ // Redactions, then the overlay, in the spec's OUTPUT px.
711
+ CGContextSaveGState(ctx);
712
+ CGContextScaleCTM(ctx, sx, sy);
713
+ for (NSDictionary *r in spec[@"redact"]) {
714
+ @autoreleasepool {
715
+ G9Redact(ctx, r, specW, specH, sx, sy, outW, outH, self.ci);
716
+ }
717
+ }
718
+ for (NSDictionary *op in spec[@"overlay"]) {
719
+ @autoreleasepool {
720
+ if ([op[@"k"] isEqualToString:@"text"]) G9DrawTextOp(ctx, op);
721
+ else G9DrawPathOp(ctx, op);
722
+ }
723
+ }
724
+ CGContextRestoreGState(ctx);
725
+
726
+ // The circle: outside the inscribed ellipse is transparent (alpha formats) or the background (JPEG).
727
+ if ([spec[@"circle"] boolValue]) {
728
+ CGContextSaveGState(ctx);
729
+ CGContextAddRect(ctx, canvas);
730
+ CGContextAddEllipseInRect(ctx, canvas);
731
+ CGContextEOClip(ctx);
732
+ if (alpha) CGContextClearRect(ctx, canvas);
733
+ else G9Fill(ctx, background ?: @"#ffffff", canvas);
734
+ CGContextRestoreGState(ctx);
735
+ }
736
+ CGImageRef image = CGBitmapContextCreateImage(ctx);
737
+ CGContextRelease(ctx);
738
+ if (!image && error) *error = G9ImageError(G9ImageErrorMemory, @"Not enough memory for the output.");
739
+ return image;
740
+ }
741
+
742
+ - (NSDictionary *)passthrough:(G9ImageSource *)s spec:(NSDictionary *)spec error:(NSError **)error {
743
+ NSString *token = spec[@"token"];
744
+ NSString *format = [G9ImageCore formatForMime:s.mime];
745
+ NSString *extension = s.path.pathExtension.lowercaseString;
746
+ if (extension.length == 0) extension = format ? [G9ImageCore extensionForFormat:format] : @"img";
747
+ NSString *folder = [self directoryFor:spec[@"dir"] error:error];
748
+ if (!folder) return nil;
749
+ NSString *path = [G9ImageCore uniquePathInDirectory:folder base:[self baseName:spec[@"name"]] extension:extension];
750
+ NSError *e = nil;
751
+ if (![NSFileManager.defaultManager copyItemAtPath:s.path toPath:path error:&e]) {
752
+ if (error) *error = G9ImageError(G9ImageErrorIO, e.localizedDescription ?: @"The file could not be copied.");
753
+ return nil;
754
+ }
755
+ if ([self cancelled:token error:error]) {
756
+ [NSFileManager.defaultManager removeItemAtPath:path error:NULL];
757
+ return nil;
758
+ }
759
+ return @{
760
+ @"path" : path,
761
+ @"mime" : s.mime,
762
+ @"width" : @((long long)s.width),
763
+ @"height" : @((long long)s.height),
764
+ @"bytes" : @(s.bytes),
765
+ @"quality" : [NSNull null],
766
+ @"format" : format ?: extension,
767
+ @"downscaled" : @(NO),
768
+ };
769
+ }
770
+
771
+ - (NSDictionary *)process:(NSDictionary *)spec error:(NSError **)error {
772
+ NSString *token = spec[@"token"];
773
+ if ([self cancelled:token error:error]) return nil;
774
+ G9ImageSource *s = [G9ImageSource open:spec[@"path"] error:error];
775
+ if (!s) return nil;
776
+ if ([spec[@"passthrough"] boolValue]) return [self passthrough:s spec:spec error:error];
777
+
778
+ NSString *format = [G9ImageCore outputFormatForRequested:spec[@"format"] sourceMime:s.mime hasAlpha:s.hasAlpha webpEncodable:G9WebPEncodable()];
779
+ BOOL alpha = [G9ImageCore formatHasAlpha:format], lossy = ![format isEqualToString:@"png"];
780
+ NSInteger quality = [spec[@"quality"] integerValue];
781
+ long long maxBytes = [spec[@"maxBytes"] longLongValue];
782
+ NSDictionary *metadata = [spec[@"keepMetadata"] boolValue] ? [G9ImageCore outputMetadataFromSourceProperties:s.properties] : nil;
783
+ NSInteger outW = [spec[@"width"] integerValue], outH = [spec[@"height"] integerValue];
784
+ BOOL downscaled = NO, memoryRetried = NO;
785
+ NSData *data = nil;
786
+ NSInteger usedQuality = quality;
787
+
788
+ for (;;) {
789
+ if ([self cancelled:token error:error]) return nil;
790
+ NSError *renderError = nil;
791
+ CGImageRef image = NULL;
792
+ @autoreleasepool {
793
+ image = [self render:s spec:spec width:outW height:outH alpha:alpha error:&renderError];
794
+ }
795
+ if (!image) {
796
+ // Out of memory: once more at half the size, then `memory`.
797
+ if ([renderError.userInfo[@"code"] isEqualToString:G9ImageErrorMemory] && !memoryRetried && (outW > 1 || outH > 1)) {
798
+ memoryRetried = YES;
799
+ downscaled = YES;
800
+ outW = MAX(1, outW / 2);
801
+ outH = MAX(1, outH / 2);
802
+ continue;
803
+ }
804
+ if (error) *error = renderError;
805
+ return nil;
806
+ }
807
+ if ([self cancelled:token error:error]) {
808
+ CGImageRelease(image);
809
+ return nil;
810
+ }
811
+ BOOL fits = YES;
812
+ if (maxBytes <= 0) {
813
+ data = G9Encode(image, format, quality, metadata);
814
+ } else if (lossy) {
815
+ // The quality search (floor 30), then 0.85 scale steps.
816
+ G9ImageEncodings *encodings = [[G9ImageEncodings alloc] init];
817
+ encodings.image = image;
818
+ encodings.format = format;
819
+ encodings.metadata = metadata;
820
+ NSInteger floorQuality = [G9ImageCore qualityFloorForQuality:quality];
821
+ NSInteger best = [G9ImageCore qualityForMaxBytes:maxBytes start:quality floor:floorQuality encoder:encodings attempts:NULL];
822
+ fits = best >= 0;
823
+ if (fits) {
824
+ data = encodings.results[@(best)];
825
+ usedQuality = best;
826
+ }
827
+ } else {
828
+ data = G9Encode(image, format, quality, metadata);
829
+ fits = data == nil || (long long)data.length <= maxBytes;
830
+ }
831
+ CGImageRelease(image);
832
+ if (fits) break;
833
+ data = nil;
834
+ // Give up once the shorter side would drop below 16 px: the limit cannot be met, and no file is written.
835
+ if (![G9ImageCore canScaleWidth:outW height:outH]) {
836
+ if (error) {
837
+ *error = G9ImageError(G9ImageErrorInvalidArgument,
838
+ [NSString stringWithFormat:@"maxBytes %lld cannot be met: the output stays larger down to "
839
+ @"quality %ld and a %ld × %ld size.",
840
+ maxBytes, (long)[G9ImageCore qualityFloorForQuality:quality], (long)outW, (long)outH]);
841
+ }
842
+ return nil;
843
+ }
844
+ outW = [G9ImageCore scaledDimension:outW];
845
+ outH = [G9ImageCore scaledDimension:outH];
846
+ downscaled = YES;
847
+ }
848
+ if (!data) {
849
+ if (error) *error = G9ImageError(G9ImageErrorIO, @"The picture could not be encoded.");
850
+ return nil;
851
+ }
852
+ if ([self cancelled:token error:error]) return nil;
853
+ NSString *folder = [self directoryFor:spec[@"dir"] error:error];
854
+ if (!folder) return nil;
855
+ NSString *path = [G9ImageCore uniquePathInDirectory:folder base:[self baseName:spec[@"name"]] extension:[G9ImageCore extensionForFormat:format]];
856
+ if (![self write:data to:path error:error]) return nil;
857
+ if ([self cancelled:token error:error]) {
858
+ [NSFileManager.defaultManager removeItemAtPath:path error:NULL];
859
+ return nil;
860
+ }
861
+ return @{
862
+ @"path" : path,
863
+ @"mime" : [G9ImageCore mimeForFormat:format],
864
+ @"width" : @(outW),
865
+ @"height" : @(outH),
866
+ @"bytes" : @(data.length),
867
+ @"quality" : lossy ? (id)@(usedQuality) : (id)[NSNull null],
868
+ @"format" : format,
869
+ @"downscaled" : @(downscaled),
870
+ };
871
+ }
872
+
873
+ @end
874
+
875
+ #pragma mark - The module
876
+
877
+ @implementation G9ImageModule
878
+
879
+ + (NSString *)name {
880
+ return @"G9ImageModule";
881
+ }
882
+
883
+ + (NSDictionary<NSString *, NSString *> *)methodLookup {
884
+ return @{
885
+ @"probe" : NSStringFromSelector(@selector(probe:callback:)),
886
+ @"preview" : NSStringFromSelector(@selector(preview:callback:)),
887
+ @"process" : NSStringFromSelector(@selector(process:callback:)),
888
+ @"cancel" : NSStringFromSelector(@selector(cancel:callback:)),
889
+ };
890
+ }
891
+
892
+ + (void)setTextFontProvider:(UIFont * (^)(CGFloat size, CGFloat weight))provider {
893
+ @synchronized([G9ImageModule class]) {
894
+ G9TextFontProvider = [provider copy];
895
+ }
896
+ Class bridge = NSClassFromString(@"G9LCFontsBridge");
897
+ SEL selector = NSSelectorFromString(@"setTextFont:");
898
+ if ([bridge respondsToSelector:selector]) {
899
+ void (*call)(id, SEL, id) = (void (*)(id, SEL, id))objc_msgSend;
900
+ call(bridge, selector, provider);
901
+ }
902
+ }
903
+
904
+ /** Validates on the caller's thread, works on the serial queue, answers one JSON string. */
905
+ - (void)submit:(NSString *)json
906
+ callback:(id)callback
907
+ validate:(NSDictionary * (^)(id args, NSString **message))validate
908
+ work:(NSDictionary * (^)(NSDictionary *args, NSError **error))work
909
+ token:(BOOL)tracksToken {
910
+ G9ImageReply reply = [(G9ImageReply)callback copy];
911
+ NSString *message = nil;
912
+ NSDictionary *args = validate([G9ImageCore objectFromJSON:json], &message);
913
+ if (!args) {
914
+ if (reply) reply([G9ImageCore failReply:G9ImageErrorInvalidArgument message:message ?: @"Invalid argument."]);
915
+ return;
916
+ }
917
+ G9ImageService *service = [G9ImageService shared];
918
+ NSString *token = tracksToken ? args[@"token"] : nil;
919
+ [service.tokens begin:token];
920
+ dispatch_async(service.queue, ^{
921
+ NSString *answer;
922
+ @autoreleasepool {
923
+ NSError *error = nil;
924
+ NSDictionary *value = nil;
925
+ @try {
926
+ value = work(args, &error);
927
+ } @catch (NSException *exception) {
928
+ error = G9ImageError(G9ImageErrorIO, exception.reason);
929
+ }
930
+ answer = value ? [G9ImageCore okReply:value] : G9ImageReplyForError(error ?: G9ImageError(G9ImageErrorIO, @"Failed."));
931
+ }
932
+ [service.tokens end:token];
933
+ if (reply) reply(answer);
934
+ });
935
+ }
936
+
937
+ - (void)probe:(NSString *)json callback:(id)callback {
938
+ [self submit:json
939
+ callback:callback
940
+ validate:^NSDictionary *(id args, NSString **message) {
941
+ return [G9ImageCore validateProbeArguments:args message:message];
942
+ }
943
+ work:^NSDictionary *(NSDictionary *args, NSError **error) {
944
+ return [[G9ImageService shared] probe:args error:error];
945
+ }
946
+ token:NO];
947
+ }
948
+
949
+ - (void)preview:(NSString *)json callback:(id)callback {
950
+ [self submit:json
951
+ callback:callback
952
+ validate:^NSDictionary *(id args, NSString **message) {
953
+ return [G9ImageCore validatePreviewArguments:args message:message];
954
+ }
955
+ work:^NSDictionary *(NSDictionary *args, NSError **error) {
956
+ return [[G9ImageService shared] preview:args error:error];
957
+ }
958
+ token:NO];
959
+ }
960
+
961
+ - (void)process:(NSString *)json callback:(id)callback {
962
+ [self submit:json
963
+ callback:callback
964
+ validate:^NSDictionary *(id args, NSString **message) {
965
+ return [G9ImageCore validateProcessSpec:args message:message];
966
+ }
967
+ work:^NSDictionary *(NSDictionary *args, NSError **error) {
968
+ return [[G9ImageService shared] process:args error:error];
969
+ }
970
+ token:YES];
971
+ }
972
+
973
+ /** Answers at once (not behind the work it stops): `{}`. */
974
+ - (void)cancel:(NSString *)json callback:(id)callback {
975
+ G9ImageReply reply = [(G9ImageReply)callback copy];
976
+ NSString *message = nil;
977
+ NSDictionary *args = [G9ImageCore validateCancelArguments:[G9ImageCore objectFromJSON:json] message:&message];
978
+ if (!args) {
979
+ if (reply) reply([G9ImageCore failReply:G9ImageErrorInvalidArgument message:message]);
980
+ return;
981
+ }
982
+ [[G9ImageService shared].tokens cancel:args[@"token"]];
983
+ if (reply) reply([G9ImageCore okReply:@{}]);
984
+ }
985
+
986
+ @end