@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,99 @@
1
+ package com.g9lynx.g9native.richtext
2
+
3
+ import com.g9lynx.g9native.G9NativeImages
4
+
5
+ import android.graphics.Bitmap
6
+ import android.graphics.BitmapFactory
7
+ import android.graphics.Canvas
8
+ import android.graphics.Paint
9
+ import android.graphics.Rect
10
+ import android.graphics.RectF
11
+ import android.os.Handler
12
+ import android.os.Looper
13
+ import android.text.style.ReplacementSpan
14
+ import android.util.LruCache
15
+ import java.util.concurrent.Executors
16
+ import kotlin.math.max
17
+ import kotlin.math.min
18
+
19
+ /**
20
+ * A document's picture (`docImage`): the object character drawn as the image across the text width (a placeholder
21
+ * until it is loaded). The address is the server's signed URL the app resolved; it is fetched by [G9NativeImages.fetch]
22
+ * (a host with a pinned client sets its own; default `HttpURLConnection`) and kept in a small cache, then the editor
23
+ * restyles ([G9RichStyle.onAsset]). Ported from G9Hub (2.5.8).
24
+ */
25
+ class G9PictureSpan(private val style: G9RichStyle, private val src: String, private val alt: String, private val width: Int) : ReplacementSpan(), G9Span {
26
+ private val bitmap: Bitmap? = if (src.isEmpty()) null else cache.get(src)
27
+
28
+ init {
29
+ if (src.isNotEmpty() && bitmap == null) load(src, style)
30
+ }
31
+
32
+ private fun height(): Int {
33
+ val b = bitmap ?: return (style.indentStep / 24f * 140).toInt()
34
+ val w = max(1, min(width, b.width * 2))
35
+ return min((w.toFloat() * b.height / max(1, b.width)).toInt(), (style.indentStep / 24f * 420).toInt())
36
+ }
37
+
38
+ override fun getSize(paint: Paint, text: CharSequence?, start: Int, end: Int, fm: Paint.FontMetricsInt?): Int {
39
+ if (fm != null) {
40
+ val h = height()
41
+ fm.ascent = -h
42
+ fm.top = -h
43
+ fm.descent = 0
44
+ fm.bottom = 0
45
+ }
46
+ return max(1, width - 2)
47
+ }
48
+
49
+ override fun draw(canvas: Canvas, text: CharSequence?, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
50
+ val h = height()
51
+ val b = bitmap
52
+ val area = RectF(x, (y - h).toFloat(), x + max(1, width - 2), y.toFloat())
53
+ val old = paint.color
54
+ if (b == null) {
55
+ paint.color = style.surface2
56
+ canvas.drawRoundRect(area, 16f, 16f, paint)
57
+ if (alt.isNotEmpty()) {
58
+ paint.color = style.text3
59
+ canvas.drawText(alt, area.left + 24f, area.centerY(), paint)
60
+ }
61
+ } else {
62
+ val scale = min(area.width() / b.width, area.height() / b.height)
63
+ val w = b.width * scale
64
+ val left = area.left + (area.width() - w) / 2
65
+ canvas.drawBitmap(b, Rect(0, 0, b.width, b.height), RectF(left, area.top, left + w, area.top + b.height * scale), paint)
66
+ }
67
+ paint.color = old
68
+ }
69
+
70
+ companion object {
71
+ private val cache = LruCache<String, Bitmap>(24)
72
+ private val loading = HashSet<String>()
73
+ private val executor = Executors.newFixedThreadPool(2)
74
+ private val main = Handler(Looper.getMainLooper())
75
+
76
+ private fun load(src: String, style: G9RichStyle) {
77
+ synchronized(loading) { if (!loading.add(src)) return }
78
+ executor.execute {
79
+ val bitmap = runCatching {
80
+ G9NativeImages.fetch(src).let { bytes ->
81
+ if (bytes == null) return@let null
82
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
83
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
84
+ var sample = 1
85
+ while (bounds.outWidth / (sample * 2) >= 1600) sample *= 2
86
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
87
+ }
88
+ }.getOrNull()
89
+ main.post {
90
+ synchronized(loading) { loading.remove(src) }
91
+ if (bitmap != null) {
92
+ cache.put(src, bitmap)
93
+ style.onAsset?.invoke()
94
+ }
95
+ }
96
+ }
97
+ }
98
+ }
99
+ }
@@ -0,0 +1,458 @@
1
+ package com.g9lynx.g9native.richtext
2
+
3
+ import android.annotation.SuppressLint
4
+ import android.content.Context
5
+ import android.graphics.Canvas
6
+ import android.graphics.Color
7
+ import android.graphics.Paint
8
+ import android.graphics.RectF
9
+ import android.graphics.Typeface
10
+ import android.text.Editable
11
+ import android.text.InputType
12
+ import android.text.TextWatcher
13
+ import android.text.method.ArrowKeyMovementMethod
14
+ import android.text.method.TextKeyListener
15
+ import android.util.TypedValue
16
+ import android.view.Gravity
17
+ import android.view.KeyEvent
18
+ import android.view.MotionEvent
19
+ import android.view.inputmethod.InputMethodManager
20
+ import android.widget.EditText
21
+ import com.lynx.tasm.behavior.shadow.text.TypefaceCache
22
+ import org.json.JSONArray
23
+ import org.json.JSONObject
24
+ import kotlin.math.abs
25
+ import kotlin.math.max
26
+ import kotlin.math.min
27
+
28
+ /**
29
+ * The text surface of `<g9-richtext>` (G9RichTextUI.kt): an `EditText` holding the document's flat text, styled line by
30
+ * line with spans from the app's line styles. Mirrors client/app `editor/element-core.ts`:
31
+ *
32
+ * - every change of the text (typing, IME composition, autocorrect, paste, deleting) is reported as one replacement
33
+ * `rtedit { seq, base, from, to, text, len }`; the display lines follow it roughly until the app answers;
34
+ * - an app message is applied only when its `ack` is the last `seq` (no edit on its way): its replacements, the line
35
+ * changes (spans of those lines redrawn), the selection, the collaborators' carets; then `rtapplied { rev }`;
36
+ * - selection and focus changes → `rtselect`; checkbox and chip taps, shortcuts → `rtaction`.
37
+ */
38
+ @SuppressLint("ViewConstructor", "AppCompatCustomView")
39
+ class G9RichEditText(context: Context) : EditText(context) {
40
+ var emitter: ((String, Map<String, Any?>) -> Unit)? = null
41
+
42
+ private var seq = 0
43
+ private var rev = 0
44
+ /** The app's lines as of [rev] (the base of the next line change). */
45
+ private var appLines: MutableList<JSONObject> = mutableListOf(JSONObject().put("t", "p").put("r", JSONArray()))
46
+ /** What is drawn: the app's lines, adjusted for edits the app has not answered yet. */
47
+ private var lines: MutableList<JSONObject> = appLines.toMutableList()
48
+ private var applying = false
49
+ private var editableMode = false
50
+ private var lastSelA = -1
51
+ private var lastSelH = -1
52
+ private var focusedNow = false
53
+ private var bottomInset = 0
54
+ private var peers: List<Peer> = emptyList()
55
+ private var beforeLength = 0
56
+ private var touchDown: Pair<Float, Float>? = null
57
+
58
+ internal val style = G9RichStyle(context)
59
+
60
+ private data class Peer(val a: Int, val h: Int, val color: Int, val name: String)
61
+
62
+ init {
63
+ background = null
64
+ gravity = Gravity.TOP or Gravity.START
65
+ isSingleLine = false
66
+ setHorizontallyScrolling(false)
67
+ isVerticalScrollBarEnabled = true
68
+ textDirection = TEXT_DIRECTION_FIRST_STRONG
69
+ textAlignment = TEXT_ALIGNMENT_GRAVITY
70
+ setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16f)
71
+ setLineSpacing(0f, 1.3f)
72
+ TypefaceCache.getCachedTypeface("G9", Typeface.NORMAL)?.let { typeface = it }
73
+ val pad = dp(16f).toInt()
74
+ setPadding(pad, dp(14f).toInt(), pad, dp(24f).toInt())
75
+ inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES or InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
76
+ setEditableMode(false)
77
+ style.onAsset = { restyle(0, lines.size) }
78
+ addTextChangedListener(object : TextWatcher {
79
+ override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
80
+ beforeLength = s.length
81
+ }
82
+
83
+ override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
84
+ if (applying) return
85
+ localEdit(start, start + before, s.subSequence(start, start + count).toString(), beforeLength)
86
+ }
87
+
88
+ override fun afterTextChanged(s: Editable) = Unit
89
+ })
90
+ }
91
+
92
+ private fun dp(value: Float): Float = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, resources.displayMetrics)
93
+
94
+ // ============================================================================================ attributes
95
+
96
+ fun setEditableMode(value: Boolean) {
97
+ editableMode = value
98
+ if (value) {
99
+ keyListener = TextKeyListener.getInstance()
100
+ movementMethod = ArrowKeyMovementMethod.getInstance()
101
+ isFocusable = true
102
+ isFocusableInTouchMode = true
103
+ isCursorVisible = true
104
+ showSoftInputOnFocus = true
105
+ } else {
106
+ keyListener = null
107
+ setTextIsSelectable(true)
108
+ showSoftInputOnFocus = false
109
+ }
110
+ }
111
+
112
+ fun setPalette(palette: JSONObject) {
113
+ style.setPalette(palette)
114
+ setTextColor(style.text)
115
+ setHintTextColor(style.text3)
116
+ highlightColor = style.selection
117
+ restyle(0, lines.size)
118
+ }
119
+
120
+ fun setPageDirection(rtl: Boolean) {
121
+ style.pageRtl = rtl
122
+ }
123
+
124
+ fun setBottomInset(value: Double) {
125
+ bottomInset = dp(value.toFloat()).toInt()
126
+ setPadding(paddingLeft, paddingTop, paddingRight, dp(24f).toInt() + bottomInset)
127
+ }
128
+
129
+ // ============================================================================================ local edits
130
+
131
+ private fun localEdit(from: Int, to: Int, text: String, length: Int) {
132
+ seq++
133
+ val removed = countNewlines(lastText, from, to)
134
+ val added = text.count { it == '\n' }
135
+ if (removed > 0 || added > 0) {
136
+ val line = countNewlines(editableText, 0, from)
137
+ val base = lines.getOrNull(line) ?: JSONObject().put("t", "p").put("r", JSONArray())
138
+ val copy = JSONObject(base.toString()).apply { remove("mk") }
139
+ repeat(min(removed, max(0, lines.size - line - 1))) { lines.removeAt(line + 1) }
140
+ repeat(added) { lines.add(min(line + 1, lines.size), copy) }
141
+ }
142
+ lastText = editableText.toString()
143
+ emit("rtedit", mapOf("seq" to seq, "base" to rev, "from" to from, "to" to to, "text" to text, "len" to length))
144
+ }
145
+
146
+ /** The text before the latest change (for line bookkeeping of removed newlines). */
147
+ private var lastText: String = ""
148
+
149
+ private fun countNewlines(text: CharSequence, from: Int, to: Int): Int {
150
+ var n = 0
151
+ for (i in max(0, from) until min(to, text.length)) if (text[i] == '\n') n++
152
+ return n
153
+ }
154
+
155
+ override fun onSelectionChanged(selStart: Int, selEnd: Int) {
156
+ super.onSelectionChanged(selStart, selEnd)
157
+ // Field initialisers of this class have not run when EditText's constructor sets the first selection.
158
+ @Suppress("SENSELESS_COMPARISON")
159
+ if (style == null || applying) return
160
+ reportSelection()
161
+ }
162
+
163
+ override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: android.graphics.Rect?) {
164
+ super.onFocusChanged(focused, direction, previouslyFocusedRect)
165
+ @Suppress("SENSELESS_COMPARISON")
166
+ if (style == null) return
167
+ focusedNow = focused
168
+ reportSelection(force = true)
169
+ }
170
+
171
+ private fun reportSelection(force: Boolean = false) {
172
+ val a = selectionStart.coerceAtLeast(0)
173
+ val h = selectionEnd.coerceAtLeast(0)
174
+ if (!force && a == lastSelA && h == lastSelH) return
175
+ lastSelA = a
176
+ lastSelH = h
177
+ emit("rtselect", mapOf("seq" to seq, "base" to rev, "a" to a, "h" to h, "focus" to focusedNow))
178
+ }
179
+
180
+ // ============================================================================================ app messages
181
+
182
+ fun applyMessage(message: JSONObject) {
183
+ if (message.optInt("ack", -1) != seq) return
184
+ val newRev = message.optInt("rev")
185
+ val full = message.optJSONObject("full")
186
+ val editable = editableText
187
+ if (full != null) {
188
+ applying = true
189
+ try {
190
+ val text = full.optString("text")
191
+ editable.replace(0, editable.length, text)
192
+ appLines = parseLines(full.optJSONArray("lines"))
193
+ lines = appLines.toMutableList()
194
+ lastText = editable.toString()
195
+ rev = newRev
196
+ restyle(0, lines.size)
197
+ val sel = message.optJSONObject("sel")
198
+ val max = editable.length
199
+ if (sel != null) setSelection(sel.optInt("a").coerceIn(0, max), sel.optInt("h").coerceIn(0, max))
200
+ else setSelection(selectionStart.coerceIn(0, max), selectionEnd.coerceIn(0, max))
201
+ } finally {
202
+ applying = false
203
+ }
204
+ afterMessage(message, newRev)
205
+ return
206
+ }
207
+ val splice = message.optJSONObject("lines")
208
+ if (splice != null && splice.optInt("of", -1) != rev) {
209
+ emit("rtaction", mapOf("kind" to "resync"))
210
+ return
211
+ }
212
+ val ops = message.optJSONArray("ops")
213
+ var firstChanged = Int.MAX_VALUE
214
+ var lastChanged = -1
215
+ applying = true
216
+ try {
217
+ if (ops != null) {
218
+ for (i in 0 until ops.length()) {
219
+ val op = ops.getJSONObject(i)
220
+ val from = op.optInt("from")
221
+ val to = op.optInt("to")
222
+ val text = op.optString("text")
223
+ if (from < 0 || to < from || to > editable.length) {
224
+ applying = false
225
+ emit("rtaction", mapOf("kind" to "resync"))
226
+ return
227
+ }
228
+ editable.replace(from, to, text)
229
+ val line = countNewlines(editable, 0, from)
230
+ firstChanged = min(firstChanged, line)
231
+ lastChanged = max(lastChanged, line + text.count { it == '\n' } + 1)
232
+ }
233
+ }
234
+ if (splice != null) {
235
+ val at = splice.optInt("at")
236
+ val del = splice.optInt("del")
237
+ val ins = parseLines(splice.optJSONArray("ins"))
238
+ val next = appLines.toMutableList()
239
+ repeat(min(del, max(0, next.size - at))) { next.removeAt(at) }
240
+ next.addAll(min(at, next.size), ins)
241
+ appLines = next
242
+ firstChanged = min(firstChanged, at)
243
+ lastChanged = max(lastChanged, at + ins.size)
244
+ }
245
+ lines = appLines.toMutableList()
246
+ lastText = editable.toString()
247
+ if (lines.size != countNewlines(editable, 0, editable.length) + 1) {
248
+ applying = false
249
+ emit("rtaction", mapOf("kind" to "resync"))
250
+ return
251
+ }
252
+ rev = newRev
253
+ if (lastChanged >= 0) restyle(firstChanged, min(lastChanged, lines.size))
254
+ message.optJSONObject("sel")?.let { sel ->
255
+ val max = editable.length
256
+ setSelection(sel.optInt("a").coerceIn(0, max), sel.optInt("h").coerceIn(0, max))
257
+ }
258
+ } finally {
259
+ applying = false
260
+ }
261
+ afterMessage(message, newRev)
262
+ }
263
+
264
+ private fun afterMessage(message: JSONObject, newRev: Int) {
265
+ message.optJSONArray("peers")?.let { list ->
266
+ peers = (0 until list.length()).map { i ->
267
+ val peer = list.getJSONObject(i)
268
+ Peer(peer.optInt("a"), peer.optInt("h"), G9RichStyle.color(peer.optString("c"), Color.GRAY), peer.optString("n"))
269
+ }
270
+ invalidate()
271
+ }
272
+ emit("rtapplied", mapOf("rev" to newRev))
273
+ reportSelection()
274
+ if (message.optBoolean("focus")) {
275
+ requestFocus()
276
+ (context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
277
+ }
278
+ }
279
+
280
+ private fun parseLines(array: JSONArray?): MutableList<JSONObject> {
281
+ val out = mutableListOf<JSONObject>()
282
+ if (array != null) for (i in 0 until array.length()) out.add(array.getJSONObject(i))
283
+ return out
284
+ }
285
+
286
+ // ============================================================================================ styling
287
+
288
+ /** Redraws the spans of lines `[from, to)`. */
289
+ private fun restyle(from: Int, to: Int) {
290
+ val editable = editableText ?: return
291
+ val starts = lineStarts(editable)
292
+ val wasApplying = applying
293
+ applying = true
294
+ try {
295
+ // Spans of earlier lines that grew into these ones (typing a newline at a line's end extends its spans):
296
+ // restyle from the line they start on.
297
+ var first = max(0, from)
298
+ while (first > 0 && first < starts.size) {
299
+ val start = starts[first]
300
+ val leaking = editable.getSpans(start, start, G9Span::class.java).any { editable.getSpanStart(it) < start && editable.getSpanEnd(it) > start }
301
+ if (!leaking) break
302
+ first--
303
+ }
304
+ for (index in first until min(to, lines.size)) {
305
+ val start = starts.getOrNull(index) ?: break
306
+ val end = if (index + 1 < starts.size) starts[index + 1] - 1 else editable.length
307
+ for (span in editable.getSpans(start, end, G9Span::class.java)) {
308
+ val s = editable.getSpanStart(span)
309
+ val e = editable.getSpanEnd(span)
310
+ if (s in start..end) editable.removeSpan(span)
311
+ else if (s < start && e > start) editable.removeSpan(span)
312
+ }
313
+ // Spans whose text was deleted shrink to nothing but keep drawing (a paragraph's marker): gone too.
314
+ for (pos in intArrayOf(start, end)) {
315
+ for (span in editable.getSpans(pos, pos, G9Span::class.java)) {
316
+ if (editable.getSpanStart(span) == editable.getSpanEnd(span)) editable.removeSpan(span)
317
+ }
318
+ }
319
+ style.apply(editable, lines[index], start, end, width - totalPaddingLeft - totalPaddingRight)
320
+ }
321
+ } finally {
322
+ applying = wasApplying
323
+ }
324
+ invalidate()
325
+ }
326
+
327
+ private fun lineStarts(text: CharSequence): IntArray {
328
+ val list = ArrayList<Int>(lines.size + 1)
329
+ list.add(0)
330
+ for (i in text.indices) if (text[i] == '\n') list.add(i + 1)
331
+ return list.toIntArray()
332
+ }
333
+
334
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
335
+ super.onSizeChanged(w, h, oldw, oldh)
336
+ @Suppress("SENSELESS_COMPARISON")
337
+ if (style != null && w != oldw) post { restyle(0, lines.size) }
338
+ }
339
+
340
+ // ============================================================================================ collaborators
341
+
342
+ private val peerPaint = Paint(Paint.ANTI_ALIAS_FLAG)
343
+ private val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG)
344
+
345
+ override fun onDraw(canvas: Canvas) {
346
+ super.onDraw(canvas)
347
+ @Suppress("SENSELESS_COMPARISON")
348
+ if (peers == null || peers.isEmpty()) return
349
+ val layout = layout ?: return
350
+ canvas.save()
351
+ canvas.clipRect((scrollX + totalPaddingLeft) - dp(2f), (scrollY + extendedPaddingTop) - dp(16f), (scrollX + width - totalPaddingRight) + dp(80f), (scrollY + height - extendedPaddingBottom).toFloat())
352
+ drawPeers(canvas, layout)
353
+ canvas.restore()
354
+ }
355
+
356
+ private fun drawPeers(canvas: Canvas, layout: android.text.Layout) {
357
+ labelPaint.textSize = dp(11f)
358
+ labelPaint.typeface = TypefaceCache.getCachedTypeface("G9Semi", Typeface.NORMAL) ?: Typeface.DEFAULT_BOLD
359
+ for (peer in peers) {
360
+ val pos = peer.h.coerceIn(0, text.length)
361
+ val line = layout.getLineForOffset(pos)
362
+ val x = totalPaddingLeft + layout.getPrimaryHorizontal(pos)
363
+ val top = (extendedPaddingTop + layout.getLineTop(line)).toFloat()
364
+ val bottom = (extendedPaddingTop + layout.getLineBottom(line)).toFloat()
365
+ peerPaint.color = peer.color
366
+ canvas.drawRect(x - dp(1f), top, x + dp(1f), bottom, peerPaint)
367
+ val label = peer.name
368
+ val w = labelPaint.measureText(label) + dp(8f)
369
+ val h = dp(15f)
370
+ canvas.drawRoundRect(RectF(x - dp(1f), top - h, x - dp(1f) + w, top), dp(4f), dp(4f), peerPaint)
371
+ labelPaint.color = Color.WHITE
372
+ canvas.drawText(label, x + dp(3f), top - dp(4f), labelPaint)
373
+ }
374
+ }
375
+
376
+ // ============================================================================================ taps and keys
377
+
378
+ @SuppressLint("ClickableViewAccessibility")
379
+ override fun onTouchEvent(event: MotionEvent): Boolean {
380
+ when (event.actionMasked) {
381
+ MotionEvent.ACTION_DOWN -> touchDown = event.x to event.y
382
+ MotionEvent.ACTION_UP -> {
383
+ val down = touchDown
384
+ touchDown = null
385
+ if (down != null && abs(down.first - event.x) < dp(8f) && abs(down.second - event.y) < dp(8f) && handleTap(event.x, event.y)) return true
386
+ }
387
+ }
388
+ return super.onTouchEvent(event)
389
+ }
390
+
391
+ /** A checkbox in the start margin, or a chip: an action for the app. */
392
+ private fun handleTap(x: Float, y: Float): Boolean {
393
+ val layout = layout ?: return false
394
+ val line = layout.getLineForVertical((y - extendedPaddingTop + scrollY).toInt())
395
+ val lineStart = layout.getLineStart(line)
396
+ val paragraph = countNewlines(editableText, 0, lineStart)
397
+ val style = lines.getOrNull(paragraph)
398
+ val paragraphStart = if (lineStart == 0) 0 else editableText.lastIndexOf('\n', lineStart - 1) + 1
399
+ val marker = style?.optJSONObject("mk")
400
+ if (marker != null && marker.optString("k") == "t" && lineStart == paragraphStart) {
401
+ val rtl = layout.getParagraphDirection(line) == android.text.Layout.DIR_RIGHT_TO_LEFT
402
+ val margin = this.style.marginOf(style)
403
+ val inside = if (rtl) x > width - totalPaddingRight - margin else x < totalPaddingLeft + margin
404
+ if (inside) {
405
+ emit("rtaction", mapOf("kind" to "check", "line" to paragraph))
406
+ return true
407
+ }
408
+ }
409
+ val offset = getOffsetForPosition(x, y)
410
+ for (pos in intArrayOf(offset, offset - 1)) {
411
+ if (pos < 0 || pos >= editableText.length) continue
412
+ val chips = editableText.getSpans(pos, pos + 1, G9ChipSpan::class.java)
413
+ if (chips.isNotEmpty() && editableText.getSpanStart(chips[0]) == pos) {
414
+ emit("rtaction", mapOf("kind" to "tap", "at" to pos))
415
+ return !editableMode
416
+ }
417
+ }
418
+ return false
419
+ }
420
+
421
+ override fun onKeyShortcut(keyCode: Int, event: KeyEvent): Boolean {
422
+ if (event.isCtrlPressed) {
423
+ val key = when (keyCode) {
424
+ KeyEvent.KEYCODE_Z -> if (event.isShiftPressed) "redo" else "undo"
425
+ KeyEvent.KEYCODE_Y -> "redo"
426
+ KeyEvent.KEYCODE_B -> "bold"
427
+ KeyEvent.KEYCODE_I -> "italic"
428
+ KeyEvent.KEYCODE_U -> "underline"
429
+ KeyEvent.KEYCODE_E -> "code"
430
+ else -> null
431
+ }
432
+ if (key != null) {
433
+ emit("rtaction", mapOf("kind" to "key", "key" to key))
434
+ return true
435
+ }
436
+ }
437
+ return super.onKeyShortcut(keyCode, event)
438
+ }
439
+
440
+ override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
441
+ if (keyCode == KeyEvent.KEYCODE_TAB && editableMode) {
442
+ emit("rtaction", mapOf("kind" to "key", "key" to if (event.isShiftPressed) "outdent" else "indent"))
443
+ return true
444
+ }
445
+ if (keyCode == KeyEvent.KEYCODE_ENTER && event.isShiftPressed && editableMode) {
446
+ // A line break inside the paragraph: U+2028 for the app (it becomes a hard break).
447
+ val start = min(selectionStart, selectionEnd).coerceAtLeast(0)
448
+ val end = max(selectionStart, selectionEnd).coerceAtLeast(0)
449
+ editableText.replace(start, end, "
")
450
+ return true
451
+ }
452
+ return super.onKeyDown(keyCode, event)
453
+ }
454
+
455
+ private fun emit(name: String, detail: Map<String, Any?>) {
456
+ emitter?.invoke(name, detail)
457
+ }
458
+ }