@g9tm/lynxcontrols-native 2.5.6 → 2.5.8

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 (45) hide show
  1. package/README.md +6 -1
  2. package/android/build.gradle.kts +11 -2
  3. package/android/src/main/java/com/g9lynx/g9native/G9Bridge.kt +47 -2
  4. package/android/src/main/java/com/g9lynx/g9native/G9NativeImages.kt +24 -0
  5. package/android/src/main/java/com/g9lynx/g9native/blurhash/G9BlurhashUI.kt +76 -0
  6. package/android/src/main/java/com/g9lynx/g9native/blurhash/core/G9Blurhash.kt +100 -0
  7. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasModel.kt +94 -0
  8. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasPaths.kt +192 -0
  9. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasUI.kt +162 -0
  10. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasView.kt +1053 -0
  11. package/android/src/main/java/com/g9lynx/g9native/richtext/G9PictureSpan.kt +99 -0
  12. package/android/src/main/java/com/g9lynx/g9native/richtext/G9RichEditText.kt +458 -0
  13. package/android/src/main/java/com/g9lynx/g9native/richtext/G9RichStyle.kt +343 -0
  14. package/android/src/main/java/com/g9lynx/g9native/richtext/G9RichTextUI.kt +94 -0
  15. package/catalog/catalog.json +2 -2
  16. package/catalog/index.md +1 -1
  17. package/dist/.tsbuildinfo +1 -1
  18. package/dist/media.d.ts +1 -1
  19. package/dist/media.d.ts.map +1 -1
  20. package/dist/services.d.ts +8 -0
  21. package/dist/services.d.ts.map +1 -1
  22. package/dist/services.js +4 -2
  23. package/dist/services.js.map +1 -1
  24. package/ios/g9lynx-native-swift.podspec +20 -0
  25. package/ios/g9lynx-native.podspec +6 -2
  26. package/ios/src/G9LCBlurhashUI.h +14 -0
  27. package/ios/src/G9LCBlurhashUI.m +28 -0
  28. package/ios/src/G9LCCanvasUI.h +18 -0
  29. package/ios/src/G9LCCanvasUI.m +81 -0
  30. package/ios/src/G9LCRichTextUI.h +16 -0
  31. package/ios/src/G9LCRichTextUI.m +71 -0
  32. package/ios/src/{G9VideoUI.h → G9LCVideoUI.h} +5 -5
  33. package/ios/src/{G9VideoUI.m → G9LCVideoUI.m} +9 -8
  34. package/ios/src/G9PointerEventsHitTest.h +5 -1
  35. package/ios/src/G9PointerEventsHitTest.m +6 -0
  36. package/ios/swift/blurhash/G9LCBlurhashView.swift +165 -0
  37. package/ios/swift/canvas/G9LCCanvasCore.swift +848 -0
  38. package/ios/swift/canvas/G9LCCanvasView.swift +482 -0
  39. package/ios/swift/richtext/G9LCRichStyle.swift +238 -0
  40. package/ios/swift/richtext/G9LCRichTextView.swift +647 -0
  41. package/ios/swift/shared/G9LCColors.swift +78 -0
  42. package/ios/swift/shared/G9LCFonts.swift +38 -0
  43. package/ios/swift/shared/G9LCImages.swift +28 -0
  44. package/ios/swift/shared/G9LCJson.swift +73 -0
  45. package/package.json +6 -4
package/README.md CHANGED
@@ -8,7 +8,10 @@ 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
- | `<g9-video>` element | `createNativeMediaProvider()` (`@g9tm/lynxcontrols-native/media`) | `G9VideoUI`: Media3 ExoPlayer 1.8.0 into a `TextureView` (opacity fades work); register `G9VideoBehaviors.create()` | `G9VideoUI`: `AVQueuePlayer` + `AVPlayerLooper` in an `AVPlayerLayer`; self-registers (`LYNX_REGISTER_UI`) |
11
+ | `<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
+ | `<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
+ | `<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`) |
14
+ | `<g9-blurhash>` element (2.5.8) | `G9BlurhashView` with `native` (`@g9tm/lynxcontrols-media`) | `G9BlurhashUI`: an `ImageView` showing a 32×32 decode (cached by hash) stretched with filtering; register `G9BlurhashBehaviors.create()` | `G9LCBlurhashUI` → `G9LCBlurhashView` (Swift, decoded off the main thread); the host registers it: `[config registerUI:G9LCBlurhashUI.class withName:@"g9-blurhash"]`. Web: none (the JSX draws its own SVG placeholder) |
12
15
  | `<input>` / `<textarea>` drawing the culture's digits (`g9-digits`, set by the library's fields) | none | `G9InputBehaviors.create()`: xelement-input's fields with a `ReplacementTransformationMethod` | `[G9InputBehaviors registerOn:config]`: XElement's fields with a digits font in front of their own (a `UIFontDescriptor` cascade list; the fonts in `ios/fonts`, from Vazirmatn, SIL OFL 1.1) |
13
16
 
14
17
  ```ts
@@ -87,6 +90,8 @@ The native identifiers are internal and did not follow the npm rename to `@g9tm/
87
90
  the Android package `com.g9lynx.g9native`, the iOS pod `g9lynx-native`, the module classes `G9SqliteModule` and
88
91
  `G9HostModule`, and the preference store `g9lynx.preferences` keep their names, so hosts and stored data are not
89
92
  affected. The pod's version follows the package version (the family's `LYNX_VERSION`).
93
+ Since 2.5.8 the Swift views (`G9LCRichTextView`, `G9LCCanvasView`, `G9LCBlurhashView`) are the second pod
94
+ `g9lynx-native-swift` in the same `ios/` folder (no Lynx dependency); a Podfile names both pods with the same `:path`.
90
95
 
91
96
  ## Commands
92
97
 
@@ -29,6 +29,13 @@ kotlin { compilerOptions { jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarg
29
29
 
30
30
  val lynx = "4.2.0"
31
31
 
32
+ // What a host may leave out (G9Hub, Riskara, 2.5.7), in its gradle.properties: `g9native.media3=false` (no <g9-video>,
33
+ // no ExoPlayer in the APK) and `g9native.sqlite=false` (no bundled SQLite). Left out, the library still compiles
34
+ // against them; the host then must not register G9VideoBehaviors / G9SqliteModule. Default: both in, as before.
35
+ fun g9Feature(name: String): Boolean = (findProperty("g9native.$name") as String?)?.trim()?.toBoolean() ?: true
36
+ val withMedia3 = g9Feature("media3")
37
+ val withSqlite = g9Feature("sqlite")
38
+
32
39
  dependencies {
33
40
  compileOnly("org.lynxsdk.lynx:lynx:$lynx")
34
41
  compileOnly("org.lynxsdk.lynx:service-api:$lynx")
@@ -44,9 +51,11 @@ dependencies {
44
51
  // G9SpeechModule asks for the microphone through the host activity's ActivityResultRegistry: compile-only, as every
45
52
  // host of these libraries ships androidx.activity (a host without it gets the current state, never a prompt).
46
53
  compileOnly("androidx.activity:activity:1.10.1")
47
- implementation("androidx.sqlite:sqlite-bundled:2.7.1")
54
+ if (withSqlite) implementation("androidx.sqlite:sqlite-bundled:2.7.1")
55
+ else compileOnly("androidx.sqlite:sqlite-bundled:2.7.1")
48
56
  // <g9-video> (video/G9VideoUI.kt): ExoPlayer drawing into a TextureView. Google Maven only.
49
- implementation("androidx.media3:media3-exoplayer:1.8.0")
57
+ if (withMedia3) implementation("androidx.media3:media3-exoplayer:1.8.0")
58
+ else compileOnly("androidx.media3:media3-exoplayer:1.8.0")
50
59
 
51
60
  // The JVM contract suite also runs as Android local unit tests (same sources as ../jvm).
52
61
  testImplementation("junit:junit:4.13.2")
@@ -5,6 +5,7 @@ import com.lynx.react.bridge.JavaOnlyArray
5
5
  import com.lynx.react.bridge.JavaOnlyMap
6
6
  import com.lynx.react.bridge.ReadableArray
7
7
  import com.lynx.react.bridge.ReadableMap
8
+ import com.lynx.react.bridge.ReadableType
8
9
 
9
10
  /**
10
11
  * Copies between Lynx bridge containers and the plain Kotlin data the cores speak (`Map`, `List`, `String`, `Double`,
@@ -13,18 +14,62 @@ import com.lynx.react.bridge.ReadableMap
13
14
  internal object G9Bridge {
14
15
  fun map(value: Any?): Map<*, *> =
15
16
  when (value) {
16
- is ReadableMap -> value.toHashMap()
17
+ is ReadableMap -> readMap(value)
17
18
  is Map<*, *> -> value
18
19
  else -> emptyMap<String, Any?>()
19
20
  }
20
21
 
21
22
  fun list(value: Any?): List<*> =
22
23
  when (value) {
23
- is ReadableArray -> value.toArrayList()
24
+ is ReadableArray -> readArray(value)
24
25
  is List<*> -> value
25
26
  else -> emptyList<Any?>()
26
27
  }
27
28
 
29
+ // A deep copy by type (2.5.7, G9Hub): `toHashMap` / `toArrayList` are deprecated in Lynx 4.2. Numbers keep the kind
30
+ // the bridge gave (Int, Long, Double), as those did: SQLite binds an Int as an integer; a type the cores do not
31
+ // speak (PiperData, TemplateData …) is null.
32
+ private fun readMap(value: ReadableMap): Map<String, Any?> {
33
+ val out = HashMap<String, Any?>(value.size())
34
+ val keys = value.keySetIterator()
35
+ while (keys.hasNextKey()) {
36
+ val key = keys.nextKey()
37
+ out[key] =
38
+ when (value.getType(key)) {
39
+ ReadableType.Boolean -> value.getBoolean(key)
40
+ ReadableType.Int -> value.getInt(key)
41
+ ReadableType.Number -> value.getDouble(key)
42
+ ReadableType.Long -> value.getLong(key)
43
+ ReadableType.String -> value.getString(key)
44
+ ReadableType.Map -> value.getMap(key)?.let(::readMap)
45
+ ReadableType.Array -> value.getArray(key)?.let(::readArray)
46
+ ReadableType.ByteArray -> value.getByteArray(key)
47
+ else -> null
48
+ }
49
+ }
50
+ return out
51
+ }
52
+
53
+ private fun readArray(value: ReadableArray): List<Any?> {
54
+ val out = ArrayList<Any?>(value.size())
55
+ for (i in 0 until value.size()) {
56
+ out.add(
57
+ when (value.getType(i)) {
58
+ ReadableType.Boolean -> value.getBoolean(i)
59
+ ReadableType.Int -> value.getInt(i)
60
+ ReadableType.Number -> value.getDouble(i)
61
+ ReadableType.Long -> value.getLong(i)
62
+ ReadableType.String -> value.getString(i)
63
+ ReadableType.Map -> value.getMap(i)?.let(::readMap)
64
+ ReadableType.Array -> value.getArray(i)?.let(::readArray)
65
+ ReadableType.ByteArray -> value.getByteArray(i)
66
+ else -> null
67
+ },
68
+ )
69
+ }
70
+ return out
71
+ }
72
+
28
73
  fun toMap(value: Map<*, *>): JavaOnlyMap {
29
74
  val out = JavaOnlyMap()
30
75
  for ((k, v) in value) {
@@ -0,0 +1,24 @@
1
+ package com.g9lynx.g9native
2
+
3
+ import java.net.HttpURLConnection
4
+ import java.net.URI
5
+
6
+ /**
7
+ * How `<g9-richtext>` and `<g9-canvas>` fetch pictures (2.5.8): the bytes of an address, or null. The default is a
8
+ * plain `HttpURLConnection` (15 s timeouts); a host with its own pinned client sets [fetch] before the first page opens.
9
+ */
10
+ object G9NativeImages {
11
+ @Volatile
12
+ var fetch: (String) -> ByteArray? = ::defaultFetch
13
+
14
+ private fun defaultFetch(src: String): ByteArray? {
15
+ val connection = URI(src).toURL().openConnection() as HttpURLConnection
16
+ return try {
17
+ connection.connectTimeout = 15_000
18
+ connection.readTimeout = 15_000
19
+ if (connection.responseCode !in 200..299) null else connection.inputStream.use { it.readBytes() }
20
+ } finally {
21
+ connection.disconnect()
22
+ }
23
+ }
24
+ }
@@ -0,0 +1,76 @@
1
+ package com.g9lynx.g9native.blurhash
2
+
3
+ import android.content.Context
4
+ import android.graphics.Bitmap
5
+ import android.graphics.drawable.BitmapDrawable
6
+ import android.util.LruCache
7
+ import android.widget.ImageView
8
+ import com.lynx.tasm.behavior.Behavior
9
+ import com.lynx.tasm.behavior.LynxContext
10
+ import com.lynx.tasm.behavior.LynxProp
11
+ import com.lynx.tasm.behavior.ui.LynxUI
12
+
13
+ /**
14
+ * `<g9-blurhash hash="LEHV6nWB2yk8pyo0adR*.7kCMdnj" punch={1} style="width:…;height:…" />` (Plan-Lynx §6): an image
15
+ * placeholder decoded natively — a 32×32 decode stretched with filtering over the element's box (fixed size, like an
16
+ * `<image>`). Put it under the `<image>` of the real picture; an invalid or empty hash draws nothing. Decoded bitmaps
17
+ * are cached by hash (lists scroll back to the same placeholders).
18
+ */
19
+ class G9BlurhashUI(context: LynxContext) : LynxUI<ImageView>(context) {
20
+ private var hash: String? = null
21
+ private var punch = 1.0
22
+
23
+ override fun createView(context: Context): ImageView = ImageView(context).apply {
24
+ scaleType = ImageView.ScaleType.FIT_XY
25
+ importantForAccessibility = ImageView.IMPORTANT_FOR_ACCESSIBILITY_NO
26
+ }
27
+
28
+ @LynxProp(name = "hash")
29
+ fun setHash(value: String?) {
30
+ if (value == hash) return
31
+ hash = value
32
+ draw()
33
+ }
34
+
35
+ @LynxProp(name = "punch", defaultDouble = 1.0)
36
+ fun setPunch(value: Double) {
37
+ if (value == punch) return
38
+ punch = value
39
+ draw()
40
+ }
41
+
42
+ private fun draw() {
43
+ val view = mView ?: return
44
+ val key = "$hash|$punch"
45
+ val bitmap = hash?.let { text ->
46
+ cache.get(key) ?: G9Blurhash.decode(text, SIZE, SIZE, punch)?.let { pixels ->
47
+ Bitmap.createBitmap(pixels, SIZE, SIZE, Bitmap.Config.ARGB_8888).also { cache.put(key, it) }
48
+ }
49
+ }
50
+ if (bitmap == null) {
51
+ view.setImageDrawable(null)
52
+ return
53
+ }
54
+ view.setImageDrawable(BitmapDrawable(view.resources, bitmap).apply { isFilterBitmap = true })
55
+ }
56
+
57
+ private companion object {
58
+ const val SIZE = 32
59
+
60
+ /** ~4 KB per entry. */
61
+ val cache = LruCache<String, Bitmap>(256)
62
+ }
63
+ }
64
+
65
+ /**
66
+ * The behaviour of `<g9-blurhash>` (`@g9tm/lynxcontrols-native`, 2.5.8). Add it with the host's own:
67
+ * `LynxViewBuilder().addBehaviors(hostBehaviors + G9BlurhashBehaviors.create())`.
68
+ */
69
+ object G9BlurhashBehaviors {
70
+ fun create(): List<Behavior> =
71
+ listOf(
72
+ object : Behavior("g9-blurhash", false, false, false) {
73
+ override fun createUI(context: LynxContext): LynxUI<*> = G9BlurhashUI(context)
74
+ },
75
+ )
76
+ }
@@ -0,0 +1,100 @@
1
+ package com.g9lynx.g9native.blurhash
2
+
3
+ import kotlin.math.PI
4
+ import kotlin.math.cos
5
+ import kotlin.math.pow
6
+ import kotlin.math.roundToInt
7
+ import kotlin.math.sign
8
+ import kotlin.math.withSign
9
+
10
+ /**
11
+ * BlurHash decoding (https://blurha.sh, the reference algorithm) for `<g9-blurhash>` (2.5.8, from G9Hub): a hash of 6–28+ characters →
12
+ * [width]×[height] ARGB pixels (the element shows a 32×32 decode stretched smoothly; that is what a blurhash is for).
13
+ * Pure Kotlin, JVM-tested.
14
+ */
15
+ object G9Blurhash {
16
+ private const val CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#\$%*+,-.:;=?@[]^_{|}~"
17
+
18
+ /** Whether [hash] is well-formed (length matches its component counts, every character in the alphabet). */
19
+ fun isValid(hash: String?): Boolean {
20
+ if (hash == null || hash.length < 6) return false
21
+ if (hash.any { CHARS.indexOf(it) < 0 }) return false
22
+ val size = decode83(hash, 0, 1)
23
+ val numY = size / 9 + 1
24
+ val numX = size % 9 + 1
25
+ return hash.length == 4 + 2 * numX * numY
26
+ }
27
+
28
+ /** ARGB pixels, or null for an invalid hash. [punch] > 1 strengthens the colours. */
29
+ fun decode(hash: String?, width: Int, height: Int, punch: Double = 1.0): IntArray? {
30
+ if (!isValid(hash) || width <= 0 || height <= 0) return null
31
+ val text = hash!!
32
+ val size = decode83(text, 0, 1)
33
+ val numY = size / 9 + 1
34
+ val numX = size % 9 + 1
35
+ val quantisedMax = decode83(text, 1, 2)
36
+ val maxValue = (quantisedMax + 1) / 166.0 * punch
37
+ val colors = Array(numX * numY) { i ->
38
+ if (i == 0) decodeDc(decode83(text, 2, 6))
39
+ else decodeAc(decode83(text, 4 + i * 2, 6 + i * 2), maxValue)
40
+ }
41
+ val cosX = Array(numX) { i -> DoubleArray(width) { x -> cos(PI * x * i / width) } }
42
+ val cosY = Array(numY) { j -> DoubleArray(height) { y -> cos(PI * y * j / height) } }
43
+ val pixels = IntArray(width * height)
44
+ for (y in 0 until height) {
45
+ for (x in 0 until width) {
46
+ var r = 0.0
47
+ var g = 0.0
48
+ var b = 0.0
49
+ for (j in 0 until numY) {
50
+ val cy = cosY[j][y]
51
+ for (i in 0 until numX) {
52
+ val basis = cosX[i][x] * cy
53
+ val color = colors[i + j * numX]
54
+ r += color[0] * basis
55
+ g += color[1] * basis
56
+ b += color[2] * basis
57
+ }
58
+ }
59
+ pixels[x + y * width] = (0xff shl 24) or (linearToSrgb(r) shl 16) or (linearToSrgb(g) shl 8) or linearToSrgb(b)
60
+ }
61
+ }
62
+ return pixels
63
+ }
64
+
65
+ /** The average colour (the DC component) as ARGB: a placeholder colour without decoding. */
66
+ fun averageColor(hash: String?): Int? {
67
+ if (!isValid(hash)) return null
68
+ val value = decode83(hash!!, 2, 6)
69
+ return (0xff shl 24) or value
70
+ }
71
+
72
+ private fun decode83(text: String, from: Int, to: Int): Int {
73
+ var value = 0
74
+ for (i in from until to) value = value * 83 + CHARS.indexOf(text[i])
75
+ return value
76
+ }
77
+
78
+ private fun decodeDc(value: Int): DoubleArray =
79
+ doubleArrayOf(srgbToLinear(value shr 16), srgbToLinear((value shr 8) and 255), srgbToLinear(value and 255))
80
+
81
+ private fun decodeAc(value: Int, maxValue: Double): DoubleArray {
82
+ val r = value / (19 * 19)
83
+ val g = (value / 19) % 19
84
+ val b = value % 19
85
+ return doubleArrayOf(signPow((r - 9) / 9.0, 2.0) * maxValue, signPow((g - 9) / 9.0, 2.0) * maxValue, signPow((b - 9) / 9.0, 2.0) * maxValue)
86
+ }
87
+
88
+ private fun signPow(value: Double, exp: Double): Double = kotlin.math.abs(value).pow(exp).withSign(value.sign)
89
+
90
+ private fun srgbToLinear(value: Int): Double {
91
+ val v = value / 255.0
92
+ return if (v <= 0.04045) v / 12.92 else ((v + 0.055) / 1.055).pow(2.4)
93
+ }
94
+
95
+ private fun linearToSrgb(value: Double): Int {
96
+ val v = value.coerceIn(0.0, 1.0)
97
+ return if (v <= 0.0031308) (v * 12.92 * 255 + 0.5).roundToInt().coerceIn(0, 255)
98
+ else ((1.055 * v.pow(1 / 2.4) - 0.055) * 255 + 0.5).roundToInt().coerceIn(0, 255)
99
+ }
100
+ }
@@ -0,0 +1,94 @@
1
+ package com.g9lynx.g9native.canvas
2
+
3
+ import android.graphics.Path
4
+ import android.graphics.RectF
5
+ import org.json.JSONArray
6
+ import org.json.JSONObject
7
+
8
+ /**
9
+ * What `<g9-canvas>` holds, parsed from the app's messages (client/app `features/whiteboard/canvas/protocol.ts`):
10
+ * items with their drawing ops (paths parsed once into [Path]s), the selection, collaborators, picture URLs.
11
+ */
12
+ sealed class CvOp
13
+
14
+ class CvPathOp(val path: Path, val stroke: Int?, val width: Float, val dash: FloatArray?, val fill: Int?, val evenOdd: Boolean) : CvOp()
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()
17
+
18
+ class CvImageOp(val file: String, val w: Float, val h: Float, val radius: Float, val crop: FloatArray?) : CvOp()
19
+
20
+ class CvItem(val id: String, val version: Int, val x: Float, val y: Float, val angle: Float, val cx: Float, val cy: Float, val opacity: Float, val bounds: RectF, val ops: List<CvOp>)
21
+
22
+ class CvRotatedBox(val box: RectF, val angle: Float)
23
+
24
+ class CvSelection(val ids: Set<String>, val boxes: List<CvRotatedBox>, val frame: CvRotatedBox?, val handles: String, val points: List<FloatArray>?)
25
+
26
+ class CvPeer(val id: String, val name: String, val color: Int, val x: Float?, val y: Float?, val boxes: List<CvRotatedBox>)
27
+
28
+ object CvParse {
29
+ fun item(o: JSONObject): CvItem {
30
+ val ops = ArrayList<CvOp>()
31
+ val list = o.optJSONArray("ops") ?: JSONArray()
32
+ for (i in 0 until list.length()) {
33
+ val op = list.optJSONObject(i) ?: continue
34
+ when (op.optString("k")) {
35
+ "p" -> ops.add(
36
+ CvPathOp(
37
+ G9CanvasPaths.parse(op.optString("d")),
38
+ if (op.has("s")) G9CanvasPaths.color(op.optString("s")) else null,
39
+ op.optDouble("w", 1.0).toFloat(),
40
+ op.optJSONArray("dash")?.let { dash -> FloatArray(dash.length()) { dash.optDouble(it).toFloat() } },
41
+ if (op.has("f")) G9CanvasPaths.color(op.optString("f")) else null,
42
+ op.optBoolean("eo", false)
43
+ )
44
+ )
45
+ "t" -> {
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)))
48
+ }
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
+ }
51
+ }
52
+ val b = o.optJSONArray("b")
53
+ return CvItem(
54
+ o.optString("id"),
55
+ o.optInt("v"),
56
+ f(o, "x"),
57
+ f(o, "y"),
58
+ f(o, "a"),
59
+ f(o, "cx"),
60
+ f(o, "cy"),
61
+ f(o, "o", 1f),
62
+ if (b != null) RectF(b.optDouble(0).toFloat(), b.optDouble(1).toFloat(), b.optDouble(2).toFloat(), b.optDouble(3).toFloat()) else RectF(),
63
+ ops
64
+ )
65
+ }
66
+
67
+ fun box(o: JSONObject?): CvRotatedBox? {
68
+ val b = o?.optJSONArray("b") ?: return null
69
+ return CvRotatedBox(RectF(b.optDouble(0).toFloat(), b.optDouble(1).toFloat(), b.optDouble(2).toFloat(), b.optDouble(3).toFloat()), o.optDouble("a", 0.0).toFloat())
70
+ }
71
+
72
+ fun boxes(a: JSONArray?): List<CvRotatedBox> = a?.let { arr -> (0 until arr.length()).mapNotNull { box(arr.optJSONObject(it)) } } ?: emptyList()
73
+
74
+ fun selection(o: JSONObject?): CvSelection? {
75
+ if (o == null) return null
76
+ val ids = o.optJSONArray("ids")?.let { arr -> (0 until arr.length()).map { arr.optString(it) }.toSet() } ?: emptySet()
77
+ val points = o.optJSONArray("points")?.let { arr -> (0 until arr.length()).map { i -> arr.optJSONArray(i).let { p -> floatArrayOf(p.optDouble(0).toFloat(), p.optDouble(1).toFloat()) } } }
78
+ return CvSelection(ids, boxes(o.optJSONArray("boxes")), box(o.optJSONObject("frame")), o.optString("handles", "none"), points)
79
+ }
80
+
81
+ fun peers(a: JSONArray): List<CvPeer> = (0 until a.length()).mapNotNull { i ->
82
+ val p = a.optJSONObject(i) ?: return@mapNotNull null
83
+ CvPeer(
84
+ p.optString("id"),
85
+ p.optString("name"),
86
+ G9CanvasPaths.color(p.optString("color")),
87
+ if (p.isNull("x") || !p.has("x")) null else p.optDouble("x").toFloat(),
88
+ if (p.isNull("y") || !p.has("y")) null else p.optDouble("y").toFloat(),
89
+ boxes(p.optJSONArray("boxes"))
90
+ )
91
+ }
92
+
93
+ private fun f(o: JSONObject, key: String, fallback: Float = 0f): Float = if (o.has(key) && !o.isNull(key)) o.optDouble(key, fallback.toDouble()).toFloat() else fallback
94
+ }
@@ -0,0 +1,192 @@
1
+ package com.g9lynx.g9native.canvas
2
+
3
+ import android.graphics.Color
4
+ import android.graphics.Path
5
+
6
+ /**
7
+ * SVG path data → [Path] (the `d` of `<g9-canvas>` path ops: roughjs's `M L C`, perfect-freehand's `M Q … L Z` with
8
+ * implicit repeats, Excalidraw's own shapes). Absolute and relative M L H V C S Q T Z; arcs are not produced by the app.
9
+ */
10
+ object G9CanvasPaths {
11
+ fun parse(d: String): Path {
12
+ val path = Path()
13
+ val tokens = tokenize(d)
14
+ var i = 0
15
+ var command = 'M'
16
+ var x = 0f
17
+ var y = 0f
18
+ var startX = 0f
19
+ var startY = 0f
20
+ var lastControlX = 0f
21
+ var lastControlY = 0f
22
+ var lastWasCurve = false
23
+ var lastWasQuad = false
24
+ fun number(): Float = (tokens.getOrNull(i++) as? Float) ?: 0f
25
+ while (i < tokens.size) {
26
+ val token = tokens[i]
27
+ if (token is Char) {
28
+ command = token
29
+ i++
30
+ if (command == 'Z' || command == 'z') {
31
+ path.close()
32
+ x = startX
33
+ y = startY
34
+ lastWasCurve = false
35
+ lastWasQuad = false
36
+ continue
37
+ }
38
+ }
39
+ val relative = command.isLowerCase()
40
+ val ox = if (relative) x else 0f
41
+ val oy = if (relative) y else 0f
42
+ when (command.uppercaseChar()) {
43
+ 'M' -> {
44
+ x = ox + number()
45
+ y = oy + number()
46
+ path.moveTo(x, y)
47
+ startX = x
48
+ startY = y
49
+ // Further pairs after M are line-tos.
50
+ command = if (relative) 'l' else 'L'
51
+ lastWasCurve = false
52
+ lastWasQuad = false
53
+ }
54
+ 'L' -> {
55
+ x = ox + number()
56
+ y = oy + number()
57
+ path.lineTo(x, y)
58
+ lastWasCurve = false
59
+ lastWasQuad = false
60
+ }
61
+ 'H' -> {
62
+ x = ox + number()
63
+ path.lineTo(x, y)
64
+ lastWasCurve = false
65
+ lastWasQuad = false
66
+ }
67
+ 'V' -> {
68
+ y = oy + number()
69
+ path.lineTo(x, y)
70
+ lastWasCurve = false
71
+ lastWasQuad = false
72
+ }
73
+ 'C' -> {
74
+ val x1 = ox + number()
75
+ val y1 = oy + number()
76
+ val x2 = ox + number()
77
+ val y2 = oy + number()
78
+ x = ox + number()
79
+ y = oy + number()
80
+ path.cubicTo(x1, y1, x2, y2, x, y)
81
+ lastControlX = x2
82
+ lastControlY = y2
83
+ lastWasCurve = true
84
+ lastWasQuad = false
85
+ }
86
+ 'S' -> {
87
+ val x1 = if (lastWasCurve) 2 * x - lastControlX else x
88
+ val y1 = if (lastWasCurve) 2 * y - lastControlY else y
89
+ val x2 = ox + number()
90
+ val y2 = oy + number()
91
+ x = ox + number()
92
+ y = oy + number()
93
+ path.cubicTo(x1, y1, x2, y2, x, y)
94
+ lastControlX = x2
95
+ lastControlY = y2
96
+ lastWasCurve = true
97
+ lastWasQuad = false
98
+ }
99
+ 'Q' -> {
100
+ val x1 = ox + number()
101
+ val y1 = oy + number()
102
+ x = ox + number()
103
+ y = oy + number()
104
+ path.quadTo(x1, y1, x, y)
105
+ lastControlX = x1
106
+ lastControlY = y1
107
+ lastWasQuad = true
108
+ lastWasCurve = false
109
+ }
110
+ 'T' -> {
111
+ val x1 = if (lastWasQuad) 2 * x - lastControlX else x
112
+ val y1 = if (lastWasQuad) 2 * y - lastControlY else y
113
+ x = ox + number()
114
+ y = oy + number()
115
+ path.quadTo(x1, y1, x, y)
116
+ lastControlX = x1
117
+ lastControlY = y1
118
+ lastWasQuad = true
119
+ lastWasCurve = false
120
+ }
121
+ else -> i++ // unknown command (arcs): skip its numbers one by one
122
+ }
123
+ }
124
+ return path
125
+ }
126
+
127
+ private fun tokenize(d: String): List<Any> {
128
+ val out = ArrayList<Any>(d.length / 3)
129
+ var i = 0
130
+ val n = d.length
131
+ while (i < n) {
132
+ val c = d[i]
133
+ when {
134
+ c.isLetter() && c != 'e' && c != 'E' -> {
135
+ out.add(c)
136
+ i++
137
+ }
138
+ c == '-' || c == '+' || c == '.' || c.isDigit() -> {
139
+ val start = i
140
+ i++
141
+ var seenDot = c == '.'
142
+ while (i < n) {
143
+ val ch = d[i]
144
+ if (ch.isDigit()) i++
145
+ else if (ch == '.' && !seenDot) {
146
+ seenDot = true
147
+ i++
148
+ } else if ((ch == 'e' || ch == 'E') && i + 1 < n) {
149
+ i++
150
+ if (d[i] == '-' || d[i] == '+') i++
151
+ } else break
152
+ }
153
+ d.substring(start, i).toFloatOrNull()?.let { out.add(it) }
154
+ }
155
+ else -> i++
156
+ }
157
+ }
158
+ return out
159
+ }
160
+
161
+ /** CSS colours the app sends: #rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/rgba(), transparent, a few names. */
162
+ fun color(value: String?, fallback: Int = Color.BLACK): Int {
163
+ val s = value?.trim()?.lowercase() ?: return fallback
164
+ 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
+ }
188
+ return runCatching { Color.parseColor(s) }.getOrDefault(fallback)
189
+ }
190
+
191
+ private fun dup(c: Char): Int = "$c$c".toInt(16)
192
+ }