@g9tm/lynxcontrols-native 2.6.19 → 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
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @g9tm/lynxcontrols-native
2
2
 
3
- Android and iOS platform layer for G9: three Lynx native modules and one element (`<g9-video>`), linked into a host by
3
+ Android and iOS platform layer for G9: four Lynx native modules and one element (`<g9-video>`), linked into a host by
4
4
  **Lynx Autolink** from `node_modules`, plus their JS adapters.
5
5
 
6
6
  | Module | JS adapter | Android (Kotlin) | iOS (Objective-C) |
@@ -8,6 +8,7 @@ Android and iOS platform layer for G9: three Lynx native modules and one element
8
8
  | `G9SqliteModule` | `createNativeSqliteDriver()` | androidx.sqlite `BundledSQLiteDriver` 2.7.1 | system `sqlite3` (iOS 15+, serial queue per session, `sqlite3_interrupt`) |
9
9
  | `G9HostModule` | `createNativeHostServices()` | `SharedPreferences`, `moveTaskToBack`, `InputMethodManager`, haptics, insets, `appDataDirectory()` = `filesDir` | `NSUserDefaults` suite, `resignFirstResponder`, `UIImpactFeedbackGenerator`, safe-area insets, `appDataDirectory()` = `Library` |
10
10
  | `G9SpeechModule` | `createNativeSpeechToText()` → `services.speech` (dictation into fields) | `SpeechRecognizer` (main thread, partial results), the microphone asked through the host activity's `ActivityResultRegistry` | `SFSpeechRecognizer` over `AVAudioEngine`; register it on the host's `LynxConfig`; Info.plist `NSMicrophoneUsageDescription` + `NSSpeechRecognitionUsageDescription` |
11
+ | `G9ImageModule` (2.7.0) | `g9ImageProbe()`, `g9ImagePreview()`, `g9ImageProcess()`, `g9ImageCancel()` (the photo editor, an app's headless "process this photo") | `BitmapFactory` bounds + `ExifInterface`, `BitmapRegionDecoder` at a subsample, a memory budget, `ExifInterface` metadata copy | ImageIO: `CGImageSourceCopyPropertiesAtIndex`, `CGImageSourceCreateThumbnailAtIndex`, `CGImageDestinationAddImage` (no WebP encoder: JPEG). Web: the page answers with a canvas (`installG9WebHost`, `@g9tm/lynxcontrols-web`) |
11
12
  | `<g9-video>` element | `createNativeMediaProvider()` (`@g9tm/lynxcontrols-native/media`) | `G9VideoUI`: Media3 ExoPlayer 1.8.0 into a `TextureView` (opacity fades work); register `G9VideoBehaviors.create()` | `G9LCVideoUI`: `AVQueuePlayer` + `AVPlayerLooper` in an `AVPlayerLayer`; the host registers it on its `LynxConfig` (2.5.7) |
12
13
  | `<g9-richtext>` element (2.5.8) | `G9RichTextEditor` (`@g9tm/lynxcontrols-richtext`) | `G9RichTextUI`: an `EditText` with spans (markers, quotes, callouts, code, chips, pictures fetched by `G9NativeImages.fetch`); register `G9RichTextBehaviors.create()` | `G9LCRichTextUI` → `G9LCRichTextView` (Swift, a `UITextView` with TextKit 1); `G9LCImages.session` for the host's pinned session; the host registers it on its `LynxConfig`: `[config registerUI:G9LCRichTextUI.class withName:@"g9-richtext"]`. Web: `registerG9RichText()` (`@g9tm/lynxcontrols-web`) |
13
14
  | `<g9-canvas>` element (2.5.8) | `G9Canvas` (`@g9tm/lynxcontrols-canvas`) | `G9CanvasUI`: a view drawing the board's items (rough shapes, free drawing, text, pictures fetched by `G9NativeImages.fetch`), gestures and collaborators' pointers; exports through `G9CanvasFiles.register`; register `G9CanvasBehaviors.create()`; fonts `fonts/Excalifont.ttf`, `Nunito.ttf`, `ComicShanns.ttf` in the app's assets | `G9LCCanvasUI` → `G9LCCanvasView` (Swift); `G9LCImages.session` for pictures, `G9LCCanvasFiles.register` for exports, the same fonts in the bundle; the host registers it: `[config registerUI:G9LCCanvasUI.class withName:@"g9-canvas"]`. Web: `registerG9Canvas({ fonts, registerFile })` (`@g9tm/lynxcontrols-web`) |
@@ -37,6 +38,44 @@ const db = createG9Sqlite({ driver: createNativeSqliteDriver(), locator: singleF
37
38
  `isAvailable(locale)` is "a recogniser exists" on Android (asking a locale needs a broadcast some recognisers never
38
39
  answer; an unsupported language ends as `no-match`) and `SFSpeechRecognizer(locale).isAvailable` on iOS.
39
40
 
41
+ - **Photos** (2.7.0, `G9ImageModule`). Four calls, each one JSON string in and one JSON envelope back, all work off
42
+ the UI thread:
43
+ - `g9ImageProbe(path)`: the oriented size, the EXIF orientation (1–8), mime, bytes and alpha, without a decode;
44
+ - `g9ImagePreview(path, { maxSide, dir })`: an oriented, screen-sized JPEG (PNG with alpha) for the editor, never
45
+ upscaled;
46
+ - `g9ImageProcess(spec)`: the output's exact `width × height`, a 2×3 `matrix` from OUTPUT px to ORIENTED source px
47
+ (crop, quarter turns, flips, straighten, scale in one), `background`, `redact` (blur / pixelate regions), `overlay`
48
+ (SVG paths and Persian/Arabic-shaped text), `circle`, `format` (`jpeg`, `png`, `webp`, `source`) and `quality`,
49
+ `maxBytes` (quality by binary search down to 30, then 0.85 scale steps: `downscaled`), `keepMetadata`,
50
+ `passthrough`, `dir`, `name`;
51
+ - `g9ImageCancel(token)`: the process whose spec carried `token` rejects with `cancelled` and leaves no file.
52
+
53
+ One set of defaults on Android, iOS and the web (the TSDoc of `G9ImageProcessSpec` lists it whole): sizes and
54
+ `maxSide` are whole numbers 1..20000; `format` `jpeg`, `quality` 90, `keepMetadata` false, redaction `strength` 0.5;
55
+ paths 1 px, `butt`, `miter`; text 32 px, weight 400, line height 1.25, `#000000`, centred. A `maxBytes` that cannot
56
+ be reached (still too big at quality 30 once the shorter side would drop below 16 px) rejects with
57
+ `invalid-argument` and writes no file.
58
+
59
+ Every failure is a `G9ImageError` whose `code` is one of `invalid-argument`, `not-found`, `decode`, `memory`, `io`,
60
+ `cancelled`, `unsupported` (no module linked, or an older one without the method). Fit an upload to a server limit:
61
+
62
+ ```ts
63
+ import { g9ImageProbe, g9ImageProcess } from '@g9tm/lynxcontrols-native';
64
+
65
+ const { width, height } = await g9ImageProbe(photo);
66
+ const scale = Math.min(1, 2048 / Math.max(width, height));
67
+ const w = Math.round(width * scale);
68
+ const h = Math.round(height * scale);
69
+ const out = await g9ImageProcess({
70
+ path: photo, width: w, height: h, matrix: [1 / scale, 0, 0, 1 / scale, 0, 0],
71
+ format: 'jpeg', quality: 85, maxBytes: 500_000, keepMetadata: true,
72
+ });
73
+ ```
74
+
75
+ On the web the page answers the same module with a canvas (`@g9tm/lynxcontrols-web`): paths are URLs, the result is
76
+ a `blob:` URL, and metadata is always stripped (a canvas encoder writes none) — the result does not say so, as the
77
+ contract has no field for it.
78
+
40
79
  - **Video** (the intro carousel's `services.media`). `<g9-video>` props: `src`, `paused`, `loop`, `muted`,
41
80
  `start-seconds`, `near-end-seconds`, `object-fit`; events `ready`, `nearend`, `looped`, `error`. The provider's
42
81
  player renders it with reactive props (no UI-method calls) and unmounts it on `dispose()`, which releases the native
@@ -13,6 +13,8 @@ android {
13
13
  defaultConfig {
14
14
  minSdk = 24
15
15
  consumerProguardFiles("consumer-rules.pro")
16
+ // src/androidTest (G9ImageModule on a device): `gradle connectedAndroidTest` from a host build that includes this project.
17
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
16
18
  }
17
19
 
18
20
  compileOptions {
@@ -56,9 +58,14 @@ dependencies {
56
58
  // <g9-video> (video/G9VideoUI.kt): ExoPlayer drawing into a TextureView. Google Maven only.
57
59
  if (withMedia3) implementation("androidx.media3:media3-exoplayer:1.8.0")
58
60
  else compileOnly("androidx.media3:media3-exoplayer:1.8.0")
61
+ // G9ImageModule (image/): EXIF orientation and the keepMetadata copy (GPS, dates, camera) onto JPEG / PNG / WebP.
62
+ implementation("androidx.exifinterface:exifinterface:1.4.1")
59
63
 
60
64
  // The JVM contract suite also runs as Android local unit tests (same sources as ../jvm).
61
65
  testImplementation("junit:junit:4.13.2")
62
66
  testImplementation("org.json:json:20250517")
63
67
  testImplementation("org.xerial:sqlite-jdbc:3.50.3.0")
68
+
69
+ androidTestImplementation("androidx.test:runner:1.6.2")
70
+ androidTestImplementation("androidx.test.ext:junit:1.2.1")
64
71
  }
@@ -1,16 +1,32 @@
1
1
  package com.g9lynx.g9native
2
2
 
3
+ import java.io.File
3
4
  import java.net.HttpURLConnection
4
5
  import java.net.URI
5
6
 
6
7
  /**
7
8
  * How `<g9-richtext>` and `<g9-canvas>` fetch pictures (2.5.8): the bytes of an address, or null. The default is a
8
9
  * plain `HttpURLConnection` (15 s timeouts); a host with its own pinned client sets [fetch] before the first page opens.
10
+ * A local file (an absolute path or a `file://` URL, e.g. the photo editor's preview on the canvas) is read directly by
11
+ * [bytes], whatever [fetch] is.
9
12
  */
10
13
  object G9NativeImages {
11
14
  @Volatile
12
15
  var fetch: (String) -> ByteArray? = ::defaultFetch
13
16
 
17
+ /** The bytes of [src]: a local file read directly, anything else through [fetch]. */
18
+ fun bytes(src: String): ByteArray? {
19
+ val file = localFile(src) ?: return fetch(src)
20
+ return if (file.isFile) file.readBytes() else null
21
+ }
22
+
23
+ /** The file of an absolute path or a `file:` URL; null for other addresses. */
24
+ fun localFile(src: String): File? = when {
25
+ src.startsWith("/") -> File(src)
26
+ src.startsWith("file:", ignoreCase = true) -> runCatching { File(URI(src)) }.getOrNull()
27
+ else -> null
28
+ }
29
+
14
30
  private fun defaultFetch(src: String): ByteArray? {
15
31
  val connection = URI(src).toURL().openConnection() as HttpURLConnection
16
32
  return try {
@@ -13,7 +13,7 @@ sealed class CvOp
13
13
 
14
14
  class CvPathOp(val path: Path, val stroke: Int?, val width: Float, val dash: FloatArray?, val fill: Int?, val evenOdd: Boolean) : CvOp()
15
15
 
16
- class CvTextOp(val lines: List<String>, val x: Float, val y: Float, val lineHeight: Float, val size: Float, val font: Int, val color: Int, val align: String, val width: Float, val rtl: Boolean) : CvOp()
16
+ class CvTextOp(val lines: List<String>, val x: Float, val y: Float, val lineHeight: Float, val size: Float, val font: Int, val color: Int, val align: String, val width: Float, val rtl: Boolean, val weight: Int = 400) : CvOp()
17
17
 
18
18
  class CvImageOp(val file: String, val w: Float, val h: Float, val radius: Float, val crop: FloatArray?) : CvOp()
19
19
 
@@ -44,7 +44,7 @@ object CvParse {
44
44
  )
45
45
  "t" -> {
46
46
  val lines = op.optJSONArray("t")?.let { arr -> List(arr.length()) { arr.optString(it) } } ?: emptyList()
47
- ops.add(CvTextOp(lines, f(op, "x"), f(op, "y"), f(op, "lh"), f(op, "size", 20f), op.optInt("font", 5), G9CanvasPaths.color(op.optString("c")), op.optString("al", "left"), f(op, "w"), op.optBoolean("rtl", false)))
47
+ ops.add(CvTextOp(lines, f(op, "x"), f(op, "y"), f(op, "lh"), f(op, "size", 20f), op.optInt("font", 5), G9CanvasPaths.color(op.optString("c")), op.optString("al", "left"), f(op, "w"), op.optBoolean("rtl", false), op.optInt("wt", 400)))
48
48
  }
49
49
  "i" -> ops.add(CvImageOp(op.optString("file"), f(op, "w"), f(op, "h"), f(op, "r"), op.optJSONArray("crop")?.let { crop -> FloatArray(4) { crop.optDouble(it).toFloat() } }))
50
50
  }
@@ -2,6 +2,7 @@ package com.g9lynx.g9native.canvas
2
2
 
3
3
  import android.graphics.Color
4
4
  import android.graphics.Path
5
+ import com.g9lynx.g9native.image.core.G9ImageColor
5
6
 
6
7
  /**
7
8
  * SVG path data → [Path] (the `d` of `<g9-canvas>` path ops: roughjs's `M L C`, perfect-freehand's `M Q … L Z` with
@@ -158,35 +159,15 @@ object G9CanvasPaths {
158
159
  return out
159
160
  }
160
161
 
161
- /** CSS colours the app sends: #rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/rgba(), transparent, a few names. */
162
+ /**
163
+ * CSS colours the app sends: #rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/rgba(), transparent (the platform-free
164
+ * [G9ImageColor], shared with G9ImageModule), and Android's named colours.
165
+ */
162
166
  fun color(value: String?, fallback: Int = Color.BLACK): Int {
163
167
  val s = value?.trim()?.lowercase() ?: return fallback
164
168
  if (s.isEmpty()) return fallback
165
- if (s == "transparent" || s == "none") return Color.TRANSPARENT
166
- if (s.startsWith("#")) {
167
- val hex = s.substring(1)
168
- return runCatching {
169
- when (hex.length) {
170
- 3 -> Color.rgb(dup(hex[0]), dup(hex[1]), dup(hex[2]))
171
- 4 -> Color.argb(dup(hex[3]), dup(hex[0]), dup(hex[1]), dup(hex[2]))
172
- 6 -> Color.rgb(hex.substring(0, 2).toInt(16), hex.substring(2, 4).toInt(16), hex.substring(4, 6).toInt(16))
173
- 8 -> Color.argb(hex.substring(6, 8).toInt(16), hex.substring(0, 2).toInt(16), hex.substring(2, 4).toInt(16), hex.substring(4, 6).toInt(16))
174
- else -> fallback
175
- }
176
- }.getOrDefault(fallback)
177
- }
178
- if (s.startsWith("rgb")) {
179
- val parts = s.substringAfter('(').substringBefore(')').split(',', ' ', '/').filter { it.isNotBlank() }.map { it.trim() }
180
- return runCatching {
181
- val r = parts[0].toFloat().toInt()
182
- val g = parts[1].toFloat().toInt()
183
- val b = parts[2].toFloat().toInt()
184
- val a = parts.getOrNull(3)?.let { if (it.endsWith("%")) it.dropLast(1).toFloat() / 100f else it.toFloat() } ?: 1f
185
- Color.argb((a * 255).toInt().coerceIn(0, 255), r, g, b)
186
- }.getOrDefault(fallback)
187
- }
169
+ G9ImageColor.parse(s)?.let { return it }
170
+ if (s.startsWith("#") || s.startsWith("rgb")) return fallback
188
171
  return runCatching { Color.parseColor(s) }.getOrDefault(fallback)
189
172
  }
190
-
191
- private fun dup(c: Char): Int = "$c$c".toInt(16)
192
173
  }
@@ -23,6 +23,8 @@ import android.util.LruCache
23
23
  import android.view.MotionEvent
24
24
  import android.view.View
25
25
  import com.g9lynx.g9native.G9NativeImages
26
+ import com.g9lynx.g9native.image.G9HostTypeface
27
+ import com.g9lynx.g9native.image.core.G9HostFont
26
28
  import com.lynx.react.bridge.JavaOnlyArray
27
29
  import org.json.JSONObject
28
30
  import java.util.concurrent.Executors
@@ -719,7 +721,7 @@ class G9CanvasView(context: Context) : View(context) {
719
721
  }
720
722
  }
721
723
  is CvTextOp -> {
722
- text.typeface = typeface(op.font)
724
+ text.typeface = typeface(op.font, op.weight)
723
725
  text.textSize = op.size
724
726
  text.color = withAlpha(op.color, alpha)
725
727
  text.textAlign = when (op.align) {
@@ -727,7 +729,9 @@ class G9CanvasView(context: Context) : View(context) {
727
729
  "right" -> Paint.Align.RIGHT
728
730
  else -> Paint.Align.LEFT
729
731
  }
730
- op.lines.forEachIndexed { i, line -> canvas.drawText(line, op.x, op.y + i * op.lineHeight, text) }
732
+ // font 100: `y` is the first line's middle, the glyph box centred on it (the image overlay's rule)
733
+ val first = if (op.font == G9HostFont.CANVAS_FONT) text.fontMetrics.let { G9HostFont.centredBaseline(op.y, it.ascent, it.descent) } else op.y
734
+ op.lines.forEachIndexed { i, line -> canvas.drawText(line, op.x, first + i * op.lineHeight, text) }
731
735
  }
732
736
  is CvImageOp -> {
733
737
  val url = files[op.file]
@@ -933,7 +937,8 @@ class G9CanvasView(context: Context) : View(context) {
933
937
 
934
938
  // ================================================================================================ fonts, pictures
935
939
 
936
- private fun typeface(font: Int): Typeface = when (font) {
940
+ private fun typeface(font: Int, weight: Int): Typeface = when (font) {
941
+ G9HostFont.CANVAS_FONT -> G9HostTypeface.get(context.assets, "", weight)
937
942
  6 -> fonts.getOrPut("nunito") { load("fonts/Nunito.ttf") }
938
943
  8, 3 -> fonts.getOrPut("comic") { load("fonts/ComicShanns.ttf") }
939
944
  2, 9 -> Typeface.SANS_SERIF
@@ -947,7 +952,7 @@ class G9CanvasView(context: Context) : View(context) {
947
952
  synchronized(loading) { if (!loading.add(url)) return null }
948
953
  executor.execute {
949
954
  val bitmap = runCatching {
950
- G9NativeImages.fetch(url).let { bytes ->
955
+ G9NativeImages.bytes(url).let { bytes ->
951
956
  if (bytes == null) return@let null
952
957
  val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
953
958
  BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
@@ -0,0 +1,27 @@
1
+ // Generated by @lynx-js/autolink-codegen. Do not edit.
2
+ // Parameter types: scripts/android-bridge-types.mjs --fix (Lynx's bridge rejects the generator's Object).
3
+ package com.g9lynx.g9native.generated;
4
+
5
+ import androidx.annotation.Nullable;
6
+ import com.lynx.jsbridge.LynxContextModule;
7
+ import com.lynx.jsbridge.LynxMethod;
8
+ import com.lynx.react.bridge.Callback;
9
+ import com.lynx.tasm.behavior.LynxContext;
10
+
11
+ public abstract class G9ImageModuleSpec extends LynxContextModule {
12
+ public G9ImageModuleSpec(LynxContext context) {
13
+ super(context);
14
+ }
15
+
16
+ @LynxMethod
17
+ public abstract void probe(String args, Callback callback);
18
+
19
+ @LynxMethod
20
+ public abstract void preview(String args, Callback callback);
21
+
22
+ @LynxMethod
23
+ public abstract void process(String args, Callback callback);
24
+
25
+ @LynxMethod
26
+ public abstract void cancel(String args, Callback callback);
27
+ }
@@ -0,0 +1,49 @@
1
+ package com.g9lynx.g9native.image
2
+
3
+ import android.content.res.AssetManager
4
+ import android.graphics.Typeface
5
+ import android.os.Build
6
+ import com.g9lynx.g9native.image.core.G9HostFont
7
+ import com.lynx.tasm.behavior.shadow.text.TypefaceCache
8
+
9
+ /**
10
+ * The typeface of a font name at a weight, shared by G9ImageModule's text overlay and `<g9-canvas>` (font 100).
11
+ * "" = the host's text font: the Lynx typeface cache's `G9` / `G9Semi` / `G9Bold` (what `<g9-richtext>` uses; the host
12
+ * registers them), else the platform default at the weight. Another name: a family the host cached in Lynx, an asset
13
+ * (`fonts/<name>.ttf|.otf` or the asset path itself), or a system family.
14
+ */
15
+ internal object G9HostTypeface {
16
+ private val fonts = HashMap<String, Typeface>()
17
+
18
+ fun get(assets: AssetManager, font: String, weight: Int): Typeface {
19
+ if (font.isEmpty()) {
20
+ val exact = G9HostFont.families(weight).firstNotNullOfOrNull { cached(it) }
21
+ return exact ?: weighted(cached(G9HostFont.BASE) ?: Typeface.DEFAULT, weight)
22
+ }
23
+ val base = synchronized(fonts) {
24
+ fonts.getOrPut(font) {
25
+ cached(font)
26
+ ?: listOf("fonts/$font.ttf", "fonts/$font.otf", font).firstNotNullOfOrNull { asset ->
27
+ runCatching { Typeface.createFromAsset(assets, asset) }.getOrNull()
28
+ }
29
+ ?: Typeface.create(font, Typeface.NORMAL)
30
+ }
31
+ }
32
+ return weighted(base, weight)
33
+ }
34
+
35
+ /** A family registered in Lynx's typeface cache; null without Lynx in the process (the instrumented tests). */
36
+ private fun cached(family: String): Typeface? =
37
+ try {
38
+ TypefaceCache.getCachedTypeface(family, Typeface.NORMAL)
39
+ } catch (e: LinkageError) {
40
+ null
41
+ }
42
+
43
+ private fun weighted(base: Typeface, weight: Int): Typeface =
44
+ when {
45
+ Build.VERSION.SDK_INT >= 28 -> Typeface.create(base, weight, false)
46
+ weight >= 600 -> Typeface.create(base, Typeface.BOLD)
47
+ else -> base
48
+ }
49
+ }
@@ -0,0 +1,222 @@
1
+ package com.g9lynx.g9native.image
2
+
3
+ import android.content.res.AssetManager
4
+ import android.graphics.Bitmap
5
+ import android.graphics.Canvas
6
+ import android.graphics.Color
7
+ import android.graphics.DashPathEffect
8
+ import android.graphics.Matrix
9
+ import android.graphics.Paint
10
+ import android.graphics.Path
11
+ import android.graphics.PorterDuff
12
+ import android.graphics.PorterDuffXfermode
13
+ import android.graphics.RectF
14
+ import android.text.Layout
15
+ import android.text.SpannableString
16
+ import android.text.Spanned
17
+ import android.text.StaticLayout
18
+ import android.text.TextDirectionHeuristics
19
+ import android.text.TextPaint
20
+ import android.text.style.LineHeightSpan
21
+ import com.g9lynx.g9native.canvas.G9CanvasPaths
22
+ import com.g9lynx.g9native.image.core.G9Affine
23
+ import com.g9lynx.g9native.image.core.G9ImageRedaction
24
+ import com.g9lynx.g9native.image.core.G9ImageSpec
25
+ import com.g9lynx.g9native.image.core.G9ImageTicket
26
+ import com.g9lynx.g9native.image.core.G9PathOp
27
+ import com.g9lynx.g9native.image.core.G9Redaction
28
+ import com.g9lynx.g9native.image.core.G9TextOp
29
+ import kotlin.math.ceil
30
+ import kotlin.math.max
31
+ import kotlin.math.roundToInt
32
+
33
+ /**
34
+ * Step 5 of the pipeline on the output bitmap: redactions, overlay ops and the circle mask. Ops are in OUTPUT px of the
35
+ * requested size; [kx]/[ky] map them onto the bitmap when the memory budget drew it smaller.
36
+ */
37
+ internal class G9ImageDraw(private val assets: AssetManager, private val bitmap: Bitmap, private val kx: Float, private val ky: Float) {
38
+ private val canvas = Canvas(bitmap)
39
+
40
+ // ============================================================================================= redactions
41
+
42
+ /** Pixelate or blur the rotated rect, clipped to it. [outW]×[outH]: the requested output (the strength's base). */
43
+ fun redact(r: G9Redaction, outW: Int, outH: Int, ticket: G9ImageTicket?) {
44
+ val k = (kx + ky) / 2.0
45
+ val rx = r.x * kx
46
+ val ry = r.y * ky
47
+ val rw = r.width * kx
48
+ val rh = r.height * ky
49
+ if (rw <= 0 || rh <= 0) return
50
+ val block = G9ImageRedaction.block(r.strength, outW, outH) * k
51
+ val radius = G9ImageRedaction.radius(r.strength, outW, outH) * k
52
+ val pad = if (r.pixelate) 0.0 else radius * 2
53
+ val box = G9ImageRedaction.bounds(rx, ry, rw, rh, r.angle, pad, bitmap.width, bitmap.height) ?: return
54
+ ticket?.check()
55
+ val sub = Bitmap.createBitmap(bitmap, box.left, box.top, box.width, box.height)
56
+ val done = if (r.pixelate) pixelate(sub, block) else blur(sub, radius)
57
+ val clip = Path().apply { addRect(RectF(rx.toFloat(), ry.toFloat(), (rx + rw).toFloat(), (ry + rh).toFloat()), Path.Direction.CW) }
58
+ clip.transform(Matrix().apply { setRotate(r.angle.toFloat(), (rx + rw / 2).toFloat(), (ry + rh / 2).toFloat()) })
59
+ canvas.save()
60
+ canvas.clipPath(clip)
61
+ canvas.drawBitmap(done, box.left.toFloat(), box.top.toFloat(), null)
62
+ canvas.restore()
63
+ if (done !== sub && done !== bitmap) done.recycle()
64
+ if (sub !== bitmap) sub.recycle()
65
+ }
66
+
67
+ /** Downscale with no filtering (each block takes one source pixel), then upscale with none (hard blocks). */
68
+ private fun pixelate(sub: Bitmap, block: Double): Bitmap {
69
+ val w = max(1, ceil(sub.width / block).toInt())
70
+ val h = max(1, ceil(sub.height / block).toInt())
71
+ val small = Bitmap.createScaledBitmap(sub, w, h, false)
72
+ val big = Bitmap.createScaledBitmap(small, sub.width, sub.height, false)
73
+ if (small !== sub && small !== big) small.recycle()
74
+ return big
75
+ }
76
+
77
+ /** A filtered downscale, a three-pass box blur at the small size, a filtered upscale. */
78
+ private fun blur(sub: Bitmap, radius: Double): Bitmap {
79
+ val factor = max(1, (radius / 3).toInt())
80
+ val w = max(1, sub.width / factor)
81
+ val h = max(1, sub.height / factor)
82
+ val scaled = Bitmap.createScaledBitmap(sub, w, h, true)
83
+ val small = if (scaled.isMutable && scaled !== sub) scaled else scaled.copy(Bitmap.Config.ARGB_8888, true).also { if (scaled !== sub) scaled.recycle() }
84
+ val pixels = IntArray(w * h)
85
+ small.getPixels(pixels, 0, w, 0, 0, w, h)
86
+ G9ImageRedaction.boxBlur(pixels, w, h, max(1, (radius / factor).roundToInt()))
87
+ small.setPixels(pixels, 0, w, 0, 0, w, h)
88
+ val big = Bitmap.createScaledBitmap(small, sub.width, sub.height, true)
89
+ if (big !== small) small.recycle()
90
+ return big
91
+ }
92
+
93
+ // ============================================================================================= overlay
94
+
95
+ fun path(op: G9PathOp) {
96
+ canvas.save()
97
+ canvas.scale(kx, ky)
98
+ op.transform?.let { canvas.concat(Matrix().apply { setValues(G9Affine.toAndroid(it)) }) }
99
+ if (op.opacity < 1) canvas.saveLayerAlpha(null, (op.opacity * 255).roundToInt())
100
+ val path = G9CanvasPaths.parse(op.d)
101
+ op.fill?.let { fill ->
102
+ canvas.drawPath(path, Paint(Paint.ANTI_ALIAS_FLAG).apply {
103
+ style = Paint.Style.FILL
104
+ color = fill
105
+ })
106
+ }
107
+ val stroke = op.stroke
108
+ if (stroke != null && op.width > 0) {
109
+ canvas.drawPath(path, Paint(Paint.ANTI_ALIAS_FLAG).apply {
110
+ style = Paint.Style.STROKE
111
+ color = stroke
112
+ strokeWidth = op.width.toFloat()
113
+ strokeCap = when (op.cap) {
114
+ "round" -> Paint.Cap.ROUND
115
+ "square" -> Paint.Cap.SQUARE
116
+ else -> Paint.Cap.BUTT
117
+ }
118
+ strokeJoin = when (op.join) {
119
+ "round" -> Paint.Join.ROUND
120
+ "bevel" -> Paint.Join.BEVEL
121
+ else -> Paint.Join.MITER
122
+ }
123
+ op.dash?.let { d ->
124
+ // SVG repeats an odd list to make it even.
125
+ val even = if (d.size % 2 == 1) d + d else d
126
+ pathEffect = DashPathEffect(FloatArray(even.size) { even[it].toFloat() }, 0f)
127
+ }
128
+ })
129
+ }
130
+ canvas.restore()
131
+ }
132
+
133
+ /** A text block centred on (x, y), rotated about its centre, over its rounded background. */
134
+ fun text(op: G9TextOp) {
135
+ if (op.text.isEmpty()) return
136
+ val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
137
+ textSize = op.size.toFloat()
138
+ color = op.color
139
+ typeface = G9HostTypeface.get(assets, op.font, op.weight)
140
+ }
141
+ val direction = when (op.rtl) {
142
+ true -> TextDirectionHeuristics.RTL
143
+ false -> TextDirectionHeuristics.LTR
144
+ null -> TextDirectionHeuristics.FIRSTSTRONG_LTR
145
+ }
146
+ val rtl = direction.isRtl(op.text, 0, op.text.length)
147
+ val alignment = when (op.align) {
148
+ "start" -> Layout.Alignment.ALIGN_NORMAL
149
+ "end" -> Layout.Alignment.ALIGN_OPPOSITE
150
+ "left" -> if (rtl) Layout.Alignment.ALIGN_OPPOSITE else Layout.Alignment.ALIGN_NORMAL
151
+ "right" -> if (rtl) Layout.Alignment.ALIGN_NORMAL else Layout.Alignment.ALIGN_OPPOSITE
152
+ else -> Layout.Alignment.ALIGN_CENTER
153
+ }
154
+ val desired = ceil(Layout.getDesiredWidth(op.text, paint).toDouble())
155
+ val width = max(1, ceil(op.maxWidth?.let { minOf(it, desired) } ?: desired).toInt())
156
+ // Every line exactly 1.25 × size tall (the shared default), the extra split above and below the glyphs.
157
+ val text = SpannableString(op.text).apply { setSpan(ExactLineHeight((op.size * G9ImageSpec.LINE_HEIGHT).roundToInt()), 0, length, Spanned.SPAN_INCLUSIVE_INCLUSIVE) }
158
+ val layout = StaticLayout.Builder.obtain(text, 0, text.length, paint, width)
159
+ .setAlignment(alignment)
160
+ .setTextDirection(direction)
161
+ .setIncludePad(false)
162
+ .build()
163
+ val lw = layout.width.toFloat()
164
+ val lh = layout.height.toFloat()
165
+ val pad = op.padding.toFloat()
166
+ val bw = lw + 2 * pad
167
+ val bh = lh + 2 * pad
168
+ val block = RectF(-bw / 2, -bh / 2, bw / 2, bh / 2)
169
+ canvas.save()
170
+ canvas.scale(kx, ky)
171
+ canvas.translate(op.x.toFloat(), op.y.toFloat())
172
+ canvas.rotate(op.angle.toFloat())
173
+ if (op.opacity < 1) canvas.saveLayerAlpha(block, (op.opacity * 255).roundToInt())
174
+ op.background?.let { bg ->
175
+ val r = op.radius.toFloat()
176
+ canvas.drawRoundRect(block, r, r, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = bg })
177
+ }
178
+ canvas.translate(-lw / 2, -lh / 2)
179
+ layout.draw(canvas)
180
+ canvas.restore()
181
+ }
182
+
183
+ // ============================================================================================= circle
184
+
185
+ /**
186
+ * Outside the ellipse inscribed in the bitmap: cleared ([alpha] formats), or for JPEG (which cannot be clear) the
187
+ * opaque base again: white, then [background] over it.
188
+ */
189
+ fun circle(alpha: Boolean, background: Int?) {
190
+ val w = bitmap.width.toFloat()
191
+ val h = bitmap.height.toFloat()
192
+ val outside = Path().apply {
193
+ fillType = Path.FillType.EVEN_ODD
194
+ addRect(0f, 0f, w, h, Path.Direction.CW)
195
+ addOval(RectF(0f, 0f, w, h), Path.Direction.CW)
196
+ }
197
+ if (alpha) {
198
+ canvas.drawPath(outside, Paint(Paint.ANTI_ALIAS_FLAG).apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR) })
199
+ } else {
200
+ canvas.drawPath(outside, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.WHITE })
201
+ background?.let { bg -> canvas.drawPath(outside, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = bg }) }
202
+ }
203
+ }
204
+
205
+ /** The non-alpha base: white, then the background colour over it. */
206
+ fun opaqueBase(background: Int?) {
207
+ canvas.drawColor(Color.WHITE)
208
+ background?.let { canvas.drawColor(it) }
209
+ }
210
+
211
+ /** Sets each line's ascent + descent to [height] px, the glyphs centred in it. */
212
+ private class ExactLineHeight(private val height: Int) : LineHeightSpan {
213
+ override fun chooseHeight(text: CharSequence, start: Int, end: Int, spanstartv: Int, lineHeight: Int, fm: Paint.FontMetricsInt) {
214
+ val glyphs = fm.descent - fm.ascent
215
+ if (glyphs <= 0) return
216
+ fm.ascent -= (height - glyphs) / 2
217
+ fm.descent = fm.ascent + height
218
+ fm.top = fm.ascent
219
+ fm.bottom = fm.descent
220
+ }
221
+ }
222
+ }
@@ -0,0 +1,54 @@
1
+ package com.g9lynx.g9native.image
2
+
3
+ import android.content.Context
4
+ import com.g9lynx.g9native.generated.G9ImageModuleSpec
5
+ import com.g9lynx.g9native.image.core.G9ImageService
6
+ import com.lynx.jsbridge.LynxMethod
7
+ import com.lynx.jsbridge.LynxNativeModule
8
+ import com.lynx.react.bridge.Callback
9
+ import com.lynx.tasm.behavior.LynxContext
10
+ import java.util.concurrent.Executors
11
+
12
+ /**
13
+ * `NativeModules.G9ImageModule` (G9PhotoEditor, 2.7.0): probe, preview, process and cancel pictures off the UI thread
14
+ * (the G9ImageModule native contract: one JSON string in, one JSON string envelope out). Linked by Lynx Autolink like the other
15
+ * modules (`@LynxNativeModule` → lynx-processor's `LynxLibraryProviderImpl`); a host does nothing more. One process-wide
16
+ * service on ONE background thread, so a 48 MP decode never runs twice at once.
17
+ * TWIN: ios/src/G9ImageModule.m.
18
+ */
19
+ @LynxNativeModule(name = "G9ImageModule")
20
+ class G9ImageModule(context: LynxContext) : G9ImageModuleSpec(context) {
21
+ private val service = service(context)
22
+
23
+ @LynxMethod
24
+ override fun probe(args: String?, callback: Callback?) = service.probe(args) { callback?.invoke(it) }
25
+
26
+ @LynxMethod
27
+ override fun preview(args: String?, callback: Callback?) = service.preview(args) { callback?.invoke(it) }
28
+
29
+ @LynxMethod
30
+ override fun process(args: String?, callback: Callback?) = service.process(args) { callback?.invoke(it) }
31
+
32
+ @LynxMethod
33
+ override fun cancel(args: String?, callback: Callback?) = service.cancel(args) { callback?.invoke(it) }
34
+
35
+ companion object {
36
+ @Volatile
37
+ private var shared: G9ImageService? = null
38
+
39
+ /** The process-wide service (its executor and cancellation tokens), created on first use. */
40
+ @JvmStatic
41
+ fun service(context: Context): G9ImageService =
42
+ shared ?: synchronized(this) {
43
+ shared ?: G9ImageService(
44
+ G9ImageProcessor(context.applicationContext ?: context),
45
+ Executors.newSingleThreadExecutor { r ->
46
+ Thread({
47
+ android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
48
+ r.run()
49
+ }, "g9-image").apply { isDaemon = true }
50
+ },
51
+ ).also { shared = it }
52
+ }
53
+ }
54
+ }