@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,464 @@
1
+ package com.g9lynx.g9native.image
2
+
3
+ import android.content.Context
4
+ import android.graphics.Bitmap
5
+ import android.graphics.BitmapFactory
6
+ import android.graphics.BitmapRegionDecoder
7
+ import android.graphics.Canvas
8
+ import android.graphics.ColorSpace
9
+ import android.graphics.Matrix
10
+ import android.graphics.Paint
11
+ import android.graphics.Rect
12
+ import android.net.Uri
13
+ import android.os.Build
14
+ import android.os.ParcelFileDescriptor
15
+ import androidx.exifinterface.media.ExifInterface
16
+ import com.g9lynx.g9native.image.core.G9Affine
17
+ import com.g9lynx.g9native.image.core.G9ImageBackend
18
+ import com.g9lynx.g9native.image.core.G9ImageBox
19
+ import com.g9lynx.g9native.image.core.G9ImageBudget
20
+ import com.g9lynx.g9native.image.core.G9ImageError
21
+ import com.g9lynx.g9native.image.core.G9ImageExifTags
22
+ import com.g9lynx.g9native.image.core.G9ImageFormat
23
+ import com.g9lynx.g9native.image.core.G9ImageNames
24
+ import com.g9lynx.g9native.image.core.G9ImageQuality
25
+ import com.g9lynx.g9native.image.core.G9ImageRegion
26
+ import com.g9lynx.g9native.image.core.G9ImageSniff
27
+ import com.g9lynx.g9native.image.core.G9ImageSource
28
+ import com.g9lynx.g9native.image.core.G9ImageTicket
29
+ import com.g9lynx.g9native.image.core.G9Orientation
30
+ import com.g9lynx.g9native.image.core.G9OverlayOp
31
+ import com.g9lynx.g9native.image.core.G9PathOp
32
+ import com.g9lynx.g9native.image.core.G9PreviewSpec
33
+ import com.g9lynx.g9native.image.core.G9ProbeSpec
34
+ import com.g9lynx.g9native.image.core.G9ProcessSpec
35
+ import com.g9lynx.g9native.image.core.G9Redaction
36
+ import com.g9lynx.g9native.image.core.G9TextOp
37
+ import java.io.ByteArrayOutputStream
38
+ import java.io.Closeable
39
+ import java.io.File
40
+ import java.io.FileInputStream
41
+ import java.io.FileNotFoundException
42
+ import java.io.FileOutputStream
43
+ import java.io.IOException
44
+ import java.io.InputStream
45
+ import java.io.OutputStream
46
+ import java.security.SecureRandom
47
+
48
+ /**
49
+ * The Android work of `G9ImageModule` (the native contract's pipeline), run on the module's one background thread.
50
+ * Decodes only the needed region at a subsample (`BitmapRegionDecoder`), applies the EXIF orientation inside the one
51
+ * draw matrix (never a second decode), keeps decode + output within 40 % of the free heap and survives an
52
+ * OutOfMemoryError once at half size.
53
+ */
54
+ internal class G9ImageProcessor(private val context: Context) : G9ImageBackend {
55
+ private val random = SecureRandom()
56
+
57
+ /** What `probe` reports, plus the raw size the pipeline needs. */
58
+ private class Info(val rawWidth: Int, val rawHeight: Int, val orientation: Int, val mime: String, val bytes: Long, val hasAlpha: Boolean) {
59
+ val oriented = G9Orientation.orientedSize(rawWidth, rawHeight, orientation)
60
+ }
61
+
62
+ // ============================================================================================= methods
63
+
64
+ override fun probe(spec: G9ProbeSpec): Map<String, Any?> = probeMap(info(spec.source))
65
+
66
+ override fun preview(spec: G9PreviewSpec): Map<String, Any?> {
67
+ val info = info(spec.source)
68
+ val (ow, oh) = info.oriented
69
+ val (w, h) = G9ImageRegion.previewSize(ow, oh, spec.maxSide)
70
+ val format = if (info.hasAlpha) "png" else "jpeg"
71
+ val matrix = G9Affine.scale(ow.toDouble() / w, oh.toDouble() / h)
72
+ val bitmap = render(spec.source, info, w, h, matrix, null, false, emptyList(), emptyList(), G9ImageFormat.hasAlpha(format), null).bitmap
73
+ try {
74
+ val out = output(spec.dir, null, format)
75
+ try {
76
+ out.tmp.outputStream().buffered().use { encode(bitmap, format, 85, it) }
77
+ val file = out.commit()
78
+ return mapOf("path" to file.absolutePath, "width" to bitmap.width, "height" to bitmap.height, "sourceWidth" to ow, "sourceHeight" to oh)
79
+ } finally {
80
+ out.discard()
81
+ }
82
+ } finally {
83
+ bitmap.recycle()
84
+ }
85
+ }
86
+
87
+ override fun process(spec: G9ProcessSpec, ticket: G9ImageTicket): Map<String, Any?> {
88
+ val info = info(spec.source)
89
+ ticket.check()
90
+ if (spec.passthrough) return passthrough(spec, info, ticket)
91
+ val format = G9ImageFormat.resolve(spec.format, info.mime)
92
+ val alpha = G9ImageFormat.hasAlpha(format)
93
+ val rendered = render(spec.source, info, spec.width, spec.height, spec.matrix, spec.background, spec.circle, spec.redact, spec.overlay, alpha, ticket)
94
+ val out = output(spec.dir, spec.name, format)
95
+ try {
96
+ ticket.check()
97
+ val lossy = G9ImageFormat.lossy(format)
98
+ var quality: Int? = if (lossy) spec.quality else null
99
+ var scale = 1.0
100
+ val maxBytes = spec.maxBytes
101
+ if (maxBytes == null) {
102
+ out.tmp.outputStream().buffered().use { encode(rendered.bitmap, format, spec.quality, it) }
103
+ ticket.check()
104
+ if (spec.keepMetadata) copyMetadata(spec.source, out.tmp)
105
+ } else {
106
+ // The metadata is added after encoding: its size comes off the target and the fit runs again if it overshoots.
107
+ var target: Long = maxBytes
108
+ val scaled = ScaledCache(rendered.bitmap)
109
+ try {
110
+ for (round in 0 until 3) {
111
+ val fit = G9ImageQuality.fit(spec.quality, target, lossy, rendered.bitmap.width, rendered.bitmap.height, { s, q ->
112
+ ticket.check()
113
+ ByteArrayOutputStream().also { encode(scaled.at(s), format, q, it) }.toByteArray()
114
+ }, { it.size.toLong() })
115
+ if (!fit.fits) throw G9ImageError.invalid("maxBytes $maxBytes cannot be reached (the smallest output is ${fit.data.size} bytes).")
116
+ out.tmp.writeBytes(fit.data)
117
+ quality = fit.quality
118
+ scale = fit.scale
119
+ ticket.check()
120
+ if (spec.keepMetadata) copyMetadata(spec.source, out.tmp)
121
+ val overshoot = out.tmp.length() - maxBytes
122
+ if (overshoot <= 0 || !spec.keepMetadata) break
123
+ target = maxOf(1L, target - overshoot - 256)
124
+ }
125
+ } finally {
126
+ scaled.recycle()
127
+ }
128
+ if (out.tmp.length() > maxBytes) throw G9ImageError.invalid("maxBytes $maxBytes cannot be reached with the kept metadata (${out.tmp.length()} bytes).")
129
+ }
130
+ ticket.check()
131
+ val (w, h) = G9ImageQuality.scaledSize(rendered.bitmap.width, rendered.bitmap.height, scale)
132
+ val file = out.commit()
133
+ return mapOf(
134
+ "path" to file.absolutePath,
135
+ "mime" to G9ImageFormat.mime(format),
136
+ "width" to w,
137
+ "height" to h,
138
+ "bytes" to file.length(),
139
+ "quality" to quality,
140
+ "format" to format,
141
+ "downscaled" to (rendered.downscaled || scale < 1.0),
142
+ )
143
+ } finally {
144
+ out.discard()
145
+ rendered.bitmap.recycle()
146
+ }
147
+ }
148
+
149
+ private fun probeMap(info: Info) =
150
+ mapOf(
151
+ "width" to info.oriented[0],
152
+ "height" to info.oriented[1],
153
+ "orientation" to info.orientation,
154
+ "mime" to info.mime,
155
+ "bytes" to info.bytes,
156
+ "hasAlpha" to info.hasAlpha,
157
+ )
158
+
159
+ /** Step 1: the bytes as they are, no decode and no re-encode. */
160
+ private fun passthrough(spec: G9ProcessSpec, info: Info, ticket: G9ImageTicket): Map<String, Any?> {
161
+ val sourceFormat = G9ImageFormat.fromMime(info.mime)
162
+ val out = output(spec.dir, spec.name, sourceFormat)
163
+ try {
164
+ open(spec.source).use { input ->
165
+ out.tmp.outputStream().use { output ->
166
+ val buffer = ByteArray(1 shl 16)
167
+ var copied = 0L
168
+ while (true) {
169
+ val n = input.read(buffer)
170
+ if (n < 0) break
171
+ output.write(buffer, 0, n)
172
+ copied += n
173
+ if (copied % (1 shl 20) < n) ticket.check()
174
+ }
175
+ }
176
+ }
177
+ ticket.check()
178
+ val file = out.commit()
179
+ return mapOf(
180
+ "path" to file.absolutePath,
181
+ "mime" to info.mime,
182
+ "width" to info.oriented[0],
183
+ "height" to info.oriented[1],
184
+ "bytes" to file.length(),
185
+ "quality" to null,
186
+ "format" to (sourceFormat ?: "source"),
187
+ "downscaled" to false,
188
+ )
189
+ } finally {
190
+ out.discard()
191
+ }
192
+ }
193
+
194
+ // ============================================================================================= source
195
+
196
+ private fun uri(source: G9ImageSource) = Uri.parse(source.uri)
197
+
198
+ private fun open(source: G9ImageSource): InputStream =
199
+ try {
200
+ if (source.file != null) FileInputStream(existing(source.file))
201
+ else context.contentResolver.openInputStream(uri(source)) ?: throw G9ImageError(G9ImageError.NOT_FOUND, "Cannot open ${source.uri}.")
202
+ } catch (e: FileNotFoundException) {
203
+ throw G9ImageError(G9ImageError.NOT_FOUND, e.message ?: "Not found.")
204
+ } catch (e: SecurityException) {
205
+ throw G9ImageError(G9ImageError.NOT_FOUND, "No permission to read ${source.uri}: ${e.message}")
206
+ }
207
+
208
+ private fun existing(path: String): File {
209
+ val file = File(path)
210
+ if (!file.isFile) throw G9ImageError(G9ImageError.NOT_FOUND, "No file at $path.")
211
+ return file
212
+ }
213
+
214
+ private fun info(source: G9ImageSource): Info {
215
+ val head = open(source).use { input ->
216
+ val buffer = ByteArray(G9ImageSniff.HEAD)
217
+ var n = 0
218
+ while (n < buffer.size) {
219
+ val r = input.read(buffer, n, buffer.size - n)
220
+ if (r < 0) break
221
+ n += r
222
+ }
223
+ buffer.copyOf(n)
224
+ }
225
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
226
+ open(source).use { BitmapFactory.decodeStream(it, null, bounds) }
227
+ if (bounds.outWidth <= 0 || bounds.outHeight <= 0) throw G9ImageError(G9ImageError.DECODE, "Not a picture this device can decode.")
228
+ val orientation = G9Orientation.normalize(
229
+ runCatching {
230
+ if (source.file != null) ExifInterface(source.file).getAttributeInt(G9ImageExifTags.ORIENTATION, 1)
231
+ else open(source).use { ExifInterface(it).getAttributeInt(G9ImageExifTags.ORIENTATION, 1) }
232
+ }.getOrNull(),
233
+ )
234
+ val bytes = if (source.file != null) File(source.file).length() else runCatching { context.contentResolver.openFileDescriptor(uri(source), "r")?.use { it.statSize } }.getOrNull() ?: -1L
235
+ val mime = bounds.outMimeType ?: G9ImageSniff.mime(head) ?: "application/octet-stream"
236
+ return Info(bounds.outWidth, bounds.outHeight, orientation, mime, bytes, G9ImageSniff.hasAlpha(head))
237
+ }
238
+
239
+ /** A region decoder over the source, with the descriptor it reads from (closed together). */
240
+ private class Region(val decoder: BitmapRegionDecoder, private val fd: ParcelFileDescriptor?) : Closeable {
241
+ override fun close() {
242
+ decoder.recycle()
243
+ fd?.close()
244
+ }
245
+ }
246
+
247
+ /** Null where the format has no region decoder (GIF, BMP, HEIF before API 28 …): the whole picture is decoded then. */
248
+ @Suppress("DEPRECATION")
249
+ private fun region(source: G9ImageSource): Region? =
250
+ try {
251
+ if (source.file != null) {
252
+ val decoder: BitmapRegionDecoder? = BitmapRegionDecoder.newInstance(source.file, false)
253
+ decoder?.let { Region(it, null) }
254
+ } else {
255
+ val fd = context.contentResolver.openFileDescriptor(uri(source), "r") ?: return null
256
+ try {
257
+ val decoder: BitmapRegionDecoder? = BitmapRegionDecoder.newInstance(fd.fileDescriptor, false)
258
+ if (decoder == null) {
259
+ fd.close()
260
+ null
261
+ } else {
262
+ Region(decoder, fd)
263
+ }
264
+ } catch (e: IOException) {
265
+ fd.close()
266
+ null
267
+ }
268
+ }
269
+ } catch (e: IOException) {
270
+ null
271
+ } catch (e: IllegalArgumentException) {
272
+ null
273
+ }
274
+
275
+ private fun decodeOptions(sample: Int) =
276
+ BitmapFactory.Options().apply {
277
+ inSampleSize = sample
278
+ inPreferredConfig = Bitmap.Config.ARGB_8888
279
+ if (Build.VERSION.SDK_INT >= 26) inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB)
280
+ }
281
+
282
+ // ============================================================================================= render
283
+
284
+ private class Rendered(val bitmap: Bitmap, val downscaled: Boolean)
285
+
286
+ /** Steps 2–5: the output bitmap (the requested size unless the memory budget shrank it). */
287
+ private fun render(
288
+ source: G9ImageSource,
289
+ info: Info,
290
+ outW: Int,
291
+ outH: Int,
292
+ matrix: DoubleArray,
293
+ background: Int?,
294
+ circle: Boolean,
295
+ redact: List<G9Redaction>,
296
+ overlay: List<G9OverlayOp>,
297
+ alpha: Boolean,
298
+ ticket: G9ImageTicket?,
299
+ ): Rendered {
300
+ val (ow, oh) = info.oriented
301
+ val orientedBox = G9ImageRegion.orientedBox(matrix, outW, outH, ow, oh)
302
+ val rawBox = orientedBox?.let { G9ImageRegion.rawBox(it, info.orientation, info.rawWidth, info.rawHeight) }
303
+ val region = rawBox?.let { region(source) }
304
+ try {
305
+ // Without a region decoder the whole picture is decoded (at the subsample) and the matrix picks the box.
306
+ val box = if (rawBox == null || region != null) rawBox else G9ImageBox(0, 0, info.rawWidth, info.rawHeight)
307
+ val ratio = G9ImageRegion.sourcePerOutput(matrix)
308
+ return try {
309
+ attempt(source, info, region, box, ratio, outW, outH, matrix, background, circle, redact, overlay, alpha, ticket, 1)
310
+ } catch (e: OutOfMemoryError) {
311
+ try {
312
+ attempt(source, info, region, box, ratio, outW, outH, matrix, background, circle, redact, overlay, alpha, ticket, 4)
313
+ } catch (e2: OutOfMemoryError) {
314
+ throw G9ImageError(G9ImageError.MEMORY, "Not enough memory for a ${outW}×$outH picture, even at half size.")
315
+ }
316
+ }
317
+ } finally {
318
+ region?.close()
319
+ }
320
+ }
321
+
322
+ /** One try; [squeeze] 4 = the OutOfMemoryError retry (a quarter of the budget: about half the size). */
323
+ private fun attempt(
324
+ source: G9ImageSource,
325
+ info: Info,
326
+ region: Region?,
327
+ box: G9ImageBox?,
328
+ ratio: Double,
329
+ outW: Int,
330
+ outH: Int,
331
+ matrix: DoubleArray,
332
+ background: Int?,
333
+ circle: Boolean,
334
+ redact: List<G9Redaction>,
335
+ overlay: List<G9OverlayOp>,
336
+ alpha: Boolean,
337
+ ticket: G9ImageTicket?,
338
+ squeeze: Int,
339
+ ): Rendered {
340
+ val rt = Runtime.getRuntime()
341
+ val available = G9ImageBudget.available(rt.maxMemory(), rt.totalMemory(), rt.freeMemory()) / squeeze
342
+ val plan = G9ImageBudget.plan(box?.width ?: 0, box?.height ?: 0, ratio, outW, outH, available)
343
+ var decoded: Bitmap? = null
344
+ var out: Bitmap? = null
345
+ try {
346
+ if (box != null) {
347
+ val options = decodeOptions(plan.sample)
348
+ decoded =
349
+ if (region != null) region.decoder.decodeRegion(Rect(box.left, box.top, box.right, box.bottom), options)
350
+ else if (source.file != null) BitmapFactory.decodeFile(source.file, options)
351
+ else open(source).use { BitmapFactory.decodeStream(it, null, options) }
352
+ if (decoded == null) throw G9ImageError(G9ImageError.DECODE, "The picture could not be decoded.")
353
+ }
354
+ ticket?.check()
355
+ out =
356
+ if (Build.VERSION.SDK_INT >= 26) Bitmap.createBitmap(plan.outWidth, plan.outHeight, Bitmap.Config.ARGB_8888, true, ColorSpace.get(ColorSpace.Named.SRGB))
357
+ else Bitmap.createBitmap(plan.outWidth, plan.outHeight, Bitmap.Config.ARGB_8888)
358
+ val kx = plan.outWidth.toFloat() / outW
359
+ val ky = plan.outHeight.toFloat() / outH
360
+ val draw = G9ImageDraw(context.assets, out, kx, ky)
361
+ if (alpha) background?.let { out.eraseColor(it) } else draw.opaqueBase(background)
362
+ if (decoded != null && box != null) {
363
+ val m = G9ImageRegion.drawMatrix(matrix, info.orientation, info.rawWidth, info.rawHeight, box, decoded.width, decoded.height)
364
+ val canvas = Canvas(out)
365
+ canvas.scale(kx, ky)
366
+ canvas.drawBitmap(decoded, Matrix().apply { setValues(G9Affine.toAndroid(m)) }, Paint(Paint.FILTER_BITMAP_FLAG or Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG))
367
+ decoded.recycle()
368
+ decoded = null
369
+ }
370
+ for (r in redact) draw.redact(r, outW, outH, ticket)
371
+ for (op in overlay) {
372
+ ticket?.check()
373
+ when (op) {
374
+ is G9PathOp -> draw.path(op)
375
+ is G9TextOp -> draw.text(op)
376
+ }
377
+ }
378
+ if (circle) draw.circle(alpha, background)
379
+ val result = Rendered(out, plan.downscaled || squeeze > 1)
380
+ out = null
381
+ return result
382
+ } finally {
383
+ decoded?.recycle()
384
+ out?.recycle()
385
+ }
386
+ }
387
+
388
+ // ============================================================================================= encode
389
+
390
+ @Suppress("DEPRECATION")
391
+ private fun encode(bitmap: Bitmap, format: String, quality: Int, stream: OutputStream) {
392
+ val compress = when (format) {
393
+ "png" -> Bitmap.CompressFormat.PNG
394
+ "webp" -> if (Build.VERSION.SDK_INT >= 30) Bitmap.CompressFormat.WEBP_LOSSY else Bitmap.CompressFormat.WEBP
395
+ else -> Bitmap.CompressFormat.JPEG
396
+ }
397
+ if (!bitmap.compress(compress, quality, stream)) throw G9ImageError(G9ImageError.IO, "The $format encoder failed.")
398
+ }
399
+
400
+ /** The output scaled for the maxBytes loop, one scaled copy alive at a time. */
401
+ private class ScaledCache(private val full: Bitmap) {
402
+ private var scale = 1.0
403
+ private var bitmap: Bitmap? = null
404
+
405
+ fun at(s: Double): Bitmap {
406
+ if (s == 1.0) return full
407
+ if (s != scale || bitmap == null) {
408
+ bitmap?.recycle()
409
+ val (w, h) = G9ImageQuality.scaledSize(full.width, full.height, s)
410
+ bitmap = Bitmap.createScaledBitmap(full, w, h, true)
411
+ scale = s
412
+ }
413
+ return bitmap!!
414
+ }
415
+
416
+ fun recycle() {
417
+ bitmap?.let { if (it !== full) it.recycle() }
418
+ bitmap = null
419
+ }
420
+ }
421
+
422
+ /** Step 7: every kept EXIF tag of the source onto the written file, Orientation = 1. Nothing to keep → nothing written. */
423
+ private fun copyMetadata(source: G9ImageSource, target: File) {
424
+ val from =
425
+ runCatching { if (source.file != null) ExifInterface(source.file) else open(source).use { ExifInterface(it) } }.getOrNull() ?: return
426
+ val tags = G9ImageExifTags.plan { from.getAttribute(it) }
427
+ if (tags.size <= 1) return
428
+ try {
429
+ val to = ExifInterface(target.absolutePath)
430
+ for ((tag, value) in tags) to.setAttribute(tag, value)
431
+ to.saveAttributes()
432
+ } catch (e: IOException) {
433
+ throw G9ImageError(G9ImageError.IO, "The metadata could not be written: ${e.message}")
434
+ } catch (e: UnsupportedOperationException) {
435
+ throw G9ImageError(G9ImageError.UNSUPPORTED, "This format cannot carry metadata here: ${e.message}")
436
+ }
437
+ }
438
+
439
+ // ============================================================================================= output files
440
+
441
+ /** A file being written: [tmp] in the destination folder, renamed to [file] by [commit]; [discard] removes leftovers. */
442
+ private class Output(val tmp: File, val file: File) {
443
+ private var committed = false
444
+
445
+ fun commit(): File {
446
+ if (file.exists() && !file.delete()) throw G9ImageError(G9ImageError.IO, "Cannot replace ${file.path}.")
447
+ if (!tmp.renameTo(file)) throw G9ImageError(G9ImageError.IO, "Cannot write ${file.path}.")
448
+ committed = true
449
+ return file
450
+ }
451
+
452
+ fun discard() {
453
+ if (!committed) tmp.delete()
454
+ }
455
+ }
456
+
457
+ private fun output(dir: String?, name: String?, format: String?): Output {
458
+ val folder = dir?.let(::File) ?: File(context.cacheDir, "g9photo")
459
+ if (!folder.isDirectory && !folder.mkdirs()) throw G9ImageError(G9ImageError.IO, "Cannot create the folder ${folder.path}.")
460
+ val ext = G9ImageFormat.extension(format)
461
+ val base = name ?: G9ImageNames.unique(ext, { File(folder, it).exists() }, System::currentTimeMillis, random::nextInt)
462
+ return Output(File(folder, ".$base.$ext.part"), File(folder, "$base.$ext"))
463
+ }
464
+ }
@@ -0,0 +1,28 @@
1
+ package com.g9lynx.g9native.image.core
2
+
3
+ /**
4
+ * The host's text font as the native drawing sees it (2.7.0): the families Lynx registered for `<g9-richtext>` and the
5
+ * page (`G9`, `G9Semi`, `G9Bold`), chosen by weight, and how a line of it sits in a fixed line height. G9ImageModule's
6
+ * text overlay (an empty `font`) and `<g9-canvas>` font [CANVAS_FONT] both use it, so the editor's canvas and the
7
+ * rendered file draw a text the same way.
8
+ */
9
+ object G9HostFont {
10
+ /** `<g9-canvas>` text op font id for the host's text font (Excalidraw's own ids stay below it). */
11
+ const val CANVAS_FONT = 100
12
+
13
+ /** The family every weight falls back to. */
14
+ const val BASE = "G9"
15
+
16
+ /** The Lynx typeface families that are exactly [weight], best first; none = [BASE] made bolder by the platform. */
17
+ fun families(weight: Int): List<String> = when {
18
+ weight >= 700 -> listOf("G9Bold")
19
+ weight >= 600 -> listOf("G9Semi", "G9Bold")
20
+ else -> listOf(BASE)
21
+ }
22
+
23
+ /**
24
+ * The baseline of a line whose glyph box is centred on [middle] (Android's font metrics: [ascent] negative,
25
+ * [descent] positive): what the overlay's exact line height does to every line.
26
+ */
27
+ fun centredBaseline(middle: Float, ascent: Float, descent: Float): Float = middle - (ascent + descent) / 2
28
+ }
@@ -0,0 +1,54 @@
1
+ package com.g9lynx.g9native.image.core
2
+
3
+ import kotlin.math.ceil
4
+ import kotlin.math.max
5
+ import kotlin.math.roundToInt
6
+ import kotlin.math.sqrt
7
+
8
+ /**
9
+ * What the decode and the output may cost: [sample] for `inSampleSize`, [scale] applied to the requested output size
10
+ * ([outWidth]×[outHeight] is what is drawn), [downscaled] when the budget forced either one, [bytes] the estimate.
11
+ */
12
+ data class G9ImagePlan(val sample: Int, val scale: Double, val outWidth: Int, val outHeight: Int, val downscaled: Boolean, val bytes: Long)
13
+
14
+ /**
15
+ * Step 3 of the pipeline: decoded region + output (ARGB_8888, 4 bytes a pixel) ≤ 40 % of the free heap
16
+ * (`Runtime.maxMemory() − used`). Over it, the sample rises while the decoded region outweighs the output; after that
17
+ * the output shrinks proportionally (the sample following the new ratio).
18
+ */
19
+ object G9ImageBudget {
20
+ const val FRACTION = 0.4
21
+ private const val BYTES_PER_PIXEL = 4L
22
+
23
+ fun available(maxMemory: Long, totalMemory: Long, freeMemory: Long) = max(0L, maxMemory - (totalMemory - freeMemory))
24
+
25
+ fun decodedBytes(regionWidth: Int, regionHeight: Int, sample: Int): Long =
26
+ ceil(regionWidth.toDouble() / sample).toLong() * ceil(regionHeight.toDouble() / sample).toLong() * BYTES_PER_PIXEL
27
+
28
+ /**
29
+ * [regionWidth]×[regionHeight]: the raw pixels to decode (0×0 when no source pixel lands); [ratio]: source px per
30
+ * output px; [available]: free heap bytes. Throws `memory` when not even a 1×1 output fits.
31
+ */
32
+ fun plan(regionWidth: Int, regionHeight: Int, ratio: Double, outWidth: Int, outHeight: Int, available: Long): G9ImagePlan {
33
+ val budget = (available * FRACTION).toLong()
34
+ var scale = 1.0
35
+ var sample = G9ImageRegion.sampleSize(ratio)
36
+ var downscaled = false
37
+ while (true) {
38
+ val w = max(1, (outWidth * scale).roundToInt())
39
+ val h = max(1, (outHeight * scale).roundToInt())
40
+ val decoded = decodedBytes(regionWidth, regionHeight, sample)
41
+ val output = w.toLong() * h * BYTES_PER_PIXEL
42
+ val cost = decoded + output
43
+ if (cost <= budget) return G9ImagePlan(sample, scale, w, h, downscaled, cost)
44
+ downscaled = true
45
+ if (decoded > output && sample < G9ImageRegion.MAX_SAMPLE) {
46
+ sample *= 2
47
+ } else {
48
+ if (w == 1 && h == 1) throw G9ImageError(G9ImageError.MEMORY, "Not enough memory for the picture ($cost bytes needed, $budget allowed).")
49
+ scale *= sqrt(budget.toDouble() / cost).coerceIn(0.5, 0.9)
50
+ sample = max(sample, G9ImageRegion.sampleSize(ratio / scale))
51
+ }
52
+ }
53
+ }
54
+ }
@@ -0,0 +1,48 @@
1
+ package com.g9lynx.g9native.image.core
2
+
3
+ /**
4
+ * CSS colours → ARGB ints, platform-free: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` / `rgba()` (commas, spaces or
5
+ * `/`, alpha as 0..1 or a percentage), `transparent` / `none`. Null for anything else (named colours: the caller decides;
6
+ * `G9CanvasPaths.color` falls back to Android's `Color.parseColor`). Shared by `<g9-canvas>` and `G9ImageModule`.
7
+ */
8
+ object G9ImageColor {
9
+ fun argb(a: Int, r: Int, g: Int, b: Int) =
10
+ (a.coerceIn(0, 255) shl 24) or (r.coerceIn(0, 255) shl 16) or (g.coerceIn(0, 255) shl 8) or b.coerceIn(0, 255)
11
+
12
+ fun parse(value: String?): Int? {
13
+ val s = value?.trim()?.lowercase() ?: return null
14
+ if (s.isEmpty()) return null
15
+ if (s == "transparent" || s == "none") return 0
16
+ if (s.startsWith("#")) return hex(s.substring(1))
17
+ if (s.startsWith("rgb")) return rgb(s)
18
+ return null
19
+ }
20
+
21
+ private fun hex(h: String): Int? {
22
+ if (h.any { Character.digit(it, 16) < 0 }) return null
23
+ fun dup(i: Int) = Character.digit(h[i], 16) * 17
24
+ fun pair(i: Int) = h.substring(i, i + 2).toInt(16)
25
+ return when (h.length) {
26
+ 3 -> argb(255, dup(0), dup(1), dup(2))
27
+ 4 -> argb(dup(3), dup(0), dup(1), dup(2))
28
+ 6 -> argb(255, pair(0), pair(2), pair(4))
29
+ 8 -> argb(pair(6), pair(0), pair(2), pair(4))
30
+ else -> null
31
+ }
32
+ }
33
+
34
+ private fun rgb(s: String): Int? {
35
+ if (!s.contains('(')) return null
36
+ val parts = s.substringAfter('(').substringBefore(')').split(',', ' ', '/').filter { it.isNotBlank() }
37
+ if (parts.size < 3 || parts.size > 4) return null
38
+ val r = parts[0].toFloatOrNull() ?: return null
39
+ val g = parts[1].toFloatOrNull() ?: return null
40
+ val b = parts[2].toFloatOrNull() ?: return null
41
+ val a =
42
+ when (val p = parts.getOrNull(3)) {
43
+ null -> 1f
44
+ else -> (if (p.endsWith("%")) p.dropLast(1).toFloatOrNull()?.div(100f) else p.toFloatOrNull()) ?: return null
45
+ }
46
+ return argb(Math.round(a * 255), r.toInt(), g.toInt(), b.toInt())
47
+ }
48
+ }
@@ -0,0 +1,19 @@
1
+ package com.g9lynx.g9native.image.core
2
+
3
+ /**
4
+ * A typed failure of `G9ImageModule` (the native contract's error codes). Everything the module throws on purpose is
5
+ * one of these; the service turns it into `{"ok":false,"error":{"code","message"}}`.
6
+ */
7
+ class G9ImageError(val code: String, message: String) : Exception(message) {
8
+ companion object {
9
+ const val INVALID = "invalid-argument"
10
+ const val NOT_FOUND = "not-found"
11
+ const val DECODE = "decode"
12
+ const val MEMORY = "memory"
13
+ const val IO = "io"
14
+ const val CANCELLED = "cancelled"
15
+ const val UNSUPPORTED = "unsupported"
16
+
17
+ fun invalid(message: String) = G9ImageError(INVALID, message)
18
+ }
19
+ }
@@ -0,0 +1,61 @@
1
+ package com.g9lynx.g9native.image.core
2
+
3
+ /**
4
+ * Step 7 (`keepMetadata`): the EXIF tags copied from the source to the output (androidx `ExifInterface` names). Every
5
+ * descriptive tag (camera, exposure, dates and offsets, GPS, description, copyright, ids); never Orientation (written
6
+ * as 1), the pixel dimensions (ImageWidth/Length, PixelX/YDimension), the thumbnail, the strip/tile layout or the
7
+ * MakerNote (binary with offsets into the old file).
8
+ */
9
+ object G9ImageExifTags {
10
+ const val ORIENTATION = "Orientation"
11
+
12
+ val COPIED: List<String> =
13
+ listOf(
14
+ // IFD0: the camera and the picture
15
+ "ImageDescription", "Make", "Model", "Software", "Artist", "Copyright", "DateTime", "XResolution", "YResolution",
16
+ "ResolutionUnit", "WhitePoint", "PrimaryChromaticities", "YCbCrCoefficients", "ReferenceBlackWhite",
17
+ "ImageUniqueID", "CameraOwnerName", "BodySerialNumber", "LensSpecification", "LensMake", "LensModel",
18
+ "LensSerialNumber",
19
+ // Exif IFD: exposure and dates
20
+ "ExposureTime", "FNumber", "ExposureProgram", "SpectralSensitivity", "PhotographicSensitivity", "ISOSpeedRatings",
21
+ "OECF", "SensitivityType", "StandardOutputSensitivity", "RecommendedExposureIndex", "ISOSpeed",
22
+ "ISOSpeedLatitudeyyy", "ISOSpeedLatitudezzz", "ExifVersion", "DateTimeOriginal", "DateTimeDigitized",
23
+ "OffsetTime", "OffsetTimeOriginal", "OffsetTimeDigitized", "ComponentsConfiguration", "CompressedBitsPerPixel",
24
+ "ShutterSpeedValue", "ApertureValue", "BrightnessValue", "ExposureBiasValue", "MaxApertureValue",
25
+ "SubjectDistance", "MeteringMode", "LightSource", "Flash", "SubjectArea", "FocalLength", "UserComment",
26
+ "SubSecTime", "SubSecTimeOriginal", "SubSecTimeDigitized", "FlashpixVersion", "ColorSpace", "RelatedSoundFile",
27
+ "FlashEnergy", "SpatialFrequencyResponse", "FocalPlaneXResolution", "FocalPlaneYResolution",
28
+ "FocalPlaneResolutionUnit", "SubjectLocation", "ExposureIndex", "SensingMethod", "FileSource", "SceneType",
29
+ "CFAPattern", "CustomRendered", "ExposureMode", "WhiteBalance", "DigitalZoomRatio", "FocalLengthIn35mmFilm",
30
+ "SceneCaptureType", "GainControl", "Contrast", "Saturation", "Sharpness", "DeviceSettingDescription",
31
+ "SubjectDistanceRange", "Gamma",
32
+ // GPS IFD
33
+ "GPSVersionID", "GPSLatitudeRef", "GPSLatitude", "GPSLongitudeRef", "GPSLongitude", "GPSAltitudeRef",
34
+ "GPSAltitude", "GPSTimeStamp", "GPSSatellites", "GPSStatus", "GPSMeasureMode", "GPSDOP", "GPSSpeedRef",
35
+ "GPSSpeed", "GPSTrackRef", "GPSTrack", "GPSImgDirectionRef", "GPSImgDirection", "GPSMapDatum",
36
+ "GPSDestLatitudeRef", "GPSDestLatitude", "GPSDestLongitudeRef", "GPSDestLongitude", "GPSDestBearingRef",
37
+ "GPSDestBearing", "GPSDestDistanceRef", "GPSDestDistance", "GPSProcessingMethod", "GPSAreaInformation",
38
+ "GPSDateStamp", "GPSDifferential", "GPSHPositioningError",
39
+ // Interoperability IFD
40
+ "InteroperabilityIndex",
41
+ )
42
+
43
+ /** Never copied (the layout of the old file, its size and its rotation). */
44
+ val DROPPED: Set<String> =
45
+ setOf(
46
+ ORIENTATION, "ImageWidth", "ImageLength", "PixelXDimension", "PixelYDimension", "ThumbnailImageWidth",
47
+ "ThumbnailImageLength", "ThumbnailOrientation", "JPEGInterchangeFormat", "JPEGInterchangeFormatLength",
48
+ "StripOffsets", "StripByteCounts", "RowsPerStrip", "Compression", "BitsPerSample", "SamplesPerPixel",
49
+ "PhotometricInterpretation", "PlanarConfiguration", "YCbCrSubSampling", "YCbCrPositioning", "MakerNote",
50
+ "NewSubfileType", "SubfileType", "DefaultCropSize", "SubIFDPointer", "ExifIFDPointer", "GPSInfoIFDPointer",
51
+ "InteroperabilityIFDPointer",
52
+ )
53
+
54
+ /** The tags to write on the output from [read] (source value or null): the copied ones present, then Orientation = 1. */
55
+ fun plan(read: (String) -> String?): List<Pair<String, String>> {
56
+ val out = ArrayList<Pair<String, String>>()
57
+ for (tag in COPIED) read(tag)?.let { out.add(tag to it) }
58
+ out.add(ORIENTATION to "1")
59
+ return out
60
+ }
61
+ }