@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
@@ -0,0 +1,1053 @@
1
+ package com.g9lynx.g9native.canvas
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.content.Context
5
+ import android.graphics.Bitmap
6
+ import android.graphics.BitmapFactory
7
+ import android.graphics.Canvas
8
+ import android.graphics.Color
9
+ import android.graphics.ColorMatrix
10
+ import android.graphics.ColorMatrixColorFilter
11
+ import android.graphics.DashPathEffect
12
+ import android.graphics.Matrix
13
+ import android.graphics.Paint
14
+ import android.graphics.Path
15
+ import android.graphics.Picture
16
+ import android.graphics.Rect
17
+ import android.graphics.RectF
18
+ import android.graphics.Typeface
19
+ import android.os.Handler
20
+ import android.os.Looper
21
+ import android.os.SystemClock
22
+ import android.util.LruCache
23
+ import android.view.MotionEvent
24
+ import android.view.View
25
+ import com.g9lynx.g9native.G9NativeImages
26
+ import com.lynx.react.bridge.JavaOnlyArray
27
+ import org.json.JSONObject
28
+ import java.util.concurrent.Executors
29
+ import kotlin.math.abs
30
+ import kotlin.math.atan2
31
+ import kotlin.math.cos
32
+ import kotlin.math.hypot
33
+ import kotlin.math.max
34
+ import kotlin.math.min
35
+ import kotlin.math.sin
36
+
37
+ /**
38
+ * The surface of `<g9-canvas>` (G9CanvasUI.kt): a [View] drawing the whiteboard on its [Canvas] and running the
39
+ * gesture rules of client/app `features/whiteboard/canvas/element-core.ts` (a line-by-line port: same states, same
40
+ * events, same thresholds). Units are Lynx px (dp); the camera is Excalidraw's `scrollX/scrollY/zoom`.
41
+ *
42
+ * Drawing: the scene layer is recorded once into a [Picture] in scene coordinates and replayed through the camera
43
+ * matrix every frame — panning and pinching never re-record it; only a scene change does. The overlay (moving items via
44
+ * the live matrix, previews, selection, marquee, eraser trail, collaborators) is drawn on top. Dark mode is Excalidraw's
45
+ * `invert(93%) hue-rotate(180deg)` as a colour matrix on the view's hardware layer.
46
+ */
47
+ @SuppressLint("ViewConstructor")
48
+ class G9CanvasView(context: Context) : View(context) {
49
+ var emitter: ((String, Map<String, Any?>) -> Unit)? = null
50
+
51
+ private val density = resources.displayMetrics.density
52
+ private val main = Handler(Looper.getMainLooper())
53
+
54
+ // ------------------------------------------------------------------ state (element-core.ts)
55
+ private val items = HashMap<String, CvItem>()
56
+ private var order: List<String> = emptyList()
57
+ private val files = HashMap<String, String>()
58
+ private var selection: CvSelection? = null
59
+ private var peers: List<CvPeer> = emptyList()
60
+ private var hidden: Set<String> = emptySet()
61
+ private var faded: Set<String> = emptySet()
62
+ var tool = "selection"
63
+ set(value) {
64
+ if (value == field) return
65
+ field = value
66
+ cancelGesture()
67
+ }
68
+ var editable = false
69
+ var background = Color.WHITE
70
+ set(value) {
71
+ field = value
72
+ sceneDirty = true
73
+ invalidate()
74
+ }
75
+ var accent = Color.rgb(0x69, 0x65, 0xdb)
76
+ var strokeColor = Color.BLACK
77
+ var strokeWidthStyle = 2f
78
+ var fillColor: Int? = null
79
+
80
+ private var scrollXv = 0f
81
+ private var scrollYv = 0f
82
+ private var zoom = 1f
83
+ private var widthDp = 0f
84
+ private var heightDp = 0f
85
+
86
+ private val previews = LinkedHashMap<Int, Preview>()
87
+ private var live: Pair<Int, Matrix>? = null
88
+ private val pointers = LinkedHashMap<Int, FloatArray>()
89
+ private var gesture: Gesture? = null
90
+ private var seq = 0
91
+ private var lastTap: FloatArray? = null
92
+ private var lastTapTime = 0L
93
+ private var lastCursor = 0L
94
+ private var lastViewEmit = 0L
95
+ private var viewPending = false
96
+ private val trail = ArrayList<FloatArray>()
97
+ private var panning = false
98
+ private var moveStarted = false
99
+
100
+ private var scenePicture: Picture? = null
101
+ private var pictureOrigin = floatArrayOf(0f, 0f)
102
+ private var sceneDirty = true
103
+
104
+ private sealed class Preview {
105
+ class Shape(val tool: String, val box: RectF) : Preview()
106
+ class Line(val tool: String, val points: List<FloatArray>) : Preview()
107
+ class Stroke(val points: FloatArrayList) : Preview()
108
+ class Point(val points: List<FloatArray>) : Preview()
109
+ }
110
+
111
+ private sealed class Gesture {
112
+ class Pan(var lastX: Float, var lastY: Float) : Gesture()
113
+ class Pinch(val a: Int, val b: Int, val startDistance: Float, val startZoom: Float, val sceneMid: FloatArray) : Gesture()
114
+ class Draw(val g: Int, val points: FloatArrayList, val pressures: FloatArrayList?) : Gesture()
115
+ class Shape(val g: Int, val tool: String, val start: FloatArray, var end: FloatArray) : Gesture()
116
+ class Line(val g: Int, val tool: String, val start: FloatArray, var end: FloatArray) : Gesture()
117
+ class Erase(val g: Int, val points: FloatArrayList) : Gesture()
118
+ class Pending(val g: Int, val start: FloatArray, var end: FloatArray, var released: Boolean) : Gesture()
119
+ class Move(val g: Int, val start: FloatArray, var end: FloatArray) : Gesture()
120
+ class Marquee(val g: Int, val start: FloatArray, var end: FloatArray) : Gesture()
121
+ class Resize(val g: Int, val handle: String, val from: RectF, val angle: Float, var to: RectF) : Gesture()
122
+ class Rotate(val g: Int, val pivot: FloatArray, val startAngle: Float, var delta: Float, val from: RectF) : Gesture()
123
+ class PointDrag(val g: Int, val index: Int, val points: MutableList<FloatArray>) : Gesture()
124
+ class Tap(val g: Int, val start: FloatArray, val screen: FloatArray, val tool: String) : Gesture()
125
+ }
126
+
127
+ class FloatArrayList {
128
+ var data = FloatArray(64)
129
+ var size = 0
130
+ fun add(v: Float) {
131
+ if (size == data.size) data = data.copyOf(size * 2)
132
+ data[size++] = v
133
+ }
134
+ operator fun get(i: Int) = data[i]
135
+ fun toArray(): JavaOnlyArray = JavaOnlyArray().also { for (i in 0 until size) it.pushDouble(data[i].toDouble()) }
136
+ }
137
+
138
+ init {
139
+ isClickable = true
140
+ isFocusable = false
141
+ }
142
+
143
+ // ================================================================================================ app → element
144
+
145
+ fun apply(message: JSONObject) {
146
+ var scene = false
147
+ if (message.optBoolean("reset", false)) {
148
+ items.clear()
149
+ order = emptyList()
150
+ scene = true
151
+ }
152
+ message.optJSONArray("items")?.let { list ->
153
+ for (i in 0 until list.length()) list.optJSONObject(i)?.let { o -> CvParse.item(o).also { items[it.id] = it } }
154
+ scene = true
155
+ }
156
+ message.optJSONArray("remove")?.let { list ->
157
+ for (i in 0 until list.length()) items.remove(list.optString(i))
158
+ scene = true
159
+ }
160
+ message.optJSONArray("order")?.let { list ->
161
+ order = List(list.length()) { list.optString(it) }
162
+ scene = true
163
+ }
164
+ message.optJSONObject("files")?.let { map ->
165
+ for (key in map.keys()) files[key] = map.optString(key)
166
+ scene = true
167
+ }
168
+ message.optJSONArray("hidden")?.let { list ->
169
+ hidden = (0 until list.length()).map { list.optString(it) }.toSet()
170
+ scene = true
171
+ }
172
+ message.optJSONArray("faded")?.let { list ->
173
+ faded = (0 until list.length()).map { list.optString(it) }.toSet()
174
+ scene = true
175
+ }
176
+ if (message.has("selection")) {
177
+ val before = selection?.ids
178
+ selection = CvParse.selection(message.optJSONObject("selection"))
179
+ if (live != null && before != selection?.ids) scene = true
180
+ }
181
+ message.optJSONArray("peers")?.let { peers = CvParse.peers(it) }
182
+ message.optJSONArray("done")?.let { list ->
183
+ for (i in 0 until list.length()) {
184
+ val g = list.optInt(i)
185
+ previews.remove(g)
186
+ if (live?.first == g) {
187
+ live = null
188
+ scene = true
189
+ }
190
+ }
191
+ }
192
+ message.optJSONObject("gesture")?.let { answer(it.optInt("id"), it.optBoolean("grab")) }
193
+ message.optJSONObject("view")?.let { setView(it.optDouble("scrollX").toFloat(), it.optDouble("scrollY").toFloat(), it.optDouble("zoom", 1.0).toFloat(), true) }
194
+ if (scene) sceneDirty = true
195
+ invalidate()
196
+ }
197
+
198
+ fun setDark(dark: Boolean) {
199
+ if (dark) {
200
+ // invert(93%) then hue-rotate(180deg), composed (CSS filter effects matrices).
201
+ val h = floatArrayOf(-0.574f, 1.43f, 0.144f, 0.426f, 0.43f, 0.144f, 0.426f, 1.43f, -0.856f)
202
+ val k = -0.86f
203
+ val offset = 0.93f * 255f
204
+ val values = floatArrayOf(
205
+ h[0] * k, h[1] * k, h[2] * k, 0f, offset,
206
+ h[3] * k, h[4] * k, h[5] * k, 0f, offset,
207
+ h[6] * k, h[7] * k, h[8] * k, 0f, offset,
208
+ 0f, 0f, 0f, 1f, 0f
209
+ )
210
+ setLayerType(LAYER_TYPE_HARDWARE, Paint().apply { colorFilter = ColorMatrixColorFilter(ColorMatrix(values)) })
211
+ } else setLayerType(LAYER_TYPE_NONE, null)
212
+ invalidate()
213
+ }
214
+
215
+ // ================================================================================================ camera
216
+
217
+ private fun toScene(x: Float, y: Float) = floatArrayOf(x / zoom - scrollXv, y / zoom - scrollYv)
218
+
219
+ private fun toScreen(x: Float, y: Float) = floatArrayOf((x + scrollXv) * zoom, (y + scrollYv) * zoom)
220
+
221
+ private fun setView(sx: Float, sy: Float, z: Float, announce: Boolean) {
222
+ if (!sx.isFinite() || !sy.isFinite() || !z.isFinite()) return
223
+ zoom = z.coerceIn(MIN_ZOOM, MAX_ZOOM)
224
+ scrollXv = sx
225
+ scrollYv = sy
226
+ if (announce) emitView(true)
227
+ invalidate()
228
+ }
229
+
230
+ private fun emitView(force: Boolean) {
231
+ val now = SystemClock.uptimeMillis()
232
+ if (force || now - lastViewEmit > 120) {
233
+ lastViewEmit = now
234
+ emitter?.invoke("cvview", mapOf("scrollX" to scrollXv.toDouble(), "scrollY" to scrollYv.toDouble(), "zoom" to zoom.toDouble(), "width" to widthDp.toDouble(), "height" to heightDp.toDouble()))
235
+ } else if (!viewPending) {
236
+ viewPending = true
237
+ main.postDelayed({
238
+ viewPending = false
239
+ emitView(true)
240
+ }, 120)
241
+ }
242
+ }
243
+
244
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
245
+ super.onSizeChanged(w, h, oldw, oldh)
246
+ widthDp = w / density
247
+ heightDp = h / density
248
+ emitView(true)
249
+ }
250
+
251
+ // ================================================================================================ selection geometry
252
+
253
+ private fun frame(): CvRotatedBox? {
254
+ val s = selection ?: return null
255
+ if (s.frame == null || s.handles == "none") return null
256
+ return s.frame
257
+ }
258
+
259
+ private fun handles(touch: Boolean): List<Triple<String, Float, Float>> {
260
+ val f = frame() ?: return emptyList()
261
+ if (!editable) return emptyList()
262
+ val b = f.box
263
+ val pad = (if (touch) 8f else 4f) / zoom
264
+ val cx = b.centerX()
265
+ val cy = b.centerY()
266
+ val left = b.left - pad
267
+ val right = b.right + pad
268
+ val top = b.top - pad
269
+ val bottom = b.bottom + pad
270
+ val list = arrayListOf(Triple("nw", left, top), Triple("ne", right, top), Triple("sw", left, bottom), Triple("se", right, bottom))
271
+ val small = b.width() * zoom < 40 || b.height() * zoom < 40
272
+ if (selection?.handles == "all" && !small) list += listOf(Triple("n", cx, top), Triple("s", cx, bottom), Triple("w", left, cy), Triple("e", right, cy))
273
+ list += Triple("rotation", cx, top - (if (touch) 34f else 22f) / zoom)
274
+ return list.map { (h, x, y) ->
275
+ val p = rotate(floatArrayOf(x, y), cx, cy, f.angle)
276
+ Triple(h, p[0], p[1])
277
+ }
278
+ }
279
+
280
+ private fun insideFrame(p: FloatArray): Boolean {
281
+ val s = selection ?: return false
282
+ val f = s.frame ?: (if (s.boxes.size == 1) s.boxes[0] else null) ?: return false
283
+ val b = f.box
284
+ val q = rotate(p, b.centerX(), b.centerY(), -f.angle)
285
+ val pad = 4f / zoom
286
+ return q[0] >= b.left - pad && q[0] <= b.right + pad && q[1] >= b.top - pad && q[1] <= b.bottom + pad
287
+ }
288
+
289
+ private fun liveMatrix(): Matrix? {
290
+ when (val g = gesture) {
291
+ is Gesture.Move -> if (moveStarted) return Matrix().apply { setTranslate(g.end[0] - g.start[0], g.end[1] - g.start[1]) }
292
+ is Gesture.Resize -> return resizeMatrix(g.from, g.to, g.angle)
293
+ is Gesture.Rotate -> return Matrix().apply { setRotate(Math.toDegrees(g.delta.toDouble()).toFloat(), g.pivot[0], g.pivot[1]) }
294
+ else -> {}
295
+ }
296
+ return live?.second
297
+ }
298
+
299
+ private fun movingIds(): Set<String> = if (liveMatrix() != null) selection?.ids ?: emptySet() else emptySet()
300
+
301
+ // ================================================================================================ touch
302
+
303
+ @SuppressLint("ClickableViewAccessibility")
304
+ override fun onTouchEvent(event: MotionEvent): Boolean {
305
+ val index = event.actionIndex
306
+ when (event.actionMasked) {
307
+ MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
308
+ parent?.requestDisallowInterceptTouchEvent(true)
309
+ pointerDown(event.getPointerId(index), event.getX(index) / density, event.getY(index) / density, kind(event, index), event.getPressure(index), event.buttonState)
310
+ }
311
+ MotionEvent.ACTION_MOVE -> {
312
+ for (h in 0 until event.historySize) for (p in 0 until event.pointerCount) pointerMove(event.getPointerId(p), event.getHistoricalX(p, h) / density, event.getHistoricalY(p, h) / density, kind(event, p), event.getHistoricalPressure(p, h))
313
+ for (p in 0 until event.pointerCount) pointerMove(event.getPointerId(p), event.getX(p) / density, event.getY(p) / density, kind(event, p), event.getPressure(p))
314
+ }
315
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> pointerUp(event.getPointerId(index), event.getX(index) / density, event.getY(index) / density, kind(event, index))
316
+ MotionEvent.ACTION_CANCEL -> {
317
+ pointers.clear()
318
+ if (gesture is Gesture.Pinch || gesture is Gesture.Pan) endCamera() else cancelGesture()
319
+ }
320
+ }
321
+ return true
322
+ }
323
+
324
+ private fun kind(event: MotionEvent, index: Int): String = when (event.getToolType(index)) {
325
+ MotionEvent.TOOL_TYPE_STYLUS, MotionEvent.TOOL_TYPE_ERASER -> "pen"
326
+ MotionEvent.TOOL_TYPE_MOUSE -> "mouse"
327
+ else -> "touch"
328
+ }
329
+
330
+ private fun pointerDown(id: Int, x: Float, y: Float, type: String, pressure: Float, buttons: Int) {
331
+ pointers[id] = floatArrayOf(x, y)
332
+ if (pointers.size == 2) {
333
+ startPinch()
334
+ return
335
+ }
336
+ if (pointers.size > 2) return
337
+ val scene = toScene(x, y)
338
+ val touch = type == "touch"
339
+ if (buttons and MotionEvent.BUTTON_SECONDARY != 0) return
340
+ if (buttons and MotionEvent.BUTTON_TERTIARY != 0 || tool == "hand" || (!editable && tool != "laser")) {
341
+ gesture = Gesture.Pan(x, y)
342
+ panning = true
343
+ return
344
+ }
345
+ val g = ++seq
346
+ when (tool) {
347
+ "freedraw" -> {
348
+ val points = FloatArrayList().apply { add(scene[0]); add(scene[1]) }
349
+ gesture = Gesture.Draw(g, points, if (type == "pen") FloatArrayList().apply { add(pressure) } else null)
350
+ }
351
+ "rectangle", "ellipse", "diamond", "frame" -> gesture = Gesture.Shape(g, tool, scene, scene)
352
+ "arrow", "line" -> gesture = Gesture.Line(g, tool, scene, scene)
353
+ "eraser" -> {
354
+ gesture = Gesture.Erase(g, FloatArrayList().apply { add(scene[0]); add(scene[1]) })
355
+ trail.clear()
356
+ trail.add(floatArrayOf(x, y, SystemClock.uptimeMillis().toFloat()))
357
+ }
358
+ "selection" -> {
359
+ val handle = handleAt(scene, touch)
360
+ val f = frame()
361
+ if (handle != null && f != null) {
362
+ gesture = if (handle == "rotation") {
363
+ val pivot = floatArrayOf(f.box.centerX(), f.box.centerY())
364
+ Gesture.Rotate(g, pivot, atan2(scene[1] - pivot[1], scene[0] - pivot[0]), 0f, RectF(f.box))
365
+ } else Gesture.Resize(g, handle, RectF(f.box), f.angle, RectF(f.box))
366
+ sceneDirty = true
367
+ } else {
368
+ val point = pointAt(scene, touch)
369
+ val s = selection
370
+ if (point != null && s?.points != null) gesture = Gesture.PointDrag(g, point, s.points.map { it.copyOf() }.toMutableList())
371
+ else if (s != null && s.ids.isNotEmpty() && insideFrame(scene)) {
372
+ gesture = Gesture.Move(g, scene, scene)
373
+ moveStarted = false
374
+ } else {
375
+ gesture = Gesture.Pending(g, scene, scene, false)
376
+ emitter?.invoke("cvdown", mapOf("g" to g, "x" to scene[0].toDouble(), "y" to scene[1].toDouble()))
377
+ }
378
+ }
379
+ }
380
+ else -> gesture = Gesture.Tap(g, scene, floatArrayOf(x, y), tool)
381
+ }
382
+ cursor(scene, true)
383
+ invalidate()
384
+ }
385
+
386
+ private fun pointerMove(id: Int, x: Float, y: Float, type: String, pressure: Float) {
387
+ val known = pointers[id] ?: return
388
+ known[0] = x
389
+ known[1] = y
390
+ val g = gesture ?: return
391
+ val scene = toScene(x, y)
392
+ val slop = (if (type == "touch") 8f else 4f) / zoom
393
+ when (g) {
394
+ is Gesture.Pan -> {
395
+ setView(scrollXv + (x - g.lastX) / zoom, scrollYv + (y - g.lastY) / zoom, zoom, false)
396
+ g.lastX = x
397
+ g.lastY = y
398
+ emitView(false)
399
+ return
400
+ }
401
+ is Gesture.Pinch -> {
402
+ updatePinch()
403
+ return
404
+ }
405
+ is Gesture.Draw -> {
406
+ val last = g.points.size - 2
407
+ if (hypot(scene[0] - g.points[last], scene[1] - g.points[last + 1]) * zoom < 1f) return
408
+ g.points.add(scene[0])
409
+ g.points.add(scene[1])
410
+ g.pressures?.add(pressure)
411
+ }
412
+ is Gesture.Shape -> g.end = scene
413
+ is Gesture.Line -> g.end = scene
414
+ is Gesture.Erase -> {
415
+ g.points.add(scene[0])
416
+ g.points.add(scene[1])
417
+ trail.add(floatArrayOf(x, y, SystemClock.uptimeMillis().toFloat()))
418
+ }
419
+ is Gesture.Pending -> g.end = scene
420
+ is Gesture.Move -> {
421
+ if (!moveStarted && hypot(scene[0] - g.start[0], scene[1] - g.start[1]) < slop) return
422
+ if (!moveStarted) {
423
+ moveStarted = true
424
+ sceneDirty = true
425
+ }
426
+ g.end = scene
427
+ }
428
+ is Gesture.Marquee -> g.end = scene
429
+ is Gesture.Resize -> g.to = resizeBox(g.from, g.angle, g.handle, scene)
430
+ is Gesture.Rotate -> g.delta = atan2(scene[1] - g.pivot[1], scene[0] - g.pivot[0]) - g.startAngle
431
+ is Gesture.PointDrag -> g.points[g.index] = scene
432
+ is Gesture.Tap -> {}
433
+ }
434
+ cursor(scene, true)
435
+ invalidate()
436
+ }
437
+
438
+ private fun pointerUp(id: Int, x: Float, y: Float, type: String) {
439
+ if (pointers.remove(id) == null) return
440
+ val g = gesture
441
+ if (g is Gesture.Pinch) {
442
+ if (pointers.isEmpty()) endCamera()
443
+ return
444
+ }
445
+ if (pointers.isNotEmpty()) return
446
+ gesture = null
447
+ if (g == null) return
448
+ val scene = toScene(x, y)
449
+ val slop = (if (type == "touch") 8f else 4f) / zoom
450
+ when (g) {
451
+ is Gesture.Pan -> endCamera()
452
+ is Gesture.Draw -> {
453
+ previews[g.g] = Preview.Stroke(g.points)
454
+ emitter?.invoke("cvstroke", mapOf("g" to g.g, "points" to g.points.toArray(), "pressures" to g.pressures?.toArray()))
455
+ }
456
+ is Gesture.Shape -> {
457
+ val b = box(g.start, g.end)
458
+ if (b.width() < slop && b.height() < slop) tap(g.g, scene, tool)
459
+ else {
460
+ previews[g.g] = Preview.Shape(g.tool, b)
461
+ emitter?.invoke("cvshape", mapOf("g" to g.g, "tool" to g.tool, "b" to boxArray(b)))
462
+ }
463
+ }
464
+ is Gesture.Line -> {
465
+ if (hypot(g.end[0] - g.start[0], g.end[1] - g.start[1]) < slop) tap(g.g, scene, tool)
466
+ else {
467
+ val points = listOf(g.start, g.end)
468
+ previews[g.g] = Preview.Line(g.tool, points)
469
+ emitter?.invoke("cvline", mapOf("g" to g.g, "tool" to g.tool, "points" to pointsArray(points)))
470
+ }
471
+ }
472
+ is Gesture.Erase -> emitter?.invoke("cverase", mapOf("g" to g.g, "points" to g.points.toArray()))
473
+ is Gesture.Pending -> {
474
+ g.end = scene
475
+ g.released = true
476
+ if (hypot(scene[0] - g.start[0], scene[1] - g.start[1]) < slop) tap(g.g, g.start, "selection") else gesture = g
477
+ }
478
+ is Gesture.Move -> {
479
+ if (!moveStarted) tap(g.g, g.start, "selection")
480
+ else {
481
+ live = g.g to Matrix().apply { setTranslate(g.end[0] - g.start[0], g.end[1] - g.start[1]) }
482
+ emitter?.invoke("cvmove", mapOf("g" to g.g, "dx" to (g.end[0] - g.start[0]).toDouble(), "dy" to (g.end[1] - g.start[1]).toDouble()))
483
+ }
484
+ }
485
+ is Gesture.Marquee -> emitter?.invoke("cvbox", mapOf("g" to g.g, "b" to boxArray(box(g.start, g.end))))
486
+ is Gesture.Resize -> {
487
+ if (g.from == g.to) sceneDirty = true
488
+ else {
489
+ live = g.g to resizeMatrix(g.from, g.to, g.angle)
490
+ emitter?.invoke("cvtransform", mapOf("g" to g.g, "handle" to g.handle, "from" to boxArray(g.from), "to" to boxArray(g.to), "angle" to 0.0))
491
+ }
492
+ }
493
+ is Gesture.Rotate -> {
494
+ if (abs(g.delta) < 1e-3f) sceneDirty = true
495
+ else {
496
+ live = g.g to Matrix().apply { setRotate(Math.toDegrees(g.delta.toDouble()).toFloat(), g.pivot[0], g.pivot[1]) }
497
+ emitter?.invoke("cvtransform", mapOf("g" to g.g, "handle" to "rotation", "from" to boxArray(g.from), "to" to boxArray(g.from), "angle" to g.delta.toDouble()))
498
+ }
499
+ }
500
+ is Gesture.PointDrag -> {
501
+ val point = g.points[g.index]
502
+ previews[g.g] = Preview.Point(g.points)
503
+ emitter?.invoke("cvpoint", mapOf("g" to g.g, "index" to g.index, "x" to point[0].toDouble(), "y" to point[1].toDouble()))
504
+ }
505
+ is Gesture.Tap -> if (hypot(x - g.screen[0], y - g.screen[1]) < (if (type == "touch") 12f else 6f)) tap(g.g, g.start, g.tool)
506
+ is Gesture.Pinch -> {}
507
+ }
508
+ cursor(scene, false)
509
+ invalidate()
510
+ }
511
+
512
+ private fun tap(g: Int, point: FloatArray, tool: String) {
513
+ val now = SystemClock.uptimeMillis()
514
+ val last = lastTap
515
+ val double = last != null && now - lastTapTime < DOUBLE_TAP_MS && hypot(point[0] - last[0], point[1] - last[1]) * zoom < 24
516
+ lastTap = if (double) null else point.copyOf()
517
+ lastTapTime = now
518
+ emitter?.invoke("cvtap", mapOf("g" to g, "x" to point[0].toDouble(), "y" to point[1].toDouble(), "count" to if (double) 2 else 1, "tool" to tool))
519
+ }
520
+
521
+ private fun answer(g: Int, grab: Boolean) {
522
+ val p = gesture as? Gesture.Pending ?: return
523
+ if (p.g != g) return
524
+ if (grab) {
525
+ moveStarted = hypot(p.end[0] - p.start[0], p.end[1] - p.start[1]) * zoom >= 4
526
+ if (moveStarted) sceneDirty = true
527
+ if (p.released) {
528
+ gesture = null
529
+ if (moveStarted) {
530
+ live = g to Matrix().apply { setTranslate(p.end[0] - p.start[0], p.end[1] - p.start[1]) }
531
+ emitter?.invoke("cvmove", mapOf("g" to g, "dx" to (p.end[0] - p.start[0]).toDouble(), "dy" to (p.end[1] - p.start[1]).toDouble()))
532
+ }
533
+ } else gesture = Gesture.Move(g, p.start, p.end)
534
+ } else {
535
+ if (p.released) {
536
+ gesture = null
537
+ emitter?.invoke("cvbox", mapOf("g" to g, "b" to boxArray(box(p.start, p.end))))
538
+ } else gesture = Gesture.Marquee(g, p.start, p.end)
539
+ }
540
+ invalidate()
541
+ }
542
+
543
+ private fun handleAt(scene: FloatArray, touch: Boolean): String? {
544
+ var best: String? = null
545
+ var bestDistance = (if (touch) 22f else 9f) / zoom
546
+ for ((h, x, y) in handles(touch)) {
547
+ val d = hypot(x - scene[0], y - scene[1])
548
+ if (d <= bestDistance) {
549
+ best = h
550
+ bestDistance = d
551
+ }
552
+ }
553
+ return best
554
+ }
555
+
556
+ private fun pointAt(scene: FloatArray, touch: Boolean): Int? {
557
+ val points = selection?.points ?: return null
558
+ if (!editable) return null
559
+ val radius = (if (touch) 20f else 8f) / zoom
560
+ for (i in points.indices) if (hypot(points[i][0] - scene[0], points[i][1] - scene[1]) <= radius) return i
561
+ return null
562
+ }
563
+
564
+ private fun startPinch() {
565
+ val unfinished = gesture
566
+ if (unfinished != null && unfinished !is Gesture.Pan && unfinished !is Gesture.Pinch) cancelGesture()
567
+ val ids = pointers.keys.toList()
568
+ val pa = pointers[ids[0]]!!
569
+ val pb = pointers[ids[1]]!!
570
+ val mid = floatArrayOf((pa[0] + pb[0]) / 2, (pa[1] + pb[1]) / 2)
571
+ gesture = Gesture.Pinch(ids[0], ids[1], max(1f, hypot(pa[0] - pb[0], pa[1] - pb[1])), zoom, toScene(mid[0], mid[1]))
572
+ panning = true
573
+ invalidate()
574
+ }
575
+
576
+ private fun updatePinch() {
577
+ val g = gesture as? Gesture.Pinch ?: return
578
+ val pa = pointers[g.a] ?: return
579
+ val pb = pointers[g.b] ?: return
580
+ val mid = floatArrayOf((pa[0] + pb[0]) / 2, (pa[1] + pb[1]) / 2)
581
+ val z = (g.startZoom * (hypot(pa[0] - pb[0], pa[1] - pb[1]) / g.startDistance)).coerceIn(MIN_ZOOM, MAX_ZOOM)
582
+ setView(mid[0] / z - g.sceneMid[0], mid[1] / z - g.sceneMid[1], z, false)
583
+ emitView(false)
584
+ }
585
+
586
+ private fun endCamera() {
587
+ gesture = null
588
+ panning = false
589
+ emitView(true)
590
+ invalidate()
591
+ }
592
+
593
+ private fun cancelGesture() {
594
+ val g = gesture
595
+ gesture = null
596
+ panning = false
597
+ if (g is Gesture.Pending) emitter?.invoke("cvbox", mapOf("g" to g.g, "b" to boxArray(RectF(g.start[0], g.start[1], g.start[0], g.start[1]))))
598
+ if (g is Gesture.Move || g is Gesture.Resize || g is Gesture.Rotate) sceneDirty = true
599
+ trail.clear()
600
+ invalidate()
601
+ }
602
+
603
+ private fun cursor(scene: FloatArray, down: Boolean) {
604
+ val now = SystemClock.uptimeMillis()
605
+ if (now - lastCursor < 50) return
606
+ lastCursor = now
607
+ emitter?.invoke("cvcursor", mapOf("x" to scene[0].toDouble(), "y" to scene[1].toDouble(), "down" to down))
608
+ }
609
+
610
+ // ================================================================================================ drawing
611
+
612
+ private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
613
+ private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply {
614
+ style = Paint.Style.STROKE
615
+ strokeCap = Paint.Cap.ROUND
616
+ strokeJoin = Paint.Join.ROUND
617
+ }
618
+ private val text = Paint(Paint.ANTI_ALIAS_FLAG)
619
+
620
+ override fun onDraw(canvas: Canvas) {
621
+ canvas.drawColor(background)
622
+ canvas.save()
623
+ canvas.scale(density, density)
624
+ canvas.scale(zoom, zoom)
625
+ canvas.translate(scrollXv, scrollYv)
626
+ if (sceneDirty || scenePicture == null) recordScene()
627
+ scenePicture?.let {
628
+ canvas.save()
629
+ canvas.translate(pictureOrigin[0], pictureOrigin[1])
630
+ canvas.drawPicture(it)
631
+ canvas.restore()
632
+ }
633
+ val matrix = liveMatrix()
634
+ if (matrix != null) {
635
+ val moving = movingIds()
636
+ for (id in order) {
637
+ if (id !in moving || id in hidden) continue
638
+ items[id]?.let { drawItem(canvas, it, matrix, 1f) }
639
+ }
640
+ }
641
+ for (preview in activePreviews()) drawPreview(canvas, preview)
642
+ drawSelection(canvas, matrix)
643
+ (gesture as? Gesture.Marquee)?.let { g ->
644
+ val b = box(g.start, g.end)
645
+ fill.color = Color.argb(20, Color.red(accent), Color.green(accent), Color.blue(accent))
646
+ canvas.drawRect(b, fill)
647
+ stroke.color = accent
648
+ stroke.strokeWidth = 1f / zoom
649
+ stroke.pathEffect = null
650
+ canvas.drawRect(b, stroke)
651
+ }
652
+ canvas.restore()
653
+ // Screen-space decorations (dp).
654
+ canvas.save()
655
+ canvas.scale(density, density)
656
+ drawTrail(canvas)
657
+ drawPeers(canvas)
658
+ canvas.restore()
659
+ }
660
+
661
+ private fun recordScene() {
662
+ sceneDirty = false
663
+ val moving = movingIds()
664
+ var minX = Float.MAX_VALUE
665
+ var minY = Float.MAX_VALUE
666
+ var maxX = -Float.MAX_VALUE
667
+ var maxY = -Float.MAX_VALUE
668
+ for (id in order) items[id]?.let {
669
+ minX = min(minX, it.bounds.left)
670
+ minY = min(minY, it.bounds.top)
671
+ maxX = max(maxX, it.bounds.right)
672
+ maxY = max(maxY, it.bounds.bottom)
673
+ }
674
+ if (minX > maxX) {
675
+ scenePicture = Picture()
676
+ pictureOrigin = floatArrayOf(0f, 0f)
677
+ return
678
+ }
679
+ val picture = Picture()
680
+ val w = (maxX - minX + 2).toInt().coerceIn(1, 1 shl 20)
681
+ val h = (maxY - minY + 2).toInt().coerceIn(1, 1 shl 20)
682
+ val c = picture.beginRecording(w, h)
683
+ c.translate(-minX + 1, -minY + 1)
684
+ for (id in order) {
685
+ if (id in moving || id in hidden) continue
686
+ items[id]?.let { drawItem(c, it, null, if (id in faded) 0.3f else 1f) }
687
+ }
688
+ picture.endRecording()
689
+ scenePicture = picture
690
+ pictureOrigin = floatArrayOf(minX - 1, minY - 1)
691
+ }
692
+
693
+ private fun drawItem(canvas: Canvas, item: CvItem, matrix: Matrix?, alpha: Float) {
694
+ canvas.save()
695
+ if (matrix != null) canvas.concat(matrix)
696
+ if (item.angle != 0f) canvas.rotate(Math.toDegrees(item.angle.toDouble()).toFloat(), item.cx, item.cy)
697
+ canvas.translate(item.x, item.y)
698
+ val a = (item.opacity * alpha).coerceIn(0f, 1f)
699
+ for (op in item.ops) drawOp(canvas, op, a)
700
+ canvas.restore()
701
+ }
702
+
703
+ private fun withAlpha(color: Int, alpha: Float): Int = Color.argb((Color.alpha(color) * alpha).toInt(), Color.red(color), Color.green(color), Color.blue(color))
704
+
705
+ private fun drawOp(canvas: Canvas, op: CvOp, alpha: Float) {
706
+ when (op) {
707
+ is CvPathOp -> {
708
+ op.fill?.let {
709
+ op.path.fillType = if (op.evenOdd) Path.FillType.EVEN_ODD else Path.FillType.WINDING
710
+ fill.color = withAlpha(it, alpha)
711
+ canvas.drawPath(op.path, fill)
712
+ }
713
+ op.stroke?.let {
714
+ stroke.color = withAlpha(it, alpha)
715
+ stroke.strokeWidth = op.width
716
+ stroke.pathEffect = op.dash?.takeIf { d -> d.size >= 2 }?.let { d -> DashPathEffect(if (d.size % 2 == 0) d else d + d, 0f) }
717
+ canvas.drawPath(op.path, stroke)
718
+ stroke.pathEffect = null
719
+ }
720
+ }
721
+ is CvTextOp -> {
722
+ text.typeface = typeface(op.font)
723
+ text.textSize = op.size
724
+ text.color = withAlpha(op.color, alpha)
725
+ text.textAlign = when (op.align) {
726
+ "center" -> Paint.Align.CENTER
727
+ "right" -> Paint.Align.RIGHT
728
+ else -> Paint.Align.LEFT
729
+ }
730
+ op.lines.forEachIndexed { i, line -> canvas.drawText(line, op.x, op.y + i * op.lineHeight, text) }
731
+ }
732
+ is CvImageOp -> {
733
+ val url = files[op.file]
734
+ val bitmap = url?.let { image(it) }
735
+ if (bitmap != null) {
736
+ canvas.save()
737
+ if (op.radius > 0) canvas.clipPath(Path().apply { addRoundRect(RectF(0f, 0f, op.w, op.h), op.radius, op.radius, Path.Direction.CW) })
738
+ val source = op.crop?.let { Rect(it[0].toInt(), it[1].toInt(), (it[0] + it[2]).toInt(), (it[1] + it[3]).toInt()) }
739
+ fill.color = withAlpha(Color.BLACK, alpha)
740
+ canvas.drawBitmap(bitmap, source, RectF(0f, 0f, op.w, op.h), fill.apply { isFilterBitmap = true })
741
+ canvas.restore()
742
+ } else {
743
+ fill.color = withAlpha(Color.rgb(0xe9, 0xec, 0xef), alpha)
744
+ canvas.drawRect(0f, 0f, op.w, op.h, fill)
745
+ }
746
+ }
747
+ }
748
+ }
749
+
750
+ private fun activePreviews(): List<Preview> {
751
+ val list = ArrayList<Preview>(previews.values)
752
+ when (val g = gesture) {
753
+ is Gesture.Draw -> list += Preview.Stroke(g.points)
754
+ is Gesture.Shape -> list += Preview.Shape(g.tool, box(g.start, g.end))
755
+ is Gesture.Line -> list += Preview.Line(g.tool, listOf(g.start, g.end))
756
+ is Gesture.PointDrag -> list += Preview.Point(g.points)
757
+ else -> {}
758
+ }
759
+ return list
760
+ }
761
+
762
+ private fun drawPreview(canvas: Canvas, preview: Preview) {
763
+ stroke.color = strokeColor
764
+ stroke.strokeWidth = strokeWidthStyle
765
+ stroke.pathEffect = null
766
+ when (preview) {
767
+ is Preview.Stroke -> {
768
+ val p = preview.points
769
+ val path = Path()
770
+ path.moveTo(p[0], p[1])
771
+ if (p.size == 2) path.lineTo(p[0] + 0.01f, p[1])
772
+ var i = 2
773
+ while (i + 1 < p.size) {
774
+ if (i + 3 < p.size) path.quadTo(p[i], p[i + 1], (p[i] + p[i + 2]) / 2, (p[i + 1] + p[i + 3]) / 2) else path.lineTo(p[i], p[i + 1])
775
+ i += 2
776
+ }
777
+ stroke.strokeWidth = strokeWidthStyle * 2.4f
778
+ canvas.drawPath(path, stroke)
779
+ }
780
+ is Preview.Shape -> {
781
+ val b = preview.box
782
+ val path = Path()
783
+ when (preview.tool) {
784
+ "ellipse" -> path.addOval(b, Path.Direction.CW)
785
+ "diamond" -> {
786
+ path.moveTo(b.centerX(), b.top)
787
+ path.lineTo(b.right, b.centerY())
788
+ path.lineTo(b.centerX(), b.bottom)
789
+ path.lineTo(b.left, b.centerY())
790
+ path.close()
791
+ }
792
+ "frame" -> {
793
+ stroke.color = Color.rgb(0xbb, 0xbb, 0xbb)
794
+ stroke.strokeWidth = 2f
795
+ path.addRoundRect(b, 8f, 8f, Path.Direction.CW)
796
+ }
797
+ else -> {
798
+ val r = min(32f, min(b.width(), b.height()) * 0.25f)
799
+ path.addRoundRect(b, r, r, Path.Direction.CW)
800
+ }
801
+ }
802
+ fillColor?.takeIf { it != Color.TRANSPARENT && preview.tool != "frame" }?.let {
803
+ fill.color = it
804
+ canvas.drawPath(path, fill)
805
+ }
806
+ canvas.drawPath(path, stroke)
807
+ }
808
+ is Preview.Line, is Preview.Point -> {
809
+ val points = if (preview is Preview.Line) preview.points else (preview as Preview.Point).points
810
+ if (preview is Preview.Point) {
811
+ stroke.color = accent
812
+ stroke.strokeWidth = 1.5f / zoom
813
+ stroke.pathEffect = DashPathEffect(floatArrayOf(4f / zoom, 4f / zoom), 0f)
814
+ }
815
+ val path = Path()
816
+ path.moveTo(points[0][0], points[0][1])
817
+ for (point in points.drop(1)) path.lineTo(point[0], point[1])
818
+ canvas.drawPath(path, stroke)
819
+ stroke.pathEffect = null
820
+ if (preview is Preview.Line && preview.tool == "arrow" && points.size > 1) {
821
+ val a = points[points.size - 2]
822
+ val b = points[points.size - 1]
823
+ val angle = atan2(b[1] - a[1], b[0] - a[0])
824
+ val size = min(25f, hypot(b[0] - a[0], b[1] - a[1]) / 2)
825
+ val head = Path()
826
+ head.moveTo(b[0] - size * cos(angle - 0.35f), b[1] - size * sin(angle - 0.35f))
827
+ head.lineTo(b[0], b[1])
828
+ head.lineTo(b[0] - size * cos(angle + 0.35f), b[1] - size * sin(angle + 0.35f))
829
+ canvas.drawPath(head, stroke)
830
+ }
831
+ }
832
+ }
833
+ }
834
+
835
+ private fun drawSelection(canvas: Canvas, matrix: Matrix?) {
836
+ val s = selection ?: return
837
+ stroke.pathEffect = null
838
+ for (b in s.boxes) strokeBox(canvas, b, accent, 1f / zoom, matrix)
839
+ if (s.frame != null && s.boxes.size > 1) {
840
+ stroke.pathEffect = DashPathEffect(floatArrayOf(2f / zoom, 2f / zoom), 0f)
841
+ strokeBox(canvas, s.frame, accent, 1f / zoom, matrix)
842
+ stroke.pathEffect = null
843
+ }
844
+ if (gesture != null && matrix != null) return
845
+ val points = s.points
846
+ if (points != null && editable) {
847
+ for (p in points) {
848
+ fill.color = Color.WHITE
849
+ canvas.drawCircle(p[0], p[1], 7f / zoom, fill)
850
+ stroke.color = accent
851
+ stroke.strokeWidth = 1.5f / zoom
852
+ canvas.drawCircle(p[0], p[1], 7f / zoom, stroke)
853
+ }
854
+ }
855
+ val size = 12f / zoom
856
+ for ((h, x, y) in handles(true)) {
857
+ fill.color = Color.WHITE
858
+ stroke.color = accent
859
+ stroke.strokeWidth = 1f / zoom
860
+ if (h == "rotation") {
861
+ canvas.drawCircle(x, y, size / 2, fill)
862
+ canvas.drawCircle(x, y, size / 2, stroke)
863
+ } else {
864
+ val r = RectF(x - size / 2, y - size / 2, x + size / 2, y + size / 2)
865
+ canvas.drawRoundRect(r, 2f / zoom, 2f / zoom, fill)
866
+ canvas.drawRoundRect(r, 2f / zoom, 2f / zoom, stroke)
867
+ }
868
+ }
869
+ }
870
+
871
+ private fun strokeBox(canvas: Canvas, box: CvRotatedBox, color: Int, width: Float, matrix: Matrix?) {
872
+ val b = box.box
873
+ val pad = 4f / zoom
874
+ val corners = floatArrayOf(b.left - pad, b.top - pad, b.right + pad, b.top - pad, b.right + pad, b.bottom + pad, b.left - pad, b.bottom + pad)
875
+ val m = Matrix().apply { setRotate(Math.toDegrees(box.angle.toDouble()).toFloat(), b.centerX(), b.centerY()) }
876
+ if (matrix != null) m.postConcat(matrix)
877
+ m.mapPoints(corners)
878
+ val path = Path()
879
+ path.moveTo(corners[0], corners[1])
880
+ for (i in 2 until 8 step 2) path.lineTo(corners[i], corners[i + 1])
881
+ path.close()
882
+ stroke.color = color
883
+ stroke.strokeWidth = width
884
+ canvas.drawPath(path, stroke)
885
+ }
886
+
887
+ private fun drawTrail(canvas: Canvas) {
888
+ val now = SystemClock.uptimeMillis().toFloat()
889
+ trail.removeAll { now - it[2] >= 300 }
890
+ if (trail.size < 2) return
891
+ for (i in 1 until trail.size) {
892
+ val age = (now - trail[i][2]) / 300f
893
+ stroke.color = Color.argb((0.6f * (1 - age) * 255).toInt().coerceIn(0, 255), 150, 150, 150)
894
+ stroke.strokeWidth = max(1f, 10f * (1 - age))
895
+ canvas.drawLine(trail[i - 1][0], trail[i - 1][1], trail[i][0], trail[i][1], stroke)
896
+ }
897
+ postInvalidateOnAnimation()
898
+ }
899
+
900
+ private val label = Paint(Paint.ANTI_ALIAS_FLAG).apply {
901
+ textSize = 11f
902
+ color = Color.WHITE
903
+ }
904
+
905
+ private fun drawPeers(canvas: Canvas) {
906
+ for (peer in peers) {
907
+ canvas.save()
908
+ canvas.scale(zoom, zoom)
909
+ canvas.translate(scrollXv, scrollYv)
910
+ for (b in peer.boxes) strokeBox(canvas, b, peer.color, 1.5f / zoom, null)
911
+ canvas.restore()
912
+ val px = peer.x ?: continue
913
+ val py = peer.y ?: continue
914
+ val (x, y) = toScreen(px, py).let { it[0] to it[1] }
915
+ if (x < -20 || y < -20 || x > widthDp + 20 || y > heightDp + 20) continue
916
+ val arrow = Path().apply {
917
+ moveTo(x, y)
918
+ lineTo(x + 1, y + 14)
919
+ lineTo(x + 4.5f, y + 10.5f)
920
+ lineTo(x + 10, y + 10)
921
+ close()
922
+ }
923
+ fill.color = peer.color
924
+ canvas.drawPath(arrow, fill)
925
+ stroke.color = Color.WHITE
926
+ stroke.strokeWidth = 1.5f
927
+ canvas.drawPath(arrow, stroke)
928
+ val w = label.measureText(peer.name) + 10
929
+ canvas.drawRoundRect(RectF(x + 10, y + 14, x + 10 + w, y + 32), 6f, 6f, fill)
930
+ canvas.drawText(peer.name, x + 15, y + 27, label)
931
+ }
932
+ }
933
+
934
+ // ================================================================================================ fonts, pictures
935
+
936
+ private fun typeface(font: Int): Typeface = when (font) {
937
+ 6 -> fonts.getOrPut("nunito") { load("fonts/Nunito.ttf") }
938
+ 8, 3 -> fonts.getOrPut("comic") { load("fonts/ComicShanns.ttf") }
939
+ 2, 9 -> Typeface.SANS_SERIF
940
+ else -> fonts.getOrPut("excalifont") { load("fonts/Excalifont.ttf") }
941
+ }
942
+
943
+ private fun load(asset: String): Typeface = runCatching { Typeface.createFromAsset(context.assets, asset) }.getOrDefault(Typeface.DEFAULT)
944
+
945
+ private fun image(url: String): Bitmap? {
946
+ cache.get(url)?.let { return it }
947
+ synchronized(loading) { if (!loading.add(url)) return null }
948
+ executor.execute {
949
+ val bitmap = runCatching {
950
+ G9NativeImages.fetch(url).let { bytes ->
951
+ if (bytes == null) return@let null
952
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
953
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
954
+ var sample = 1
955
+ while (bounds.outWidth / (sample * 2) >= 2048) sample *= 2
956
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
957
+ }
958
+ }.getOrNull()
959
+ main.post {
960
+ synchronized(loading) { loading.remove(url) }
961
+ if (bitmap != null) {
962
+ cache.put(url, bitmap)
963
+ sceneDirty = true
964
+ invalidate()
965
+ }
966
+ }
967
+ }
968
+ return null
969
+ }
970
+
971
+ /** Renders every item to a PNG-ready bitmap (`exportImage`). Waits briefly for pictures that are still loading. */
972
+ fun renderExport(scale: Float, padding: Float, withBackground: Boolean): Bitmap? {
973
+ val list = order.mapNotNull { items[it] }
974
+ if (list.isEmpty()) return null
975
+ var minX = Float.MAX_VALUE
976
+ var minY = Float.MAX_VALUE
977
+ var maxX = -Float.MAX_VALUE
978
+ var maxY = -Float.MAX_VALUE
979
+ for (it in list) {
980
+ minX = min(minX, it.bounds.left)
981
+ minY = min(minY, it.bounds.top)
982
+ maxX = max(maxX, it.bounds.right)
983
+ maxY = max(maxY, it.bounds.bottom)
984
+ }
985
+ val width = ((maxX - minX + padding * 2) * scale).toInt().coerceAtLeast(1)
986
+ val height = ((maxY - minY + padding * 2) * scale).toInt().coerceAtLeast(1)
987
+ val fit = min(1f, min(8192f / width, 8192f / height))
988
+ val bitmap = Bitmap.createBitmap((width * fit).toInt().coerceAtLeast(1), (height * fit).toInt().coerceAtLeast(1), Bitmap.Config.ARGB_8888)
989
+ val c = Canvas(bitmap)
990
+ if (withBackground) c.drawColor(background)
991
+ c.scale(scale * fit, scale * fit)
992
+ c.translate(padding - minX, padding - minY)
993
+ for (item in list) drawItem(c, item, null, 1f)
994
+ return bitmap
995
+ }
996
+
997
+ // ================================================================================================ geometry helpers
998
+
999
+ private fun resizeBox(from: RectF, angle: Float, handle: String, point: FloatArray): RectF {
1000
+ val q = rotate(point, from.centerX(), from.centerY(), -angle)
1001
+ var x1 = from.left
1002
+ var y1 = from.top
1003
+ var x2 = from.right
1004
+ var y2 = from.bottom
1005
+ if ('w' in handle) x1 = min(q[0], x2 - 1)
1006
+ if ('e' in handle) x2 = max(q[0], x1 + 1)
1007
+ if ('n' in handle) y1 = min(q[1], y2 - 1)
1008
+ if ('s' in handle) y2 = max(q[1], y1 + 1)
1009
+ return RectF(x1, y1, x2, y2)
1010
+ }
1011
+
1012
+ private fun resizeMatrix(from: RectF, to: RectF, angle: Float): Matrix {
1013
+ val m = Matrix()
1014
+ m.setTranslate(-from.left, -from.top)
1015
+ m.postScale(to.width() / max(1e-6f, from.width()), to.height() / max(1e-6f, from.height()))
1016
+ m.postTranslate(to.left, to.top)
1017
+ if (angle != 0f) {
1018
+ val degrees = Math.toDegrees(angle.toDouble()).toFloat()
1019
+ val r = Matrix().apply { setRotate(-degrees, from.centerX(), from.centerY()) }
1020
+ r.postConcat(m)
1021
+ r.postRotate(degrees, from.centerX(), from.centerY())
1022
+ return r
1023
+ }
1024
+ return m
1025
+ }
1026
+
1027
+ private fun box(a: FloatArray, b: FloatArray) = RectF(min(a[0], b[0]), min(a[1], b[1]), max(a[0], b[0]), max(a[1], b[1]))
1028
+
1029
+ private fun boxArray(b: RectF) = JavaOnlyArray.of(b.left.toDouble(), b.top.toDouble(), b.right.toDouble(), b.bottom.toDouble())
1030
+
1031
+ private fun pointsArray(points: List<FloatArray>) = JavaOnlyArray().also { list -> for (p in points) list.pushArray(JavaOnlyArray.of(p[0].toDouble(), p[1].toDouble())) }
1032
+
1033
+ private fun rotate(p: FloatArray, cx: Float, cy: Float, angle: Float): FloatArray {
1034
+ if (angle == 0f) return p
1035
+ val c = cos(angle)
1036
+ val s = sin(angle)
1037
+ val dx = p[0] - cx
1038
+ val dy = p[1] - cy
1039
+ return floatArrayOf(dx * c - dy * s + cx, dx * s + dy * c + cy)
1040
+ }
1041
+
1042
+ companion object {
1043
+ private const val MIN_ZOOM = 0.1f
1044
+ private const val MAX_ZOOM = 30f
1045
+ private const val DOUBLE_TAP_MS = 350L
1046
+ private val fonts = HashMap<String, Typeface>()
1047
+ private val cache = object : LruCache<String, Bitmap>(48 * 1024 * 1024) {
1048
+ override fun sizeOf(key: String, value: Bitmap) = value.byteCount
1049
+ }
1050
+ private val loading = HashSet<String>()
1051
+ private val executor = Executors.newFixedThreadPool(2)
1052
+ }
1053
+ }