@g9tm/lynxcontrols-native 2.5.7 → 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 (33) hide show
  1. package/README.md +5 -0
  2. package/android/src/main/java/com/g9lynx/g9native/G9NativeImages.kt +24 -0
  3. package/android/src/main/java/com/g9lynx/g9native/blurhash/G9BlurhashUI.kt +76 -0
  4. package/android/src/main/java/com/g9lynx/g9native/blurhash/core/G9Blurhash.kt +100 -0
  5. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasModel.kt +94 -0
  6. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasPaths.kt +192 -0
  7. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasUI.kt +162 -0
  8. package/android/src/main/java/com/g9lynx/g9native/canvas/G9CanvasView.kt +1053 -0
  9. package/android/src/main/java/com/g9lynx/g9native/richtext/G9PictureSpan.kt +99 -0
  10. package/android/src/main/java/com/g9lynx/g9native/richtext/G9RichEditText.kt +458 -0
  11. package/android/src/main/java/com/g9lynx/g9native/richtext/G9RichStyle.kt +343 -0
  12. package/android/src/main/java/com/g9lynx/g9native/richtext/G9RichTextUI.kt +94 -0
  13. package/catalog/catalog.json +1 -1
  14. package/catalog/index.md +1 -1
  15. package/dist/.tsbuildinfo +1 -1
  16. package/ios/g9lynx-native-swift.podspec +20 -0
  17. package/ios/g9lynx-native.podspec +6 -2
  18. package/ios/src/G9LCBlurhashUI.h +14 -0
  19. package/ios/src/G9LCBlurhashUI.m +28 -0
  20. package/ios/src/G9LCCanvasUI.h +18 -0
  21. package/ios/src/G9LCCanvasUI.m +81 -0
  22. package/ios/src/G9LCRichTextUI.h +16 -0
  23. package/ios/src/G9LCRichTextUI.m +71 -0
  24. package/ios/swift/blurhash/G9LCBlurhashView.swift +165 -0
  25. package/ios/swift/canvas/G9LCCanvasCore.swift +848 -0
  26. package/ios/swift/canvas/G9LCCanvasView.swift +482 -0
  27. package/ios/swift/richtext/G9LCRichStyle.swift +238 -0
  28. package/ios/swift/richtext/G9LCRichTextView.swift +647 -0
  29. package/ios/swift/shared/G9LCColors.swift +78 -0
  30. package/ios/swift/shared/G9LCFonts.swift +38 -0
  31. package/ios/swift/shared/G9LCImages.swift +28 -0
  32. package/ios/swift/shared/G9LCJson.swift +73 -0
  33. package/package.json +6 -4
package/README.md CHANGED
@@ -9,6 +9,9 @@ Android and iOS platform layer for G9: three Lynx native modules and one element
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
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
 
@@ -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
+ }
@@ -0,0 +1,162 @@
1
+ package com.g9lynx.g9native.canvas
2
+
3
+ import android.content.Context
4
+ import android.graphics.Bitmap
5
+ import com.lynx.react.bridge.Callback
6
+ import com.lynx.react.bridge.JavaOnlyMap
7
+ import com.lynx.react.bridge.ReadableMap
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.LynxUIMethod
12
+ import com.lynx.tasm.behavior.LynxUIMethodConstants
13
+ import com.lynx.tasm.behavior.ui.LynxUI
14
+ import com.lynx.tasm.event.LynxDetailEvent
15
+ import org.json.JSONObject
16
+ import java.util.concurrent.Executors
17
+
18
+ /**
19
+ * `<g9-canvas tool editable theme background accent stroke bindcv…>` (Plan-Lynx §6, W11): the drawing surface of a
20
+ * whiteboard ([G9CanvasView]). The scene, editing and sync are the app's (client/app `features/whiteboard`); this
21
+ * element draws the items it is sent and reports gestures. Protocol: `canvas/protocol.ts`; gesture rules:
22
+ * `canvas/element-core.ts`.
23
+ *
24
+ * Methods: `apply({ json })` (a message), `exportImage({ token, scale, padding, background, name })` → `cvexport`.
25
+ */
26
+ class G9CanvasUI(context: LynxContext) : LynxUI<G9CanvasView>(context) {
27
+ // LynxUI's constructor calls createView before this class's initialisers run: no initialiser here.
28
+ private lateinit var surface: G9CanvasView
29
+
30
+ override fun createView(context: Context): G9CanvasView {
31
+ val view = G9CanvasView(context)
32
+ view.emitter = { name, detail -> emit(name, detail) }
33
+ surface = view
34
+ return view
35
+ }
36
+
37
+ @LynxProp(name = "tool")
38
+ fun setTool(value: String?) {
39
+ mView?.tool = value ?: "selection"
40
+ }
41
+
42
+ @LynxProp(name = "editable", defaultBoolean = false)
43
+ fun setEditable(value: Boolean) {
44
+ mView?.editable = value
45
+ }
46
+
47
+ @LynxProp(name = "theme")
48
+ fun setTheme(value: String?) {
49
+ mView?.setDark(value == "dark")
50
+ }
51
+
52
+ @LynxProp(name = "background")
53
+ fun setBackground(value: String?) {
54
+ mView?.background = G9CanvasPaths.color(value, android.graphics.Color.WHITE)
55
+ }
56
+
57
+ @LynxProp(name = "accent")
58
+ fun setAccent(value: String?) {
59
+ mView?.accent = G9CanvasPaths.color(value, android.graphics.Color.rgb(0x69, 0x65, 0xdb))
60
+ }
61
+
62
+ @LynxProp(name = "stroke")
63
+ fun setStroke(value: String?) {
64
+ val view = mView ?: return
65
+ val o = runCatching { JSONObject(value ?: "{}") }.getOrNull() ?: return
66
+ view.strokeColor = G9CanvasPaths.color(o.optString("color"), android.graphics.Color.BLACK)
67
+ view.strokeWidthStyle = o.optDouble("width", 2.0).toFloat()
68
+ view.fillColor = if (o.has("fill")) G9CanvasPaths.color(o.optString("fill")) else null
69
+ }
70
+
71
+ /** The app's message (`invoke({ method: 'apply', params: { json } })`). */
72
+ @LynxUIMethod
73
+ fun apply(params: ReadableMap, callback: Callback) {
74
+ val json = params.getString("json")
75
+ if (!json.isNullOrEmpty()) runCatching { mView?.apply(JSONObject(json)) }.onFailure { android.util.Log.w(TAG, "apply failed", it) }
76
+ callback.invoke(LynxUIMethodConstants.SUCCESS)
77
+ }
78
+
79
+ /** Renders the board to a PNG registered in the file store (like a picked file); answers with `cvexport`. */
80
+ @LynxUIMethod
81
+ fun exportImage(params: ReadableMap, callback: Callback) {
82
+ callback.invoke(LynxUIMethodConstants.SUCCESS)
83
+ val view = mView ?: return
84
+ val token = if (params.hasKey("token")) params.getString("token") ?: "" else ""
85
+ val scale = if (params.hasKey("scale")) params.getDouble("scale").toFloat() else 2f
86
+ val padding = if (params.hasKey("padding")) params.getDouble("padding").toFloat() else 24f
87
+ val background = !params.hasKey("background") || params.getBoolean("background")
88
+ val name = (if (params.hasKey("name")) params.getString("name") else null)?.takeIf { it.isNotBlank() } ?: "whiteboard.png"
89
+ val bitmap = runCatching { view.renderExport(scale, padding, background) }.getOrNull()
90
+ if (bitmap == null) {
91
+ emit("cvexport", mapOf("token" to token, "error" to "empty"))
92
+ return
93
+ }
94
+ io.execute {
95
+ try {
96
+ val app = view.context.applicationContext
97
+ val dir = java.io.File(app.cacheDir, "g9canvas").apply { mkdirs() }
98
+ val file = java.io.File(dir, "board-${System.currentTimeMillis()}.png")
99
+ file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
100
+ val entry = G9CanvasFiles.register(file, name, "image/png") + mapOf("width" to bitmap.width, "height" to bitmap.height)
101
+ val ref = JavaOnlyMap()
102
+ for ((key, value) in entry) {
103
+ when (value) {
104
+ null -> ref.putNull(key)
105
+ is Int -> ref.putInt(key, value)
106
+ is Long -> ref.putDouble(key, value.toDouble())
107
+ is Double -> ref.putDouble(key, value)
108
+ is Boolean -> ref.putBoolean(key, value)
109
+ else -> ref.putString(key, value.toString())
110
+ }
111
+ }
112
+ view.post { emit("cvexport", mapOf("token" to token, "file" to ref)) }
113
+ } catch (e: Exception) {
114
+ view.post { emit("cvexport", mapOf("token" to token, "error" to (e.message ?: "export_failed"))) }
115
+ } finally {
116
+ bitmap.recycle()
117
+ }
118
+ }
119
+ }
120
+
121
+ private fun emit(name: String, detail: Map<String, Any?>) {
122
+ // The event adds its own fields to the map: a mutable copy.
123
+ lynxContext.eventEmitter.sendCustomEvent(LynxDetailEvent(sign, name, HashMap(detail)))
124
+ }
125
+
126
+ override fun destroy() {
127
+ if (::surface.isInitialized) surface.emitter = null
128
+ super.destroy()
129
+ }
130
+
131
+ companion object {
132
+ private val io = Executors.newSingleThreadExecutor { runnable -> Thread(runnable, "g9-canvas-export").apply { isDaemon = true } }
133
+ }
134
+ }
135
+
136
+ private const val TAG = "G9Canvas"
137
+
138
+ /** Registers `<g9-canvas>` on the app's page (host/G9Pages.kt). */
139
+ /**
140
+ * How an exported board becomes the app's file (2.5.8): the PNG written to the app's cache, then [register] gives the
141
+ * `cvexport` event its `file` (`id`, `name`, `size`, `mime`, `uri`). A host with its own file store sets [register].
142
+ */
143
+ object G9CanvasFiles {
144
+ @Volatile
145
+ var register: (java.io.File, String, String) -> Map<String, Any?> = { file, name, mime ->
146
+ mapOf("id" to file.absolutePath, "name" to name, "size" to file.length(), "mime" to mime, "uri" to "file://${file.absolutePath}")
147
+ }
148
+ }
149
+
150
+ /**
151
+ * The behaviour of `<g9-canvas>` (`@g9tm/lynxcontrols-native`, 2.5.8). Add it with the host's own:
152
+ * `LynxViewBuilder().addBehaviors(hostBehaviors + G9CanvasBehaviors.create())`. The board's fonts are the app's
153
+ * assets `fonts/Excalifont.ttf`, `fonts/Nunito.ttf`, `fonts/ComicShanns.ttf` (the default typeface without them).
154
+ */
155
+ object G9CanvasBehaviors {
156
+ fun create(): List<Behavior> =
157
+ listOf(
158
+ object : Behavior("g9-canvas", false, false, false) {
159
+ override fun createUI(context: LynxContext): LynxUI<*> = G9CanvasUI(context)
160
+ },
161
+ )
162
+ }