compose-rust 0.0.11

Declarative UI in Rust, rendered by an AOT-compiled Compose Multiplatform engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
package dev.darkpyonix.composerust.foundation

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.type
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import dev.darkpyonix.composerust.design.HostPlatform
import dev.darkpyonix.composerust.design.ResolvedTheme
import dev.darkpyonix.composerust.foundation.code.CodeEditorCallbacks
import dev.darkpyonix.composerust.foundation.code.CodeEditorLook
import dev.darkpyonix.composerust.foundation.code.CodeEditorModel
import dev.darkpyonix.composerust.foundation.code.CodeEditorSurface
import dev.darkpyonix.composerust.foundation.code.EditorOutput
import dev.darkpyonix.composerust.foundation.code.EditorScroll
import dev.darkpyonix.composerust.foundation.code.WordWrapRule
import dev.darkpyonix.composerust.protocol.CodeEditorColorsRecord
import dev.darkpyonix.composerust.protocol.ColorRole
import dev.darkpyonix.composerust.protocol.CodeEditorRecords
import dev.darkpyonix.composerust.protocol.FontRefRecords
import dev.darkpyonix.composerust.protocol.HostEvent
import dev.darkpyonix.composerust.protocol.HoverPhase
import dev.darkpyonix.composerust.protocol.MinimapSide
import dev.darkpyonix.composerust.protocol.WordWrapMode
import dev.darkpyonix.composerust.protocol.PropertyKind
import dev.darkpyonix.composerust.protocol.PropertyValue
import dev.darkpyonix.composerust.protocol.TypeRole
import dev.darkpyonix.composerust.runtime.EventDispatcher
import dev.darkpyonix.composerust.ui.node.AssetCache
import dev.darkpyonix.composerust.ui.node.FontChain
import dev.darkpyonix.composerust.ui.node.Node
import dev.darkpyonix.composerust.ui.node.NodeTable
import dev.darkpyonix.composerust.ui.role
import dev.darkpyonix.composerust.ui.textStyle
import java.nio.ByteBuffer
import java.nio.ByteOrder

/**
 * A code editor bound to its node.
 *
 * The document, the selection, the undo history and the decorations live in the node's
 * [CodeEditorModel], which the batches the Host sends feed and the surface edits. This only
 * resolves how the editor looks from the design system and carries what the model and the
 * surface have to say to the Host: each committed change, an edit refused, a lens or a gutter
 * mark pressed or a suggestion accepted, a pointer at rest, the save shortcut, and what the
 * Host listens to about the editor itself: the selection, the lines on screen, focus, folds
 * and whether an input method is composing.
 */
@Composable
internal fun HostCodeEditor(
    node: Node,
    modifier: Modifier,
    dispatcher: EventDispatcher,
    theme: ResolvedTheme,
    table: NodeTable,
    assets: AssetCache? = null,
) {
    val model = node.code ?: return
    val tabWidth = (node.property(PropertyKind.TabWidth) as? PropertyValue.Integer)?.value
        ?.toInt()
        ?.takeIf { it > 0 }
    // The application's own font list, where it gave one: the editor is set in its first
    // family and a letter that family lacks comes from the next one that has it.
    val fontBlob = node.bytes(PropertyKind.Font)
    val fontChain = remember(fontBlob, assets?.size) {
        if (fontBlob == null || assets == null) {
            null
        } else {
            FontRefRecords.decodeBlob(fontBlob)?.let { resolveFontChain(it, assets, mutableListOf()) }
        }
    }
    // Every property the look is made of is read here, so that changing one of them makes
    // a new look and leaving them alone keeps the one there is.
    val look = remember(
        theme,
        tabWidth,
        fontChain,
        node.property(PropertyKind.TypeRole),
        node.property(PropertyKind.FontSize),
        node.property(PropertyKind.LineHeight),
        node.property(PropertyKind.LineNumbers),
        node.property(PropertyKind.GutterMinWidthDp),
        node.property(PropertyKind.GutterPaddingDp),
        node.property(PropertyKind.TextInsetDp),
        node.bytes(PropertyKind.CodeEditorColors),
        node.property(PropertyKind.Minimap),
        node.property(PropertyKind.WordWrap),
        node.bytes(PropertyKind.ContentPaddingDp),
        node.property(PropertyKind.FixedGutterColumns),
    ) { codeEditorLook(node, theme, tabWidth, fontChain) }
    val currentDispatcher by rememberUpdatedState(dispatcher)
    val keyPreview = remember(node) { codeEditorKeyPreview(node, { currentDispatcher }) }
    val callbacks = remember(node, model) {
        CodeEditorCallbacks(
            onOutput = { node.sendCodeOutput(model.drainOutput(includeReports = true), currentDispatcher) },
            onSave = {
                val handler = node.handler(PropertyKind.OnSave)
                if (handler != null) {
                    currentDispatcher.dispatch(
                        HostEvent.CodeSaveRequested(node.id, handler, model.document.version),
                    )
                }
            },
            onHover = { decoration, position, rest ->
                val handler = node.handler(PropertyKind.OnHover)
                if (handler != null) {
                    currentDispatcher.dispatch(
                        HostEvent.CodeHovered(
                            node.id,
                            handler,
                            decoration,
                            position.line,
                            position.column,
                            if (rest) HoverPhase.Rest else HoverPhase.Leave,
                        ),
                    )
                }
            },
            onKeyPreview = keyPreview,
            // The Host's pointer events over the editor go through the same router as every
            // other node's, so a press the editor does not consume goes on to the nearest
            // subscribed node around it.
            codePointer = { target ->
                if (node.subscribesToCodePointer()) {
                    codePointerEvents(node, table.pointers, currentDispatcher, target)
                } else {
                    Modifier
                }
            },
        )
    }
    // A listener attached after the editor was drawn has the row height and the offset
    // waiting for it in the model. Nothing else may redraw the editor soon, so they are
    // sent now.
    val hearsMetrics = node.handler(PropertyKind.OnCodeMetrics) != null
    val hearsScroll = node.handler(PropertyKind.OnCodeScrolled) != null
    val hearsCaret = node.handler(PropertyKind.OnCaretRect) != null
    LaunchedEffect(model, hearsMetrics, hearsScroll, hearsCaret) {
        if (hearsMetrics || hearsScroll || hearsCaret) callbacks.onOutput()
    }
    val focusRequest = node.focusRequestRevision
    CodeEditorSurface(model, look, callbacks, modifier, focusRequest = focusRequest) { scrolling ->
        // The editor scrolls down its document by an offset it keeps itself and along its
        // lines by an ordinary scroll state. Both take the Host's scroll requests and
        // both are in the report.
        HostScroll(
            node,
            table,
            remember(scrolling) {
                OffsetScrollSurface(
                    x = scrolling.horizontal?.axis(),
                    y = scrolling.vertical.axis(scrolling.viewportHeight),
                    mainVertical = true,
                )
            },
        )
    }
}

/** The editor's own offset down its document, as an axis a scroll request can move. */
private fun EditorScroll.axis(viewport: () -> Int): ScrollAxis = ScrollAxis(
    state = scrollable,
    value = { offset },
    max = { max },
    viewport = viewport,
    measured = { viewport() > 0 },
    jump = { target -> scrollTo(target) },
)

/**
 * What an editor offers the Host before it handles a key: the `KeyDown` record a key handler
 * hears, sent to the node's `OnKeyPreview` handler, whose answer says whether the Host took
 * the key. Nothing is sent while an input method composes, for a release, or where nothing
 * listens. Every event passes through [held], so a repeat is marked as one.
 */
internal fun codeEditorKeyPreview(
    node: Node,
    dispatcher: () -> EventDispatcher,
    held: HeldKeys = HeldKeys(),
): (KeyEvent, Boolean) -> Boolean = { event, composing ->
    val handler = node.handler(PropertyKind.OnKeyPreview)
    if (handler == null) {
        held.observe(event.type, event.key)
        false
    } else {
        dispatchKeyDown(node.id, handler, event, composing, dispatcher(), held)
    }
}

/** The colours the application gave this editor, or null where it gave none that can be read. */
internal fun Node.codeEditorColors(): CodeEditorColorsRecord? =
    bytes(PropertyKind.CodeEditorColors)?.let { bytes ->
        // What cannot be read was reported when the property arrived; here it is only left out.
        CodeEditorRecords.decodeCodeEditorColors(bytes) {}.firstOrNull()
    }

/**
 * A length in dp the application set on the node, or null where it set none. Zero is a
 * length like any other here: a text inset of nothing is a thing to ask for. A length
 * below zero or one that is not a number is left to the design system.
 */
private fun Node.lengthOrNull(kind: PropertyKind): Dp? = when (val value = property(kind)) {
    is PropertyValue.Float -> value.value
    is PropertyValue.Integer -> value.value.toFloat()
    else -> null
}?.takeIf { it >= 0f && it.isFinite() }?.dp

/**
 * The room above the first line and below the last an application gave an editor, in dp,
 * or null where it gave none or the bytes are not eight of two lengths of zero or more.
 */
internal fun contentPaddingDp(bytes: ByteArray): Pair<Float, Float>? {
    if (bytes.size != CONTENT_PADDING_BYTES) return null
    // Read as bits: the byte buffer the iOS renderer shares this file with has no getFloat.
    val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
    val top = Float.fromBits(buffer.getInt(0))
    val bottom = Float.fromBits(buffer.getInt(4))
    if (!top.isFinite() || !bottom.isFinite() || top < 0f || bottom < 0f) return null
    return top to bottom
}

/** Two `f32` lengths in dp: above the first line, then below the last. */
internal const val CONTENT_PADDING_BYTES = 8

/**
 * What an editor looks like here, resolved to plain values: the design system's editor,
 * with the type, the gutter and the colours the application set on the node over it.
 */
internal fun codeEditorLook(
    node: Node,
    theme: ResolvedTheme,
    tabWidth: Int?,
    fontChain: FontChain? = null,
): CodeEditorLook {
    val style = theme.rules.codeEditor(theme)
    val colors = node.codeEditorColors()
    // What cannot be read was reported when the property arrived; here it is left at none.
    val padding = node.bytes(PropertyKind.ContentPaddingDp)?.let(::contentPaddingDp)
    // The role, the size and the row height are the node's where it has them, and the
    // monospace rung of the type ladder where it does not.
    val type = node.textStyle(theme, TypeRole.Mono)
    return CodeEditorLook(
        textStyle = type.copy(color = style.text, fontFamily = fontChain?.primary ?: type.fontFamily),
        container = colors?.container?.let { theme.color(it) } ?: style.container,
        gutter = colors?.gutter?.let { theme.color(it) } ?: style.gutter,
        lineNumber = colors?.lineNumber?.let { theme.color(it) } ?: style.lineNumber,
        currentLineNumber = colors?.currentLineNumber?.let { theme.color(it) } ?: style.currentLineNumber,
        currentLine = colors?.currentLine?.let { theme.color(it) } ?: style.currentLine,
        currentLineBorder = style.currentLineBorder,
        gutterDivider = style.gutterDivider,
        gutterDividerWidth = style.gutterDividerWidth,
        gutterPadding = node.lengthOrNull(PropertyKind.GutterPaddingDp) ?: style.gutterPadding,
        textInset = node.lengthOrNull(PropertyKind.TextInsetDp) ?: style.textInset,
        selection = style.selection,
        cursor = style.cursor,
        underlineWidth = style.underlineWidth,
        underline = { decoration ->
            style.underlineColor(decoration.severity, decoration.color, theme) to
                style.underlineShape(decoration.severity)
        },
        paint = { paint -> theme.color(paint) },
        ghostTextAlpha = style.ghostTextAlpha,
        lens = style.lens,
        tabWidth = tabWidth ?: style.tabWidth,
        hoverDelayMillis = style.hoverDelayMillis,
        commandIsMeta = theme.platform == HostPlatform.MacOs || theme.platform == HostPlatform.Ios,
        // A mark takes the role the Host named, and otherwise the lens's quiet ink.
        gutterMark = { role -> if (role == null) style.lens else theme.color(role) },
        foldMarker = style.lineNumber,
        // The same for every design system: the width and gap of a change-marker bar.
        changeBarWidth = 4.dp,
        changeBarGap = 12.dp,
        lineNumbers = node.flag(PropertyKind.LineNumbers, default = true),
        gutterMinWidth = node.lengthOrNull(PropertyKind.GutterMinWidthDp) ?: 0.dp,
        fontFallback = fontChain?.let { chain -> { text: String -> chain.spans(text) } },
        lineBackground = { role -> diffTint(role, theme, strong = false) },
        rangeBackground = { role -> diffTint(role, theme, strong = true) },
        minimapSide = node.role(PropertyKind.Minimap, MinimapSide.entries.toTypedArray()),
        wordWrap = node.wordWrap(),
        contentPaddingTop = padding?.first?.dp ?: 0.dp,
        contentPaddingBottom = padding?.second?.dp ?: 0.dp,
        fixedGutterColumns = node.flag(PropertyKind.FixedGutterColumns, default = false),
        currentLineGutter = colors?.currentLineGutter?.let { theme.color(it) } ?: Color.Unspecified,
    )
}

/**
 * Where the application asked long lines to break: the `WordWrapMode` tag in the low 16 bits
 * of the property and the columns above them. Null where it asked for none, or for a rule
 * that is not one, which the table reported when it arrived.
 */
internal fun Node.wordWrap(): WordWrapRule? = (property(PropertyKind.WordWrap) as? PropertyValue.Integer)?.value?.let(::wordWrapRule)

/** The rule an integer of the `WordWrap` property says, or null where it says none or is not one. */
internal fun wordWrapRule(value: Long): WordWrapRule? {
    if (value < 0) return null
    val mode = WordWrapMode.entries.getOrNull((value and 0xffff).toInt() - 1) ?: return null
    val columns = value shr 16
    if (columns > Int.MAX_VALUE) return null
    return when (mode) {
        WordWrapMode.Viewport -> if (columns == 0L) WordWrapRule(mode, 0) else null
        WordWrapMode.Column, WordWrapMode.Bounded -> if (columns > 0) WordWrapRule(mode, columns.toInt()) else null
    }
}

/**
 * What a line background ([strong] false) or a range background ([strong] true) in a role
 * is drawn with. An added or a removed line takes the design system's container tint for
 * it and the changed characters its emphasis tint, the same pair a diff badge uses. A role
 * that is already one of those tints is drawn as it is. Any other role is laid over the
 * text as a wash, light enough that the code stays readable.
 */
internal fun diffTint(role: ColorRole, theme: ResolvedTheme, strong: Boolean): Color = when (role) {
    ColorRole.DiffAdded -> theme.color(if (strong) ColorRole.DiffAddedEmphasis else ColorRole.DiffAddedContainer)
    ColorRole.DiffRemoved -> theme.color(if (strong) ColorRole.DiffRemovedEmphasis else ColorRole.DiffRemovedContainer)
    ColorRole.DiffAddedContainer,
    ColorRole.DiffRemovedContainer,
    ColorRole.DiffAddedEmphasis,
    ColorRole.DiffRemovedEmphasis,
    -> theme.color(role)
    else -> theme.color(role).let { ink ->
        // The same strengths the container and the emphasis tints are mixed at.
        val wash = when {
            strong && theme.dark -> 0.40f
            strong -> 0.30f
            theme.dark -> 0.20f
            else -> 0.12f
        }
        ink.copy(alpha = ink.alpha * wash)
    }
}

/**
 * Turns what an editor's model queued into events for the Host, in the order it was queued.
 *
 * An event goes only where the application listens: a change with no `on_change` handler
 * has nobody to tell. A record the Host sent that could not be honoured is reported through
 * [onError] instead, so it becomes a protocol error.
 */
internal fun Node.codeEvents(outputs: List<EditorOutput>, onError: (String) -> Unit): List<HostEvent> {
    if (outputs.isEmpty()) return emptyList()
    val events = ArrayList<HostEvent>(outputs.size)
    for (output in outputs) {
        when (output) {
            is EditorOutput.Changed -> {
                val handler = handler(PropertyKind.OnValueChange) ?: continue
                val change = output.change
                events += HostEvent.CodeChanged(
                    id,
                    handler,
                    change.version,
                    change.start.line,
                    change.start.column,
                    change.end.line,
                    change.end.column,
                    change.text,
                )
            }
            is EditorOutput.Rejected -> {
                val handler = handler(PropertyKind.OnEditRejected) ?: continue
                events += HostEvent.CodeEditRejected(
                    id,
                    handler,
                    output.requestId,
                    output.baseVersion,
                    output.currentVersion,
                    output.start.line,
                    output.start.column,
                    output.end.line,
                    output.end.column,
                )
            }
            is EditorOutput.Activated -> {
                val handler = handler(PropertyKind.OnDecorationClick) ?: continue
                events += HostEvent.DecorationActivated(id, handler, output.id)
            }
            is EditorOutput.SelectionMoved -> {
                val handler = handler(PropertyKind.OnSelectionChange) ?: continue
                val selection = output.selection
                events += HostEvent.SelectionChanged(
                    id,
                    handler,
                    output.version,
                    selection.anchor.line,
                    selection.anchor.column,
                    selection.caret.line,
                    selection.caret.column,
                )
            }
            // Every selection, as anchor and active pairs, to the same listener as the
            // primary one.
            is EditorOutput.SelectionsMoved -> {
                val handler = handler(PropertyKind.OnSelectionChange) ?: continue
                val values = IntArray(output.selections.size * 4)
                for ((index, selection) in output.selections.withIndex()) {
                    values[index * 4] = selection.anchor.line
                    values[index * 4 + 1] = selection.anchor.column
                    values[index * 4 + 2] = selection.caret.line
                    values[index * 4 + 3] = selection.caret.column
                }
                events += HostEvent.SelectionsChanged(id, handler, output.version, values)
            }
            is EditorOutput.VisibleRange -> {
                val handler = handler(PropertyKind.OnVisibleRangeChange) ?: continue
                events += HostEvent.VisibleRangeChanged(id, handler, output.version, output.first, output.last)
            }
            is EditorOutput.Focus -> {
                val handler = handler(PropertyKind.OnEditorFocusChange) ?: continue
                events += HostEvent.EditorFocusChanged(id, handler, output.focused)
            }
            is EditorOutput.FoldToggled -> {
                val handler = handler(PropertyKind.OnFoldChange) ?: continue
                events += HostEvent.FoldChanged(id, handler, output.startLine, output.collapsed)
            }
            // Pixels cross as a whole number in a double, the unit the scroll command takes.
            is EditorOutput.LineHeight -> {
                val handler = handler(PropertyKind.OnCodeMetrics) ?: continue
                events += HostEvent.CodeMetrics(id, handler, output.px.toDouble())
            }
            is EditorOutput.Scrolled -> {
                val handler = handler(PropertyKind.OnCodeScrolled) ?: continue
                events += HostEvent.CodeScrolled(id, handler, output.offsetPx.toDouble())
            }
            // In the window's dp, the scroll and the zoom already in them.
            is EditorOutput.Caret -> {
                val handler = handler(PropertyKind.OnCaretRect) ?: continue
                val (position, rect) = output.report
                events += HostEvent.CaretRect(
                    id,
                    handler,
                    position.line,
                    position.column,
                    rect.x,
                    rect.y,
                    rect.width,
                    rect.height,
                )
            }
            // An answer goes to the query and names no handler: the Host asked, so it is
            // waiting for it whether or not anything on the editor listens.
            is EditorOutput.PositionAnswer -> {
                val rect = output.rect
                events += HostEvent.PositionRect(
                    id,
                    0L,
                    output.request,
                    rect != null,
                    rect?.x ?: 0f,
                    rect?.y ?: 0f,
                    rect?.width ?: 0f,
                    rect?.height ?: 0f,
                )
            }
            is EditorOutput.Composing -> {
                val handler = handler(PropertyKind.OnCompositionChange) ?: continue
                events += HostEvent.CompositionChanged(id, handler, output.composing)
            }
            is EditorOutput.GroupResult -> {
                val handler = handler(PropertyKind.OnEditGroupResult) ?: continue
                events += HostEvent.CodeEditGroupResult(
                    id,
                    handler,
                    output.requestId,
                    output.status,
                    output.baseVersion,
                    output.currentVersion,
                    output.index,
                )
            }
            is EditorOutput.Error -> onError(output.message)
        }
    }
    return events
}

/** Sends what the surface made the model queue, straight away, on the UI thread. */
private fun Node.sendCodeOutput(outputs: List<EditorOutput>, dispatcher: EventDispatcher) {
    val events = codeEvents(outputs) { message ->
        dispatcher.dispatch(
            HostEvent.ProtocolError(
                nodeId = 0,
                handlerId = 0,
                code = CODE_EDITOR_ERROR,
                message = "code editor $id: $message",
            ),
        )
    }
    for (event in events) dispatcher.dispatch(event)
}

/** The protocol error code a code editor reports a record it could not honour with. */
internal const val CODE_EDITOR_ERROR = 9