//! Deterministic Kotlin protocol generation from the Rust schema.
use crate::protocol::{
BatchEncoder, HostEvent, Mutation, PropertyValue, ProtocolError, encode_event,
};
use crate::schema::{
ANDROID_BRIDGE_CLASS, BOUNDARY_SCHEMA, BoundaryOp, BoundaryParam, Color, ColorRole,
ColorScheme, DESIGN_SYSTEM_SCHEMA, DesignSystem, EVENT_SCHEMA, EventPayloadType, FieldSchema,
FieldSlot, FieldType, HOVER_PHASE_SCHEMA, KEY_SCHEMA, Key, MODIFIER_SCHEMA,
NOTIFICATION_PERMISSION_SCHEMA, NotificationImportance, NotificationPermission,
NotificationPresentation, PROPERTY_SCHEMA, PROTOCOL_VERSION, Paint, PropertyKind,
ROLE_ENUM_SCHEMA, SCHEMA_HASH, Selection, ShapeRole, SpaceRole, Theme, WEB_BATCH_BYTES,
WEB_BATCH_FIELDS, WEB_EVENT_BUFFER_BYTES, WEB_EVENT_BUFFER_MAX_BYTES, WEB_EVENT_BUFFER_OFFSET,
WEB_LEND_EVENT_BUFFER_SYMBOL, WEB_MODULE_GLOBAL, WEB_RENDERER_IMPORT_MODULE,
WEB_RUST_REGION_BASE, WEB_START_SYMBOL, WEB_TABLE_GLOBAL, WIDGET_SCHEMA,
WINDOW_HEIGHT_CLASS_SCHEMA, WINDOW_SIZE_CLASS_SCHEMA, WidgetKind,
};
use crate::schema::{
AnimatedProperty, Animation, AnimationControl, AnimationEvents, ColorInterpolation, FillMode,
Keyframe, KeyframeValue, PlayState, PlaybackDirection, StepPosition, Timing, TransformFunction,
};
use crate::tokens::DESIGN_TOKENS;
use crate::{EventPayload, Modifier};
use std::fmt::Write as _;
/// The Kotlin Toolchain compiles the module's `src` tree by convention and offers no way to
/// add another source root, so generated Kotlin lives inside `src`.
pub const GENERATED_RELATIVE_PATH: &str = "../renderer/desktop/src/protocol/Protocol.gen.kt";
/// The schema's hash, as a line of text beside the crate.
///
/// The renderer carries the same number, compiled into it, and the two are compared when
/// the first call crosses the boundary. That comparison happens at run time, which is
/// late: a renderer built from another schema produces a program that builds, starts,
/// opens a window and draws nothing. The build script reads this file and the one in the
/// renderer's distribution so the disagreement is reported while there is still a build to
/// stop.
pub const SCHEMA_HASH_RELATIVE_PATH: &str = "schema-hash.txt";
pub const MUTATION_VECTOR_RELATIVE_PATH: &str = "tests/vectors/mutations.bin";
pub const EVENT_VECTOR_RELATIVE_PATH: &str = "tests/vectors/events.bin";
pub const TRANSFORM_3D_VECTOR_RELATIVE_PATH: &str = "tests/vectors/transform3d.bin";
pub const BACKGROUND_BRUSH_VECTOR_RELATIVE_PATH: &str = "tests/vectors/background_brush.bin";
pub const VECTOR_DESCRIPTION_RELATIVE_PATH: &str = "tests/vectors/vectors.json";
const KOTLIN_PACKAGE: &str = "dev.darkpyonix.composerust.protocol";
/// The schema's hash on its own line, for the file the build script compares.
pub fn generate_schema_hash() -> String {
format!("{SCHEMA_HASH:#018x}\n")
}
pub fn generate_kotlin() -> String {
let mut output = String::new();
output.push_str("// Generated by `cargo run -p compose-rust --bin codegen`. DO NOT EDIT.\n\n");
writeln!(output, "package {KOTLIN_PACKAGE}\n").unwrap();
output.push_str("import java.nio.ByteBuffer\n");
output.push_str("import java.nio.ByteOrder\n");
output.push_str("import java.nio.charset.StandardCharsets\n\n");
write_enum(&mut output, "WidgetKind", WIDGET_SCHEMA);
write_enum(&mut output, "PropertyKind", PROPERTY_SCHEMA);
write_enum(&mut output, "Key", KEY_SCHEMA);
write_enum(&mut output, "WindowSizeClass", WINDOW_SIZE_CLASS_SCHEMA);
write_enum(&mut output, "WindowHeightClass", WINDOW_HEIGHT_CLASS_SCHEMA);
for role in ROLE_ENUM_SCHEMA {
write_enum(&mut output, role.name, role.variants);
}
writeln!(
output,
"/**\n \
* The `TypeRole` property of text with no rung of the ladder at all: CSS text, whose\n \
* size, weight and font are its own. Present and zero; an absent property is the\n \
* widget's default rung.\n \
*/\n\
const val TYPE_ROLE_NONE: Int = {}\n",
crate::schema::TypeRole::None as u16
)
.unwrap();
// Who owns the frame loop. The value is one byte of the handshake, so the two sides
// have to agree on it before anything else is said.
output.push_str(
r#"enum class LoopMode(val wire: Byte) {
/** The Renderer runs the loop and the Host blocks inside it. Desktop. */
Renderer(0),
/** The platform owns the process and the loop. Android, iOS and the web. */
Platform(1),
}
"#,
);
// Colour crosses the boundary only as a Paint, so there is exactly one representation
// of colour in the schema.
output.push_str(
r#"sealed interface Paint {
data class Role(val role: ColorRole) : Paint
/** A literal 0xAARRGGBB colour. */
data class Literal(val argb: Int) : Paint
/**
* A registered brush: a gradient, or a picture laid out as a fill.
*
* An id, because a list of stops does not fit the two words a paint has and because a
* brush has to outlive the frame that draws it.
*/
data class Asset(val assetId: Int) : Paint
}
data class Theme(
val designSystem: DesignSystem,
val fallback: DesignSystem,
val colorScheme: ColorScheme,
val adaptive: Boolean,
/**
* The font asset each type role resolves to, indexed by the role's ordinal, with zero
* where the role keeps the system font.
*
* Per theme rather than per node: an application changes what a role is made of and
* every piece of text in that role changes with it. A node that could name a font
* would be a node deciding typography.
*/
val fonts: List<Int> = List(TypeRole.entries.size) { 0 },
/**
* The application's own colours, laid over whichever design system this resolves to.
*
* Both schemes arrive together, so a switch between light and dark is answered from
* here and never asks the Host. Empty where the application gave none.
*/
val palette: List<PaletteEntry> = emptyList(),
/**
* What was wrong with entries the palette arrived with, one sentence each.
*
* Those entries are already left out of [palette] and the rest of it stands. Whoever
* applies the theme reports each of these as a protocol error: a theme is never thrown
* away whole for one bad entry, because that would open the application with no colours
* at all.
*/
val paletteProblems: List<String> = emptyList(),
) {
/** The font asset for [role], or null where the role keeps the system font. */
fun font(role: TypeRole): Int? = fonts.getOrNull(role.ordinal)?.takeIf { it != 0 }
/** The colour the application gave [role] in this scheme, as 0xAARRGGBB, or null. */
fun paletteColor(role: ColorRole, dark: Boolean): Int? =
palette.firstOrNull { it.role == role && it.dark == dark }?.argb
}
/** One role's colour in one scheme, as the application gave it. */
data class PaletteEntry(val role: ColorRole, val dark: Boolean, val argb: Int)
/**
* Application-level overlay theme tokens for Dialog, Menu, Dropdown, Sheet and the transient
* message. Every measure is in dp, and 0 keeps the design system's own.
*/
data class OverlayTokens(
val sheetCornerRadius: Int = 0,
val dialogCornerRadius: Int = 0,
val popupCornerRadius: Int = 0,
val sheetElevation: Int = 0,
val popupElevation: Int = 0,
val dialogElevation: Int = 0,
val sheetPadding: Int = 0,
val dialogPadding: Int = 0,
val popupPadding: Int = 0,
val scrim: Long = 0L,
val toastElevation: Int = 0,
val toastCornerRadius: Int = 0,
)
/**
* What the application asked of its own window.
*
* A zero measurement means the application did not ask, so the choice is the Renderer's.
* This arrives in the first batch, which the Renderer reads before it stands the window
* up; a platform where the window is not ours ignores it.
*/
data class Window(
val chrome: Chrome,
/**
* Which of the two title bars this window has.
*
* `Chrome` says who draws the caption; this says, inside that, what kind of window the
* caption belongs to. What it is worth in pixels is this side's answer: on macOS how
* far in the buttons sit and how round the window is, on Windows and Linux how tall
* the caption is.
*/
val titleBar: TitleBar,
/**
* What the window calls itself.
*
* Empty means the application said nothing and the renderer uses its own name. A
* desktop lists windows by this, so a window with no title of its own is listed
* under whatever the renderer happened to be called.
*/
val title: String,
/**
* The picture the window wears, as an asset id, or zero for none.
*
* An id rather than a path or a name: a path is a fact about the machine the
* application was built on, and a name asks the toolkit to find something it may not
* have. Zero leaves the toolkit's own icon, which is what every window here wore
* until this existed.
*/
val icon: Int,
val width: Int,
val height: Int,
val minWidth: Int,
val minHeight: Int,
val resizable: Boolean,
/**
* The application's zoom level, or null where it left the level to the renderer.
*
* A level here is applied, remembered and reported back the way one chosen with the
* keys is. Always inside -8..8.
*/
val zoomLevel: Int? = null,
/**
* One window, or several. With [WindowMode.Windows] the root's children are
* `Window` nodes and the rest of this record describes no window.
*/
val mode: WindowMode = WindowMode.Single,
/** What happens when the last window goes. Only read in [WindowMode.Windows]. */
val lastWindowClosed: LastWindowClosed = LastWindowClosed.Exit,
/**
* Whether the implicit single window reports every whole-dp change of its size, not
* only a change of size class. Windows made of `Window` nodes use the node property.
*/
val reportSize: Boolean = false,
)
"#,
);
output.push_str("sealed interface PropertyValue {\n");
output.push_str(" data object None : PropertyValue\n");
output.push_str(" data class Text(val value: String) : PropertyValue\n");
output.push_str(" data class Bool(val value: Boolean) : PropertyValue\n");
output.push_str(" data class Integer(val value: Long) : PropertyValue\n");
output.push_str(" data class Float(val value: kotlin.Float) : PropertyValue\n");
// Compared by identity, not content: a new Bytes value means the Host sent a new
// list, and copying a command list to compare it every recomposition is exactly the
// per-frame work the fixed layout exists to avoid.
output.push_str(" class Bytes(val value: ByteArray) : PropertyValue\n");
output.push_str("}\n\n");
write_draw_commands(&mut output);
write_text_spans(&mut output);
write_code_editor_records(&mut output);
write_font_refs(&mut output);
write_measure_records(&mut output);
output.push_str("sealed interface Modifier {\n");
for variant in MODIFIER_SCHEMA {
if variant.fields.is_empty() {
writeln!(output, " data object {} : Modifier", variant.name).unwrap();
} else {
write!(output, " data class {}(", variant.name).unwrap();
for (index, field) in variant.fields.iter().enumerate() {
if index != 0 {
output.push_str(", ");
}
write!(output, "val {}: {}", field.name, kotlin_type(field.ty)).unwrap();
}
output.push_str(") : Modifier\n");
}
}
output.push_str("}\n\n");
output.push_str(
r#"/** How the segment from one keyframe to the next is timed. */
sealed interface Timing {
data object Linear : Timing
/** CSS `cubic-bezier(x1, y1, x2, y2)`, with both `x` between 0 and 1. */
data class CubicBezier(val x1: kotlin.Float, val y1: kotlin.Float, val x2: kotlin.Float, val y2: kotlin.Float) : Timing
/** CSS `steps(count, position)`. */
data class Steps(val count: Int, val position: StepPosition) : Timing
}
/**
* One CSS transform function and its values, the unused ones zero: a translation in dp, a
* rotation in degrees (not folded into one turn), a scale, a skew in degrees, or the six
* values of `matrix()`.
*/
data class TransformFunction(
val kind: TransformFunctionKind,
val v0: kotlin.Float,
val v1: kotlin.Float,
val v2: kotlin.Float,
val v3: kotlin.Float,
val v4: kotlin.Float,
val v5: kotlin.Float,
)
/** What one keyframe holds, which is what its animation's property takes. */
sealed interface KeyframeValue {
data class Alpha(val value: kotlin.Float) : KeyframeValue
/** For `Color`, `Background` and `BorderColor`. A role is resolved against the theme every frame. */
data class PaintValue(val paint: Paint) : KeyframeValue
/** The same kinds in the same order in every keyframe of one animation. */
data class Transform(val functions: List<TransformFunction>) : KeyframeValue
}
data class Keyframe(
val offset: kotlin.Float,
val timing: Timing,
/** Start from what the node shows the frame the animation begins. First keyframe only. */
val fromPresented: Boolean,
val value: KeyframeValue,
)
/**
* One animation for the Renderer to play on its own frame clock until it ends.
*
* Keyed by `(nodeId, property, slot)`: a second one under the same key replaces the first,
* and of the ones in effect on one property the highest slot shows. Timing follows Web
* Animations Level 1. `events` is a set of bits: 1 ready, 2 active, 4 iteration, 8 end.
*/
data class Animation(
val nodeId: Int,
val animationId: Int,
val property: AnimatedProperty,
val slot: Int,
val direction: PlaybackDirection,
val fill: FillMode,
val playState: PlayState,
val interpolation: ColorInterpolation?,
val startTimeNanos: Long,
val delayMs: kotlin.Float,
val durationMs: kotlin.Float,
val iterations: kotlin.Float,
val originX: kotlin.Float,
val originY: kotlin.Float,
val events: Int,
val keyframes: List<Keyframe>,
)
/**
* Bytes that stay where the Host wrote them, inside the batch being applied. They are valid
* only while the record that carries them is applied: the arena is the Host's, and its next
* call writes over it. [copy] takes them out when they have to outlive that.
*/
class BatchBytes(val buffer: ByteBuffer, val index: Int, val size: Int) {
/** The bytes, copied into an array of their own. */
fun copy(): ByteArray {
val copy = ByteArray(size)
val mark = buffer.position()
buffer.position(index)
buffer.get(copy, 0, size)
buffer.position(mark)
return copy
}
override fun equals(other: Any?): Boolean =
this === other || (other is BatchBytes && copy().contentEquals(other.copy()))
override fun hashCode(): Int = copy().contentHashCode()
override fun toString(): String = "BatchBytes(size=$size)"
companion object {
/** Bytes of this side's own, for a test or a preview with no batch behind it. */
fun of(bytes: ByteArray): BatchBytes = BatchBytes(ByteBuffer.wrap(bytes), 0, bytes.size)
}
}
sealed interface Mutation {
data class Create(val nodeId: Int, val widget: WidgetKind) : Mutation
data class SetProp(val nodeId: Int, val property: PropertyKind, val value: PropertyValue) : Mutation
data class SetModifier(val nodeId: Int, val index: Int, val modifier: Modifier) : Mutation
data class Insert(val parentId: Int, val nodeId: Int, val index: Int) : Mutation
data class Move(val parentId: Int, val nodeId: Int, val index: Int) : Mutation
data class Remove(val nodeId: Int) : Mutation
data class SetText(val nodeId: Int, val text: String, val selectionStart: Int, val selectionEnd: Int) : Mutation
data class AppendText(val nodeId: Int, val text: String) : Mutation
data class SetTheme(val theme: Theme) : Mutation
data class SetWindow(val window: Window) : Mutation
/**
* The bytes of one asset. `kind` is the raw wire tag rather than an [AssetKind],
* because a kind this Renderer cannot read has to be reported as a protocol error by
* the asset cache instead of stopping the rest of the batch from being applied.
*
* `bytes` is already a copy: the batch buffer is only valid for the call that carried
* it, and an asset has to outlive the frame that draws it.
*/
data class RegisterAsset(val assetId: Int, val kind: Int, val bytes: ByteArray) : Mutation {
override fun equals(other: Any?): Boolean =
this === other ||
(other is RegisterAsset && assetId == other.assetId && kind == other.kind &&
bytes.contentEquals(other.bytes))
override fun hashCode(): Int =
(assetId * 31 + kind) * 31 + bytes.contentHashCode()
}
data class ReleaseAsset(val assetId: Int) : Mutation
/**
* One sentence to say to the user, with an optional thing to do about it.
*
* It names no node because it is not in the tree. The Host says it once; how long it
* stays, where it sits and what happens when a second one arrives while the first is
* still up are the Renderer's to decide.
*
* `handlerId` is 0 when the message has no action, and `action` is then empty.
*
* `vertical` and `horizontal` are where the application asked for it to be drawn and
* `offsetDp` how far from that edge; null leaves each to the design system.
*/
data class ShowMessage(
val handlerId: Long,
val text: String,
val action: String,
val duration: MessageDuration,
val vertical: MessageVertical? = null,
val horizontal: MessageHorizontal? = null,
val offsetDp: Float? = null,
) : Mutation
/**
* One notification to show outside the window.
*
* Not a node: it outlives the component that posted it, and when it goes away is up to
* the user in the notification centre. Posting again under the same `key` replaces it;
* an empty `key` is named by the Renderer and can be neither replaced nor withdrawn. An
* empty action label is no button.
*/
data class PostNotification(
val key: String,
val title: String,
val body: String,
val channel: String,
val action1: String,
val action2: String,
val importance: NotificationImportance,
val presentation: NotificationPresentation,
) : Mutation
/** Takes back the notification posted under `key`, if it is still showing. */
data class WithdrawNotification(val key: String) : Mutation
/** Asks the platform for permission. The answer comes back as an event. */
data object RequestNotificationPermission : Mutation
/**
* An edit the application asks of a code editor: replace a range of the document as it
* stood at `baseVersion` with `text`.
*
* The document is this side's, so this is a request. Where the reader has typed since
* `baseVersion` the range is moved along with what they typed; where they typed in the
* same place the edit is refused and `CodeEditRejected` returns `requestId`. Lines and
* columns count from zero and columns are UTF-16 units.
*/
data class EditCode(
val nodeId: Int,
val requestId: Int,
val baseVersion: Int,
val startLine: Int,
val startColumn: Int,
val endLine: Int,
val endColumn: Int,
val text: String,
) : Mutation
/** One animation to play on the Renderer's own frame clock until it ends. */
data class StartAnimation(val animation: Animation) : Mutation
/**
* Pauses, resumes or cancels the animation under a key, if it is still the one with
* this id. Anything else is left alone: an animation that already ended is not an
* error to stop.
*/
data class ControlAnimation(
val nodeId: Int,
val animationId: Int,
val property: AnimatedProperty,
val slot: Int,
val op: AnimationControl,
val atTimeNanos: Long,
) : Mutation
/**
* Puts a code editor's selection between two places in the document as it stood at
* `baseVersion`. Both ends are moved along with whatever was typed since. An end outside
* the document, or between the two halves of a pair, drops the command and is reported.
*/
data class SetSelection(
val nodeId: Int,
val baseVersion: Int,
val anchorLine: Int,
val anchorColumn: Int,
val activeLine: Int,
val activeColumn: Int,
) : Mutation
/**
* Scrolls a code editor until a range of the document, as it stood at `baseVersion`, is
* on screen. A range inside a folded stretch unfolds it first.
*/
data class RevealRange(
val nodeId: Int,
val baseVersion: Int,
val startLine: Int,
val startColumn: Int,
val endLine: Int,
val endColumn: Int,
val align: RevealAlign,
) : Mutation
/** Folds or unfolds the stretch of a code editor that starts on `startLine`. */
data class SetFolded(val nodeId: Int, val startLine: Int, val collapsed: Boolean) : Mutation
/**
* A theme for one `Window` node, over the application's. A window without
* one follows the application's theme.
*/
data class SetWindowTheme(val nodeId: Int, val theme: Theme) : Mutation
/** Brings a window forward and makes it the key window. Happens once. */
data class FocusWindow(val nodeId: Int) : Mutation
/** Moves input focus to [nodeId], or clears focus when [nodeId] is 0. */
data class RequestFocus(val nodeId: Int) : Mutation
/**
* Asks the platform for a file dialog on the window [window] (0 is the implicit root
* window). Answered exactly once, later, by a `FileDialogResult` event carrying
* [request]. [filters] is one string: a label and its comma-joined extensions as a pair,
* pairs joined by NUL.
*/
data class ShowFileDialog(
val request: Int,
val window: Int,
val kind: FileDialogKind,
val defaultFilter: Int,
val title: String,
val directory: String,
val name: String,
val filters: String,
) : Mutation
/** Sets application-level overlay theme tokens for Dialog, Menu, Dropdown and Sheet. */
data class SetOverlayTokens(val overlay: OverlayTokens) : Mutation
/**
* Puts [text] on the platform clipboard as plain text. Not answered: a Renderer with no
* clipboard drops it. [text] can be anything the application copies, so it is never
* written to a log.
*/
data class SetClipboardText(val text: String) : Mutation {
override fun toString(): String = "SetClipboardText(length=${text.length})"
}
/**
* Asks for the plain text on the platform clipboard. Answered exactly once, later, by a
* `ClipboardText` event carrying [request].
*/
data class ReadClipboard(val request: Int) : Mutation
/**
* Scrolls a code editor so that [offsetPx] physical pixels of its document are above
* the top of its view. The same unit the `CodeScrolled` event reports.
*/
data class SetScrollOffset(val nodeId: Int, val offsetPx: Double) : Mutation
/**
* Asks something of the file the Renderer holds [handle] for: read it, write [data] to
* it, list a folder, or find the child called [name] (making a file of that name when
* [create]). Answered exactly once, later: by an `IoAnswer` carrying [request], or for a
* listing or a child that was found by a `FileHandles`. [data] is the user's file, so it
* is never written to a log.
*/
data class FileCall(
val request: Int,
val op: FileOp,
val create: Boolean,
val handle: Int,
val name: String,
val data: ByteArray,
) : Mutation {
override fun equals(other: Any?): Boolean =
this === other ||
(other is FileCall && request == other.request && op == other.op &&
create == other.create && handle == other.handle && name == other.name &&
data.contentEquals(other.data))
override fun hashCode(): Int =
((request * 31 + op.hashCode()) * 31 + handle) * 31 + data.contentHashCode()
override fun toString(): String =
"FileCall(request=$request, op=$op, create=$create, handle=$handle, length=${data.size})"
}
/** The Host names [handle] nowhere any more; the file behind it may be let go of. */
data class ReleaseFileHandle(val handle: Int) : Mutation
/**
* Asks for one operation on the application's storage, which the Renderer carries out
* where it is the side that can reach it (a browser's IndexedDB). Answered exactly once,
* later, by an `IoAnswer` event carrying [request]. [store] is the application
* identifier, [key] the value's name (empty for `Keys`), and [data] the value to write,
* read in place and valid only while this record is applied (empty for every other
* operation).
*/
data class StorageCall(
val request: Int,
val op: StorageOp,
val store: String,
val key: String,
val data: BatchBytes,
) : Mutation
/**
* Asks the scroll container [nodeId] to go to an offset in physical pixels. [flags] is
* the wire word ([ScrollWire.TO_ANIMATE], [ScrollWire.TO_X], [ScrollWire.TO_Y]): an
* axis whose bit is off is not touched. [item] is the lazy list item the offset is
* measured from and 0 elsewhere. The fields are as sent; the node table checks them.
*/
data class ScrollTo(
val nodeId: Int,
val item: Int,
val flags: Int,
val xPx: Double,
val yPx: Double,
) : Mutation
/**
* Asks the scroll container [nodeId] to bring a rectangle into view. [targetKind] is one
* of the `ScrollWire.TARGET_*` values and says what the rectangle is measured from;
* [alignX] and [alignY] are `ScrollWire.ALIGN_*` values. The fields are as sent; the
* node table checks them.
*/
data class ScrollIntoView(
val nodeId: Int,
val target: Int,
val targetKind: Int,
val alignX: Int,
val alignY: Int,
val flags: Int,
val rectXPx: Double,
val rectYPx: Double,
val rectWidthPx: Double,
val rectHeightPx: Double,
) : Mutation
/**
* Sets every selection of the code editor [nodeId] at once, the first the primary one,
* each read against the document as it stood at [baseVersion]. [selections] is 16-byte
* records: anchor line, anchor column, active line, active column.
*/
data class SetSelections(
val nodeId: Int,
val baseVersion: Int,
val selections: ByteArray,
) : Mutation {
override fun equals(other: Any?): Boolean =
this === other ||
(other is SetSelections && nodeId == other.nodeId && baseVersion == other.baseVersion &&
selections.contentEquals(other.selections))
override fun hashCode(): Int = (nodeId * 31 + baseVersion) * 31 + selections.contentHashCode()
}
/**
* Replaces a range of the code editor [nodeId]'s document, as it stood at
* [baseVersion], with [snippet], and opens its tab stops: `$1`, `${1:placeholder}`,
* `${1|one,two|}`, `$0`, and `\$` for a dollar sign. What it leaves is reported as
* ordinary changes. Lines and columns count from zero and columns are UTF-16 units.
*/
data class InsertSnippet(
val nodeId: Int,
val baseVersion: Int,
val startLine: Int,
val startColumn: Int,
val endLine: Int,
val endColumn: Int,
val snippet: String,
) : Mutation
/**
* Asks the code editor [nodeId] where a caret at [line] and [column] would be drawn.
* Answered once by a `PositionRect` event carrying [request].
*/
data class QueryPositionRect(
val nodeId: Int,
val request: Int,
val line: Int,
val column: Int,
) : Mutation
/**
* Several edits the application asks of a code editor as one: replace every range in
* [edits] with its text, all of them or none, and answer with one
* `CodeEditGroupResult` carrying [requestId].
*
* [edits] is the blob as it came, read by `CodeEditorRecords.decodeEditGroup`. Every
* range in it is in the document as it stood at [baseVersion]. [malformed] is set, and
* [edits] empty, where the record itself could not be read but its head could: the
* decoder reports the protocol error, and the editor still owes the group its answer.
*/
data class EditCodeGroup(
val nodeId: Int,
val requestId: Int,
val baseVersion: Int,
val edits: ByteArray,
val malformed: String? = null,
) : Mutation {
override fun equals(other: Any?): Boolean =
this === other ||
(other is EditCodeGroup && nodeId == other.nodeId && requestId == other.requestId &&
baseVersion == other.baseVersion && edits.contentEquals(other.edits) &&
malformed == other.malformed)
override fun hashCode(): Int =
((nodeId * 31 + requestId) * 31 + baseVersion) * 31 + edits.contentHashCode()
}
}
/** The words of the scroll records: flag bits, target kinds and alignments. */
object ScrollWire {
const val TO_ANIMATE = 1
const val TO_X = 2
const val TO_Y = 4
const val TO_KNOWN = TO_ANIMATE or TO_X or TO_Y
const val TARGET_CONTENT = 0
const val TARGET_NODE = 1
const val TARGET_ITEM = 2
const val ALIGN_KEEP = 0
const val ALIGN_START = 1
const val ALIGN_CENTER = 2
const val ALIGN_END = 3
const val ALIGN_NEAREST = 4
const val INTO_VIEW_ANIMATE = 1
const val CHANGED_SETTLED = 1
const val CHANGED_CAN_SCROLL_BACKWARD = 2
const val CHANGED_CAN_SCROLL_FORWARD = 4
}
"#,
);
output.push_str("sealed interface HostEvent {\n");
output.push_str(" val nodeId: Int\n");
output.push_str(" val handlerId: Long\n\n");
for event in EVENT_SCHEMA {
write!(
output,
" data class {}(override val nodeId: Int, override val handlerId: Long",
event.name
)
.unwrap();
match event.payload {
EventPayloadType::None => {}
EventPayloadType::Text => output.push_str(", val text: String"),
EventPayloadType::ProtocolError => {
output.push_str(", val code: Int, val message: String");
}
EventPayloadType::KeyDown => {
output.push_str(", val key: Key, val shiftKey: Boolean, val ctrlKey: Boolean, val altKey: Boolean, val metaKey: Boolean, val repeat: Boolean, val code: Int, val text: String");
}
EventPayloadType::Range => output.push_str(", val start: Int, val count: Int"),
EventPayloadType::Double => output.push_str(", val value: Double"),
EventPayloadType::WindowSize => {
output.push_str(
", val widthDp: kotlin.Float, val heightDp: kotlin.Float, val sizeClass: WindowSizeClass, val heightClass: WindowHeightClass, val safeAreaTop: kotlin.Float, val safeAreaLeading: kotlin.Float, val safeAreaTrailing: kotlin.Float",
);
}
EventPayloadType::DesignSystem => output.push_str(", val system: DesignSystem"),
EventPayloadType::NotificationActivation => {
output.push_str(", val action: Int, val key: String");
}
EventPayloadType::NotificationPermission => {
output.push_str(", val state: NotificationPermission");
}
EventPayloadType::CodeChange => output.push_str(
", val version: Int, val startLine: Int, val startColumn: Int, val endLine: Int, val endColumn: Int, val text: String",
),
EventPayloadType::CodeEditRejected => output.push_str(
", val requestId: Int, val baseVersion: Int, val currentVersion: Int, val startLine: Int, val startColumn: Int, val endLine: Int, val endColumn: Int",
),
EventPayloadType::CodeHover => output.push_str(
", val decoration: Long, val line: Int, val column: Int, val phase: HoverPhase",
),
EventPayloadType::CodeSave => output.push_str(", val version: Int"),
EventPayloadType::Decoration => output.push_str(", val decoration: Long"),
EventPayloadType::Animation => output.push_str(
", val animationId: Int, val kind: AnimationEventKind, val property: AnimatedProperty, val slot: Int, val iteration: Int, val elapsedMs: kotlin.Float, val timeNanos: Long",
),
EventPayloadType::ReducedMotion => output.push_str(", val state: ReducedMotion"),
EventPayloadType::ColorScheme => output.push_str(", val scheme: SystemColorScheme"),
EventPayloadType::Pointer => output.push_str(
", val kind: PointerKind, val pointerId: Int, val pointerType: PointerType, val x: kotlin.Float, val y: kotlin.Float, val buttons: Int, val button: Int, val modifiers: Int, val clickCount: Int, val deltaX: kotlin.Float, val deltaY: kotlin.Float, val deltaMode: WheelDeltaMode, val timestampNanos: Long",
),
EventPayloadType::Zoom => {
output.push_str(", val k: kotlin.Float, val os: kotlin.Float, val level: Int");
}
EventPayloadType::CodeSelection => output.push_str(
", val version: Int, val anchorLine: Int, val anchorColumn: Int, val activeLine: Int, val activeColumn: Int",
),
EventPayloadType::CodeVisibleRange => {
output.push_str(", val version: Int, val firstLine: Int, val lastLine: Int");
}
EventPayloadType::CodeFocus => output.push_str(", val focused: Boolean"),
EventPayloadType::CodeFold => {
output.push_str(", val startLine: Int, val collapsed: Boolean");
}
EventPayloadType::CodeComposition => output.push_str(", val composing: Boolean"),
EventPayloadType::WindowFocus => output.push_str(", val focused: Boolean"),
EventPayloadType::WindowMove => output.push_str(
", val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float",
),
EventPayloadType::WindowDrag => output.push_str(
", val phase: Int, val screenX: kotlin.Float, val screenY: kotlin.Float, val overWindow: Int",
),
EventPayloadType::WindowDragOver => output.push_str(
", val kind: Int, val window: Int, val x: kotlin.Float, val y: kotlin.Float",
),
EventPayloadType::WindowRequest => output.push_str(", val request: Int, val key: String"),
// The filter is the position of the filter in use, or -1 (the wire's 0xFFFFFFFF)
// when there is none.
EventPayloadType::FileDialogResult => output.push_str(
", val request: Int, val status: FileDialogStatus, val filter: Int, val paths: String",
),
// The status is a word: 0 no text, 1 text, 2 text too long to carry. The length is
// the text's size in UTF-8 bytes. The text itself is never in `toString`.
EventPayloadType::ClipboardText => output.push_str(
", val request: Int, val status: Int, val length: Int, val text: String",
),
// What an input or output request handed back: a value or a file read, keys joined
// by NUL, or nothing. Never in `toString`, because it is the application's data.
EventPayloadType::IoAnswer => {
output.push_str(", val request: Int, val status: IoStatus, val data: ByteArray")
}
// The names are NUL separated; the kinds are one letter per name, `f` or `d`.
EventPayloadType::FileHandles => output.push_str(
", val request: Int, val status: FileDialogStatus, val filter: Int, val delivery: FileDelivery, val firstHandle: Int, val names: String, val kinds: String",
),
// Every length is in physical pixels. The flags are the `ScrollWire.CHANGED_*` bits.
EventPayloadType::ScrollChanged => output.push_str(
", val item: Int, val flags: Int, val xPx: Double, val yPx: Double, val maxXPx: Double, val maxYPx: Double, val viewportWidthPx: Double, val viewportHeightPx: Double",
),
// The size a node's size motion settled at, in dp.
EventPayloadType::MotionFinished => {
output.push_str(", val widthDp: kotlin.Float, val heightDp: kotlin.Float")
}
// In the window's dp, the scroll and the zoom already in them.
EventPayloadType::CodeCaretRect => output.push_str(
", val line: Int, val column: Int, val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float",
),
// `found` is false where the position is not on screen, and the rectangle is then
// all zero.
EventPayloadType::CodePositionRect => output.push_str(
", val request: Int, val found: Boolean, val x: kotlin.Float, val y: kotlin.Float, val width: kotlin.Float, val height: kotlin.Float",
),
// The pointer's fields, then the character under it: -1 and -1 where it is over
// none.
// `currentVersion` is after the group's last change where it went in, and the
// document's version where it did not.
EventPayloadType::CodeEditGroupResult => output.push_str(
", val requestId: Int, val status: EditGroupStatus, val baseVersion: Int, val currentVersion: Int, val index: Int",
),
// Four numbers per selection: anchor line, anchor column, active line, active
// column, the primary selection first.
EventPayloadType::CodeSelections => {
output.push_str(", val version: Int, val selections: IntArray")
}
EventPayloadType::CodePointer => output.push_str(
", val kind: PointerKind, val pointerId: Int, val pointerType: PointerType, val x: kotlin.Float, val y: kotlin.Float, val buttons: Int, val button: Int, val modifiers: Int, val clickCount: Int, val deltaX: kotlin.Float, val deltaY: kotlin.Float, val deltaMode: WheelDeltaMode, val timestampNanos: Long, val line: Int, val column: Int",
),
}
if event.payload == EventPayloadType::CodeSelections {
writeln!(
output,
") : HostEvent {{\n override fun equals(other: Any?): Boolean =\n this === other ||\n (other is {name} && nodeId == other.nodeId && handlerId == other.handlerId &&\n version == other.version && selections.contentEquals(other.selections))\n\n override fun hashCode(): Int = (nodeId * 31 + version) * 31 + selections.contentHashCode()\n\n override fun toString(): String =\n \"{name}(nodeId=$nodeId, handlerId=$handlerId, version=$version, selections=${{selections.toList()}})\"\n }}",
name = event.name
)
.unwrap();
} else if event.payload == EventPayloadType::IoAnswer {
writeln!(
output,
") : HostEvent {{\n override fun equals(other: Any?): Boolean =\n this === other ||\n (other is {name} && nodeId == other.nodeId && handlerId == other.handlerId &&\n request == other.request && status == other.status && data.contentEquals(other.data))\n\n override fun hashCode(): Int = (request * 31 + status.hashCode()) * 31 + data.contentHashCode()\n\n override fun toString(): String =\n \"{name}(request=$request, status=$status, length=${{data.size}})\"\n }}",
name = event.name
)
.unwrap();
} else if event.payload == EventPayloadType::ClipboardText {
// What the clipboard held can be anything the user copied, so no log line that
// prints the event prints the text.
output.push_str(
") : HostEvent {\n override fun toString(): String =\n \"ClipboardText(request=$request, status=$status, length=$length)\"\n }\n",
);
} else {
output.push_str(") : HostEvent\n");
}
}
output.push_str("}\n\n");
output.push_str(
r#"class ProtocolException(message: String, val offset: Int) :
IllegalArgumentException("$message at byte offset $offset")
object Protocol {
"#,
);
writeln!(
output,
" const val SCHEMA_HASH: Long = {}L",
SCHEMA_HASH as i64
)
.unwrap();
writeln!(
output,
" const val PROTOCOL_VERSION: Int = {PROTOCOL_VERSION}"
)
.unwrap();
output.push_str(
r#"
private const val TAG_ENVELOPE = 0
private const val TAG_CREATE = 1
private const val TAG_SET_PROP = 2
private const val TAG_SET_MODIFIER = 3
private const val TAG_INSERT = 4
private const val TAG_MOVE = 5
private const val TAG_REMOVE = 6
private const val TAG_SET_TEXT = 7
private const val TAG_APPEND_TEXT = 8
private const val TAG_SET_THEME = 9
private const val TAG_REGISTER_ASSET = 10
private const val TAG_RELEASE_ASSET = 11
private const val TAG_SHOW_MESSAGE = 12
private const val TAG_SET_WINDOW = 13
private const val TAG_POST_NOTIFICATION = 14
private const val TAG_WITHDRAW_NOTIFICATION = 15
private const val TAG_REQUEST_NOTIFICATION_PERMISSION = 16
private const val TAG_EDIT_CODE = 17
private const val TAG_START_ANIMATION = 18
private const val TAG_CONTROL_ANIMATION = 19
private const val TAG_SET_SELECTION = 20
private const val TAG_REVEAL_RANGE = 21
private const val TAG_SET_FOLDED = 22
private const val TAG_SET_WINDOW_THEME = 23
private const val TAG_FOCUS_WINDOW = 24
private const val TAG_REQUEST_FOCUS = 25
private const val TAG_SHOW_FILE_DIALOG = 26
private const val TAG_SET_OVERLAY_TOKENS = 27
private const val TAG_EDIT_CODE_GROUP = 28
private const val TAG_SET_CLIPBOARD_TEXT = 29
private const val TAG_READ_CLIPBOARD = 31
private const val TAG_SET_SCROLL_OFFSET = 30
private const val TAG_STORAGE_CALL = 32
private const val TAG_FILE_CALL = 33
private const val TAG_RELEASE_FILE_HANDLE = 34
private const val TAG_SCROLL_TO = 35
private const val TAG_SCROLL_INTO_VIEW = 36
private const val TAG_QUERY_POSITION_RECT = 39
private const val TAG_INSERT_SNIPPET = 40
private const val TAG_SET_SELECTIONS = 41
private const val ENVELOPE_LENGTH = 12
private const val ANIMATION_HEADER_LENGTH = 52
private const val KEYFRAME_HEAD_LENGTH = 24
private const val TRANSFORM_FUNCTION_LENGTH = 28
/** Four role tags, one font asset id per type role, then the palette's reference. */
private val THEME_RECORD_LENGTH = 20 + 4 * TypeRole.entries.size
/** Bytes of one palette entry: a role tag, a scheme tag and a colour. */
const val PALETTE_ENTRY_LENGTH = 8
/**
* The high bit of each of eight bytes, which is where UTF-8 stops being ASCII. Written
* as a negative literal because 0x8080808080808080 does not fit a signed `Long`; the
* bits are what matter and they are the same either way.
*/
private const val ASCII_HIGH_BITS = -0x7f7f7f7f7f7f7f80L
private const val VALUE_NONE = 0
private const val VALUE_TEXT = 1
private const val VALUE_BOOL = 2
private const val VALUE_INTEGER = 3
private const val VALUE_FLOAT = 4
private const val VALUE_BYTES = 5
/** Decodes a batch in place. Must not copy the buffer; only strings become Kotlin Strings. */
fun decode(batch: ByteBuffer, onMutation: (Mutation) -> Unit) {
val base = batch.position()
val available = batch.remaining()
val previousOrder = batch.order()
batch.order(ByteOrder.LITTLE_ENDIAN)
try {
requireRange(available, 0, ENVELOPE_LENGTH, 0)
if (readU16(batch, base, available, 0) != TAG_ENVELOPE ||
readU16(batch, base, available, 2) != ENVELOPE_LENGTH
) {
throw ProtocolException("invalid batch envelope", 0)
}
val recordsLengthLong = readU32(batch, base, available, 4)
val countLong = readU32(batch, base, available, 8)
if (recordsLengthLong < ENVELOPE_LENGTH ||
recordsLengthLong > available.toLong() ||
recordsLengthLong % 4L != 0L
) {
throw ProtocolException("invalid records length", 4)
}
if (countLong > Int.MAX_VALUE.toLong()) {
throw ProtocolException("record count is too large", 8)
}
val recordsLength = recordsLengthLong.toInt()
val count = countLong.toInt()
var offset = ENVELOPE_LENGTH
var decoded = 0
while (offset < recordsLength) {
requireRange(recordsLength, offset, 4, offset)
val tag = readU16(batch, base, available, offset)
val length = readU16(batch, base, available, offset + 2)
if (length < 4 || length % 4 != 0 || offset.toLong() + length > recordsLength) {
throw ProtocolException("invalid record length", offset + 2)
}
val mutation = when (tag) {
TAG_CREATE -> {
requireRecordLength(length, 12, offset)
Mutation.Create(
readU32(batch, base, available, offset + 4).toInt(),
widgetKind(readU16(batch, base, available, offset + 8), offset + 8),
)
}
TAG_SET_PROP -> {
requireRecordLength(length, 24, offset)
val value = when (val valueKind = readU16(batch, base, available, offset + 10)) {
VALUE_NONE -> PropertyValue.None
VALUE_TEXT -> PropertyValue.Text(readString(batch, base, available, offset + 12))
VALUE_BOOL -> PropertyValue.Bool(readU64(batch, base, available, offset + 12) != 0L)
VALUE_INTEGER -> PropertyValue.Integer(readU64(batch, base, available, offset + 12))
VALUE_FLOAT -> PropertyValue.Float(
kotlin.Float.fromBits(readU64(batch, base, available, offset + 12).toInt()),
)
VALUE_BYTES -> PropertyValue.Bytes(readBytes(batch, base, available, offset + 12))
else -> throw ProtocolException("unknown property value tag $valueKind", offset + 10)
}
Mutation.SetProp(
readU32(batch, base, available, offset + 4).toInt(),
propertyKind(readU16(batch, base, available, offset + 8), offset + 8),
value,
)
}
TAG_SET_MODIFIER -> {
// The modifier's tag fixes the record's length: 28 bytes, and eight
// more for each word its value takes beyond the first two.
if (length < 28) requireRecordLength(length, 28, offset)
val modifierTag = readU16(batch, base, available, offset + 10)
requireRecordLength(length, 28 + 8 * modifierExtraWords(modifierTag, offset + 10), offset)
Mutation.SetModifier(
readU32(batch, base, available, offset + 4).toInt(),
readU16(batch, base, available, offset + 8),
modifier(modifierTag, batch, base, available, offset + 12, offset + 10),
)
}
TAG_INSERT -> {
requireRecordLength(length, 16, offset)
Mutation.Insert(
readU32(batch, base, available, offset + 4).toInt(),
readU32(batch, base, available, offset + 8).toInt(),
readU32(batch, base, available, offset + 12).toInt(),
)
}
TAG_MOVE -> {
requireRecordLength(length, 16, offset)
Mutation.Move(
readU32(batch, base, available, offset + 4).toInt(),
readU32(batch, base, available, offset + 8).toInt(),
readU32(batch, base, available, offset + 12).toInt(),
)
}
TAG_REMOVE -> {
requireRecordLength(length, 8, offset)
Mutation.Remove(readU32(batch, base, available, offset + 4).toInt())
}
TAG_SET_TEXT -> {
requireRecordLength(length, 24, offset)
Mutation.SetText(
readU32(batch, base, available, offset + 4).toInt(),
readString(batch, base, available, offset + 8),
readU32(batch, base, available, offset + 16).toInt(),
readU32(batch, base, available, offset + 20).toInt(),
)
}
TAG_APPEND_TEXT -> {
requireRecordLength(length, 16, offset)
Mutation.AppendText(
readU32(batch, base, available, offset + 4).toInt(),
readString(batch, base, available, offset + 8),
)
}
TAG_SET_THEME -> {
requireRecordLength(length, THEME_RECORD_LENGTH, offset)
Mutation.SetTheme(theme(batch, base, available, offset + 4))
}
TAG_SET_WINDOW_THEME -> {
requireRecordLength(length, THEME_RECORD_LENGTH + 4, offset)
Mutation.SetWindowTheme(
readU32(batch, base, available, offset + 4).toInt(),
theme(batch, base, available, offset + 8),
)
}
TAG_FOCUS_WINDOW -> {
requireRecordLength(length, 8, offset)
Mutation.FocusWindow(readU32(batch, base, available, offset + 4).toInt())
}
TAG_REQUEST_FOCUS -> {
requireRecordLength(length, 8, offset)
Mutation.RequestFocus(readU32(batch, base, available, offset + 4).toInt())
}
TAG_SHOW_FILE_DIALOG -> {
requireRecordLength(length, 48, offset)
Mutation.ShowFileDialog(
readU32(batch, base, available, offset + 4).toInt(),
readU32(batch, base, available, offset + 8).toInt(),
fileDialogKind(readU16(batch, base, available, offset + 12), offset + 12),
readU16(batch, base, available, offset + 14),
readString(batch, base, available, offset + 16),
readString(batch, base, available, offset + 24),
readString(batch, base, available, offset + 32),
readString(batch, base, available, offset + 40),
)
}
TAG_SET_OVERLAY_TOKENS -> {
requireRecordLength(length, 32, offset)
Mutation.SetOverlayTokens(
OverlayTokens(
sheetCornerRadius = readU16(batch, base, available, offset + 4),
dialogCornerRadius = readU16(batch, base, available, offset + 6),
popupCornerRadius = readU16(batch, base, available, offset + 8),
sheetElevation = readU16(batch, base, available, offset + 10),
popupElevation = readU16(batch, base, available, offset + 12),
dialogElevation = readU16(batch, base, available, offset + 14),
sheetPadding = readU16(batch, base, available, offset + 16),
dialogPadding = readU16(batch, base, available, offset + 18),
popupPadding = readU16(batch, base, available, offset + 20),
scrim = readU32(batch, base, available, offset + 24),
toastElevation = readU16(batch, base, available, offset + 28),
toastCornerRadius = readU16(batch, base, available, offset + 30),
),
)
}
TAG_SET_CLIPBOARD_TEXT -> {
requireRecordLength(length, 12, offset)
Mutation.SetClipboardText(readString(batch, base, available, offset + 4))
}
TAG_READ_CLIPBOARD -> {
requireRecordLength(length, 8, offset)
Mutation.ReadClipboard(readU32(batch, base, available, offset + 4).toInt())
}
TAG_STORAGE_CALL -> {
requireRecordLength(length, 36, offset)
Mutation.StorageCall(
readU32(batch, base, available, offset + 4).toInt(),
storageOp(readU16(batch, base, available, offset + 8), offset + 8),
readString(batch, base, available, offset + 12),
readString(batch, base, available, offset + 20),
readByteView(batch, base, available, offset + 28),
)
}
TAG_FILE_CALL -> {
requireRecordLength(length, 32, offset)
val create = readU16(batch, base, available, offset + 10)
if (create > 1) {
throw ProtocolException("invalid create flag $create", offset + 10)
}
Mutation.FileCall(
readU32(batch, base, available, offset + 4).toInt(),
fileOp(readU16(batch, base, available, offset + 8), offset + 8),
create == 1,
readU32(batch, base, available, offset + 12).toInt(),
readString(batch, base, available, offset + 16),
readBytes(batch, base, available, offset + 24),
)
}
TAG_RELEASE_FILE_HANDLE -> {
requireRecordLength(length, 8, offset)
Mutation.ReleaseFileHandle(readU32(batch, base, available, offset + 4).toInt())
}
TAG_SCROLL_TO -> {
requireRecordLength(length, 32, offset)
Mutation.ScrollTo(
nodeId = readU32(batch, base, available, offset + 4).toInt(),
item = readU32(batch, base, available, offset + 8).toInt(),
flags = readU32(batch, base, available, offset + 12).toInt(),
xPx = Double.fromBits(readU64(batch, base, available, offset + 16)),
yPx = Double.fromBits(readU64(batch, base, available, offset + 24)),
)
}
TAG_SCROLL_INTO_VIEW -> {
requireRecordLength(length, 52, offset)
Mutation.ScrollIntoView(
nodeId = readU32(batch, base, available, offset + 4).toInt(),
target = readU32(batch, base, available, offset + 8).toInt(),
targetKind = readU16(batch, base, available, offset + 12),
alignX = readU16(batch, base, available, offset + 14),
alignY = readU16(batch, base, available, offset + 16),
flags = readU16(batch, base, available, offset + 18),
rectXPx = Double.fromBits(readU64(batch, base, available, offset + 20)),
rectYPx = Double.fromBits(readU64(batch, base, available, offset + 28)),
rectWidthPx = Double.fromBits(readU64(batch, base, available, offset + 36)),
rectHeightPx = Double.fromBits(readU64(batch, base, available, offset + 44)),
)
}
TAG_EDIT_CODE_GROUP -> {
// A group that cannot be read is still answered. Where its head
// can be, the node, the request and as much of the rest as is
// there go to the editor first, so the result it owes follows the
// protocol error this record raises.
if (length != 24) {
if (length >= 12) {
onMutation(
Mutation.EditCodeGroup(
readU32(batch, base, available, offset + 4).toInt(),
readU32(batch, base, available, offset + 8).toInt(),
if (length >= 16) readU32(batch, base, available, offset + 12).toInt() else 0,
ByteArray(0),
malformed = "an EditCodeGroup record is $length bytes, not 24",
),
)
}
requireRecordLength(length, 24, offset)
}
val nodeId = readU32(batch, base, available, offset + 4).toInt()
val requestId = readU32(batch, base, available, offset + 8).toInt()
val baseVersion = readU32(batch, base, available, offset + 12).toInt()
val edits = try {
readBytes(batch, base, available, offset + 16)
} catch (error: ProtocolException) {
onMutation(
Mutation.EditCodeGroup(
nodeId,
requestId,
baseVersion,
ByteArray(0),
malformed = "an EditCodeGroup record names edits outside the batch",
),
)
throw error
}
Mutation.EditCodeGroup(nodeId, requestId, baseVersion, edits)
}
TAG_SET_SELECTIONS -> {
requireRecordLength(length, 20, offset)
Mutation.SetSelections(
nodeId = readU32(batch, base, available, offset + 4).toInt(),
baseVersion = readU32(batch, base, available, offset + 8).toInt(),
selections = readBytes(batch, base, available, offset + 12),
)
}
TAG_INSERT_SNIPPET -> {
requireRecordLength(length, 36, offset)
Mutation.InsertSnippet(
nodeId = readU32(batch, base, available, offset + 4).toInt(),
baseVersion = readU32(batch, base, available, offset + 8).toInt(),
startLine = readU32(batch, base, available, offset + 12).toInt(),
startColumn = readU32(batch, base, available, offset + 16).toInt(),
endLine = readU32(batch, base, available, offset + 20).toInt(),
endColumn = readU32(batch, base, available, offset + 24).toInt(),
snippet = readString(batch, base, available, offset + 28),
)
}
TAG_QUERY_POSITION_RECT -> {
requireRecordLength(length, 20, offset)
Mutation.QueryPositionRect(
nodeId = readU32(batch, base, available, offset + 4).toInt(),
request = readU32(batch, base, available, offset + 8).toInt(),
line = readU32(batch, base, available, offset + 12).toInt(),
column = readU32(batch, base, available, offset + 16).toInt(),
)
}
TAG_SET_WINDOW -> {
requireRecordLength(length, 32, offset)
// Bit 0 is `resizable`, bit 1 asks for every whole-dp size change; the
// mode and the last window policy are the nibbles above the second
// byte. Anything else standing is a record the sides disagree on.
val flags = readU16(batch, base, available, offset + 16)
if ((flags and 0x00FC) != 0) {
throw ProtocolException("invalid window flags $flags", offset + 16)
}
val resizable = flags and 1
val reportSize = (flags and 0x0002) != 0
// A byte saying whether there is a zoom level, then the level as a
// signed byte.
val zoom = readU16(batch, base, available, offset + 18)
val zoomLevel = when (zoom and 0xFF) {
0 -> null
1 -> (zoom shr 8).toByte().toInt().also { level ->
if (level < -8 || level > 8) {
throw ProtocolException("invalid zoom level $level", offset + 19)
}
}
else -> throw ProtocolException("invalid zoom flag $zoom", offset + 18)
}
Mutation.SetWindow(
Window(
chrome(readU16(batch, base, available, offset + 4), offset + 4),
titleBar(readU16(batch, base, available, offset + 6), offset + 6),
readString(batch, base, available, offset + 20),
readU32(batch, base, available, offset + 28).toInt(),
readU16(batch, base, available, offset + 8),
readU16(batch, base, available, offset + 10),
readU16(batch, base, available, offset + 12),
readU16(batch, base, available, offset + 14),
resizable == 1,
zoomLevel,
windowMode((flags shr 8) and 0xF, offset + 16),
lastWindowClosed(flags shr 12, offset + 16),
reportSize,
),
)
}
TAG_REGISTER_ASSET -> {
requireRecordLength(length, 20, offset)
Mutation.RegisterAsset(
readU32(batch, base, available, offset + 4).toInt(),
readU16(batch, base, available, offset + 8),
readBytes(batch, base, available, offset + 12),
)
}
TAG_RELEASE_ASSET -> {
requireRecordLength(length, 8, offset)
Mutation.ReleaseAsset(readU32(batch, base, available, offset + 4).toInt())
}
TAG_SHOW_MESSAGE -> {
requireRecordLength(length, 40, offset)
// Tag 0 in either placement word is "the design system's place",
// and a placement is both halves or neither.
val rawVertical = readU16(batch, base, available, offset + 30)
val rawHorizontal = readU16(batch, base, available, offset + 32)
if ((rawVertical == 0) != (rawHorizontal == 0)) {
throw ProtocolException("a message placement needs both an edge and an end", offset + 30)
}
val rawOffset = Float.fromBits(readU32(batch, base, available, offset + 36).toInt())
Mutation.ShowMessage(
readU64(batch, base, available, offset + 4),
readString(batch, base, available, offset + 12),
readString(batch, base, available, offset + 20),
messageDuration(readU16(batch, base, available, offset + 28), offset + 28),
if (rawVertical == 0) null else messageVertical(rawVertical, offset + 30),
if (rawHorizontal == 0) null else messageHorizontal(rawHorizontal, offset + 32),
if (rawOffset.isNaN()) null else rawOffset,
)
}
TAG_POST_NOTIFICATION -> {
requireRecordLength(length, 56, offset)
Mutation.PostNotification(
readString(batch, base, available, offset + 4),
readString(batch, base, available, offset + 12),
readString(batch, base, available, offset + 20),
readString(batch, base, available, offset + 28),
readString(batch, base, available, offset + 36),
readString(batch, base, available, offset + 44),
notificationImportance(readU16(batch, base, available, offset + 52), offset + 52),
notificationPresentation(readU16(batch, base, available, offset + 54), offset + 54),
)
}
TAG_WITHDRAW_NOTIFICATION -> {
requireRecordLength(length, 12, offset)
Mutation.WithdrawNotification(readString(batch, base, available, offset + 4))
}
TAG_REQUEST_NOTIFICATION_PERMISSION -> {
requireRecordLength(length, 4, offset)
Mutation.RequestNotificationPermission
}
TAG_EDIT_CODE -> {
requireRecordLength(length, 40, offset)
Mutation.EditCode(
readU32(batch, base, available, offset + 4).toInt(),
readU32(batch, base, available, offset + 8).toInt(),
readU32(batch, base, available, offset + 12).toInt(),
readU32(batch, base, available, offset + 16).toInt(),
readU32(batch, base, available, offset + 20).toInt(),
readU32(batch, base, available, offset + 24).toInt(),
readU32(batch, base, available, offset + 28).toInt(),
readString(batch, base, available, offset + 32),
)
}
TAG_START_ANIMATION -> {
if (length < ANIMATION_HEADER_LENGTH) {
requireRecordLength(length, ANIMATION_HEADER_LENGTH, offset)
}
Mutation.StartAnimation(animation(batch, base, available, offset, length))
}
TAG_CONTROL_ANIMATION -> {
requireRecordLength(length, 24, offset)
Mutation.ControlAnimation(
readU32(batch, base, available, offset + 4).toInt(),
readU32(batch, base, available, offset + 8).toInt(),
animatedProperty(readU8(batch, base, available, offset + 12), offset + 12),
readU8(batch, base, available, offset + 13),
animationControl(readU8(batch, base, available, offset + 14), offset + 14),
readU64(batch, base, available, offset + 16),
)
}
TAG_SET_SELECTION -> {
requireRecordLength(length, 28, offset)
Mutation.SetSelection(
readU32(batch, base, available, offset + 4).toInt(),
readU32(batch, base, available, offset + 8).toInt(),
readU32(batch, base, available, offset + 12).toInt(),
readU32(batch, base, available, offset + 16).toInt(),
readU32(batch, base, available, offset + 20).toInt(),
readU32(batch, base, available, offset + 24).toInt(),
)
}
TAG_REVEAL_RANGE -> {
requireRecordLength(length, 32, offset)
Mutation.RevealRange(
readU32(batch, base, available, offset + 4).toInt(),
readU32(batch, base, available, offset + 8).toInt(),
readU32(batch, base, available, offset + 12).toInt(),
readU32(batch, base, available, offset + 16).toInt(),
readU32(batch, base, available, offset + 20).toInt(),
readU32(batch, base, available, offset + 24).toInt(),
revealAlign(readU32(batch, base, available, offset + 28).toInt(), offset + 28),
)
}
TAG_SET_FOLDED -> {
requireRecordLength(length, 16, offset)
Mutation.SetFolded(
readU32(batch, base, available, offset + 4).toInt(),
readU32(batch, base, available, offset + 8).toInt(),
flag(readU32(batch, base, available, offset + 12), offset + 12),
)
}
TAG_SET_SCROLL_OFFSET -> {
requireRecordLength(length, 16, offset)
Mutation.SetScrollOffset(
readU32(batch, base, available, offset + 4).toInt(),
kotlin.Double.fromBits(readU64(batch, base, available, offset + 8)),
)
}
else -> throw ProtocolException("unknown mutation tag $tag", offset)
}
onMutation(mutation)
decoded += 1
offset += length
}
if (offset != recordsLength || decoded != count) {
throw ProtocolException("record count does not match envelope", offset)
}
} finally {
batch.order(previousOrder)
}
}
/** The body of a `SetTheme` that starts at `at`, which `SetWindowTheme` also carries. */
private fun theme(batch: ByteBuffer, base: Int, available: Int, at: Int): Theme {
val adaptive = readU16(batch, base, available, at + 6)
if (adaptive > 1) {
throw ProtocolException("invalid adaptive flag $adaptive", at + 6)
}
// One slot per type role, in the order the wire fixes them in.
val fonts = List(TypeRole.entries.size) { role ->
readU32(batch, base, available, at + 8 + 4 * role).toInt()
}
val (entries, problems) = palette(
readBytes(batch, base, available, at + 8 + 4 * TypeRole.entries.size),
)
return Theme(
designSystem(readU16(batch, base, available, at), at),
designSystem(readU16(batch, base, available, at + 2), at + 2),
colorScheme(readU16(batch, base, available, at + 4), at + 4),
adaptive == 1,
fonts,
entries,
problems,
)
}
/**
* Reads a palette, keeping every sound entry and saying what was wrong with the rest.
*
* Lenient on purpose, unlike the rest of the batch: an unknown role, a scheme that is
* neither light nor dark, a second value for the same role and scheme, or a length
* that is not a whole number of entries is one entry's fault, and the others are
* still what the application asked for.
*/
fun palette(bytes: ByteArray): Pair<List<PaletteEntry>, List<String>> {
if (bytes.isEmpty()) return emptyList<PaletteEntry>() to emptyList()
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
val entries = ArrayList<PaletteEntry>(bytes.size / PALETTE_ENTRY_LENGTH)
val problems = ArrayList<String>()
if (bytes.size % PALETTE_ENTRY_LENGTH != 0) {
problems += "a palette of ${bytes.size} bytes is not a whole number of " +
"$PALETTE_ENTRY_LENGTH byte entries; the bytes past the last whole one are ignored"
}
for (index in 0 until bytes.size / PALETTE_ENTRY_LENGTH) {
val at = index * PALETTE_ENTRY_LENGTH
val roleTag = buffer.getShort(at).toInt() and 0xffff
val schemeTag = buffer.getShort(at + 2).toInt() and 0xffff
val argb = buffer.getInt(at + 4)
val role = paletteRole(roleTag)
if (role == null) {
problems += "palette entry $index names colour role $roleTag, which does not exist"
continue
}
val dark = when (schemeTag) {
1 -> false
2 -> true
else -> {
problems += "palette entry $index gives $role for scheme $schemeTag; " +
"an entry is for light (1) or dark (2), and following the system is not a scheme"
continue
}
}
if (entries.any { it.role == role && it.dark == dark }) {
problems += "palette entry $index gives $role in ${if (dark) "dark" else "light"} " +
"a second time; the first value stands"
continue
}
entries += PaletteEntry(role, dark, argb)
}
return entries to problems
}
/** Encodes one event into `out` (little-endian), returns bytes written. */
fun encodeEvent(event: HostEvent, out: ByteBuffer): Int {
val start = out.position()
val previousOrder = out.order()
out.order(ByteOrder.LITTLE_ENDIAN)
try {
val text = when (event) {
"#,
);
for event in EVENT_SCHEMA {
match event.payload {
EventPayloadType::Text | EventPayloadType::KeyDown => {
writeln!(
output,
" is HostEvent.{} -> event.text.toByteArray(StandardCharsets.UTF_8)",
event.name
)
.unwrap();
}
EventPayloadType::ProtocolError => {
writeln!(
output,
" is HostEvent.{} -> event.message.toByteArray(StandardCharsets.UTF_8)",
event.name
)
.unwrap();
}
EventPayloadType::NotificationActivation | EventPayloadType::WindowRequest => {
writeln!(
output,
" is HostEvent.{} -> event.key.toByteArray(StandardCharsets.UTF_8)",
event.name
)
.unwrap();
}
EventPayloadType::FileDialogResult => {
writeln!(
output,
" is HostEvent.{} -> event.paths.toByteArray(StandardCharsets.UTF_8)",
event.name
)
.unwrap();
}
EventPayloadType::ClipboardText => {
writeln!(
output,
" is HostEvent.{} -> event.text.toByteArray(StandardCharsets.UTF_8)",
event.name
)
.unwrap();
}
EventPayloadType::IoAnswer => {
writeln!(
output,
" is HostEvent.{} -> event.data",
event.name
)
.unwrap();
}
// Both strings ride after the record, the names first and the kinds after them.
EventPayloadType::FileHandles => {
writeln!(
output,
" is HostEvent.{} -> event.names.toByteArray(StandardCharsets.UTF_8) + event.kinds.toByteArray(StandardCharsets.UTF_8)",
event.name
)
.unwrap();
}
EventPayloadType::None
| EventPayloadType::ScrollChanged
| EventPayloadType::CodeCaretRect
| EventPayloadType::CodePositionRect
| EventPayloadType::CodePointer
| EventPayloadType::CodeEditGroupResult => {
writeln!(
output,
" is HostEvent.{} -> null",
event.name
)
.unwrap();
}
// The selections as little-endian words behind the record, written byte by byte:
// the Kotlin/Native buffer this runs on has no `allocate` and no `array`.
EventPayloadType::CodeSelections => {
writeln!(
output,
" is HostEvent.{} -> ByteArray(event.selections.size * 4).also {{ bytes -> event.selections.forEachIndexed {{ index, value -> for (shift in 0 until 4) bytes[index * 4 + shift] = (value ushr (8 * shift)).toByte() }} }}",
event.name
)
.unwrap();
}
EventPayloadType::CodeChange => {
writeln!(
output,
" is HostEvent.{} -> event.text.toByteArray(StandardCharsets.UTF_8)",
event.name
)
.unwrap();
}
EventPayloadType::Range
| EventPayloadType::Double
| EventPayloadType::WindowSize
| EventPayloadType::DesignSystem
| EventPayloadType::NotificationPermission
| EventPayloadType::CodeEditRejected
| EventPayloadType::CodeHover
| EventPayloadType::CodeSave
| EventPayloadType::Decoration
| EventPayloadType::Animation
| EventPayloadType::ReducedMotion
| EventPayloadType::ColorScheme
| EventPayloadType::Pointer
| EventPayloadType::CodeSelection
| EventPayloadType::CodeVisibleRange
| EventPayloadType::CodeFocus
| EventPayloadType::CodeFold
| EventPayloadType::CodeComposition
| EventPayloadType::WindowFocus
| EventPayloadType::WindowMove
| EventPayloadType::WindowDrag
| EventPayloadType::WindowDragOver
| EventPayloadType::MotionFinished
| EventPayloadType::Zoom => {
writeln!(
output,
" is HostEvent.{} -> null",
event.name
)
.unwrap();
}
}
}
output.push_str(
r#" }
val recordLength = when (event) {
"#,
);
for event in EVENT_SCHEMA {
let length = match event.payload {
EventPayloadType::None => 16,
EventPayloadType::Text => 24,
EventPayloadType::ProtocolError => 28,
EventPayloadType::KeyDown => 32,
EventPayloadType::Range => 24,
EventPayloadType::Double => 24,
EventPayloadType::WindowSize => 44,
// A tag and the padding that keeps the record a multiple of four.
EventPayloadType::DesignSystem => 20,
// A word and a string reference, the protocol error's shape.
EventPayloadType::NotificationActivation => 28,
EventPayloadType::NotificationPermission => 20,
EventPayloadType::CodeChange => 44,
EventPayloadType::CodeEditRejected => 44,
EventPayloadType::CodeHover => 36,
// A version and the padding that keeps the record a multiple of four.
EventPayloadType::CodeSave => 24,
EventPayloadType::Decoration => 24,
EventPayloadType::Animation => 40,
EventPayloadType::ReducedMotion => 20,
EventPayloadType::ColorScheme => 20,
EventPayloadType::Pointer => 72,
EventPayloadType::CodeSelection => 36,
EventPayloadType::CodeVisibleRange => 28,
// A flag and the padding that keeps the record a multiple of four.
EventPayloadType::CodeFocus | EventPayloadType::CodeComposition => 24,
EventPayloadType::CodeFold => 24,
// Two floats and a level, three words after the header.
EventPayloadType::Zoom => 28,
// A flag and nothing else, the editor focus event's shape without its padding.
EventPayloadType::WindowFocus => 20,
// Four floats, or a phase or a kind with the rest of the words.
EventPayloadType::WindowMove
| EventPayloadType::WindowDrag
| EventPayloadType::WindowDragOver => 32,
// A word and a string reference, the protocol error's shape.
EventPayloadType::WindowRequest => 28,
// The request, the status and the filter, then the paths' reference.
EventPayloadType::FileDialogResult => 36,
// The request, the status and the length, then the text's reference.
EventPayloadType::ClipboardText => 36,
// The request and the status, then the data's reference.
EventPayloadType::IoAnswer => 32,
// Five words, then the names' and the kinds' references.
EventPayloadType::FileHandles => 52,
// The item and the flags, then six doubles.
EventPayloadType::ScrollChanged => 72,
// Two floats after the header.
EventPayloadType::MotionFinished => 24,
// Two words and four floats.
EventPayloadType::CodeCaretRect | EventPayloadType::CodePositionRect => 40,
// The pointer record and two words.
EventPayloadType::CodePointer => 80,
// Five words.
EventPayloadType::CodeEditGroupResult => 36,
// The version, then the selections' reference.
EventPayloadType::CodeSelections => 28,
};
writeln!(
output,
" is HostEvent.{} -> {length}",
event.name
)
.unwrap();
}
output.push_str(
r#" }
val totalLength = recordLength.toLong() + (text?.size ?: 0)
if (totalLength > Int.MAX_VALUE || totalLength > out.remaining().toLong()) {
throw ProtocolException("event output buffer is too small", 0)
}
val tag = when (event) {
"#,
);
for event in EVENT_SCHEMA {
writeln!(
output,
" is HostEvent.{} -> {}",
event.name, event.tag
)
.unwrap();
}
output.push_str(
r#" }
out.putShort(tag.toShort())
out.putShort(recordLength.toShort())
out.putInt(event.nodeId)
out.putLong(event.handlerId)
when (event) {
"#,
);
for event in EVENT_SCHEMA {
match event.payload {
EventPayloadType::None => {
writeln!(
output,
" is HostEvent.{} -> Unit",
event.name
)
.unwrap();
}
EventPayloadType::Text => {
writeln!(
output,
" is HostEvent.{} -> writeStringReference(out, recordLength, text!!)",
event.name
)
.unwrap();
}
EventPayloadType::ProtocolError => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.code)\n");
output.push_str(
" writeStringReference(out, recordLength, text!!)\n",
);
output.push_str(" }\n");
}
EventPayloadType::KeyDown => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putShort(keyTag(event.key).toShort())\n");
output.push_str(" var modifiers = 0\n");
output.push_str(
" if (event.shiftKey) modifiers = modifiers or 0x01\n",
);
output.push_str(
" if (event.ctrlKey) modifiers = modifiers or 0x02\n",
);
output.push_str(
" if (event.altKey) modifiers = modifiers or 0x04\n",
);
output.push_str(
" if (event.metaKey) modifiers = modifiers or 0x08\n",
);
output.push_str(" out.put(modifiers.toByte())\n");
output.push_str(
" out.put((if (event.repeat) 1 else 0).toByte())\n",
);
output.push_str(" out.putInt(event.code)\n");
output.push_str(
" writeStringReference(out, recordLength, text!!)\n",
);
output.push_str(" }\n");
}
EventPayloadType::Range => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.start)\n");
output.push_str(" out.putInt(event.count)\n");
output.push_str(" }\n");
}
EventPayloadType::DesignSystem => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(designSystemTag(event.system))\n");
output.push_str(" }\n");
}
EventPayloadType::NotificationActivation => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.action)\n");
output.push_str(
" writeStringReference(out, recordLength, text!!)\n",
);
output.push_str(" }\n");
}
EventPayloadType::CodeChange => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
for field in [
"version",
"startLine",
"startColumn",
"endLine",
"endColumn",
] {
writeln!(output, " out.putInt(event.{field})").unwrap();
}
output.push_str(
" writeStringReference(out, recordLength, text!!)\n",
);
output.push_str(" }\n");
}
EventPayloadType::CodeEditRejected => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
for field in [
"requestId",
"baseVersion",
"currentVersion",
"startLine",
"startColumn",
"endLine",
"endColumn",
] {
writeln!(output, " out.putInt(event.{field})").unwrap();
}
output.push_str(" }\n");
}
EventPayloadType::CodeHover => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putLong(event.decoration)\n");
output.push_str(" out.putInt(event.line)\n");
output.push_str(" out.putInt(event.column)\n");
output.push_str(" out.putInt(hoverPhaseTag(event.phase))\n");
output.push_str(" }\n");
}
EventPayloadType::CodeSave => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.version)\n");
output.push_str(" out.putInt(0)\n");
output.push_str(" }\n");
}
EventPayloadType::Decoration => {
writeln!(
output,
" is HostEvent.{} -> out.putLong(event.decoration)",
event.name
)
.unwrap();
}
EventPayloadType::NotificationPermission => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(
" out.putInt(notificationPermissionTag(event.state))\n",
);
output.push_str(" }\n");
}
EventPayloadType::Animation => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.animationId)\n");
output.push_str(
" out.put(animationEventKindTag(event.kind).toByte())\n",
);
output.push_str(
" out.put(animatedPropertyTag(event.property).toByte())\n",
);
output.push_str(" out.put(event.slot.toByte())\n");
output.push_str(" out.put(0.toByte())\n");
output.push_str(" out.putInt(event.iteration)\n");
output.push_str(" out.putFloat(event.elapsedMs)\n");
output.push_str(" out.putLong(event.timeNanos)\n");
output.push_str(" }\n");
}
EventPayloadType::ReducedMotion => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(reducedMotionTag(event.state))\n");
output.push_str(" }\n");
}
EventPayloadType::ColorScheme => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(
" out.putInt(systemColorSchemeTag(event.scheme))\n",
);
output.push_str(" }\n");
}
EventPayloadType::Pointer | EventPayloadType::CodePointer => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(pointerKindTag(event.kind))\n");
output.push_str(" out.putInt(event.pointerId)\n");
output.push_str(
" out.putInt(pointerTypeTag(event.pointerType))\n",
);
output.push_str(" out.putFloat(event.x)\n");
output.push_str(" out.putFloat(event.y)\n");
output.push_str(" out.putInt(event.buttons)\n");
output.push_str(" out.putInt(event.button)\n");
output.push_str(" out.putInt(event.modifiers)\n");
output.push_str(" out.putInt(event.clickCount)\n");
output.push_str(" out.putFloat(event.deltaX)\n");
output.push_str(" out.putFloat(event.deltaY)\n");
output.push_str(
" out.putInt(wheelDeltaModeTag(event.deltaMode))\n",
);
output.push_str(" out.putLong(event.timestampNanos)\n");
if event.payload == EventPayloadType::CodePointer {
output.push_str(" out.putInt(event.line)\n");
output.push_str(" out.putInt(event.column)\n");
}
output.push_str(" }\n");
}
EventPayloadType::CodeSelections => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.version)\n");
output.push_str(
" writeStringReference(out, recordLength, text!!)\n",
);
output.push_str(" }\n");
}
EventPayloadType::CodeEditGroupResult => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.requestId)\n");
output
.push_str(" out.putInt(editGroupStatusTag(event.status))\n");
for field in ["baseVersion", "currentVersion", "index"] {
writeln!(output, " out.putInt(event.{field})").unwrap();
}
output.push_str(" }\n");
}
EventPayloadType::CodeSelection => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
for field in [
"version",
"anchorLine",
"anchorColumn",
"activeLine",
"activeColumn",
] {
writeln!(output, " out.putInt(event.{field})").unwrap();
}
output.push_str(" }\n");
}
EventPayloadType::CodeVisibleRange => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
for field in ["version", "firstLine", "lastLine"] {
writeln!(output, " out.putInt(event.{field})").unwrap();
}
output.push_str(" }\n");
}
EventPayloadType::CodeFocus => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(if (event.focused) 1 else 0)\n");
output.push_str(" out.putInt(0)\n");
output.push_str(" }\n");
}
EventPayloadType::CodeFold => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.startLine)\n");
output.push_str(" out.putInt(if (event.collapsed) 1 else 0)\n");
output.push_str(" }\n");
}
EventPayloadType::CodeComposition => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(if (event.composing) 1 else 0)\n");
output.push_str(" out.putInt(0)\n");
output.push_str(" }\n");
}
EventPayloadType::Double => {
writeln!(
output,
" is HostEvent.{} -> out.putDouble(event.value)",
event.name
)
.unwrap();
}
EventPayloadType::Zoom => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putFloat(event.k)\n");
output.push_str(" out.putFloat(event.os)\n");
output.push_str(" out.putInt(event.level)\n");
output.push_str(" }\n");
}
EventPayloadType::WindowFocus => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(if (event.focused) 1 else 0)\n");
output.push_str(" }\n");
}
EventPayloadType::WindowMove => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
for field in ["x", "y", "width", "height"] {
writeln!(output, " out.putFloat(event.{field})").unwrap();
}
output.push_str(" }\n");
}
EventPayloadType::WindowDrag => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.phase)\n");
output.push_str(" out.putFloat(event.screenX)\n");
output.push_str(" out.putFloat(event.screenY)\n");
output.push_str(" out.putInt(event.overWindow)\n");
output.push_str(" }\n");
}
EventPayloadType::WindowDragOver => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.kind)\n");
output.push_str(" out.putInt(event.window)\n");
output.push_str(" out.putFloat(event.x)\n");
output.push_str(" out.putFloat(event.y)\n");
output.push_str(" }\n");
}
EventPayloadType::FileDialogResult => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.request)\n");
output.push_str(
" out.putInt(fileDialogStatusTag(event.status))\n",
);
output.push_str(" out.putInt(event.filter)\n");
output.push_str(
" writeStringReference(out, recordLength, text!!)\n",
);
output.push_str(" }\n");
}
EventPayloadType::ClipboardText => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.request)\n");
output.push_str(" out.putInt(event.status)\n");
output.push_str(" out.putInt(event.length)\n");
output.push_str(
" writeStringReference(out, recordLength, text!!)\n",
);
output.push_str(" }\n");
}
EventPayloadType::IoAnswer => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.request)\n");
output.push_str(" out.putInt(ioStatusTag(event.status))\n");
output.push_str(
" writeStringReference(out, recordLength, text!!)\n",
);
output.push_str(" }\n");
}
EventPayloadType::MotionFinished => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putFloat(event.widthDp)\n");
output.push_str(" out.putFloat(event.heightDp)\n");
output.push_str(" }\n");
}
EventPayloadType::ScrollChanged => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.item)\n");
output.push_str(" out.putInt(event.flags)\n");
output.push_str(" out.putDouble(event.xPx)\n");
output.push_str(" out.putDouble(event.yPx)\n");
output.push_str(" out.putDouble(event.maxXPx)\n");
output.push_str(" out.putDouble(event.maxYPx)\n");
output.push_str(" out.putDouble(event.viewportWidthPx)\n");
output.push_str(" out.putDouble(event.viewportHeightPx)\n");
output.push_str(" }\n");
}
EventPayloadType::CodeCaretRect => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.line)\n");
output.push_str(" out.putInt(event.column)\n");
for field in ["x", "y", "width", "height"] {
writeln!(output, " out.putFloat(event.{field})").unwrap();
}
output.push_str(" }\n");
}
EventPayloadType::CodePositionRect => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.request)\n");
output.push_str(" out.putInt(if (event.found) 1 else 0)\n");
for field in ["x", "y", "width", "height"] {
writeln!(
output,
" out.putFloat(if (event.found) event.{field} else 0f)"
)
.unwrap();
}
output.push_str(" }\n");
}
EventPayloadType::FileHandles => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.request)\n");
output.push_str(
" out.putInt(fileDialogStatusTag(event.status))\n",
);
output.push_str(" out.putInt(event.filter)\n");
output
.push_str(" out.putInt(fileDeliveryTag(event.delivery))\n");
output.push_str(" out.putInt(event.firstHandle)\n");
output.push_str(
" val namesLength = event.names.toByteArray(StandardCharsets.UTF_8).size\n",
);
output.push_str(" out.putInt(recordLength)\n");
output.push_str(" out.putInt(namesLength)\n");
output.push_str(" out.putInt(recordLength + namesLength)\n");
output.push_str(" out.putInt(text!!.size - namesLength)\n");
output.push_str(" }\n");
}
EventPayloadType::WindowRequest => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putInt(event.request)\n");
output.push_str(
" writeStringReference(out, recordLength, text!!)\n",
);
output.push_str(" }\n");
}
EventPayloadType::WindowSize => {
writeln!(output, " is HostEvent.{} -> {{", event.name).unwrap();
output.push_str(" out.putFloat(event.widthDp)\n");
output.push_str(" out.putFloat(event.heightDp)\n");
output.push_str(
" out.putInt(windowSizeClassTag(event.sizeClass))\n",
);
output.push_str(
" out.putInt(windowHeightClassTag(event.heightClass))\n",
);
output.push_str(" out.putFloat(event.safeAreaTop)\n");
output.push_str(" out.putFloat(event.safeAreaLeading)\n");
output.push_str(" out.putFloat(event.safeAreaTrailing)\n");
output.push_str(" }\n");
}
}
}
output.push_str(
r#" }
if (text != null) out.put(text)
return out.position() - start
} finally {
out.order(previousOrder)
}
}
/**
* Handshake payload the Renderer sends to compose_rust_host_init.
*
* `loopMode` says who owns the frame loop: the Renderer on desktop, the platform on
* Android, iOS and the web.
*/
fun handshake(out: ByteBuffer, loopMode: LoopMode = LoopMode.Renderer): Int {
val start = out.position()
if (out.remaining() < 12) {
throw ProtocolException("handshake output buffer is too small", 0)
}
val previousOrder = out.order()
out.order(ByteOrder.LITTLE_ENDIAN)
try {
out.putLong(SCHEMA_HASH)
out.putShort(PROTOCOL_VERSION.toShort())
out.put(loopMode.wire)
out.put(0.toByte()) // Reserved for alignment.
return out.position() - start
} finally {
out.order(previousOrder)
}
}
private fun writeStringReference(out: ByteBuffer, offset: Int, bytes: ByteArray) {
out.putInt(offset)
out.putInt(bytes.size)
}
private fun widgetKind(tag: Int, offset: Int): WidgetKind = when (tag) {
"#,
);
for variant in WIDGET_SCHEMA {
writeln!(
output,
" {} -> WidgetKind.{}",
variant.tag, variant.name
)
.unwrap();
}
output.push_str(
r#" else -> throw ProtocolException("unknown widget tag $tag", offset)
}
private fun propertyKind(tag: Int, offset: Int): PropertyKind = when (tag) {
"#,
);
for variant in PROPERTY_SCHEMA {
writeln!(
output,
" {} -> PropertyKind.{}",
variant.tag, variant.name
)
.unwrap();
}
output.push_str(
r#" else -> throw ProtocolException("unknown property tag $tag", offset)
}
private fun keyTag(key: Key): Int = when (key) {
"#,
);
for variant in KEY_SCHEMA {
writeln!(output, " Key.{} -> {}", variant.name, variant.tag).unwrap();
}
output.push_str(" }\n\n");
output.push_str(
" private fun windowSizeClassTag(sizeClass: WindowSizeClass): Int = when (sizeClass) {\n",
);
for variant in WINDOW_SIZE_CLASS_SCHEMA {
writeln!(
output,
" WindowSizeClass.{} -> {}",
variant.name, variant.tag
)
.unwrap();
}
output.push_str(" }\n\n");
output.push_str(
" private fun windowHeightClassTag(heightClass: WindowHeightClass): Int = when (heightClass) {\n",
);
for variant in WINDOW_HEIGHT_CLASS_SCHEMA {
writeln!(
output,
" WindowHeightClass.{} -> {}",
variant.name, variant.tag
)
.unwrap();
}
output.push_str(" }\n\n");
// The one role enum that travels the other way as well: the Renderer reports which
// system it resolved the theme to, so it needs the tag for one as well as the value
// for a tag.
output
.push_str(" private fun designSystemTag(system: DesignSystem): Int = when (system) {\n");
for variant in DESIGN_SYSTEM_SCHEMA {
writeln!(
output,
" DesignSystem.{} -> {}",
variant.name, variant.tag
)
.unwrap();
}
output.push_str(" }\n\n");
// A code editor reports whether a pointer arrived or left, so this one travels out.
output.push_str(" private fun hoverPhaseTag(phase: HoverPhase): Int = when (phase) {\n");
for variant in HOVER_PHASE_SCHEMA {
writeln!(
output,
" HoverPhase.{} -> {}",
variant.name, variant.tag
)
.unwrap();
}
output.push_str(" }\n\n");
// The permission travels this way too: the Renderer is the side that learns it.
output.push_str(
" private fun notificationPermissionTag(state: NotificationPermission): Int = when (state) {\n",
);
for variant in NOTIFICATION_PERMISSION_SCHEMA {
writeln!(
output,
" NotificationPermission.{} -> {}",
variant.name, variant.tag
)
.unwrap();
}
output.push_str(" }\n\n");
// The dialog's status travels out too: the Renderer is the side that learns how it ended.
output.push_str(
" private fun fileDialogStatusTag(status: FileDialogStatus): Int = when (status) {\n",
);
for variant in crate::schema::FILE_DIALOG_STATUS_SCHEMA {
writeln!(
output,
" FileDialogStatus.{} -> {}",
variant.name, variant.tag
)
.unwrap();
}
output.push_str(" }\n\n");
// How a file reached the Renderer, and how a request for bytes ended: the Renderer is
// the side that learns both.
for (function, name, variants) in [
(
"fileDeliveryTag",
"FileDelivery",
crate::schema::FILE_DELIVERY_SCHEMA,
),
("ioStatusTag", "IoStatus", crate::schema::IO_STATUS_SCHEMA),
// What became of a grouped edit, which only the Renderer can know.
(
"editGroupStatusTag",
"EditGroupStatus",
crate::schema::EDIT_GROUP_STATUS_SCHEMA,
),
] {
writeln!(
output,
" private fun {function}(value: {name}): Int = when (value) {{"
)
.unwrap();
for variant in variants {
writeln!(output, " {name}.{} -> {}", variant.name, variant.tag).unwrap();
}
output.push_str(" }\n\n");
}
// The enums the Renderer writes into animation events and the motion setting.
for (function, name, variants) in [
(
"animationEventKindTag",
"AnimationEventKind",
crate::schema::ANIMATION_EVENT_KIND_SCHEMA,
),
(
"animatedPropertyTag",
"AnimatedProperty",
crate::schema::ANIMATED_PROPERTY_SCHEMA,
),
(
"reducedMotionTag",
"ReducedMotion",
crate::schema::REDUCED_MOTION_SCHEMA,
),
(
"systemColorSchemeTag",
"SystemColorScheme",
crate::schema::SYSTEM_COLOR_SCHEME_SCHEMA,
),
(
"pointerKindTag",
"PointerKind",
crate::schema::POINTER_KIND_SCHEMA,
),
(
"pointerTypeTag",
"PointerType",
crate::schema::POINTER_TYPE_SCHEMA,
),
(
"wheelDeltaModeTag",
"WheelDeltaMode",
crate::schema::WHEEL_DELTA_MODE_SCHEMA,
),
] {
writeln!(
output,
" private fun {function}(value: {name}): Int = when (value) {{"
)
.unwrap();
for variant in variants {
writeln!(output, " {name}.{} -> {}", variant.name, variant.tag).unwrap();
}
output.push_str(" }\n\n");
}
// The palette's own role lookup answers null rather than throwing, because an entry
// naming a role this side does not know is reported and skipped, not the end of the
// batch.
output.push_str(" private fun paletteRole(tag: Int): ColorRole? = when (tag) {\n");
for variant in crate::schema::COLOR_ROLE_SCHEMA {
writeln!(
output,
" {} -> ColorRole.{}",
variant.tag, variant.name
)
.unwrap();
}
output.push_str(" else -> null\n }\n\n");
for role in ROLE_ENUM_SCHEMA {
writeln!(
output,
" private fun {}(tag: Int, offset: Int): {} = when (tag) {{",
lower_camel(role.name),
role.name
)
.unwrap();
for variant in role.variants {
writeln!(
output,
" {} -> {}.{}",
variant.tag, role.name, variant.name
)
.unwrap();
}
writeln!(
output,
" else -> throw ProtocolException(\"unknown {} tag $tag\", offset)",
role.name
)
.unwrap();
output.push_str(" }\n\n");
}
output.push_str(
r#" private fun paint(bits: Long, offset: Int): Paint {
val value = bits.toInt()
return when (val kind = (bits ushr 32).toInt()) {
1 -> Paint.Role(colorRole(value, offset))
2 -> Paint.Literal(value)
3 -> Paint.Asset(value)
else -> throw ProtocolException("unknown paint kind $kind", offset)
}
}
/** A word that says yes or no. Any value but 0 and 1 is a record the sides disagree on. */
private fun flag(word: Long, offset: Int): Boolean = when (word) {
0L -> false
1L -> true
else -> throw ProtocolException("invalid flag $word", offset)
}
/** A value that has to be a number. NaN or an infinity is a record the sides disagree on. */
private fun finite(value: kotlin.Float, offset: Int): kotlin.Float =
if (value.isFinite()) value else throw ProtocolException("$value is not a finite number", offset)
/**
* How many eight byte words a modifier's value takes beyond the two every record has.
* The tag fixes it, so a record of any other length is refused before it is read.
*/
private fun modifierExtraWords(tag: Int, offset: Int): Int = when (tag) {
"#,
);
for variant in MODIFIER_SCHEMA {
writeln!(output, " {} -> {}", variant.tag, variant.extra_words).unwrap();
}
output.push_str(
r#" else -> throw ProtocolException("unknown modifier tag $tag", offset)
}
private fun modifier(tag: Int, batch: ByteBuffer, base: Int, available: Int, at: Int, offset: Int): Modifier {
val first = readU64(batch, base, available, at)
val second = readU64(batch, base, available, at + 8)
return when (tag) {
"#,
);
for variant in MODIFIER_SCHEMA {
write!(
output,
" {} -> Modifier.{}",
variant.tag, variant.name
)
.unwrap();
if variant.fields.is_empty() {
output.push('\n');
} else {
output.push('(');
for (index, field) in variant.fields.iter().enumerate() {
if index != 0 {
output.push_str(", ");
}
output.push_str(&modifier_decode_expression(field));
}
output.push_str(")\n");
}
}
output.push_str(
r#" else -> throw ProtocolException("unknown modifier tag $tag", offset)
}
}
/**
* An arena range with no UTF-8 requirement, used by both a drawing command list and an
* asset's bytes. For an asset this is the one copy this side makes, and it happens at
* registration rather than per frame.
*/
private fun readBytes(batch: ByteBuffer, base: Int, available: Int, referenceOffset: Int): ByteArray {
val offsetLong = readU32(batch, base, available, referenceOffset)
val lengthLong = readU32(batch, base, available, referenceOffset + 4)
if (offsetLong > Int.MAX_VALUE || lengthLong > Int.MAX_VALUE) {
throw ProtocolException("byte range is too large", referenceOffset)
}
val offset = offsetLong.toInt()
val length = lengthLong.toInt()
requireRange(available, offset, length, referenceOffset)
val copy = ByteArray(length)
copyOut(batch, base + offset, copy, length)
return copy
}
/**
* An arena range left where it lies, for bytes the Renderer hands straight on (a value
* to store) while the record is applied, so this side copies nothing itself.
*/
private fun readByteView(batch: ByteBuffer, base: Int, available: Int, referenceOffset: Int): BatchBytes {
val offsetLong = readU32(batch, base, available, referenceOffset)
val lengthLong = readU32(batch, base, available, referenceOffset + 4)
if (offsetLong > Int.MAX_VALUE || lengthLong > Int.MAX_VALUE) {
throw ProtocolException("byte range is too large", referenceOffset)
}
val offset = offsetLong.toInt()
val length = lengthLong.toInt()
requireRange(available, offset, length, referenceOffset)
return BatchBytes(batch, base + offset, length)
}
/**
* Copies a range of the arena into an array.
*
* The absolute bulk read that says the same thing in one call, `get(index, array,
* offset, length)`, arrived in Java 13 and is not in every Android runtime this has to
* run on. So the read goes through the buffer's own position, which every version has,
* and puts it back afterwards: the arena is read from one thread and a position left
* where the last read ended would make the next one read the wrong bytes.
*
* Nothing is allocated. A `duplicate()` would avoid touching the position and costs an
* object per call on a path that runs per string in every batch.
*/
private fun copyOut(batch: ByteBuffer, at: Int, into: ByteArray, length: Int) {
val mark = batch.position()
batch.position(at)
batch.get(into, 0, length)
batch.position(mark)
}
/**
* The string Compose is handed, and the only copy of the text this side makes.
*
* Validating and building are two passes rather than one because the two things that
* do both are each wrong here. `String(bytes, UTF_8)` replaces a malformed byte with
* U+FFFD, and a malformed string means the two sides disagree about the arena, which
* has to be reported rather than drawn. A `CharsetDecoder` reports it, but assembles
* the text as `char` first, two bytes a character, and then copies that into the
* `String`, and it needs a decoder and two buffer views of its own to do it.
*
* So the bytes are checked where they lie, which allocates nothing, and then copied
* once into a buffer this object keeps and handed to `String`, which by then has
* nothing left to replace. What remains is the one allocation the string itself is.
*/
private fun readString(batch: ByteBuffer, base: Int, available: Int, referenceOffset: Int): String {
val offsetLong = readU32(batch, base, available, referenceOffset)
val lengthLong = readU32(batch, base, available, referenceOffset + 4)
if (offsetLong > Int.MAX_VALUE || lengthLong > Int.MAX_VALUE) {
throw ProtocolException("string range is too large", referenceOffset)
}
val offset = offsetLong.toInt()
val length = lengthLong.toInt()
requireRange(available, offset, length, referenceOffset)
if (length == 0) {
return ""
}
requireUtf8(batch, base + offset, length, offset)
val scratch = stringBytes(length)
copyOut(batch, base + offset, scratch, length)
return String(scratch, 0, length, StandardCharsets.UTF_8)
}
/**
* Reads a range of the arena as UTF-8 without building anything out of it.
*
* The bounds are Unicode's, and the ones that look arbitrary are the point. A two byte
* sequence starts at 0xc2 because 0xc0 and 0xc1 could only encode what one byte
* already encodes; the second byte after 0xe0 starts at 0xa0 and after 0xf0 at 0x90
* for the same reason; 0xed stops at 0x9f because the surrogate halves follow it; and
* four byte sequences stop at 0xf4 0x8f because U+10FFFF is the last code point. The
* platform's decoder refuses every one of those, and this has to refuse them too, or
* a range it called text would come out of `String` as replacement characters.
*/
private fun requireUtf8(batch: ByteBuffer, start: Int, length: Int, errorOffset: Int) {
var index = 0
while (index < length) {
val lead = batch.get(start + index).toInt() and 0xff
if (lead < 0x80) {
index += 1
// Eight bytes at a time for as long as the text stays ASCII, which most
// text is and all of a streaming append usually is: a long with no high
// bit anywhere in it is eight characters that need nothing else checked.
// The mask is the same at both ends, so which order the long is read in
// does not matter. Entered only after an ASCII byte, so text with no
// ASCII in it never pays for the attempt.
while (index + 8 <= length &&
batch.getLong(start + index) and ASCII_HIGH_BITS == 0L
) {
index += 8
}
continue
}
val width = when {
lead >= 0xc2 && lead <= 0xdf -> 2
lead >= 0xe0 && lead <= 0xef -> 3
lead >= 0xf0 && lead <= 0xf4 -> 4
else -> malformedUtf8(errorOffset)
}
if (index + width > length) {
malformedUtf8(errorOffset)
}
val lowest = when (lead) {
0xe0 -> 0xa0
0xf0 -> 0x90
else -> 0x80
}
val highest = when (lead) {
0xed -> 0x9f
0xf4 -> 0x8f
else -> 0xbf
}
val second = batch.get(start + index + 1).toInt() and 0xff
if (second < lowest || second > highest) {
malformedUtf8(errorOffset)
}
var step = 2
while (step < width) {
val continuation = batch.get(start + index + step).toInt() and 0xff
if (continuation < 0x80 || continuation > 0xbf) {
malformedUtf8(errorOffset)
}
step += 1
}
index += width
}
}
private fun malformedUtf8(errorOffset: Int): Nothing =
throw ProtocolException("string is not valid UTF-8", errorOffset)
/**
* The buffer every string is copied through, grown to fit and then kept.
*
* A frame's strings go through it one after another, so a stream of keystrokes costs
* nothing here once it is big enough. It doubles rather than fitting exactly, because
* text that grows a character at a time would otherwise reallocate on every keystroke.
*
* One buffer is enough, and it needs no lock, because a batch is decoded on the
* Renderer's UI thread and on no other: the Host's worker threads update signals and
* ask for a frame, they never call across the boundary themselves. Two threads
* decoding at once would hand each other half a string.
*/
private var stringScratch = ByteArray(256)
private fun stringBytes(length: Int): ByteArray {
val scratch = stringScratch
if (scratch.size >= length) {
return scratch
}
var size = scratch.size
while (size < length) {
size = if (size > Int.MAX_VALUE / 2) length else size + size
}
val grown = ByteArray(size)
stringScratch = grown
return grown
}
/**
* Reads one `StartAnimation` record and refuses anything that is not an animation this
* Renderer could play, asking the same questions the Host's decoder asks of the same
* bytes: known values, at least two keyframes, offsets from 0 to 1 that never go back,
* a duration and an iteration count that are numbers and not negative, values of the
* property's own kind, transform lists lined up across keyframes, and a length that
* holds exactly its keyframes.
*/
private fun animation(batch: ByteBuffer, base: Int, available: Int, start: Int, length: Int): Animation {
val end = start + length
fun float(at: Int): kotlin.Float = kotlin.Float.fromBits(readU32(batch, base, available, at).toInt())
fun bad(message: String, at: Int): Nothing = throw ProtocolException("invalid animation: $message", at)
val property = animatedProperty(readU8(batch, base, available, start + 12), start + 12)
val colour = property == AnimatedProperty.Color || property == AnimatedProperty.Background ||
property == AnimatedProperty.BorderColor
val rawInterpolation = readU8(batch, base, available, start + 17)
val interpolation = when {
colour -> colorInterpolation(rawInterpolation, start + 17)
rawInterpolation == 0 -> null
else -> bad("only a colour has an interpolation", start + 17)
}
val keyframeCount = readU16(batch, base, available, start + 18)
val delayMs = float(start + 28)
val durationMs = float(start + 32)
val iterations = float(start + 36)
val originX = float(start + 40)
val originY = float(start + 44)
val events = readU8(batch, base, available, start + 48)
if (keyframeCount < 2) bad("$keyframeCount keyframes", start + 18)
if (!delayMs.isFinite()) bad("delay $delayMs", start + 28)
if (!durationMs.isFinite() || durationMs < 0f) bad("duration $durationMs", start + 32)
if (iterations.isNaN() || iterations < 0f) bad("iteration count $iterations", start + 36)
if (!originX.isFinite() || !originY.isFinite()) bad("origin", start + 40)
if (events and 0xf.inv() != 0) bad("event bits $events", start + 48)
val keyframes = ArrayList<Keyframe>(keyframeCount)
var at = start + ANIMATION_HEADER_LENGTH
for (index in 0 until keyframeCount) {
if (at + KEYFRAME_HEAD_LENGTH > end) bad("keyframe $index runs past the record", at)
val keyframeOffset = float(at)
val flags = readU16(batch, base, available, at + 6)
val timing = when (timingKind(readU8(batch, base, available, at + 4), at + 4)) {
TimingKind.Linear -> Timing.Linear
TimingKind.CubicBezier -> {
val x1 = float(at + 8)
val y1 = float(at + 12)
val x2 = float(at + 16)
val y2 = float(at + 20)
if (!(x1.isFinite() && y1.isFinite() && x2.isFinite() && y2.isFinite()) ||
x1 < 0f || x1 > 1f || x2 < 0f || x2 > 1f
) {
bad("cubic-bezier($x1, $y1, $x2, $y2)", at + 8)
}
Timing.CubicBezier(x1, y1, x2, y2)
}
TimingKind.Steps -> {
val position = stepPosition(readU8(batch, base, available, at + 5), at + 5)
val count = readU32(batch, base, available, at + 8)
val least = if (position == StepPosition.JumpNone) 2L else 1L
if (count < least || count > Int.MAX_VALUE) bad("steps($count, $position)", at + 8)
Timing.Steps(count.toInt(), position)
}
}
if (flags and 1.inv() != 0 || (index > 0 && flags != 0)) bad("keyframe flags $flags", at + 6)
if (!(keyframeOffset >= 0f && keyframeOffset <= 1f)) bad("keyframe offset $keyframeOffset", at)
val valueAt = at + KEYFRAME_HEAD_LENGTH
val value: KeyframeValue
when (property) {
AnimatedProperty.Alpha -> {
val alpha = float(valueAt)
if (!alpha.isFinite()) bad("alpha $alpha", valueAt)
value = KeyframeValue.Alpha(alpha)
at = valueAt + 4
}
AnimatedProperty.Color, AnimatedProperty.Background, AnimatedProperty.BorderColor -> {
val paint = paint(readU64(batch, base, available, valueAt), valueAt)
if (paint is Paint.Asset) bad("a brush cannot be mixed with another colour", valueAt)
value = KeyframeValue.PaintValue(paint)
at = valueAt + 8
}
AnimatedProperty.Transform -> {
val count = readU16(batch, base, available, valueAt)
val functions = ArrayList<TransformFunction>(count)
for (function in 0 until count) {
val functionAt = valueAt + 4 + TRANSFORM_FUNCTION_LENGTH * function
if (functionAt + TRANSFORM_FUNCTION_LENGTH > end) bad("transform function runs past the record", functionAt)
val rawKind = readU32(batch, base, available, functionAt)
if (rawKind > Int.MAX_VALUE) bad("transform function kind $rawKind", functionAt)
val kind = transformFunctionKind(rawKind.toInt(), functionAt)
val values = FloatArray(6) { float(functionAt + 4 + 4 * it) }
if (!values.all { it.isFinite() }) bad("transform values", functionAt + 4)
functions += TransformFunction(kind, values[0], values[1], values[2], values[3], values[4], values[5])
}
value = KeyframeValue.Transform(functions)
at = valueAt + 4 + TRANSFORM_FUNCTION_LENGTH * count
}
}
keyframes += Keyframe(keyframeOffset, timing, flags != 0, value)
}
if (at != end) bad("the record is $length bytes and its keyframes end at ${at - start}", start + 2)
if (keyframes.first().offset != 0f || keyframes.last().offset != 1f) bad("offsets do not run from 0 to 1", start)
for (index in 1 until keyframes.size) {
if (keyframes[index].offset < keyframes[index - 1].offset) bad("offsets go back", start)
}
val shape = (keyframes.first().value as? KeyframeValue.Transform)?.functions?.map { it.kind }
if (shape != null &&
keyframes.any { (it.value as KeyframeValue.Transform).functions.map { function -> function.kind } != shape }
) {
bad("transform lists differ between keyframes", start)
}
return Animation(
nodeId = readU32(batch, base, available, start + 4).toInt(),
animationId = readU32(batch, base, available, start + 8).toInt(),
property = property,
slot = readU8(batch, base, available, start + 13),
direction = playbackDirection(readU8(batch, base, available, start + 14), start + 14),
fill = fillMode(readU8(batch, base, available, start + 15), start + 15),
playState = playState(readU8(batch, base, available, start + 16), start + 16),
interpolation = interpolation,
startTimeNanos = readU64(batch, base, available, start + 20),
delayMs = delayMs,
durationMs = durationMs,
iterations = iterations,
originX = originX,
originY = originY,
events = events,
keyframes = keyframes,
)
}
private fun readU8(batch: ByteBuffer, base: Int, available: Int, offset: Int): Int {
requireRange(available, offset, 1, offset)
return batch.get(base + offset).toInt() and 0xff
}
private fun readU16(batch: ByteBuffer, base: Int, available: Int, offset: Int): Int {
requireRange(available, offset, 2, offset)
return batch.getShort(base + offset).toInt() and 0xffff
}
private fun readU32(batch: ByteBuffer, base: Int, available: Int, offset: Int): Long {
requireRange(available, offset, 4, offset)
return batch.getInt(base + offset).toLong() and 0xffff_ffffL
}
private fun readU64(batch: ByteBuffer, base: Int, available: Int, offset: Int): Long {
requireRange(available, offset, 8, offset)
return batch.getLong(base + offset)
}
private fun requireRecordLength(actual: Int, expected: Int, offset: Int) {
if (actual != expected) {
throw ProtocolException("invalid record length $actual for tag", offset + 2)
}
}
private fun requireRange(available: Int, offset: Int, length: Int, errorOffset: Int) {
if (offset < 0 || length < 0 || offset.toLong() + length > available.toLong()) {
throw ProtocolException("truncated or out-of-range data", errorOffset)
}
}
}
"#,
);
write_design_tokens(&mut output);
output
}
/// The token tables are authored in Rust and executed in the Renderer, so they are
/// generated into the Renderer binary at build time instead of crossing the boundary.
fn write_design_tokens(output: &mut String) {
output.push_str(
r#"
/** One rung of the type ladder. Sizes are sp, spacing may be negative. */
data class TypeToken(
val size: Float,
val weight: Int,
val lineHeight: Float,
val letterSpacing: Float,
val monospace: Boolean,
)
/**
* The generated half of one design system's tables: colours, type, shapes and spacing.
*
* Arrays are indexed by the role's ordinal, which matches its wire tag minus one.
* The rules that consume them (elevation rendering, ButtonVariant styling, motion) are
* written by hand in the Renderer.
*/
class DesignTokenTable(
val system: DesignSystem,
/** The published guideline these values come from. */
val reference: String,
val defaultFamily: String,
val monospaceFamily: String,
private val lightColors: IntArray,
private val darkColors: IntArray,
private val typeScale: Array<TypeToken>,
private val shapeRadii: FloatArray,
private val spaces: FloatArray,
) {
/** The 0xAARRGGBB value for a role. `dark` is the scheme the Renderer resolved. */
fun color(role: ColorRole, dark: Boolean): Int =
if (dark) darkColors[role.ordinal] else lightColors[role.ordinal]
fun type(role: TypeRole): TypeToken = typeScale[role.ordinal]
/** Corner radius in dp. */
fun radius(role: ShapeRole): Float = shapeRadii[role.ordinal]
/** Spacing in dp. */
fun space(role: SpaceRole): Float = spaces[role.ordinal]
}
object DesignTokens {
"#,
);
for table in DESIGN_TOKENS {
let name = upper_snake(&format!("{:?}", table.system));
writeln!(
output,
" val {name}: DesignTokenTable = DesignTokenTable("
)
.unwrap();
writeln!(output, " DesignSystem.{:?},", table.system).unwrap();
writeln!(output, " \"{}\",", table.reference).unwrap();
writeln!(output, " \"{}\",", table.default_family).unwrap();
writeln!(output, " \"{}\",", table.monospace_family).unwrap();
for dark in [false, true] {
output.push_str(" intArrayOf(\n");
for token in table.colors.iter() {
let color = if dark { token.dark } else { token.light };
writeln!(
output,
" 0x{:08x}.toInt(), // {:?}",
color.to_argb(),
token.role
)
.unwrap();
}
output.push_str(" ),\n");
}
output.push_str(" arrayOf(\n");
for token in table.type_scale.iter() {
writeln!(
output,
" TypeToken({:?}f, {}, {:?}f, {:?}f, {}), // {:?}",
token.size,
token.weight,
token.line_height,
token.letter_spacing,
token.monospace,
token.role
)
.unwrap();
}
output.push_str(" ),\n floatArrayOf(");
for (index, token) in table.shapes.iter().enumerate() {
if index != 0 {
output.push_str(", ");
}
write!(output, "{:?}f", token.radius).unwrap();
}
output.push_str("),\n floatArrayOf(");
for (index, token) in table.spaces.iter().enumerate() {
if index != 0 {
output.push_str(", ");
}
write!(output, "{:?}f", token.value).unwrap();
}
output.push_str("),\n )\n\n");
}
output.push_str(" fun of(system: DesignSystem): DesignTokenTable = when (system) {\n");
for table in DESIGN_TOKENS {
writeln!(
output,
" DesignSystem.{:?} -> {}",
table.system,
upper_snake(&format!("{:?}", table.system))
)
.unwrap();
}
output.push_str(" }\n}\n");
}
fn upper_snake(name: &str) -> String {
let mut output = String::new();
for (index, character) in name.chars().enumerate() {
if character.is_uppercase() && index != 0 {
output.push('_');
}
output.extend(character.to_uppercase());
}
output
}
/// One of each drawing command, in schema order, with a string region behind them.
pub fn canvas_vector() -> crate::drawing::DrawList {
crate::drawing::DrawList::builder()
.line(Paint::Role(ColorRole::Primary), 1.0, 2.0, 3.0, 4.0, 1.5)
.rect(
Paint::Literal(Color::argb(0xff11_2233)),
0.0,
0.0,
8.0,
9.0,
0.0,
)
.round_rect(
Paint::Role(ColorRole::Surface),
1.0,
2.0,
3.0,
4.0,
5.0,
6.0,
)
.circle(Paint::Role(ColorRole::Error), 4.0, 5.0, 6.0, 0.5)
.arc(
Paint::Role(ColorRole::Outline),
1.0,
2.0,
3.0,
0.0,
90.0,
2.0,
)
.polyline_ref(Paint::Role(ColorRole::Secondary), 42, 3.0)
.text_at(
Paint::Role(ColorRole::OnSurface),
"한글",
7.0,
8.0,
crate::schema::TypeRole::Label,
)
.build()
}
/// The palette the vector's theme carries: one role in both schemes and one in light only,
/// with an alpha that is not opaque, so both sides read every field of an entry.
pub const VECTOR_PALETTE: crate::palette::Palette = crate::palette::Palette::new()
.with(
ColorRole::Primary,
Color::rgb(0xe8590c),
Color::rgb(0xff8a4c),
)
.with_light(ColorRole::SyntaxKeyword, Color::argb(0x8011_2233));
/// Two runs: one with a text colour, a background and bold, one with a literal background
/// only, so both paints and their absence are in the vector.
pub fn spans_vector() -> crate::spans::TextSpans {
use crate::spans::{TextSpan, TextSpans};
TextSpans::new([
TextSpan::new(0, 4)
.bold()
.with_color(Paint::Role(ColorRole::SyntaxKeyword))
.with_background(Paint::Role(ColorRole::DiffAddedEmphasis)),
TextSpan::new(5, 2).with_background(Paint::Literal(Color::argb(0xff44_5566))),
])
}
/// The document the code editor in the mutation vector opens with. Its second line holds a
/// Hangul syllable, one UTF-16 unit, and an emoji, two of them, so every column after it
/// is one a byte count or a character count would get wrong.
pub const CODE_VECTOR_TEXT: &str = "fn main() {\n let 한 = \"😀\";\n}\n";
/// The snippet in the mutation vector.
pub const CODE_SNIPPET_VECTOR: &str = "} // ${1:name} = ${1:name}, ${2|한,😀|} \\$5$0";
/// The grouped edit in the mutation vector, against [`CODE_VECTOR_TEXT`] after the vector's
/// single edit put `mut ` in front of the name: the first word becomes `pub fn` and the
/// emoji, a surrogate pair, becomes another one. Listed back to front, which a group may be.
pub const CODE_EDIT_GROUP_VECTOR: &[(u32, u32, u32, u32, &str)] =
&[(1, 17, 1, 19, "🎉"), (0, 0, 0, 2, "pub fn")];
fn code_edit_group_vector() -> Result<Vec<u8>, ProtocolError> {
use crate::code::CodeRange;
let edits: Vec<(CodeRange, &str)> = CODE_EDIT_GROUP_VECTOR
.iter()
.map(|&(start_line, start_column, end_line, end_column, text)| {
(
CodeRange::of(start_line, start_column, end_line, end_column),
text,
)
})
.collect();
let mut bytes = Vec::new();
crate::code::encode_edit_group(&edits, &mut bytes)?;
Ok(bytes)
}
/// One decoration of each kind, with a colour role on one of them and text on two, and the
/// two backgrounds after them.
fn code_decoration_vector() -> crate::code::Decorations {
use crate::code::{CodeRange, Decoration, Position};
use crate::schema::Severity;
crate::code::Decorations::new([
Decoration::underline(0, CodeRange::of(1, 8, 1, 9), Severity::Warning)
.with_color(ColorRole::Error),
Decoration::code_lens(0, 0, "Run", 41),
Decoration::hover_anchor(0, CodeRange::of(0, 3, 0, 7), 42),
Decoration::ghost_text(0, Position::new(2, 1), " // end", 43),
Decoration::line_background(0, 1, 2, ColorRole::DiffAdded),
Decoration::range_background(0, CodeRange::of(1, 8, 1, 9), ColorRole::DiffAdded),
])
}
/// Two syntax colour runs, the second across the emoji.
fn code_span_vector() -> crate::code::SyntaxSpans {
use crate::code::{CodeRange, SyntaxSpan};
crate::code::SyntaxSpans::new([
SyntaxSpan::role(0, CodeRange::of(0, 0, 0, 2), ColorRole::Primary),
SyntaxSpan::role(0, CodeRange::of(1, 12, 1, 16), ColorRole::Tertiary),
])
}
/// Two folds, one folded, the second inside the first, and three gutter marks of the three
/// kinds, one with a colour role and one carrying an emoji.
fn code_fold_vector() -> crate::code::Folds {
use crate::code::Fold;
crate::code::Folds::new([Fold::new(0, 0, 2), Fold::new(0, 1, 3).collapsed()])
}
/// The selections of the mutation vector's `SetSelections`.
pub const CODE_SELECTIONS_VECTOR: &[(u32, u32, u32, u32)] =
&[(0, 3, 0, 7), (1, 12, 1, 8), (2, 0, 2, 0)];
fn code_selections_vector() -> Vec<u8> {
let selections: Vec<_> = CODE_SELECTIONS_VECTOR
.iter()
.map(
|&(anchor_line, anchor_column, active_line, active_column)| {
(
crate::code::Position::new(anchor_line, anchor_column),
crate::code::Position::new(active_line, active_column),
)
},
)
.collect();
let mut bytes = Vec::new();
crate::code::encode_selections(&selections, &mut bytes);
bytes
}
/// Two view zones, one of them with text that is not ASCII and one half a row high.
fn code_view_zone_vector() -> crate::code::ViewZones {
use crate::code::ViewZone;
crate::code::ViewZones::new([
ViewZone::new(0, 2.0).with_text("− 2줄"),
ViewZone::new(1, 0.5),
])
}
fn code_gutter_vector() -> crate::code::GutterDecorations {
use crate::code::GutterDecoration;
crate::code::GutterDecorations::new([
GutterDecoration::dot(0, 0, 51),
GutterDecoration::bar(0, 1, 0).with_color(ColorRole::Tertiary),
GutterDecoration::glyph(0, 2, '\u{1F41B}', 52),
])
}
/// Two keyframes each, the first eased and starting from what is presented, the second
/// linear; every other field set to something other than its default, so a field read
/// from the wrong offset cannot pass.
fn vector_animation(
node_id: u32,
animation_id: u32,
property: AnimatedProperty,
slot: u8,
values: [KeyframeValue; 2],
) -> Animation<'static> {
let colour = matches!(
property,
AnimatedProperty::Color | AnimatedProperty::Background | AnimatedProperty::BorderColor
);
let [first, last] = values;
Animation {
node_id,
animation_id,
property,
slot,
direction: PlaybackDirection::Alternate,
fill: FillMode::Both,
play_state: PlayState::Running,
interpolation: colour.then_some(ColorInterpolation::SrgbPremultiplied),
start_time_nanos: 0,
delay_ms: -250.0,
duration_ms: 1000.0,
iterations: 2.5,
origin_x: if property == AnimatedProperty::Transform {
0.5
} else {
0.0
},
origin_y: if property == AnimatedProperty::Transform {
0.25
} else {
0.0
},
events: AnimationEvents::ACTIVE.union(AnimationEvents::END),
keyframes: std::borrow::Cow::Owned(vec![
Keyframe {
offset: 0.0,
timing: Timing::CubicBezier {
x1: 0.25,
y1: 0.1,
x2: 0.25,
y2: 1.0,
},
from_presented: true,
value: first,
},
Keyframe {
offset: 0.6,
timing: Timing::Steps {
count: 4,
position: StepPosition::JumpBoth,
},
from_presented: false,
value: last.clone(),
},
Keyframe {
offset: 1.0,
timing: Timing::Linear,
from_presented: false,
value: last,
},
]),
}
}
const VECTOR_TRANSLATE: [TransformFunction; 2] = [
TransformFunction::translate(0.0, 0.0),
TransformFunction::translate(24.0, -8.0),
];
const VECTOR_ROTATE: [TransformFunction; 2] = [
TransformFunction::rotate(0.0),
TransformFunction::rotate(720.0),
];
const VECTOR_SCALE: [TransformFunction; 2] = [
TransformFunction::scale(1.0, 1.0),
TransformFunction::scale(1.5, 0.5),
];
const VECTOR_SKEW: [TransformFunction; 2] = [
TransformFunction::skew(0.0, 0.0),
TransformFunction::skew(10.0, -5.0),
];
const VECTOR_MATRIX: [TransformFunction; 2] = [
TransformFunction::matrix(1.0, 0.0, 0.0, 1.0, 0.0, 0.0),
TransformFunction::matrix(0.75, 0.5, -0.25, 1.25, 12.0, -6.0),
];
/// `rotate(0) translateX(0) scale(1)` to `rotate(360deg) translateX(100px) scale(2)`.
const VECTOR_THREE: [TransformFunction; 6] = [
TransformFunction::rotate(0.0),
TransformFunction::translate(0.0, 0.0),
TransformFunction::scale(1.0, 1.0),
TransformFunction::rotate(360.0),
TransformFunction::translate(100.0, 0.0),
TransformFunction::scale(2.0, 2.0),
];
/// A transform animation on the vector's box from the first half of `functions` to the
/// second.
fn vector_transform(
animation_id: u32,
slot: u8,
functions: &'static [TransformFunction],
) -> Animation<'static> {
let (from, to) = functions.split_at(functions.len() / 2);
vector_animation(
8,
animation_id,
AnimatedProperty::Transform,
slot,
[
KeyframeValue::Transform(std::borrow::Cow::Borrowed(from)),
KeyframeValue::Transform(std::borrow::Cow::Borrowed(to)),
],
)
}
/// The little-endian bytes of some `f32`, the layout a window's size, position and drag
/// anchor travel in.
fn floats_le(values: &[f32]) -> Vec<u8> {
values
.iter()
.flat_map(|value| value.to_bits().to_le_bytes())
.collect()
}
/// The three font features the mutation vector's text carries: tabular figures on,
/// ligatures off, and a character variant whose value needs more than one byte.
pub const FONT_FEATURE_VECTOR: [crate::font_features::FontFeature; 3] = [
crate::font_features::FontFeature::TABULAR_NUMS,
crate::font_features::FontFeature::NO_LIGATURES,
crate::font_features::FontFeature::new(b"cv01", 0x0102),
];
pub fn generate_mutation_vector() -> Result<Vec<u8>, ProtocolError> {
let canvas_vector_bytes = canvas_vector();
let spans_vector_bytes = spans_vector();
let decorations = code_decoration_vector();
let syntax_spans = code_span_vector();
let folds = code_fold_vector();
let gutter = code_gutter_vector();
let window_size = floats_le(&[800.0, 600.0]);
let window_min_size = floats_le(&[320.0, 240.0]);
let window_position = floats_le(&[100.5, -20.0]);
let font_features = crate::font_features::font_feature_bytes(&FONT_FEATURE_VECTOR);
let edit_group = code_edit_group_vector()?;
let view_zones = code_view_zone_vector();
let code_selections = code_selections_vector();
let mut drag_from_pointer = 1_u32.to_le_bytes().to_vec();
drag_from_pointer.extend_from_slice(&floats_le(&[12.5, 8.0]));
let mutations = [
Mutation::SetTheme(
Theme::adaptive(DesignSystem::Cupertino)
.with_color_scheme(ColorScheme::Dark)
.with_palette(&VECTOR_PALETTE),
),
Mutation::Create {
node_id: 1,
widget: WidgetKind::Box,
},
Mutation::SetProp {
node_id: 2,
property: PropertyKind::Text,
value: PropertyValue::String("안녕"),
},
Mutation::SetProp {
node_id: 2,
property: PropertyKind::Enabled,
value: PropertyValue::Bool(true),
},
Mutation::SetProp {
node_id: 2,
property: PropertyKind::OnClick,
value: PropertyValue::Integer(99),
},
Mutation::SetProp {
node_id: 2,
property: PropertyKind::Multiline,
value: PropertyValue::Float(1.5),
},
Mutation::SetProp {
node_id: 2,
property: PropertyKind::Placeholder,
value: PropertyValue::None,
},
Mutation::SetModifier {
node_id: 1,
index: 0,
modifier: Modifier::Empty,
},
Mutation::SetModifier {
node_id: 1,
index: 1,
modifier: Modifier::Padding(16.0),
},
Mutation::SetModifier {
node_id: 1,
index: 2,
modifier: Modifier::FillMaxWidth,
},
Mutation::SetModifier {
node_id: 1,
index: 3,
modifier: Modifier::FillMaxHeight,
},
Mutation::SetModifier {
node_id: 1,
index: 4,
modifier: Modifier::Width(120.0),
},
Mutation::SetModifier {
node_id: 1,
index: 5,
modifier: Modifier::Height(48.0),
},
Mutation::SetModifier {
node_id: 1,
index: 6,
modifier: Modifier::Size {
width: 20.0,
height: 30.0,
},
},
Mutation::SetModifier {
node_id: 1,
index: 7,
modifier: Modifier::Background(Paint::Literal(Color::argb(0xff11_2233))),
},
Mutation::SetModifier {
node_id: 1,
index: 8,
modifier: Modifier::Clickable { handler_id: 42 },
},
Mutation::SetModifier {
node_id: 1,
index: 9,
modifier: Modifier::Background(Paint::Role(ColorRole::Surface)),
},
Mutation::SetModifier {
node_id: 1,
index: 10,
modifier: Modifier::PaddingRole(SpaceRole::Md),
},
Mutation::SetModifier {
node_id: 1,
index: 11,
modifier: Modifier::PaddingEach {
start: 1.0,
top: 2.0,
end: 3.0,
bottom: 4.0,
},
},
Mutation::SetModifier {
node_id: 1,
index: 12,
modifier: Modifier::Weight(0.5),
},
Mutation::SetModifier {
node_id: 1,
index: 13,
modifier: Modifier::Shape {
top_start: 4.0,
top_end: 8.0,
bottom_end: 12.0,
bottom_start: 16.0,
},
},
Mutation::SetModifier {
node_id: 1,
index: 14,
modifier: Modifier::ShapeRole(ShapeRole::Large),
},
Mutation::SetModifier {
node_id: 1,
index: 15,
modifier: Modifier::Border {
width: 2.0,
paint: Paint::Role(ColorRole::Outline),
},
},
Mutation::SetModifier {
node_id: 1,
index: 16,
modifier: Modifier::Elevation(6.0),
},
// A size report with the flag off is the record it always was, the second word
// zero; with it on, the second word is one.
Mutation::SetModifier {
node_id: 1,
index: 17,
modifier: Modifier::ObserveSize {
token: 9,
every_dp: false,
},
},
Mutation::SetModifier {
node_id: 1,
index: 18,
modifier: Modifier::ObserveSize {
token: 9,
every_dp: true,
},
},
Mutation::Insert {
parent_id: 1,
node_id: 2,
index: 0,
},
Mutation::Move {
parent_id: 1,
node_id: 2,
index: 1,
},
Mutation::Remove { node_id: 3 },
Mutation::SetText {
node_id: 4,
text: "compose",
selection: Some(Selection { start: 1, end: 4 }),
},
Mutation::AppendText {
node_id: 4,
text: " token",
},
Mutation::Create {
node_id: 5,
widget: WidgetKind::Canvas,
},
// Every drawing command, so both sides decode the same fixed-length records and
// the same text region behind them.
Mutation::SetProp {
node_id: 5,
property: PropertyKind::Commands,
value: PropertyValue::Bytes(canvas_vector_bytes.as_bytes()),
},
// A chosen chip and the screen's one action, so both sides agree on the two tags
// and on the properties each of them carries.
Mutation::Create {
node_id: 6,
widget: WidgetKind::Chip,
},
Mutation::SetProp {
node_id: 6,
property: PropertyKind::Text,
value: PropertyValue::String("필터"),
},
Mutation::SetProp {
node_id: 6,
property: PropertyKind::Checked,
value: PropertyValue::Bool(true),
},
Mutation::SetProp {
node_id: 6,
property: PropertyKind::OnClick,
value: PropertyValue::Integer(101),
},
Mutation::Create {
node_id: 7,
widget: WidgetKind::FloatingAction,
},
Mutation::SetProp {
node_id: 7,
property: PropertyKind::Text,
value: PropertyValue::String("New"),
},
Mutation::SetProp {
node_id: 7,
property: PropertyKind::Icon,
value: PropertyValue::Integer(crate::schema::IconRole::Add as i64),
},
Mutation::SetProp {
node_id: 7,
property: PropertyKind::OnClick,
value: PropertyValue::Integer(102),
},
Mutation::RegisterAsset {
asset_id: 5,
kind: crate::schema::AssetKind::Png,
bytes: &[0x89, b'P', b'N', b'G'],
},
Mutation::ReleaseAsset { asset_id: 5 },
// A message with an action, so both sides agree on the one record that is not a
// node: two string references, a duration and a handler id.
Mutation::ShowMessage {
handler_id: 77,
text: "삭제했습니다",
action: "Undo",
duration: crate::schema::MessageDuration::Long,
placement: None,
offset_dp: None,
},
// And one that names where it goes: two placement tags and an offset after the
// fields every message has.
Mutation::ShowMessage {
handler_id: 0,
text: "복사했습니다",
action: "",
duration: crate::schema::MessageDuration::Short,
placement: Some(crate::schema::MessagePlacement {
vertical: crate::schema::MessageVertical::Bottom,
horizontal: crate::schema::MessageHorizontal::Center,
}),
offset_dp: Some(96.0),
},
// The three notification commands: six string references and two closed enums, one
// string reference, and a bare header that is the shortest record on the wire.
Mutation::PostNotification {
key: "session/7",
title: "세션이 끝났습니다",
body: "테스트 214개 통과",
channel: "세션",
action_1: "열기",
action_2: "",
importance: NotificationImportance::Urgent,
presentation: NotificationPresentation::WhenInactive,
},
Mutation::WithdrawNotification { key: "session/7" },
Mutation::RequestNotificationPermission,
// Text runs with a text colour and a background each, so both sides read the
// same 36 byte records.
Mutation::SetProp {
node_id: 2,
property: PropertyKind::Spans,
value: PropertyValue::Bytes(spans_vector_bytes.as_bytes()),
},
// A split pane's one property of its own.
Mutation::SetProp {
node_id: 2,
property: PropertyKind::Collapsible,
value: PropertyValue::Bool(true),
},
// A button's kind: a role tag in the fixed record, like the variant, so both sides
// agree on the property tag and on the value it carries.
Mutation::SetProp {
node_id: 2,
property: PropertyKind::ButtonKind,
value: PropertyValue::Integer(crate::schema::ButtonKind::ActionKey as i64),
},
// A box whose children sit where the Host put them, and the seven modifiers an HTML
// and CSS screen is drawn with. Two of them are longer than 28 bytes, which is the
// rule both decoders have to read the same way. They come after every older record,
// so the bytes of those are where they always were.
Mutation::Create {
node_id: 8,
widget: WidgetKind::AbsoluteBox,
},
Mutation::SetModifier {
node_id: 8,
index: 0,
modifier: Modifier::Offset { x: 12.5, y: -4.0 },
},
Mutation::SetModifier {
node_id: 8,
index: 1,
modifier: Modifier::RequiredSize {
width: 320.0,
height: 180.0,
},
},
Mutation::SetModifier {
node_id: 8,
index: 2,
modifier: Modifier::BorderEach {
top: 1.0,
right: 2.0,
bottom: 3.0,
left: 4.0,
top_paint: Paint::Literal(Color::argb(0xff11_2233)),
right_paint: Paint::Role(ColorRole::Outline),
bottom_paint: Paint::Literal(Color::argb(0x8044_5566)),
left_paint: Paint::Role(ColorRole::Primary),
},
},
Mutation::SetModifier {
node_id: 8,
index: 3,
modifier: Modifier::CornerEach {
top_left: 4.0,
top_right: 8.0,
bottom_right: 12.0,
bottom_left: 16.0,
},
},
Mutation::SetModifier {
node_id: 8,
index: 4,
modifier: Modifier::Shadow {
x: 0.0,
y: 2.0,
blur: 6.0,
spread: -1.0,
paint: Paint::Literal(Color::argb(0x4000_0000)),
},
},
Mutation::SetModifier {
node_id: 8,
index: 5,
modifier: Modifier::Clip(true),
},
Mutation::SetModifier {
node_id: 8,
index: 6,
modifier: Modifier::Alpha(0.5),
},
// A transform whose eight values are all different, so a value read from the
// wrong half of the wrong word cannot pass.
Mutation::SetModifier {
node_id: 8,
index: 7,
modifier: Modifier::Transform {
a: 0.75,
b: 0.5,
c: -0.25,
d: 1.25,
e: 12.0,
f: -6.0,
origin_x: 0.5,
origin_y: 0.25,
},
},
// Animations the Renderer plays itself: one for each property, a transform for
// each function kind and one of three functions, and a control record. Opacity and
// transform play on the box above, which has both; colour and background name node
// 2, which the vector never creates.
Mutation::StartAnimation(vector_animation(
8,
1,
AnimatedProperty::Alpha,
0,
[KeyframeValue::Alpha(0.0), KeyframeValue::Alpha(1.0)],
)),
Mutation::StartAnimation(vector_animation(
2,
2,
AnimatedProperty::Color,
0,
[
KeyframeValue::Paint(Paint::Role(ColorRole::Primary)),
KeyframeValue::Paint(Paint::Literal(Color::argb(0x8011_2233))),
],
)),
Mutation::StartAnimation(vector_animation(
2,
3,
AnimatedProperty::Background,
1,
[
KeyframeValue::Paint(Paint::Literal(Color::argb(0xff00_0000))),
KeyframeValue::Paint(Paint::Role(ColorRole::Surface)),
],
)),
Mutation::StartAnimation(vector_transform(4, 0, &VECTOR_TRANSLATE)),
Mutation::StartAnimation(vector_transform(5, 1, &VECTOR_ROTATE)),
Mutation::StartAnimation(vector_transform(6, 2, &VECTOR_SCALE)),
Mutation::StartAnimation(vector_transform(7, 3, &VECTOR_SKEW)),
Mutation::StartAnimation(vector_transform(8, 4, &VECTOR_MATRIX)),
Mutation::StartAnimation(vector_transform(9, 5, &VECTOR_THREE)),
Mutation::ControlAnimation {
node_id: 8,
animation_id: 1,
property: AnimatedProperty::Alpha,
slot: 0,
op: AnimationControl::Pause,
at_time_nanos: 1_500_000_000,
},
// The border colour, after every record that was here before it so their bytes
// stay where they were. Node 2 again, which the vector never creates.
Mutation::StartAnimation(vector_animation(
2,
10,
AnimatedProperty::BorderColor,
0,
[
KeyframeValue::Paint(Paint::Role(ColorRole::Outline)),
KeyframeValue::Paint(Paint::Literal(Color::argb(0xff33_6699))),
],
)),
// A code editor with both of its lists and one edit asked of it, so both sides
// read the decoration and colour run records, and the edit record, at the same
// offsets.
Mutation::Create {
node_id: 12,
widget: WidgetKind::CodeEditor,
},
Mutation::SetProp {
node_id: 12,
property: PropertyKind::Text,
value: PropertyValue::String(CODE_VECTOR_TEXT),
},
Mutation::SetProp {
node_id: 12,
property: PropertyKind::Decorations,
value: PropertyValue::Bytes(decorations.as_bytes()),
},
Mutation::SetProp {
node_id: 12,
property: PropertyKind::SyntaxSpans,
value: PropertyValue::Bytes(syntax_spans.as_bytes()),
},
Mutation::EditCode {
node_id: 12,
request_id: 7,
base_version: 0,
start_line: 1,
start_column: 8,
end_line: 1,
end_column: 8,
text: "mut ",
},
// The code editor's later additions, after every record that was here before them
// so their bytes stay where they were: the two lists, a selection made backwards,
// a range to reveal and a fold.
Mutation::SetProp {
node_id: 12,
property: PropertyKind::Folds,
value: PropertyValue::Bytes(folds.as_bytes()),
},
Mutation::SetProp {
node_id: 12,
property: PropertyKind::GutterDecorations,
value: PropertyValue::Bytes(gutter.as_bytes()),
},
Mutation::SetSelection {
node_id: 12,
base_version: 0,
anchor_line: 1,
anchor_column: 12,
active_line: 0,
active_column: 3,
},
Mutation::RevealRange {
node_id: 12,
base_version: 1,
start_line: 1,
start_column: 12,
end_line: 1,
end_column: 16,
align: crate::schema::RevealAlign::Center,
},
Mutation::SetFolded {
node_id: 12,
start_line: 0,
collapsed: true,
},
// The windows, after every record that was here before them so their
// bytes stay where they were: the window record in its multi-window form, a
// window with each of its properties and handlers, the two properties a node that
// is not a window can take, and the two commands.
Mutation::SetWindow(
crate::schema::Window::new()
.with_windows()
.with_last_window_closed(crate::schema::LastWindowClosed::KeepRunning)
.with_title("문서")
.with_icon(5)
.with_chrome(crate::schema::Chrome::System)
.with_size(800, 600)
.with_min_size(320, 240)
.resizable(false)
.with_zoom_level(-2)
.with_report_size(true),
),
Mutation::Create {
node_id: 20,
widget: WidgetKind::Window,
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::WindowTitle,
value: PropertyValue::String("보조 창"),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::WindowSize,
value: PropertyValue::Bytes(&window_size),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::WindowMinSize,
value: PropertyValue::Bytes(&window_min_size),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::WindowResizable,
value: PropertyValue::Bool(false),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::WindowChrome,
value: PropertyValue::Integer(i64::from(crate::schema::Chrome::System as u16)),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::WindowTitleBar,
value: PropertyValue::Integer(i64::from(crate::schema::TitleBar::Simple as u16)),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::WindowIcon,
value: PropertyValue::Integer(5),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::WindowPosition,
value: PropertyValue::Bytes(&window_position),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::WindowRestoreKey,
value: PropertyValue::String("ws/1:2"),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::WindowZoomLevel,
value: PropertyValue::Integer(-2),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::DragFromPointer,
value: PropertyValue::Bytes(&drag_from_pointer),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::OnWindowCloseRequested,
value: PropertyValue::Integer(201),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::OnWindowFocusChanged,
value: PropertyValue::Integer(202),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::OnWindowMoved,
value: PropertyValue::Integer(203),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::OnWindowDrag,
value: PropertyValue::Integer(204),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::OnWindowUnavailable,
value: PropertyValue::Integer(205),
},
Mutation::SetProp {
node_id: 20,
property: PropertyKind::OnWindowClosed,
value: PropertyValue::Integer(206),
},
Mutation::Insert {
parent_id: 0,
node_id: 20,
index: 1,
},
Mutation::SetProp {
node_id: 1,
property: PropertyKind::OnWindowDragOver,
value: PropertyValue::Integer(207),
},
Mutation::SetProp {
node_id: 1,
property: PropertyKind::TearOffKey,
value: PropertyValue::String("tab/3"),
},
Mutation::SetWindowTheme {
node_id: 20,
theme: Theme::unified(DesignSystem::Material3).with_color_scheme(ColorScheme::Dark),
},
Mutation::FocusWindow { node_id: 20 },
Mutation::SetModifier {
node_id: 8,
index: 8,
modifier: Modifier::MatchParentSize,
},
Mutation::RequestFocus { node_id: 1 },
// A dialog on the implicit root window, with every string filled and a list of two
// filters in the one NUL separated string.
Mutation::ShowFileDialog {
request: 7,
window: 0,
kind: crate::schema::FileDialogKind::OpenFiles,
default_filter: 1,
title: "파일 고르기",
directory: "/home/한글",
name: "보고서.txt",
filters: "이미지\0png,jpg\0문서\0pdf,txt",
},
// Plain text for the platform clipboard.
Mutation::SetClipboardText {
text: "초대 링크"
},
// A clipboard read, answered by the ClipboardText event in the event vector.
Mutation::ReadClipboard { request: 9 },
// A storage write for the Renderer to carry out, answered by the IoAnswer event in
// the event vector. The value holds a NUL and Hangul, which a string could not.
Mutation::StorageCall {
request: 11,
op: crate::schema::StorageOp::Write,
store: "dev.darkpyonix.composerust.samples.todo",
key: "tasks.tsv",
data: "1\t0\t할 일\0".as_bytes(),
},
// A write to a file the Renderer holds handle 3 for, with bytes that are not text.
Mutation::FileCall {
request: 0x8000_0011,
op: crate::schema::FileOp::Write,
create: false,
handle: 3,
name: "",
data: &[0x00, 0xff, 0x7f, 0x80],
},
// The child of a folder by a Korean name, made when it is not there.
Mutation::FileCall {
request: 0x8000_0012,
op: crate::schema::FileOp::Child,
create: true,
handle: 4,
name: "새 문서.txt",
data: &[],
},
Mutation::ReleaseFileHandle { handle: 3 },
// The two scroll requests: an animated jump along y measured from item 3 of a lazy
// list, and a descendant node brought to the nearest edge.
Mutation::ScrollTo {
node_id: 10,
item: 3,
flags: crate::schema::scroll_to_flags::ANIMATE | crate::schema::scroll_to_flags::Y,
x_px: 0.0,
y_px: 120.5,
},
Mutation::ScrollIntoView {
node_id: 10,
target: 12,
target_kind: crate::schema::scroll_target_kind::NODE,
align_x: crate::schema::ScrollAlign::Keep as u16,
align_y: crate::schema::ScrollAlign::Nearest as u16,
flags: crate::schema::scroll_into_view_flags::ANIMATE,
rect: crate::schema::Rect::new(0.0, 8.0, 40.0, 24.5),
},
// A wrapping row with every one of its layout properties, appended after every
// older record so none of them moves.
Mutation::Create {
node_id: 21,
widget: WidgetKind::FlowRow,
},
Mutation::SetProp {
node_id: 21,
property: PropertyKind::HorizontalSpacing,
value: PropertyValue::Float(8.0),
},
Mutation::SetProp {
node_id: 21,
property: PropertyKind::VerticalSpacing,
value: PropertyValue::Float(12.0),
},
Mutation::SetProp {
node_id: 21,
property: PropertyKind::HorizontalAlignment,
value: PropertyValue::Integer(i64::from(
crate::schema::HorizontalAlignment::Center as u16,
)),
},
Mutation::SetProp {
node_id: 21,
property: PropertyKind::VerticalAlignment,
value: PropertyValue::Integer(i64::from(
crate::schema::VerticalAlignment::Bottom as u16,
)),
},
Mutation::SetProp {
node_id: 21,
property: PropertyKind::MaxItemsInEachRow,
value: PropertyValue::Integer(3),
},
// The code editor's scroll command, after everything that was here before it. The
// offset has a fraction so that a reader of the wrong width cannot pass.
Mutation::SetScrollOffset {
node_id: 12,
offset_px: 1234.5,
},
// The width a split pane stacks below, with a fraction so that a value read from
// the wrong half of the record cannot pass.
Mutation::SetProp {
node_id: 2,
property: PropertyKind::CollapseBelow,
value: PropertyValue::Float(720.5),
},
// The two physical text alignments, which do not swap in right-to-left text.
Mutation::SetProp {
node_id: 2,
property: PropertyKind::TextAlign,
value: PropertyValue::Integer(crate::schema::TextAlign::Left as i64),
},
Mutation::SetProp {
node_id: 2,
property: PropertyKind::TextAlign,
value: PropertyValue::Integer(crate::schema::TextAlign::Right as i64),
},
// A question about where a place on the editor's second line is, after its scroll
// command.
Mutation::QueryPositionRect {
node_id: 12,
request: 17,
line: 1,
column: 8,
},
// The overlay tokens with every field set to its own value, the transient
// message's two at the end of the record, before the record that stays last.
Mutation::SetOverlayTokens(
crate::schema::OverlayTokens::new()
.sheet_corner_radius(24)
.dialog_corner_radius(16)
.popup_corner_radius(12)
.sheet_elevation(8)
.popup_elevation(4)
.dialog_elevation(6)
.sheet_padding(20)
.dialog_padding(18)
.popup_padding(10)
.scrim_argb(0x8000_0000)
.toast_elevation(7)
.toast_corner_radius(14),
),
// A text with three font features, one of them a value above one byte, after
// every older record but the last.
Mutation::Create {
node_id: 22,
widget: WidgetKind::Text,
},
Mutation::SetProp {
node_id: 22,
property: PropertyKind::FontFeatureSettings,
value: PropertyValue::Bytes(&font_features),
},
// The code editor's grouped edit and the handler it answers, before the record
// that stays last: the first word of the document and the emoji, written against
// the version the single edit above produced, so a reader that takes a pair of
// UTF-16 units for one character, or counts text offsets from the wrong place,
// reads a different group.
Mutation::SetProp {
node_id: 12,
property: PropertyKind::OnEditGroupResult,
value: PropertyValue::Integer(32),
},
Mutation::EditCodeGroup {
node_id: 12,
request_id: 8,
base_version: 1,
edits: &edit_group,
},
// The editor's minimap, on the right.
Mutation::SetProp {
node_id: 12,
property: PropertyKind::Minimap,
value: PropertyValue::Integer(i64::from(u16::from(crate::schema::MinimapSide::Right))),
},
// Three selections of the editor, the second made backwards, so a reader that takes
// the anchor for the active end or reads a record of the wrong length sees others.
Mutation::SetSelections {
node_id: 12,
base_version: 1,
selections: &code_selections,
},
// A snippet over the editor's closing brace, with a placeholder, a mirror of it, a
// choice, an escaped dollar sign and a final stop, so a reader that drops a byte of
// the text or reads the range from the wrong place reads another snippet.
Mutation::InsertSnippet {
node_id: 12,
base_version: 3,
start_line: 2,
start_column: 0,
end_line: 2,
end_column: 1,
snippet: CODE_SNIPPET_VECTOR,
},
// Its word wrap: at forty columns or the edge of the view, whichever comes first, so a
// reader that reads the mode and the columns from the wrong bits reads another rule.
Mutation::SetProp {
node_id: 12,
property: PropertyKind::WordWrap,
value: PropertyValue::Integer(crate::code::WordWrap::Bounded(40).to_value()),
},
// Its view zones: two rows after the first line with text in them, and a half-row
// after the second with none, so a reader that takes the height for a whole number
// or reads the text from the wrong place reads different zones.
Mutation::SetProp {
node_id: 12,
property: PropertyKind::ViewZones,
value: PropertyValue::Bytes(view_zones.as_bytes()),
},
// Last, so every byte before it is where it was.
Mutation::SetModifier {
node_id: 8,
index: 9,
modifier: Modifier::CornerCurve { smoothing: 0.6 },
},
];
let mut encoder = BatchEncoder::default();
for mutation in &mutations {
encoder.encode(mutation)?;
}
Ok(encoder.finish()?.to_vec())
}
/// The matrix the 3D transform vector carries: sixteen different values, so a value read
/// from the wrong half of the wrong word cannot pass.
pub const TRANSFORM_3D_VECTOR_MATRIX: [f32; 16] = [
0.5, -0.25, 1.5, 0.125, -2.0, 3.0, 0.75, -0.5, 4.0, -1.25, 2.5, -0.0625, 12.0, -6.0, 8.0, 1.0,
];
/// One batch holding one `Transform3D` on node 3, the only record 92 bytes long. It is a
/// file of its own so that every byte of the main mutation vector stays where it was.
pub fn generate_transform_3d_vector() -> Result<Vec<u8>, ProtocolError> {
let mut encoder = BatchEncoder::default();
encoder.encode(&Mutation::SetModifier {
node_id: 3,
index: 0,
modifier: Modifier::Transform3D {
m: TRANSFORM_3D_VECTOR_MATRIX,
origin_x: 0.5,
origin_y: 0.25,
backface_hidden: true,
},
})?;
Ok(encoder.finish()?.to_vec())
}
/// One batch holding one `BackgroundBrush` on node 4, the only record 52 bytes long. It is a
/// file of its own, as the 3D transform is, so that every byte of the main mutation vector
/// stays where it was. Every field is a different value, so a field read from the wrong
/// half of the wrong word cannot pass.
pub fn generate_background_brush_vector() -> Result<Vec<u8>, ProtocolError> {
let mut encoder = BatchEncoder::default();
encoder.encode(&Mutation::SetModifier {
node_id: 4,
index: 2,
modifier: Modifier::BackgroundBrush {
x: 12.5,
y: -4.0,
width: 48.0,
height: 24.0,
paint: Paint::Asset(9),
repeat: crate::schema::BackgroundRepeat::RepeatX,
tile_width: 56.0,
tile_height: 30.0,
},
})?;
Ok(encoder.finish()?.to_vec())
}
pub fn generate_event_vector() -> Result<Vec<u8>, ProtocolError> {
let selections = code_selections_vector();
let events = [
HostEvent {
node_id: 7,
handler_id: 11,
payload: EventPayload::Clicked,
},
HostEvent {
node_id: 8,
handler_id: 12,
payload: EventPayload::TextChanged("한글"),
},
HostEvent {
node_id: 8,
handler_id: 13,
payload: EventPayload::TextSubmitted("done"),
},
HostEvent {
node_id: 8,
handler_id: 14,
payload: EventPayload::FocusLost,
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::ProtocolError {
code: 9,
message: "bad tag",
},
},
HostEvent {
node_id: 9,
handler_id: 15,
payload: EventPayload::KeyDown {
key: Key::Enter,
shift_key: true,
ctrl_key: true,
alt_key: true,
meta_key: true,
repeat: true,
code: 0x28,
text: "Enter",
},
},
HostEvent {
node_id: 10,
handler_id: 16,
payload: EventPayload::RangeRequested {
start: 100,
count: 20,
},
},
HostEvent {
node_id: 11,
handler_id: 17,
payload: EventPayload::ValueChanged(-19_723.5),
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::WindowSizeChanged {
width_dp: 840.0,
height_dp: 600.0,
class: crate::schema::WindowSizeClass::Expanded,
height_class: crate::schema::WindowHeightClass::Medium,
safe_area_top: 0.0,
safe_area_leading: 0.0,
safe_area_trailing: 0.0,
},
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::NotificationActivated {
action: 1,
key: "session/7",
},
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::NotificationPermissionChanged(NotificationPermission::Denied),
},
HostEvent {
node_id: 12,
handler_id: 18,
payload: EventPayload::CodeChanged {
version: 1,
start_line: 1,
start_column: 8,
end_line: 1,
end_column: 8,
text: "mut ",
},
},
HostEvent {
node_id: 12,
handler_id: 19,
payload: EventPayload::CodeEditRejected {
request_id: 7,
base_version: 0,
current_version: 2,
start_line: 1,
start_column: 8,
end_line: 1,
end_column: 9,
},
},
HostEvent {
node_id: 12,
handler_id: 20,
payload: EventPayload::CodeHovered {
decoration: 42,
line: 0,
column: 4,
phase: crate::schema::HoverPhase::Rest,
},
},
HostEvent {
node_id: 12,
handler_id: 21,
payload: EventPayload::CodeSaveRequested { version: 2 },
},
HostEvent {
node_id: 12,
handler_id: 22,
payload: EventPayload::DecorationActivated { decoration: 41 },
},
HostEvent {
node_id: 8,
handler_id: 0,
payload: EventPayload::AnimationEvent {
animation_id: 7,
kind: crate::schema::AnimationEventKind::End,
property: AnimatedProperty::Transform,
slot: 2,
iteration: 3,
elapsed_ms: 3000.0,
time_nanos: 123_456_789_012,
},
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::ReducedMotionChanged(crate::schema::ReducedMotion::On),
},
HostEvent {
node_id: 13,
handler_id: 23,
payload: EventPayload::Pointer {
kind: crate::schema::PointerKind::Down,
pointer_id: 1,
pointer_type: crate::schema::PointerType::Mouse,
x: 12.5,
y: -3.0,
buttons: 9,
button: 8,
modifiers: 5,
click_count: 2,
delta_x: 0.0,
delta_y: 0.0,
delta_mode: crate::schema::WheelDeltaMode::Pixel,
timestamp_nanos: 987_654_321_000,
},
},
HostEvent {
node_id: 12,
handler_id: 23,
payload: EventPayload::SelectionChanged {
version: 2,
anchor_line: 1,
anchor_column: 12,
active_line: 0,
active_column: 3,
},
},
HostEvent {
node_id: 12,
handler_id: 24,
payload: EventPayload::VisibleRangeChanged {
version: 2,
first_line: 0,
last_line: 3,
},
},
HostEvent {
node_id: 12,
handler_id: 25,
payload: EventPayload::EditorFocusChanged { focused: true },
},
HostEvent {
node_id: 12,
handler_id: 26,
payload: EventPayload::FoldChanged {
start_line: 0,
collapsed: true,
},
},
HostEvent {
node_id: 12,
handler_id: 27,
payload: EventPayload::CompositionChanged { composing: true },
},
// The windows, after every event that was here before them.
HostEvent {
node_id: 20,
handler_id: 201,
payload: EventPayload::WindowCloseRequested,
},
HostEvent {
node_id: 20,
handler_id: 202,
payload: EventPayload::WindowFocusChanged { focused: true },
},
HostEvent {
node_id: 20,
handler_id: 203,
payload: EventPayload::WindowMoved {
x: 100.5,
y: -20.0,
width: 800.0,
height: 600.0,
},
},
HostEvent {
node_id: 20,
handler_id: 204,
payload: EventPayload::WindowDrag {
phase: 2,
screen_x: 640.25,
screen_y: 360.5,
over_window: 21,
},
},
HostEvent {
node_id: 1,
handler_id: 207,
payload: EventPayload::WindowDragOver {
kind: 4,
window: 20,
x: 12.5,
y: 3.0,
},
},
HostEvent {
node_id: 20,
handler_id: 205,
payload: EventPayload::WindowUnavailable,
},
HostEvent {
node_id: 20,
handler_id: 206,
payload: EventPayload::WindowClosed,
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::WindowRequested {
key: "ws/1:2",
request: 3,
},
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::ApplicationReopen,
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::FileDialogResult {
request: 7,
status: crate::schema::FileDialogStatus::Chosen,
filter: 1,
paths: "/Users/한글/문서.txt\0/tmp/a b.png",
},
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::ClipboardText {
request: 9,
status: crate::clipboard::read_status::TEXT,
len: "한글\n줄 🙂".len() as u32,
text: "한글\n줄 🙂",
},
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::IoAnswer {
request: 11,
status: crate::schema::IoStatus::Ok,
data: &[0xea, 0xb0, 0x92, 0x00, 0xff],
},
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::IoAnswer {
request: 0x8000_0011,
status: crate::schema::IoStatus::Ok,
data: &[0x00, 0xff, 0x7f, 0x80],
},
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::FileHandles {
request: 7,
status: crate::schema::FileDialogStatus::Chosen,
filter: 1,
delivery: crate::schema::FileDelivery::Handle,
first_handle: 3,
names: "문서.txt\0사진",
kinds: "fd",
},
},
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::StorageLocation(
"/data/user/0/dev.darkpyonix.composerust.samples.todo/files",
),
},
HostEvent {
node_id: 10,
handler_id: 21,
payload: EventPayload::ScrollChanged {
item: 3,
settled: true,
can_scroll_backward: true,
can_scroll_forward: false,
x_px: 0.0,
y_px: 700.5,
max_x_px: 0.0,
max_y_px: -1.0,
viewport_width_px: 320.0,
viewport_height_px: 300.0,
},
},
HostEvent {
node_id: 12,
handler_id: 28,
payload: EventPayload::CodeMetrics {
line_height_px: 40.0,
},
},
HostEvent {
node_id: 12,
handler_id: 29,
payload: EventPayload::CodeScrolled { offset_px: 1234.5 },
},
// A node's size motion settled, after everything that was here before.
HostEvent {
node_id: 14,
handler_id: 30,
payload: EventPayload::MotionFinished {
width_dp: 240.5,
height_dp: 0.0,
},
},
// The caret's rectangle and the answer to the position query in the mutation
// vector, each with fractions a reader of the wrong width cannot pass.
HostEvent {
node_id: 12,
handler_id: 30,
payload: EventPayload::CaretRect {
line: 1,
column: 8,
rect: crate::code::CodeRect::new(120.5, 64.25, 2.0, 20.0),
},
},
HostEvent {
node_id: 12,
handler_id: 0,
payload: EventPayload::PositionRect {
request: 17,
rect: Some(crate::code::CodeRect::new(88.75, 64.25, 2.0, 20.0)),
},
},
// A Cmd-click over the emoji's column on the editor's second line.
HostEvent {
node_id: 12,
handler_id: 31,
payload: EventPayload::CodePointer {
kind: crate::schema::PointerKind::Down,
pointer_id: 1,
pointer_type: crate::schema::PointerType::Mouse,
x: 96.5,
y: 30.25,
buttons: 1,
button: 1,
modifiers: 8,
click_count: 1,
delta_x: 0.0,
delta_y: 0.0,
delta_mode: crate::schema::WheelDeltaMode::Pixel,
timestamp_nanos: 123_456_789_000,
position: Some(crate::code::Position::new(1, 13)),
},
},
// What became of the grouped edit in the mutation vector: both of its edits went
// in, so the version moved two past the one it was written against.
HostEvent {
node_id: 12,
handler_id: 32,
payload: EventPayload::CodeEditGroupResult {
request_id: 8,
status: crate::schema::EditGroupStatus::Applied,
base_version: 1,
current_version: 3,
index: 2,
},
},
// The system appearance turning dark, addressed to the Host.
HostEvent {
node_id: 0,
handler_id: 0,
payload: EventPayload::ColorSchemeChanged(crate::schema::SystemColorScheme::Dark),
},
// Every selection of the editor the mutation vector set, a caret and a selection made
// backwards, to its selection listener.
HostEvent {
node_id: 12,
handler_id: 33,
payload: EventPayload::SelectionsChanged {
version: 4,
selections: &selections,
},
},
];
let mut output = Vec::new();
let mut encoded = Vec::new();
for event in &events {
encode_event(event, &mut encoded)?;
output.extend_from_slice(&encoded);
}
Ok(output)
}
pub fn generate_vector_description() -> String {
format!(
r#"{{
"format": "compose-rust protocol vectors v1",
"schemaHashUnsigned": "{SCHEMA_HASH}",
"byteOrder": "little-endian",
"mutations": {{
"file": "mutations.bin",
"description": "One batch covering every record, property value, modifier layout, drawing command, asset, message, notification command, palette entry, text run, split pane property, the HTML and CSS drawing elements, the animations the Renderer plays and code editor record",
"recordCount": 129,
"palette": [
{{ "role": "Primary", "scheme": "Light", "argb": "ffe8590c" }},
{{ "role": "Primary", "scheme": "Dark", "argb": "ffff8a4c" }},
{{ "role": "SyntaxKeyword", "scheme": "Light", "argb": "80112233" }}
],
"spanRecordLength": 36,
"strings": ["안녕", "compose", " token", "필터", "New", "삭제했습니다", "Undo", "session/7", "세션이 끝났습니다", "테스트 214개 통과", "세션", "열기", "", "session/7", "fn main() {{\n let 한 = \"😀\";\n}}\n", "mut ", "문서", "보조 창", "ws/1:2", "tab/3", "파일 고르기", "/home/한글", "보고서.txt", "이미지\u0000png,jpg\u0000문서\u0000pdf,txt", "초대 링크", "dev.darkpyonix.composerust.samples.todo", "tasks.tsv", "", "새 문서.txt"],
"assets": [{{ "assetId": 5, "kind": "Png", "bytes": "89504e47" }}]
}},
"transform3d": {{
"file": "transform3d.bin",
"description": "One batch with one 92 byte Transform3D modifier on node 3: the column-major matrix, the origin (0.5, 0.25) and backface-visibility hidden",
"recordCount": 1,
"length": 104,
"matrix": [0.5, -0.25, 1.5, 0.125, -2.0, 3.0, 0.75, -0.5, 4.0, -1.25, 2.5, -0.0625, 12.0, -6.0, 8.0, 1.0],
"originX": 0.5,
"originY": 0.25,
"backfaceHidden": true
}},
"backgroundBrush": {{
"file": "background_brush.bin",
"description": "One batch with one 52 byte BackgroundBrush modifier on node 4 at chain position 2: the rectangle (12.5, -4, 48, 24), the brush asset 9, RepeatX and the step (56, 30)",
"recordCount": 1,
"x": 12.5,
"y": -4.0,
"width": 48.0,
"height": 24.0,
"paintAsset": 9,
"repeat": "RepeatX",
"tileWidth": 56.0,
"tileHeight": 30.0
}},
"events": {{
"file": "events.bin",
"description": "Forty-nine independently decodable event records concatenated in schema order",
"records": [
{{ "type": "Clicked", "offset": 0, "length": 16, "nodeId": 7, "handlerId": 11 }},
{{ "type": "TextChanged", "offset": 16, "length": 30, "nodeId": 8, "handlerId": 12, "text": "한글" }},
{{ "type": "TextSubmitted", "offset": 46, "length": 28, "nodeId": 8, "handlerId": 13, "text": "done" }},
{{ "type": "FocusLost", "offset": 74, "length": 16, "nodeId": 8, "handlerId": 14 }},
{{ "type": "ProtocolError", "offset": 90, "length": 35, "nodeId": 0, "handlerId": 0, "code": 9, "message": "bad tag" }},
{{ "type": "KeyDown", "offset": 125, "length": 37, "nodeId": 9, "handlerId": 15, "key": "Enter", "shiftKey": true, "ctrlKey": true, "altKey": true, "metaKey": true, "repeat": true, "code": 40, "text": "Enter" }},
{{ "type": "RangeRequested", "offset": 162, "length": 24, "nodeId": 10, "handlerId": 16, "start": 100, "count": 20 }},
{{ "type": "ValueChanged", "offset": 186, "length": 24, "nodeId": 11, "handlerId": 17, "value": -19723.5 }},
{{ "type": "WindowSizeChanged", "offset": 210, "length": 44, "nodeId": 0, "handlerId": 0, "widthDp": 840.0, "heightDp": 600.0, "sizeClass": "Expanded", "heightClass": "Medium", "safeAreaTop": 0.0, "safeAreaLeading": 0.0, "safeAreaTrailing": 0.0 }},
{{ "type": "NotificationActivated", "offset": 254, "length": 37, "nodeId": 0, "handlerId": 0, "action": 1, "key": "session/7" }},
{{ "type": "NotificationPermissionChanged", "offset": 291, "length": 20, "nodeId": 0, "handlerId": 0, "state": "Denied" }},
{{ "type": "CodeChanged", "offset": 311, "length": 48, "nodeId": 12, "handlerId": 18, "version": 1, "startLine": 1, "startColumn": 8, "endLine": 1, "endColumn": 8, "text": "mut " }},
{{ "type": "CodeEditRejected", "offset": 359, "length": 44, "nodeId": 12, "handlerId": 19, "requestId": 7, "baseVersion": 0, "currentVersion": 2, "startLine": 1, "startColumn": 8, "endLine": 1, "endColumn": 9 }},
{{ "type": "CodeHovered", "offset": 403, "length": 36, "nodeId": 12, "handlerId": 20, "decoration": 42, "line": 0, "column": 4, "phase": "Rest" }},
{{ "type": "CodeSaveRequested", "offset": 439, "length": 24, "nodeId": 12, "handlerId": 21, "version": 2 }},
{{ "type": "DecorationActivated", "offset": 463, "length": 24, "nodeId": 12, "handlerId": 22, "decoration": 41 }},
{{ "type": "AnimationEvent", "offset": 487, "length": 40, "nodeId": 8, "handlerId": 0, "animationId": 7, "kind": "End", "property": "Transform", "slot": 2, "iteration": 3, "elapsedMs": 3000.0, "timeNanos": 123456789012 }},
{{ "type": "ReducedMotionChanged", "offset": 527, "length": 20, "nodeId": 0, "handlerId": 0, "state": "On" }},
{{ "type": "Pointer", "offset": 547, "length": 72, "nodeId": 13, "handlerId": 23, "kind": "Down", "pointerId": 1, "pointerType": "Mouse", "x": 12.5, "y": -3.0, "buttons": 9, "button": 8, "modifiers": 5, "clickCount": 2, "deltaX": 0.0, "deltaY": 0.0, "deltaMode": "Pixel", "timestampNanos": 987654321000 }},
{{ "type": "SelectionChanged", "offset": 619, "length": 36, "nodeId": 12, "handlerId": 23, "version": 2, "anchorLine": 1, "anchorColumn": 12, "activeLine": 0, "activeColumn": 3 }},
{{ "type": "VisibleRangeChanged", "offset": 655, "length": 28, "nodeId": 12, "handlerId": 24, "version": 2, "firstLine": 0, "lastLine": 3 }},
{{ "type": "EditorFocusChanged", "offset": 683, "length": 24, "nodeId": 12, "handlerId": 25, "focused": true }},
{{ "type": "FoldChanged", "offset": 707, "length": 24, "nodeId": 12, "handlerId": 26, "startLine": 0, "collapsed": true }},
{{ "type": "CompositionChanged", "offset": 731, "length": 24, "nodeId": 12, "handlerId": 27, "composing": true }},
{{ "type": "WindowCloseRequested", "offset": 755, "length": 16, "nodeId": 20, "handlerId": 201 }},
{{ "type": "WindowFocusChanged", "offset": 771, "length": 20, "nodeId": 20, "handlerId": 202, "focused": true }},
{{ "type": "WindowMoved", "offset": 791, "length": 32, "nodeId": 20, "handlerId": 203, "x": 100.5, "y": -20.0, "width": 800.0, "height": 600.0 }},
{{ "type": "WindowDrag", "offset": 823, "length": 32, "nodeId": 20, "handlerId": 204, "phase": 2, "screenX": 640.25, "screenY": 360.5, "overWindow": 21 }},
{{ "type": "WindowDragOver", "offset": 855, "length": 32, "nodeId": 1, "handlerId": 207, "kind": 4, "window": 20, "x": 12.5, "y": 3.0 }},
{{ "type": "WindowUnavailable", "offset": 887, "length": 16, "nodeId": 20, "handlerId": 205 }},
{{ "type": "WindowClosed", "offset": 903, "length": 16, "nodeId": 20, "handlerId": 206 }},
{{ "type": "WindowRequested", "offset": 919, "length": 34, "nodeId": 0, "handlerId": 0, "request": 3, "key": "ws/1:2" }},
{{ "type": "ApplicationReopen", "offset": 953, "length": 16, "nodeId": 0, "handlerId": 0 }},
{{ "type": "FileDialogResult", "offset": 969, "length": 73, "nodeId": 0, "handlerId": 0, "request": 7, "status": "Chosen", "filter": 1, "paths": "/Users/한글/문서.txt\u0000/tmp/a b.png" }},
{{ "type": "ClipboardText", "offset": 1042, "length": 51, "nodeId": 0, "handlerId": 0, "request": 9, "status": 1, "textLength": 15, "text": "한글\n줄 🙂" }},
{{ "type": "IoAnswer", "offset": 1093, "length": 37, "nodeId": 0, "handlerId": 0, "request": 11, "status": "Ok", "data": "eab09200ff" }},
{{ "type": "IoAnswer", "offset": 1130, "length": 36, "nodeId": 0, "handlerId": 0, "request": 2147483665, "status": "Ok", "data": "00ff7f80" }},
{{ "type": "FileHandles", "offset": 1166, "length": 71, "nodeId": 0, "handlerId": 0, "request": 7, "status": "Chosen", "filter": 1, "delivery": "Handle", "firstHandle": 3, "names": "문서.txt\u0000사진", "kinds": "fd" }},
{{ "type": "StorageLocation", "offset": 1237, "length": 82, "nodeId": 0, "handlerId": 0, "text": "/data/user/0/dev.darkpyonix.composerust.samples.todo/files" }},
{{ "type": "ScrollChanged", "offset": 1319, "length": 72, "nodeId": 10, "handlerId": 21, "item": 3, "flags": 3, "xPx": 0.0, "yPx": 700.5, "maxXPx": 0.0, "maxYPx": -1.0, "viewportWidthPx": 320.0, "viewportHeightPx": 300.0 }},
{{ "type": "CodeMetrics", "offset": 1391, "length": 24, "nodeId": 12, "handlerId": 28, "value": 40.0 }},
{{ "type": "CodeScrolled", "offset": 1415, "length": 24, "nodeId": 12, "handlerId": 29, "value": 1234.5 }},
{{ "type": "MotionFinished", "offset": 1439, "length": 24, "nodeId": 14, "handlerId": 30, "widthDp": 240.5, "heightDp": 0.0 }},
{{ "type": "CaretRect", "offset": 1463, "length": 40, "nodeId": 12, "handlerId": 30, "line": 1, "column": 8, "x": 120.5, "y": 64.25, "width": 2.0, "height": 20.0 }},
{{ "type": "PositionRect", "offset": 1503, "length": 40, "nodeId": 12, "handlerId": 0, "request": 17, "found": true, "x": 88.75, "y": 64.25, "width": 2.0, "height": 20.0 }},
{{ "type": "CodePointer", "offset": 1543, "length": 80, "nodeId": 12, "handlerId": 31, "kind": "Down", "pointerId": 1, "pointerType": "Mouse", "x": 96.5, "y": 30.25, "buttons": 1, "button": 1, "modifiers": 8, "clickCount": 1, "deltaX": 0.0, "deltaY": 0.0, "deltaMode": "Pixel", "timestampNanos": 123456789000, "line": 1, "column": 13 }},
{{ "type": "CodeEditGroupResult", "offset": 1623, "length": 36, "nodeId": 12, "handlerId": 32, "requestId": 8, "status": "Applied", "baseVersion": 1, "currentVersion": 3, "index": 2 }},
{{ "type": "ColorSchemeChanged", "offset": 1659, "length": 20, "nodeId": 0, "handlerId": 0, "scheme": "Dark" }},
{{ "type": "SelectionsChanged", "offset": 1679, "length": 76, "nodeId": 12, "handlerId": 33, "version": 4, "selections": [[0, 3, 0, 7], [1, 12, 1, 8], [2, 0, 2, 0]] }}
]
}}
}}
"#
)
}
fn write_enum(output: &mut String, name: &str, variants: &[crate::schema::EnumVariantSchema]) {
write!(output, "enum class {name} {{ ").unwrap();
for (index, variant) in variants.iter().enumerate() {
if index != 0 {
output.push_str(", ");
}
output.push_str(variant.name);
}
output.push_str(" }\n\n");
}
/// Role types are package-qualified: `Modifier.ShapeRole` would otherwise shadow the
/// `ShapeRole` enum inside its own declaration.
fn kotlin_type(ty: FieldType) -> String {
match ty {
FieldType::Float => "kotlin.Float".to_owned(),
FieldType::U32 => "Int".to_owned(),
FieldType::U64 => "Long".to_owned(),
FieldType::Paint => "Paint".to_owned(),
FieldType::Role(name) => format!("{KOTLIN_PACKAGE}.{name}"),
FieldType::Bool => "Boolean".to_owned(),
FieldType::FiniteFloat => "kotlin.Float".to_owned(),
}
}
/// The Kotlin expression for the `u64` word a field lives in, and whether it occupies the
/// high 32 bits. The first two words are read for every modifier; a word past them is read
/// only by the modifier that has it.
fn slot_word(slot: FieldSlot) -> (String, bool) {
let (index, high) = slot.word();
let word = match index {
0 => "first".to_owned(),
1 => "second".to_owned(),
_ => format!("readU64(batch, base, available, at + {})", 8 * index),
};
(word, high)
}
fn modifier_decode_expression(field: &FieldSchema) -> String {
let (word, high) = slot_word(field.slot);
let narrow = if high {
format!("({word} ushr 32).toInt()")
} else {
format!("{word}.toInt()")
};
match field.ty {
FieldType::Float => format!("kotlin.Float.fromBits({narrow})"),
FieldType::U32 => narrow,
FieldType::U64 => word,
FieldType::Paint => format!("paint({word}, offset)"),
FieldType::Role(name) => format!("{}({narrow}, offset)", lower_camel(name)),
FieldType::Bool => format!("flag({word}, offset)"),
FieldType::FiniteFloat => format!("finite(kotlin.Float.fromBits({narrow}), offset)"),
}
}
fn lower_camel(name: &str) -> String {
let mut characters = name.chars();
match characters.next() {
Some(first) => first.to_lowercase().chain(characters).collect(),
None => String::new(),
}
}
/// The drawing command vocabulary, mirrored into Kotlin with a decoder for the byte blob a
/// `Canvas` node carries.
fn write_draw_commands(output: &mut String) {
use crate::drawing::{COMMAND_LEN, DRAW_COMMAND_SCHEMA, DrawFieldType};
output.push_str(
"/**\n * One drawing command. Coordinates are dp from the Canvas's top-left corner.\n *\n \
* Colour is a [Paint], so a command may name a ColorRole and the design system\n \
* decides what it looks like.\n */\n",
);
output.push_str("sealed interface DrawCommand {\n");
output.push_str(" val paint: Paint\n\n");
for command in DRAW_COMMAND_SCHEMA {
write!(
output,
" data class {}(override val paint: Paint",
command.name
)
.unwrap();
for field in command.fields {
let ty = match field.ty {
DrawFieldType::Float => "kotlin.Float",
DrawFieldType::U32 => "Int",
DrawFieldType::Role(name) => name,
};
write!(output, ", val {}: {ty}", field.name).unwrap();
}
output.push_str(") : DrawCommand\n");
}
output.push_str("}\n\n");
output.push_str(
r#"/** Decodes a Canvas command list: fixed-size records, then the TextAt strings. */
object DrawCommands {
"#,
);
writeln!(output, " const val COMMAND_LENGTH = {COMMAND_LEN}\n").unwrap();
output.push_str(
r#" fun decode(bytes: ByteArray): List<DrawCommand> {
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
val commands = ArrayList<DrawCommand>(bytes.size / COMMAND_LENGTH)
var offset = 0
while (offset + COMMAND_LENGTH <= bytes.size) {
val tag = buffer.getShort(offset).toInt() and 0xffff
val length = buffer.getShort(offset + 2).toInt() and 0xffff
// The text region starts where the records stop decoding, so an unreadable
// record ends the list rather than failing the whole batch.
if (length != COMMAND_LENGTH) break
val paintBits = buffer.getLong(offset + 4)
val kind = (paintBits ushr 32).toInt()
if (kind != 1 && kind != 2) break
val paint = if (kind == 1) {
Paint.Role(colorRoleOrNull(paintBits.toInt()) ?: break)
} else {
Paint.Literal(paintBits.toInt())
}
fun word(index: Int): Int = buffer.getInt(offset + 12 + index * 4)
fun real(index: Int): kotlin.Float = kotlin.Float.fromBits(word(index))
val command = when (tag) {
"#,
);
for command in DRAW_COMMAND_SCHEMA {
write!(
output,
" {} -> DrawCommand.{}(paint",
command.tag, command.name
)
.unwrap();
for field in command.fields {
match field.ty {
DrawFieldType::Float => write!(output, ", real({})", field.word).unwrap(),
DrawFieldType::U32 => write!(output, ", word({})", field.word).unwrap(),
DrawFieldType::Role(name) => write!(
output,
", {}OrNull(word({})) ?: break",
lower_first(name),
field.word
)
.unwrap(),
}
}
output.push_str(")\n");
}
output.push_str(
r#" else -> break
}
commands.add(command)
offset += COMMAND_LENGTH
}
return commands
}
/** The string a TextAt points at, measured from the start of the list. */
fun textOf(bytes: ByteArray, command: DrawCommand.TextAt): String {
val end = command.textOffset.toLong() + command.textLength.toLong()
if (command.textOffset < 0 || command.textLength < 0 || end > bytes.size.toLong()) {
return ""
}
return String(bytes, command.textOffset, command.textLength, StandardCharsets.UTF_8)
}
"#,
);
// Role lookups that answer null rather than throwing: a command list is data inside a
// property value, and one bad word must end the list, not the batch.
let mut roles: Vec<&str> = DRAW_COMMAND_SCHEMA
.iter()
.flat_map(|command| command.fields.iter())
.filter_map(|field| match field.ty {
DrawFieldType::Role(name) => Some(name),
_ => None,
})
.collect();
roles.push("ColorRole");
roles.dedup();
for role in roles {
let variants = ROLE_ENUM_SCHEMA
.iter()
.find(|entry| entry.name == role)
.expect("a drawing command names a role the schema declares")
.variants;
writeln!(
output,
" private fun {}OrNull(tag: Int): {role}? = when (tag) {{",
lower_first(role)
)
.unwrap();
for variant in variants {
writeln!(output, " {} -> {role}.{}", variant.tag, variant.name).unwrap();
}
output.push_str(" else -> null\n }\n\n");
}
output.push_str("}\n\n");
}
/// The run list a `Text` carries, mirrored into Kotlin with its decoder.
///
/// The layout is read from `spans.rs`, so a field added there moves here without anyone
/// counting bytes by hand on either side.
fn write_text_spans(output: &mut String) {
use crate::spans::{
FLAG_BOLD, FLAG_ITALIC, FLAG_STRIKETHROUGH, FLAG_UNDERLINE, SPAN_BACKGROUND_AT,
SPAN_COLOR_AT, SPAN_FLAGS_AT, SPAN_HANDLER_AT, SPAN_LEN, SPAN_LENGTH_AT, SPAN_ROLE_AT,
SPAN_START_AT,
};
let role_kind = Paint::Role(ColorRole::Primary).to_bits() >> 32;
let literal_kind = Paint::Literal(Color::argb(0)).to_bits() >> 32;
let asset_kind = Paint::Asset(0).to_bits() >> 32;
output.push_str(
r#"/**
* One run of different treatment inside a Text's string, as the Host wrote it.
*
* Offsets are bytes of the string's UTF-8, because that is what the string is measured in
* on the side that wrote them. A null paint is a run that says nothing about that colour.
*/
data class TextSpanRecord(
val start: Int,
val length: Int,
val typeRole: TypeRole?,
val color: Paint?,
/** What is painted behind this run's letters only. */
val background: Paint?,
val bold: Boolean,
val italic: Boolean,
val underline: Boolean,
val strikethrough: Boolean,
/** The handler a press on this run reports to, or zero where it is not a link. */
val handlerId: Long,
)
/** Decodes the run list a Text carries in its `Spans` property. */
object SpanRecords {
"#,
);
writeln!(output, " const val SPAN_LENGTH = {SPAN_LEN}").unwrap();
for (name, value) in [
("START_AT", SPAN_START_AT),
("LENGTH_AT", SPAN_LENGTH_AT),
("ROLE_AT", SPAN_ROLE_AT),
("FLAGS_AT", SPAN_FLAGS_AT),
("COLOR_AT", SPAN_COLOR_AT),
("BACKGROUND_AT", SPAN_BACKGROUND_AT),
("HANDLER_AT", SPAN_HANDLER_AT),
] {
writeln!(output, " private const val {name} = {value}").unwrap();
}
for (name, value) in [
("FLAG_BOLD", FLAG_BOLD),
("FLAG_ITALIC", FLAG_ITALIC),
("FLAG_UNDERLINE", FLAG_UNDERLINE),
("FLAG_STRIKETHROUGH", FLAG_STRIKETHROUGH),
] {
writeln!(output, " private const val {name} = {value}").unwrap();
}
output.push_str(
r#"
/** The runs in [bytes], or null where it is not a whole number of records. */
fun decode(bytes: ByteArray): List<TextSpanRecord>? {
if (bytes.size % SPAN_LENGTH != 0) return null
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
return decodeAt(buffer, bytes.size, 0, bytes.size / SPAN_LENGTH)
}
/**
* The [count] runs whose records start at [at] in [buffer], or null where they reach
* past [limit]. What a measure request carries, in place.
*/
fun decodeAt(buffer: ByteBuffer, limit: Int, at: Int, count: Int): List<TextSpanRecord>? {
if (count < 0 || at < 0 || at.toLong() + count.toLong() * SPAN_LENGTH > limit.toLong()) {
return null
}
val previous = buffer.order()
buffer.order(ByteOrder.LITTLE_ENDIAN)
try {
return List(count) { index ->
val record = at + index * SPAN_LENGTH
val flags = buffer.getShort(record + FLAGS_AT).toInt() and 0xffff
TextSpanRecord(
start = buffer.getInt(record + START_AT),
length = buffer.getInt(record + LENGTH_AT),
typeRole = typeRoleOrNull(buffer.getShort(record + ROLE_AT).toInt() and 0xffff),
color = paintOrNull(buffer.getLong(record + COLOR_AT)),
background = paintOrNull(buffer.getLong(record + BACKGROUND_AT)),
bold = flags and FLAG_BOLD != 0,
italic = flags and FLAG_ITALIC != 0,
underline = flags and FLAG_UNDERLINE != 0,
strikethrough = flags and FLAG_STRIKETHROUGH != 0,
handlerId = buffer.getLong(record + HANDLER_AT),
)
}
} finally {
buffer.order(previous)
}
}
/** A paint, or null for zero and for anything that does not decode. */
private fun paintOrNull(bits: Long): Paint? {
val value = bits.toInt()
return when ((bits ushr 32).toInt()) {
"#,
);
writeln!(
output,
" {role_kind} -> colorRoleOrNull(value)?.let {{ Paint.Role(it) }}"
)
.unwrap();
writeln!(output, " {literal_kind} -> Paint.Literal(value)").unwrap();
writeln!(output, " {asset_kind} -> Paint.Asset(value)").unwrap();
output.push_str(" else -> null\n }\n }\n\n");
for role in ["ColorRole", "TypeRole"] {
let variants = ROLE_ENUM_SCHEMA
.iter()
.find(|entry| entry.name == role)
.expect("the span record names a role the schema declares")
.variants;
writeln!(
output,
" private fun {}OrNull(tag: Int): {role}? = when (tag) {{",
lower_first(role)
)
.unwrap();
for variant in variants {
writeln!(output, " {} -> {role}.{}", variant.tag, variant.name).unwrap();
}
output.push_str(" else -> null\n }\n\n");
}
output.push_str("}\n\n");
}
/// The records a code editor's decorations and syntax colour runs travel in, mirrored into
/// Kotlin with a decoder for each blob.
///
/// A record that cannot be read is reported through `onError` and left out, and the rest of
/// the list is still read: a list is data inside a property value, and one bad record is
/// that record's problem rather than the batch's.
fn write_code_editor_records(output: &mut String) {
use crate::code::{
CODE_EDITOR_COLORS_RECORD, DECORATION_RECORD, FOLD_RECORD, GUTTER_DECORATION_RECORD,
RecordFieldType, RecordSchema, SYNTAX_SPAN_RECORD, VIEW_ZONE_RECORD,
};
let records: [(RecordSchema, &str, &str); 6] = [
(
DECORATION_RECORD,
"decodeDecorations",
"One decoration over a code editor's document: an underline, a lens above a line, a \
hover anchor or an inline suggestion. The range is in the document at `version`; \
columns are UTF-16 units. `id` is the application's own name for it, zero where \
it cannot be pressed.",
),
(
SYNTAX_SPAN_RECORD,
"decodeSyntaxSpans",
"One colour run of a code editor's syntax. The range is in the document at \
`version`; columns are UTF-16 units.",
),
(
FOLD_RECORD,
"decodeFolds",
"One stretch of a code editor's lines that can be folded. Folding keeps \
`startLine` and hides the lines after it up to `endLine`; both are in the \
document at `version`.",
),
(
GUTTER_DECORATION_RECORD,
"decodeGutterDecorations",
"One mark beside a line number of a code editor. The line is in the document at \
`version`; `glyph` is a Unicode scalar value, used when the kind is a glyph. \
`id` is the application's own name for it, zero where it cannot be pressed.",
),
(
CODE_EDITOR_COLORS_RECORD,
"decodeCodeEditorColors",
"The colours an application gives a code editor, one role for each part. A part with no role keeps the design system's colour.",
),
(
VIEW_ZONE_RECORD,
"decodeViewZones",
"Room after a line of a code editor that is not text, `heightLines` rows high, \
with `text` drawn dimmed in it. `afterLine` is in the document as it is when the \
list arrives.",
),
];
let kotlin_field_type = |ty: RecordFieldType| -> String {
match ty {
RecordFieldType::U32 => "Int".to_owned(),
RecordFieldType::U64 => "Long".to_owned(),
RecordFieldType::Role { name, optional } => {
format!("{name}{}", if optional { "?" } else { "" })
}
RecordFieldType::Paint => "Paint".to_owned(),
RecordFieldType::Flag => "Boolean".to_owned(),
RecordFieldType::F32 => "kotlin.Float".to_owned(),
RecordFieldType::Text => "String".to_owned(),
}
};
for (schema, _, doc) in records {
writeln!(output, "/** {doc} */").unwrap();
writeln!(output, "data class {}(", schema.name).unwrap();
for field in schema.fields {
writeln!(
output,
" val {}: {},",
field.name,
kotlin_field_type(field.ty)
)
.unwrap();
}
output.push_str(")\n\n");
}
output.push_str(
r#"/**
* One edit of a grouped edit: a range of the document as it stood at the group's base
* version, and the text that replaces it.
*/
data class CodeEditRecord(
val startLine: Int,
val startColumn: Int,
val endLine: Int,
val endColumn: Int,
val text: String,
)
/**
* Reads the blobs a code editor carries.
*
* A record that cannot be read, a kind or a role this side does not know or a text that
* points outside the blob, is reported through `onError` and left out. The rest of the list
* is read regardless. A grouped edit is the exception: it goes in whole or not at all, so a
* blob with anything wrong in it is not read at all.
*/
object CodeEditorRecords {
const val CODE_EDIT_LENGTH = 24
/**
* The edits of an `EditCodeGroup`, in the order they were sent, or null, with the
* reason given to [onError], where the blob is not one.
*
* The blob is a count, then one 24-byte record per edit (the range, then the text's
* offset and length), then the texts. A text's offset counts from the start of the
* texts. A count the blob is too short for, a text outside it or not UTF-8, or bytes
* after the last text make the blob unreadable.
*/
fun decodeEditGroup(bytes: ByteArray, onError: (String) -> Unit): List<CodeEditRecord>? {
if (bytes.size < 4) {
onError("a grouped edit is ${bytes.size} bytes, too short for its count")
return null
}
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
val count = buffer.getInt(0).toLong() and 0xffff_ffffL
val textsStart = 4L + count * CODE_EDIT_LENGTH
if (textsStart > bytes.size) {
onError("a grouped edit says it has $count edits and is ${bytes.size} bytes")
return null
}
val edits = ArrayList<CodeEditRecord>(count.toInt())
var textsEnd = textsStart
for (index in 0 until count.toInt()) {
val at = 4 + index * CODE_EDIT_LENGTH
val start = textsStart + (buffer.getInt(at + 16).toLong() and 0xffff_ffffL)
val length = buffer.getInt(at + 20).toLong() and 0xffff_ffffL
if (start + length > bytes.size) {
onError("edit $index of a grouped edit names text outside it")
return null
}
val text = textOf(bytes, start.toInt(), length.toInt()) ?: run {
onError("edit $index of a grouped edit has text that is not UTF-8")
return null
}
textsEnd = maxOf(textsEnd, start + length)
edits += CodeEditRecord(
buffer.getInt(at),
buffer.getInt(at + 4),
buffer.getInt(at + 8),
buffer.getInt(at + 12),
text,
)
}
if (textsEnd != bytes.size.toLong()) {
onError("a grouped edit has ${bytes.size - textsEnd} bytes after its last text")
return null
}
return edits
}
"#,
);
for (schema, function, _) in records {
let constant = match schema.name {
"DecorationRecord" => "DECORATION_LENGTH",
"FoldRecord" => "FOLD_LENGTH",
"GutterDecorationRecord" => "GUTTER_DECORATION_LENGTH",
"CodeEditorColorsRecord" => "CODE_EDITOR_COLORS_LENGTH",
"ViewZoneRecord" => "VIEW_ZONE_LENGTH",
_ => "SYNTAX_SPAN_LENGTH",
};
writeln!(output, " const val {constant} = {}\n", schema.length).unwrap();
let text_field = schema
.fields
.iter()
.find(|field| field.ty == RecordFieldType::Text);
writeln!(
output,
" fun {function}(bytes: ByteArray, onError: (String) -> Unit): List<{}> {{",
schema.name
)
.unwrap();
output.push_str(
" val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)\n",
);
writeln!(
output,
" val records = ArrayList<{}>(bytes.size / {constant})",
schema.name
)
.unwrap();
output.push_str(" var end = bytes.size\n");
output.push_str(" var offset = 0\n");
output.push_str(" var index = 0\n");
writeln!(output, " while (offset + {constant} <= end) {{").unwrap();
if let Some(text) = text_field {
// The records end where the text region begins: the first offset any record
// names for its text.
writeln!(
output,
" val textOffset = buffer.getInt(offset + {})",
text.offset
)
.unwrap();
writeln!(
output,
" val textLength = buffer.getInt(offset + {})",
text.offset + 4
)
.unwrap();
output.push_str(
" if (textLength != 0 && textOffset >= 0 && textOffset < end) end = textOffset\n",
);
}
writeln!(
output,
" read{}(buffer, bytes, offset, index, onError)?.let(records::add)",
schema.name
)
.unwrap();
writeln!(output, " offset += {constant}").unwrap();
output.push_str(" index += 1\n");
output.push_str(" }\n");
if text_field.is_none() {
output.push_str(" if (offset != bytes.size) {\n");
output.push_str(
" onError(\"${bytes.size - offset} bytes after the last whole record\")\n",
);
output.push_str(" }\n");
}
output.push_str(" return records\n");
output.push_str(" }\n\n");
writeln!(
output,
" private fun read{}(buffer: ByteBuffer, bytes: ByteArray, offset: Int, index: Int, onError: (String) -> Unit): {}? {{",
schema.name, schema.name
)
.unwrap();
for field in schema.fields {
let at = field.offset;
match field.ty {
RecordFieldType::U32 => {
writeln!(
output,
" val {} = buffer.getInt(offset + {at})",
field.name
)
.unwrap();
}
RecordFieldType::U64 => {
writeln!(
output,
" val {} = buffer.getLong(offset + {at})",
field.name
)
.unwrap();
}
RecordFieldType::Role { name, optional } => {
writeln!(
output,
" val {}Tag = buffer.getShort(offset + {at}).toInt() and 0xffff",
field.name
)
.unwrap();
let lookup = format!("{}OrNull({}Tag)", lower_first(name), field.name);
let refuse = format!(
"run {{ onError(\"record $index has an unknown {} ${{{}Tag}}\"); return null }}",
field.name, field.name
);
if optional {
writeln!(
output,
" val {} = if ({}Tag == 0) null else {lookup} ?: {refuse}",
field.name, field.name
)
.unwrap();
} else {
writeln!(output, " val {} = {lookup} ?: {refuse}", field.name)
.unwrap();
}
}
RecordFieldType::Paint => {
writeln!(
output,
" val {} = paintOrNull(buffer.getLong(offset + {at})) ?: run {{ onError(\"record $index has an unreadable {}\"); return null }}",
field.name, field.name
)
.unwrap();
}
RecordFieldType::Flag => {
writeln!(
output,
" val {} = when (buffer.getInt(offset + {at})) {{ 0 -> false; 1 -> true; else -> run {{ onError(\"record $index has a {} that is neither 0 nor 1\"); return null }} }}",
field.name, field.name
)
.unwrap();
}
RecordFieldType::F32 => {
writeln!(
output,
// Read as the word it is and turned into a float, because the
// Kotlin/Native buffer this runs on reads no floats.
" val {} = kotlin.Float.fromBits(buffer.getInt(offset + {at}))",
field.name
)
.unwrap();
}
RecordFieldType::Text => {
writeln!(
output,
" val {} = textOf(bytes, buffer.getInt(offset + {at}), buffer.getInt(offset + {})) ?: run {{ onError(\"record $index names text outside the list\"); return null }}",
field.name,
at + 4
)
.unwrap();
}
}
}
write!(output, " return {}(", schema.name).unwrap();
for (index, field) in schema.fields.iter().enumerate() {
if index != 0 {
output.push_str(", ");
}
output.push_str(field.name);
}
output.push_str(")\n }\n\n");
}
output.push_str(
r#" /** UTF-8 text behind the records, or null where the range leaves the blob or is not text. */
private fun textOf(bytes: ByteArray, offset: Int, length: Int): String? {
if (length == 0) return ""
if (offset < 0 || length < 0 || offset.toLong() + length.toLong() > bytes.size.toLong()) return null
return try {
bytes.decodeToString(offset, offset + length, throwOnInvalidSequence = true)
} catch (error: CharacterCodingException) {
null
}
}
private fun paintOrNull(bits: Long): Paint? {
val value = bits.toInt()
return when ((bits ushr 32).toInt()) {
1 -> colorRoleOrNull(value)?.let { Paint.Role(it) }
2 -> Paint.Literal(value)
3 -> Paint.Asset(value)
else -> null
}
}
"#,
);
let mut roles: Vec<&str> = [
DECORATION_RECORD,
SYNTAX_SPAN_RECORD,
FOLD_RECORD,
GUTTER_DECORATION_RECORD,
CODE_EDITOR_COLORS_RECORD,
]
.iter()
.flat_map(|schema| schema.fields.iter())
.filter_map(|field| match field.ty {
RecordFieldType::Role { name, .. } => Some(name),
_ => None,
})
.collect();
roles.push("ColorRole");
roles.sort_unstable();
roles.dedup();
for role in roles {
let variants = ROLE_ENUM_SCHEMA
.iter()
.find(|entry| entry.name == role)
.expect("a code editor record names a role the schema declares")
.variants;
writeln!(
output,
" private fun {}OrNull(tag: Int): {role}? = when (tag) {{",
lower_first(role)
)
.unwrap();
for variant in variants {
writeln!(output, " {} -> {role}.{}", variant.tag, variant.name).unwrap();
}
output.push_str(" else -> null\n }\n\n");
}
output.push_str("}\n\n");
}
/// The font candidates of text with no role, and the table that gives a run its own.
fn write_font_refs(output: &mut String) {
use crate::fonts::{
FONT_REF_ASSET, FONT_REF_GENERIC, FONT_REF_KIND_AT, FONT_REF_LEN, FONT_REF_LENGTH_AT,
FONT_REF_SYSTEM, FONT_REF_VALUE_AT, MAX_FONT_REFS,
};
use crate::spans::{
SPAN_FONT_COUNT_AT, SPAN_FONT_ENTRY_LEN, SPAN_FONT_OFFSET_AT, SPAN_FONT_SPAN_AT,
};
output.push_str(
r#"/**
* One font to try for text with no role, in the order a CSS font list gives them. The first
* one the Renderer can resolve is the one the text is set in.
*/
sealed interface FontRef {
/** A font the application registered as an asset. */
data class Asset(val assetId: Int) : FontRef
/** A family installed on the machine, by name. */
data class System(val name: String) : FontRef
/** A family CSS names without naming a font. */
data class Generic(val family: GenericFamily) : FontRef
}
/** Decodes font candidate lists, wherever they sit: a property, a run or a measure request. */
object FontRefRecords {
"#,
);
writeln!(output, " const val RECORD_LENGTH = {FONT_REF_LEN}").unwrap();
writeln!(output, " const val MAX_REFS = {MAX_FONT_REFS}").unwrap();
for (name, value) in [
("KIND_AT", FONT_REF_KIND_AT),
("VALUE_AT", FONT_REF_VALUE_AT),
("LENGTH_AT", FONT_REF_LENGTH_AT),
] {
writeln!(output, " private const val {name} = {value}").unwrap();
}
for (name, value) in [
("ASSET", FONT_REF_ASSET),
("SYSTEM", FONT_REF_SYSTEM),
("GENERIC", FONT_REF_GENERIC),
] {
writeln!(output, " private const val {name} = {value}").unwrap();
}
output.push_str(
r#"
/**
* The [count] candidates whose records start at [at] in [buffer], each name read from
* the same buffer, or null where anything reaches past [limit] or names a kind this
* decoder does not know.
*/
fun decode(buffer: ByteBuffer, limit: Int, at: Int, count: Int): List<FontRef>? {
if (count < 0 || count > MAX_REFS) return null
if (at < 0 || at.toLong() + count.toLong() * RECORD_LENGTH > limit.toLong()) return null
val previous = buffer.order()
buffer.order(ByteOrder.LITTLE_ENDIAN)
try {
val refs = ArrayList<FontRef>(count)
for (index in 0 until count) {
val record = at + index * RECORD_LENGTH
val value = buffer.getInt(record + VALUE_AT)
refs += when (buffer.getInt(record + KIND_AT)) {
ASSET -> FontRef.Asset(value)
SYSTEM -> {
val length = buffer.getInt(record + LENGTH_AT)
if (value < 0 || length < 0 || value.toLong() + length > limit.toLong()) {
return null
}
// Relative rather than absolute: the absolute bulk read is not on
// every Android runtime this has to compile against.
val name = ByteArray(length)
val mark = buffer.position()
buffer.position(value)
buffer.get(name, 0, length)
buffer.position(mark)
FontRef.System(name.decodeToString())
}
GENERIC -> FontRef.Generic(genericFamilyOrNull(value) ?: return null)
else -> return null
}
}
return refs
} finally {
buffer.order(previous)
}
}
/** The list a `Font` property carries: a count, then the records and their names. */
fun decodeBlob(bytes: ByteArray): List<FontRef>? {
if (bytes.isEmpty()) return emptyList()
if (bytes.size < 4) return null
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
return decode(buffer, bytes.size, 4, buffer.getInt(0))
}
"#,
);
let generic = ROLE_ENUM_SCHEMA
.iter()
.find(|entry| entry.name == "GenericFamily")
.expect("the font records name a generic family the schema declares")
.variants;
output.push_str(
" private fun genericFamilyOrNull(tag: Int): GenericFamily? = when (tag) {
",
);
for variant in generic {
writeln!(
output,
" {} -> GenericFamily.{}",
variant.tag, variant.name
)
.unwrap();
}
output.push_str(
" else -> null
}
}
",
);
output.push_str(
r#"/**
* Which runs of a Text name fonts of their own, and which: the `SpanFonts` property, or
* the same table inside a measure request. Keyed by the run's index in its run list.
*/
object SpanFontRecords {
"#,
);
writeln!(output, " const val ENTRY_LENGTH = {SPAN_FONT_ENTRY_LEN}").unwrap();
for (name, value) in [
("SPAN_AT", SPAN_FONT_SPAN_AT),
("OFFSET_AT", SPAN_FONT_OFFSET_AT),
("COUNT_AT", SPAN_FONT_COUNT_AT),
] {
writeln!(output, " private const val {name} = {value}").unwrap();
}
output.push_str(
r#"
/** The [count] entries starting at [at] in [buffer], or null where any is malformed. */
fun decode(buffer: ByteBuffer, limit: Int, at: Int, count: Int): Map<Int, List<FontRef>>? {
if (count < 0 || at < 0 || at.toLong() + count.toLong() * ENTRY_LENGTH > limit.toLong()) {
return null
}
val previous = buffer.order()
buffer.order(ByteOrder.LITTLE_ENDIAN)
val entries = try {
List(count) { index ->
val entry = at + index * ENTRY_LENGTH
Triple(
buffer.getInt(entry + SPAN_AT),
buffer.getInt(entry + OFFSET_AT),
buffer.getInt(entry + COUNT_AT),
)
}
} finally {
buffer.order(previous)
}
val fonts = HashMap<Int, List<FontRef>>(count)
for ((span, offset, refs) in entries) {
fonts[span] = FontRefRecords.decode(buffer, limit, offset, refs) ?: return null
}
return fonts
}
/** The table a `SpanFonts` property carries: a count, then the entries and their lists. */
fun decodeBlob(bytes: ByteArray): Map<Int, List<FontRef>>? {
if (bytes.isEmpty()) return emptyMap()
if (bytes.size < 4) return null
val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
return decode(buffer, bytes.size, 4, buffer.getInt(0))
}
}
"#,
);
}
/// The record layout of a measure call, as constants both sides read the same bytes by.
fn write_measure_records(output: &mut String) {
use crate::measure as m;
output.push_str(
r#"/**
* The layout of a measure call: the request records the Host writes, the result records
* the Renderer writes back, and what each status means. The records and their offsets are
* the Host's, generated from its schema, so nobody counts bytes by hand on this side.
*/
object MeasureRecords {
"#,
);
let ints: &[(&str, i64)] = &[
("RECORD_LENGTH", m::MEASURE_RECORD_LEN as i64),
("RESULT_LENGTH", m::MEASURE_RESULT_LEN as i64),
("KIND_TEXT", i64::from(m::MEASURE_TEXT)),
("KIND_NODE", i64::from(m::MEASURE_NODE)),
("KIND_AT", m::MEASURE_KIND_AT as i64),
("TEXT_TYPE_ROLE_AT", m::TEXT_TYPE_ROLE_AT as i64),
("TEXT_TEXT_OFFSET_AT", m::TEXT_TEXT_OFFSET_AT as i64),
("TEXT_TEXT_LENGTH_AT", m::TEXT_TEXT_LENGTH_AT as i64),
("TEXT_SPANS_OFFSET_AT", m::TEXT_SPANS_OFFSET_AT as i64),
("TEXT_SPANS_COUNT_AT", m::TEXT_SPANS_COUNT_AT as i64),
(
"TEXT_SPAN_FONTS_OFFSET_AT",
m::TEXT_SPAN_FONTS_OFFSET_AT as i64,
),
(
"TEXT_SPAN_FONTS_COUNT_AT",
m::TEXT_SPAN_FONTS_COUNT_AT as i64,
),
("TEXT_FONT_OFFSET_AT", m::TEXT_FONT_OFFSET_AT as i64),
("TEXT_FONT_COUNT_AT", m::TEXT_FONT_COUNT_AT as i64),
("TEXT_FONT_SIZE_AT", m::TEXT_FONT_SIZE_AT as i64),
("TEXT_FONT_WEIGHT_AT", m::TEXT_FONT_WEIGHT_AT as i64),
("TEXT_ITALIC_AT", m::TEXT_ITALIC_AT as i64),
("TEXT_WRAP_AT", m::TEXT_WRAP_AT as i64),
("TEXT_LETTER_SPACING_AT", m::TEXT_LETTER_SPACING_AT as i64),
("TEXT_LINE_HEIGHT_AT", m::TEXT_LINE_HEIGHT_AT as i64),
("TEXT_MAX_LINES_AT", m::TEXT_MAX_LINES_AT as i64),
("TEXT_TAB_SIZE_AT", m::TEXT_TAB_SIZE_AT as i64),
("TEXT_WORD_BREAK_AT", m::TEXT_WORD_BREAK_AT as i64),
("TEXT_OVERFLOW_WRAP_AT", m::TEXT_OVERFLOW_WRAP_AT as i64),
("TEXT_ABSOLUTE_SIZE_AT", m::TEXT_ABSOLUTE_SIZE_AT as i64),
("TEXT_CONSTRAINT_AT", m::TEXT_CONSTRAINT_AT as i64),
("TEXT_WIDTH_AT", m::TEXT_WIDTH_AT as i64),
("TEXT_ZOOM_AT", m::TEXT_ZOOM_AT as i64),
("NODE_ID_AT", m::NODE_ID_AT as i64),
("NODE_MIN_WIDTH_AT", m::NODE_MIN_WIDTH_AT as i64),
("NODE_MAX_WIDTH_AT", m::NODE_MAX_WIDTH_AT as i64),
("NODE_MIN_HEIGHT_AT", m::NODE_MIN_HEIGHT_AT as i64),
("NODE_MAX_HEIGHT_AT", m::NODE_MAX_HEIGHT_AT as i64),
("NODE_ZOOM_AT", m::NODE_ZOOM_AT as i64),
(
"CONSTRAINT_MIN_CONTENT",
i64::from(m::CONSTRAINT_MIN_CONTENT),
),
(
"CONSTRAINT_MAX_CONTENT",
i64::from(m::CONSTRAINT_MAX_CONTENT),
),
("CONSTRAINT_AT_MOST", i64::from(m::CONSTRAINT_AT_MOST)),
("RESULT_WIDTH_AT", m::RESULT_WIDTH_AT as i64),
("RESULT_HEIGHT_AT", m::RESULT_HEIGHT_AT as i64),
(
"RESULT_FIRST_BASELINE_AT",
m::RESULT_FIRST_BASELINE_AT as i64,
),
("RESULT_LAST_BASELINE_AT", m::RESULT_LAST_BASELINE_AT as i64),
(
"RESULT_LAST_LINE_WIDTH_AT",
m::RESULT_LAST_LINE_WIDTH_AT as i64,
),
("RESULT_LINE_COUNT_AT", m::RESULT_LINE_COUNT_AT as i64),
("RESULT_FLAGS_AT", m::RESULT_FLAGS_AT as i64),
("RESULT_STATUS_AT", m::RESULT_STATUS_AT as i64),
("FLAG_TRUNCATED", i64::from(m::FLAG_TRUNCATED)),
("STATUS_OK", i64::from(m::RESULT_OK)),
("STATUS_UNKNOWN_NODE", i64::from(m::RESULT_UNKNOWN_NODE)),
("STATUS_MALFORMED", i64::from(m::RESULT_MALFORMED)),
("CALL_OK", 0),
("CALL_UNREADABLE", i64::from(m::MEASURE_UNREADABLE)),
("CALL_OFF_UI_THREAD", i64::from(m::MEASURE_OFF_UI_THREAD)),
("CALL_UNAVAILABLE", i64::from(m::MEASURE_UNAVAILABLE)),
];
for (name, value) in ints {
writeln!(output, " const val {name} = {value}").unwrap();
}
output.push_str(
"}
",
);
}
fn lower_first(name: &str) -> String {
let mut characters = name.chars();
match characters.next() {
Some(first) => first.to_lowercase().chain(characters).collect(),
None => String::new(),
}
}
// ---------------------------------------------------------------------------------------
// Android bindings.
//
// The JNI shims and the Kotlin `external fun` declarations are two renderings of
// `BOUNDARY_SCHEMA`. Writing either by hand is forbidden, and generating both from one
// table is what keeps the symbol names, the argument order and the `out` layout identical
// on the two sides.
// ---------------------------------------------------------------------------------------
/// Generated Rust, compiled into the cdylib only when the target is Android.
pub const JNI_RUST_RELATIVE_PATH: &str = "src/boundary_jni.gen.rs";
/// Generated Kotlin. The Kotlin Toolchain compiles the module's `src` tree by convention.
pub const ANDROID_BRIDGE_RELATIVE_PATH: &str = "../renderer/android/src/bridge/HostBridge.gen.kt";
pub const ANDROID_FAST_NATIVE_RELATIVE_PATH: &str =
"../renderer/android/src/bridge/FastNative.gen.kt";
const ANDROID_KOTLIN_PACKAGE: &str = "dev.darkpyonix.composerust.ui.platform";
/// `out` slots, in order. The Kotlin side reads them by the same generated constants.
const OUT_SLOTS: &[(&str, &str)] = &[
("BatchOffset", "the batch's start inside the arena"),
("BatchLength", "the batch's length in bytes"),
("Result", "the handler's synchronous result"),
(
"ArenaAddress",
"the arena's base address, which moves when it grows",
),
("ArenaCapacity", "the arena's capacity in bytes"),
];
fn jni_symbol(op_name: &str) -> String {
// JNI mangles `.` to `_`. No name here contains `_` or a non-ASCII character, so the
// escaping forms (`_1`, `_0`) never arise.
format!(
"Java_{}_native{}",
ANDROID_BRIDGE_CLASS.replace('/', "_"),
op_name
)
}
fn kotlin_native_name(op_name: &str) -> String {
format!("native{op_name}")
}
/// Emits the Rust half of the Android boundary: one `extern "system"` shim per operation,
/// `JNI_OnLoad`, and the upcall a worker thread makes to ask for a frame.
pub fn generate_jni_rust() -> String {
let mut output = String::new();
output.push_str("// Generated by `cargo run -p compose-rust --bin codegen`. DO NOT EDIT.\n");
output.push_str(
r#"//! JNI shims for the Android boundary.
//!
//! Kotlin owns the process and the frame loop, so every call here starts on the Renderer
//! UI thread and returns on the same call stack. Nothing is copied: a call reports where
//! its batch sits inside the Host's arena, and the Renderer reads the arena through a
//! direct byte buffer it made once.
#![allow(non_snake_case)]
use crate::boundary::{
MutationBatch, RendererApi, STATUS_OK, STATUS_PROTOCOL_ERROR, current_arena,
install_renderer_api,
};
use crate::measure::{
MEASURE_OFF_UI_THREAD, MEASURE_RESULT_LEN, MEASURE_UNAVAILABLE, MEASURE_UNREADABLE,
MeasureResult,
};
use jni::JNIEnv;
use jni::JavaVM;
use jni::objects::{GlobalRef, JByteBuffer, JClass, JLongArray, JStaticMethodID, JValue};
use jni::signature::{Primitive, ReturnType};
use jni::sys::jobject;
use jni::sys::{JNI_ERR, JNI_VERSION_1_6, jint, jlong, jvalue};
use std::ffi::c_int;
use std::os::raw::c_void;
use std::sync::OnceLock;
unsafe extern "C" {
/// Defined by the application's cdylib through `compose_rust::android_main!`. It
/// registers the root component before the Renderer's first init call.
fn compose_rust_android_main();
}
"#,
);
writeln!(
output,
"/// The number of `out` slots a batch-returning call writes."
)
.unwrap();
writeln!(
output,
"pub const OUT_SLOTS: usize = {};\n",
OUT_SLOTS.len()
)
.unwrap();
output.push_str(
r#"struct FrameRequestUpcall {
class: GlobalRef,
method: JStaticMethodID,
/// `onMeasure`, on the same class.
measure: JStaticMethodID,
}
static VM: OnceLock<JavaVM> = OnceLock::new();
static UPCALL: OnceLock<FrameRequestUpcall> = OnceLock::new();
/// The Activity owns the loop, so the Host never runs one.
extern "C" fn platform_run() -> c_int {
STATUS_OK as c_int
}
/// Called from a Host worker thread, never from the UI thread.
///
/// The worker attaches to the JavaVM once and stays attached for the life of the process:
/// attaching and detaching around every call would cost more than the frame it asks for.
extern "C" fn request_frame() {
let (Some(vm), Some(upcall)) = (VM.get(), UPCALL.get()) else {
return;
};
let Ok(mut env) = vm.attach_current_thread_permanently() else {
return;
};
let class = <&JClass>::from(upcall.class.as_obj());
// SAFETY: the method id was resolved on this class for the signature `()V`, and the
// argument list matches it.
let result = unsafe {
env.call_static_method_unchecked(
class,
upcall.method,
ReturnType::Primitive(Primitive::Void),
&[],
)
};
if result.is_err() {
// A failed upcall is not worth aborting the process for. Clearing the pending
// exception leaves the VM usable.
let _ = env.exception_clear();
}
}
/// Called by the Host, inside a call the Renderer made, to measure.
///
/// The thread is the UI thread the call came in on, which the VM already knows, so its
/// environment is taken rather than attached: a thread the VM does not know cannot be the
/// UI thread, and attaching it would only hide that. Both buffers are wrapped where they
/// lie, for this call only, and nothing is copied either way.
unsafe extern "C" fn measure(
requests: *const u8,
length: u32,
count: u32,
results: *mut MeasureResult,
) -> i32 {
let (Some(vm), Some(upcall)) = (VM.get(), UPCALL.get()) else {
return MEASURE_UNAVAILABLE;
};
let Ok(mut env) = vm.get_env() else {
return MEASURE_OFF_UI_THREAD;
};
if requests.is_null() || results.is_null() {
return MEASURE_UNREADABLE;
}
let Some(result_bytes) = (count as usize).checked_mul(MEASURE_RESULT_LEN) else {
return MEASURE_UNREADABLE;
};
// SAFETY: the Host lends `length` bytes of requests and room for `count` results for
// the length of this call, and the views made here do not outlive it.
let Ok(request_view) =
(unsafe { env.new_direct_byte_buffer(requests.cast_mut(), length as usize) })
else {
return MEASURE_UNREADABLE;
};
// SAFETY: as above.
let Ok(result_view) = (unsafe { env.new_direct_byte_buffer(results.cast(), result_bytes) })
else {
return MEASURE_UNREADABLE;
};
let class = <&JClass>::from(upcall.class.as_obj());
let arguments = [
JValue::Object(&request_view).as_jni(),
jvalue { i: count as jint },
JValue::Object(&result_view).as_jni(),
];
// SAFETY: the method id was resolved on this class for the signature
// `(Ljava/nio/ByteBuffer;ILjava/nio/ByteBuffer;)I`, and the arguments match it.
let answer = unsafe {
env.call_static_method_unchecked(
class,
upcall.measure,
ReturnType::Primitive(Primitive::Int),
&arguments,
)
};
let status = match answer.and_then(|value| value.i()) {
Ok(status) => status,
Err(_) => {
let _ = env.exception_clear();
MEASURE_UNAVAILABLE
}
};
let _ = env.delete_local_ref(request_view);
let _ = env.delete_local_ref(result_view);
status
}
/// Resolves a direct byte buffer to the address the Host may read `length` bytes from.
fn direct_address(env: &JNIEnv<'_>, buffer: &JByteBuffer<'_>, length: jint) -> Option<*const u8> {
if length < 0 {
return None;
}
let address = env.get_direct_buffer_address(buffer).ok()?;
let capacity = env.get_direct_buffer_capacity(buffer).ok()?;
if capacity < length as usize {
return None;
}
Some(address.cast_const())
}
/// Reports where the batch sits, without copying a byte of it.
fn report(env: &mut JNIEnv<'_>, out: &JLongArray<'_>, batch: &MutationBatch) {
let (base, capacity) = current_arena();
let offset = if batch.ptr.is_null() || base.is_null() {
0
} else {
(batch.ptr as usize).wrapping_sub(base as usize)
};
let values: [jlong; OUT_SLOTS] = [
offset as jlong,
jlong::from(batch.len),
batch.result,
base as usize as jlong,
capacity as jlong,
];
let _ = env.set_long_array_region(out, 0, &values);
}
"#,
);
for op in BOUNDARY_SCHEMA {
write!(output, "{}", jni_shim(op)).unwrap();
}
output.push_str(
r#"/// Hands the Renderer a view of the Host's arena, not a copy of it.
///
/// Not a boundary operation: it exposes no Host behaviour, it only tells the JVM where
/// memory it may already read lives. The Renderer asks for it once, and again whenever a
/// call reports a different arena address, which is what happens when the arena grows and
/// moves.
#[unsafe(no_mangle)]
pub extern "system" fn ARENA_SYMBOL(mut env: JNIEnv<'_>, _class: JClass<'_>) -> jobject {
let (base, capacity) = current_arena();
if base.is_null() || capacity == 0 {
return std::ptr::null_mut();
}
// SAFETY: the arena belongs to this thread's Host and stays where it is until it
// grows, and every call reports the address so the Renderer can notice that.
match unsafe { env.new_direct_byte_buffer(base.cast_mut(), capacity) } {
Ok(buffer) => buffer.into_raw(),
Err(_) => std::ptr::null_mut(),
}
}
/// Runs on `System.loadLibrary`, before any boundary call.
///
/// # Safety
/// The JavaVM calls this with its own `JavaVM` pointer.
#[unsafe(no_mangle)]
pub unsafe extern "system" fn JNI_OnLoad(vm: *mut jni::sys::JavaVM, _reserved: *mut c_void) -> jint {
// SAFETY: the pointer comes from the JavaVM itself.
let Ok(vm) = (unsafe { JavaVM::from_raw(vm) }) else {
return JNI_ERR;
};
let Ok(mut env) = vm.attach_current_thread_permanently() else {
return JNI_ERR;
};
// The class is resolved here, on a Java-created thread, and kept as a global
// reference. A Host worker thread's class loader cannot see application classes, so
// looking it up later would fail.
let Ok(class) = env.find_class(BRIDGE_CLASS) else {
return JNI_ERR;
};
let Ok(method) = env.get_static_method_id(&class, "onFrameRequested", "()V") else {
return JNI_ERR;
};
let Ok(measure_method) = env.get_static_method_id(
&class,
"onMeasure",
"(Ljava/nio/ByteBuffer;ILjava/nio/ByteBuffer;)I",
) else {
return JNI_ERR;
};
let Ok(global) = env.new_global_ref(&class) else {
return JNI_ERR;
};
let _ = UPCALL.set(FrameRequestUpcall {
class: global,
method,
measure: measure_method,
});
let _ = VM.set(vm);
let _ = install_renderer_api(RendererApi {
run: platform_run,
request_frame,
measure,
});
// SAFETY: the application's cdylib defines this symbol.
unsafe { compose_rust_android_main() };
JNI_VERSION_1_6
}
"#,
);
writeln!(
output,
"\nconst BRIDGE_CLASS: &str = \"{ANDROID_BRIDGE_CLASS}\";"
)
.unwrap();
// The arena view's symbol is derived like every other one, so it is substituted here
// rather than spelled out in the template above.
rustfmt(output.replace("ARENA_SYMBOL", &jni_symbol("ArenaBuffer")))
}
/// Formats generated Rust the way `cargo fmt` would, so the checked-in file is already
/// what the formatter wants and the staleness test compares like with like.
///
/// A missing or failing `rustfmt` leaves the source as written: the file still compiles,
/// and `cargo fmt --check` is what reports the difference.
fn rustfmt(source: String) -> String {
use std::io::Write as _;
use std::process::{Command, Stdio};
let Ok(mut child) = Command::new("rustfmt")
.args(["--edition", "2024", "--emit", "stdout", "--quiet"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
else {
return source;
};
let Some(mut stdin) = child.stdin.take() else {
return source;
};
let written = stdin.write_all(source.as_bytes());
// Closing the pipe is what tells rustfmt the input has ended, so the drop is the
// point of the statement rather than tidiness. `ChildStdin` has no `Drop` on wasm,
// where `std::process` is a stub, and clippy sees the call there and not the reason.
#[allow(clippy::drop_non_drop)]
drop(stdin);
let Ok(output) = child.wait_with_output() else {
return source;
};
if written.is_err() || !output.status.success() {
return source;
}
String::from_utf8(output.stdout).unwrap_or(source)
}
fn jni_shim(op: &BoundaryOp) -> String {
let mut output = String::new();
writeln!(output, "/// `{}`, which calls `{}`.", op.name, op.symbol).unwrap();
output.push_str("#[unsafe(no_mangle)]\npub extern \"system\" fn ");
write!(output, "{}", jni_symbol(op.name)).unwrap();
output.push_str("(\n");
if op.returns_batch {
output.push_str(" mut env: JNIEnv<'_>,\n");
} else {
output.push_str(" _env: JNIEnv<'_>,\n");
}
output.push_str(" _class: JClass<'_>,\n");
for param in op.params {
match param {
BoundaryParam::Bytes { name } => {
writeln!(output, " {name}: JByteBuffer<'_>,").unwrap();
writeln!(output, " {name}_length: jint,").unwrap();
}
BoundaryParam::Nanos { name } => {
writeln!(output, " {}: jlong,", snake_case(name)).unwrap();
}
}
}
if op.returns_batch {
output.push_str(" out: JLongArray<'_>,\n");
}
output.push_str(") -> jint {\n");
let mut arguments = Vec::new();
for param in op.params {
match param {
BoundaryParam::Bytes { name } => {
writeln!(
output,
" let Some(address) = direct_address(&env, &{name}, {name}_length) else {{"
)
.unwrap();
output.push_str(" return STATUS_PROTOCOL_ERROR;\n };\n");
arguments.push("address".to_owned());
arguments.push(format!("{name}_length as u32"));
}
BoundaryParam::Nanos { name } => {
arguments.push(format!("{} as u64", snake_case(name)));
}
}
}
if op.returns_batch || op.name == "ReleaseBatch" {
output.push_str(" let mut batch = MutationBatch::default();\n");
arguments.push("&raw mut batch".to_owned());
}
let call = format!("crate::boundary::{}({})", op.symbol, arguments.join(", "));
if op.symbol == "compose_rust_host_shutdown" {
writeln!(output, " {call};").unwrap();
output.push_str(" STATUS_OK\n}\n\n");
return output;
}
output.push_str(
" // SAFETY: every pointer above addresses the number of readable bytes the\n\
\x20 // boundary contract promises, and the batch is local to this call.\n",
);
let statement = if op.returns_batch {
format!(" let status = unsafe {{ {call} }};")
} else {
format!(" unsafe {{ {call} }};")
};
// rustfmt breaks an unsafe block that does not fit on one line, so the generator
// writes the broken form itself and the generated file needs no reformatting.
if statement.len() > 100 {
if op.returns_batch {
output.push_str(" let status = unsafe {\n");
} else {
output.push_str(" unsafe {\n");
}
writeln!(output, " {call}").unwrap();
output.push_str(" };\n");
} else {
output.push_str(&statement);
output.push('\n');
}
if op.returns_batch {
output.push_str(" report(&mut env, &out, &batch);\n status\n}\n\n");
} else {
output.push_str(" STATUS_OK\n}\n\n");
}
output
}
fn snake_case(name: &str) -> String {
let mut output = String::new();
for (index, character) in name.char_indices() {
if character.is_ascii_uppercase() {
if index != 0 {
output.push('_');
}
output.push(character.to_ascii_lowercase());
} else {
output.push(character);
}
}
output
}
/// Emits the Kotlin half: the `external fun` declarations, the `out` slot indices and the
/// upcall a Host worker thread makes to ask for a frame.
pub fn generate_android_bridge_kotlin() -> String {
let mut output = String::new();
output.push_str("// Generated by `cargo run -p compose-rust --bin codegen`. DO NOT EDIT.\n");
output.push_str("@file:JvmName(\"HostBridge\")\n\n");
writeln!(output, "package {ANDROID_KOTLIN_PACKAGE}\n").unwrap();
output.push_str("import android.util.Log\n");
output.push_str("import dalvik.annotation.optimization.FastNative\n");
output.push_str("import java.nio.ByteBuffer\n\n");
output.push_str(
r#"// The Android boundary.
//
// Every declaration below is generated from the Rust boundary schema, so it cannot drift
// from the shims that implement it. A batch-returning call writes the slots below into the
// caller's reusable LongArray and copies nothing: the batch itself stays in the Host's
// arena, which the caller reads through one direct ByteBuffer.
"#,
);
for (index, (name, description)) in OUT_SLOTS.iter().enumerate() {
writeln!(output, "/** Slot {index}: {description}. */").unwrap();
writeln!(
output,
"const val OUT_{}: Int = {index}",
screaming_snake_case(name)
)
.unwrap();
}
writeln!(
output,
"\n/** The size of the `out` array a batch-returning call expects. */"
)
.unwrap();
writeln!(output, "const val OUT_SLOTS: Int = {}\n", OUT_SLOTS.len()).unwrap();
for op in BOUNDARY_SCHEMA {
writeln!(output, "/** `{}`, which calls `{}`. */", op.name, op.symbol).unwrap();
if op.fast {
output.push_str("@FastNative\n");
}
write!(output, "external fun {}(", kotlin_native_name(op.name)).unwrap();
let mut parameters = Vec::new();
for param in op.params {
match param {
BoundaryParam::Bytes { name } => {
parameters.push(format!("{name}: ByteBuffer"));
parameters.push(format!("{name}Length: Int"));
}
BoundaryParam::Nanos { name } => parameters.push(format!("{name}: Long")),
}
}
if op.returns_batch {
parameters.push("out: LongArray".to_owned());
}
writeln!(output, "{}): Int\n", parameters.join(", ")).unwrap();
}
output.push_str(
r#"/**
* A view of the Host's batch arena.
*
* Null before the Host exists. Ask again whenever `OUT_ARENA_ADDRESS` changes: a grown
* arena is a new allocation, and the old view points at freed memory.
*/
external fun nativeArenaBuffer(): ByteBuffer?
/**
* Called from a Host worker thread through JNI.
*
* It must stay cheap and thread-safe: it only bumps a counter the UI thread observes
* inside its frame clock, so any number of requests between two frames become one frame.
*/
fun onFrameRequested() {
// Evidence that domain work stays off the UI thread, off by default. Turn it on with
// `adb shell setprop log.tag.dxc-frame VERBOSE`: the thread named in the line is the
// Host worker that asked, and it is never the UI thread.
if (Log.isLoggable(FRAME_TAG, Log.VERBOSE)) {
Log.v(FRAME_TAG, "frame requested by ${Thread.currentThread().name}")
}
FrameRequests.request()
}
/**
* Called by the Host through JNI to measure, on the UI thread and inside a call this side
* made.
*
* Both buffers are views of the Host's own memory, made for this call and dropped after
* it: the requests it wrote and the room for the results it reads back. Nothing is copied.
*/
fun onMeasure(requests: ByteBuffer, count: Int, results: ByteBuffer): Int =
dev.darkpyonix.composerust.runtime.RendererMeasure.measure(requests, count, results)
private const val FRAME_TAG = "dxc-frame"
"#,
);
output
}
/// The `@FastNative` annotation is not in `android.jar`: the runtime reads it off the dex
/// by name.
pub fn generate_fast_native_kotlin() -> String {
String::from(
r#"// Generated by `cargo run -p compose-rust --bin codegen`. DO NOT EDIT.
package dalvik.annotation.optimization
/**
* The runtime's marker for a native method that needs no thread state transition.
*
* The runtime carries it, but `android.jar` does not declare it, so the only way to apply
* it from application code is to declare it. It is matched by type descriptor, and a
* runtime that does not know it ignores it, which is why an unannotated call still works.
*
* A method carrying it must not run long: the thread stays in the runnable state, so the
* garbage collector cannot suspend it while the call is in flight. Only calls that cannot
* run the VirtualDom carry it.
*/
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.FUNCTION)
annotation class FastNative
"#,
)
}
fn screaming_snake_case(name: &str) -> String {
let mut output = String::new();
for (index, character) in name.char_indices() {
if character.is_ascii_uppercase() && index != 0 {
output.push('_');
}
output.push(character.to_ascii_uppercase());
}
output
}
// ---------------------------------------------------------------------------------------
// Web bindings.
//
// Four renderings of one table. The Kotlin import declarations, the trampoline module, the
// page's loader module and the Rust wasm shims all come from `BOUNDARY_SCHEMA` and the
// memory constants beside it, so the argument order, the symbol names, the table slots and
// the record layout cannot drift apart. A browser would not report the drift: an import
// that nobody satisfies stops the module from being instantiated, a slot holding the wrong
// function traps on a signature mismatch at the first frame, and an offset read four bytes
// off draws a wrong screen.
// ---------------------------------------------------------------------------------------
/// Generated Rust, compiled into the cdylib only when the target is wasm.
pub const WASM_RUST_RELATIVE_PATH: &str = "src/boundary_wasm.gen.rs";
/// Generated Kotlin. The Kotlin Toolchain compiles the module's `src` tree by convention.
pub const WEB_BRIDGE_RELATIVE_PATH: &str = "../renderer/web/src/bridge/HostBridge.gen.kt";
/// Generated JavaScript, in the module's resource tree, which is copied next to `web.mjs`.
pub const WEB_LOADER_RELATIVE_PATH: &str = "../renderer/web/resources/compose-rust-host.gen.mjs";
/// The same loader beside the test page.
///
/// The Kotlin module imports the loader by a relative module name, so a page that has the
/// Kotlin module and not the loader does not load at all. The page a Kotlin/Wasm test runs
/// on is generated by the toolchain from `testResources`, so the loader has to be there as
/// well, or every test in the module stops before it starts.
pub const WEB_TEST_LOADER_RELATIVE_PATH: &str =
"../renderer/web/testResources/compose-rust-host.gen.mjs";
/// The loader's file name, which is also the module name the Kotlin imports name.
///
/// Kotlin/Wasm turns `@WasmImport("<module>", ...)` into `import * as ... from '<module>'`
/// in the JavaScript it generates beside its own module, so a relative name resolves to the
/// file next to that one, which is where the loader is copied.
pub const WEB_LOADER_FILE_NAME: &str = "compose-rust-host.gen.mjs";
const WEB_KOTLIN_PACKAGE: &str = "dev.darkpyonix.composerust.ui.platform";
/// The file name the loader fetches the Host from, next to itself.
pub const WEB_HOST_WASM_NAME: &str = "compose_rust_host.wasm";
/// How much shared memory the Host's module declares it needs.
///
/// The Kotlin module's memory starts at zero pages, so the page has to grow it to at least
/// the minimum the Host's imported memory declares before the two types match. The number
/// is fixed here and passed to the Host's linker as `--initial-memory`, so the loader and
/// the link agree by construction rather than by the loader guessing.
pub const WEB_MEMORY_MIN_PAGES: u32 = 128;
/// The wasm symbol for one logical operation on the web.
///
/// The Host exports it, the trampoline exports a function of the same name and type that
/// calls it through the table, and the Kotlin import names it.
fn web_symbol(op_name: &str) -> String {
format!("compose_rust_host_web_{}", snake_case(op_name))
}
/// The Kotlin name for it. Compose conventions, so camelCase.
fn web_kotlin_name(op_name: &str) -> String {
format!("host{op_name}")
}
/// The width of one value that crosses the web boundary.
///
/// Every call is wasm to wasm, so a value crosses as the wasm type it already is. A 64-bit
/// frame timestamp is one `i64` rather than two halves: nothing on the path is JavaScript,
/// so nothing turns it into a `BigInt`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum WebValue {
I32,
I64,
}
impl WebValue {
fn kotlin(self) -> &'static str {
match self {
Self::I32 => "Int",
Self::I64 => "Long",
}
}
fn rust(self) -> &'static str {
match self {
Self::I32 => "u32",
Self::I64 => "u64",
}
}
fn wasm(self) -> u8 {
match self {
Self::I32 => WASM_I32,
Self::I64 => WASM_I64,
}
}
}
/// The arguments one operation takes on the web, in order, as (name, width).
///
/// A byte range is an address and a length, both in the one shared memory. A call that
/// answers with a batch, and the one that releases it, also name the record to write it
/// into. Every operation answers with an `i32` status.
fn web_parameters(op: &BoundaryOp) -> Vec<(String, WebValue)> {
let mut parameters = Vec::new();
for param in op.params {
match param {
BoundaryParam::Bytes { name } => {
parameters.push(((*name).to_owned(), WebValue::I32));
parameters.push((format!("{name}Length"), WebValue::I32));
}
BoundaryParam::Nanos { name } => {
parameters.push(((*name).to_owned(), WebValue::I64));
}
}
}
if op.returns_batch || op.name == "ReleaseBatch" {
parameters.push(("out".to_owned(), WebValue::I32));
}
parameters
}
/// One function the trampoline carries: the Host export its slot holds, and what it takes.
struct WebCall {
symbol: String,
parameters: Vec<(String, WebValue)>,
}
/// Every Renderer to Host call, in the order of the trampoline's slots.
///
/// The boundary operations come first, in the order of `BOUNDARY_SCHEMA`, so an operation's
/// slot is its place in that table. After them comes the one setup call the Renderer makes
/// once the Host is running: borrowing a larger event buffer. It is not a boundary
/// operation, but it is still a call from the Renderer into the Host, and it goes through
/// the same table so that no call from this side has JavaScript on it.
fn web_calls() -> Vec<WebCall> {
let mut calls: Vec<WebCall> = BOUNDARY_SCHEMA
.iter()
.map(|op| WebCall {
symbol: web_symbol(op.name),
parameters: web_parameters(op),
})
.collect();
calls.push(WebCall {
symbol: WEB_LEND_EVENT_BUFFER_SYMBOL.to_owned(),
parameters: vec![("minLength".to_owned(), WebValue::I32)],
});
calls
}
const WASM_I32: u8 = 0x7F;
const WASM_I64: u8 = 0x7E;
const WASM_FUNCREF: u8 = 0x70;
fn wasm_uleb(mut value: u32, output: &mut Vec<u8>) {
loop {
let byte = (value & 0x7F) as u8;
value >>= 7;
if value == 0 {
output.push(byte);
return;
}
output.push(byte | 0x80);
}
}
fn wasm_sleb(mut value: i32, output: &mut Vec<u8>) {
loop {
let byte = (value & 0x7F) as u8;
value >>= 7;
let done = (value == 0 && byte & 0x40 == 0) || (value == -1 && byte & 0x40 != 0);
if done {
output.push(byte);
return;
}
output.push(byte | 0x80);
}
}
fn wasm_name(name: &str, output: &mut Vec<u8>) {
wasm_uleb(name.len() as u32, output);
output.extend_from_slice(name.as_bytes());
}
fn wasm_section(id: u8, payload: &[u8], output: &mut Vec<u8>) {
output.push(id);
wasm_uleb(payload.len() as u32, output);
output.extend_from_slice(payload);
}
/// The trampoline every Renderer to Host call goes through, as a wasm module.
///
/// It is what lets a Kotlin import reach a Rust export with no JavaScript on the call. The
/// Rust module imports the memory the Kotlin module defines, so Kotlin is instantiated
/// first, and at that moment there is no Rust export to hand its imports. Kotlin/Wasm
/// cannot declare an imported table, so it cannot call through one itself. This module
/// can: it imports `env.table`, and for every call exports a function of the call's own
/// type that passes its arguments on with `call_indirect` through the call's slot, which is
/// its place in [`web_calls`]. Kotlin imports these, and the Renderer's `main` fills the
/// slots with the Host's exports once the Host exists. A call is then one wasm `call` and
/// one `call_indirect`.
///
/// It is assembled here byte by byte rather than by a tool, because it is a few hundred
/// bytes and has to follow the schema exactly, and the generator already has the schema.
pub fn generate_web_trampoline_wasm() -> Vec<u8> {
// One type per distinct signature, and every operation's index into that list.
let calls = web_calls();
let mut signatures: Vec<Vec<u8>> = Vec::new();
let mut type_of: Vec<u32> = Vec::new();
for call in &calls {
let params: Vec<u8> = call
.parameters
.iter()
.map(|(_, value)| value.wasm())
.collect();
let index = match signatures.iter().position(|known| *known == params) {
Some(index) => index,
None => {
signatures.push(params);
signatures.len() - 1
}
};
type_of.push(index as u32);
}
let count = calls.len() as u32;
let mut types = Vec::new();
wasm_uleb(signatures.len() as u32, &mut types);
for params in &signatures {
types.push(0x60);
wasm_uleb(params.len() as u32, &mut types);
types.extend_from_slice(params);
// Every call answers with one i32: a status, or the address a lend hands back.
wasm_uleb(1, &mut types);
types.push(WASM_I32);
}
// (import "env" "table" (table <count> funcref))
let mut imports = Vec::new();
wasm_uleb(1, &mut imports);
wasm_name("env", &mut imports);
wasm_name("table", &mut imports);
imports.push(0x01);
imports.push(WASM_FUNCREF);
imports.push(0x00);
wasm_uleb(count, &mut imports);
let mut functions = Vec::new();
wasm_uleb(count, &mut functions);
for index in &type_of {
wasm_uleb(*index, &mut functions);
}
let mut exports = Vec::new();
wasm_uleb(count, &mut exports);
for (slot, call) in calls.iter().enumerate() {
wasm_name(&call.symbol, &mut exports);
exports.push(0x00);
wasm_uleb(slot as u32, &mut exports);
}
let mut code = Vec::new();
wasm_uleb(count, &mut code);
for (slot, call) in calls.iter().enumerate() {
let mut body = Vec::new();
// No locals beyond the parameters.
wasm_uleb(0, &mut body);
for parameter in 0..call.parameters.len() {
body.push(0x20); // local.get
wasm_uleb(parameter as u32, &mut body);
}
body.push(0x41); // i32.const
wasm_sleb(slot as i32, &mut body);
body.push(0x11); // call_indirect
wasm_uleb(type_of[slot], &mut body);
body.push(0x00); // table 0
body.push(0x0B); // end
wasm_uleb(body.len() as u32, &mut code);
code.extend_from_slice(&body);
}
let mut module = vec![0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00];
wasm_section(1, &types, &mut module);
wasm_section(2, &imports, &mut module);
wasm_section(3, &functions, &mut module);
wasm_section(7, &exports, &mut module);
wasm_section(10, &code, &mut module);
module
}
/// The one call that is not a boundary operation: bringing the Host into being.
///
/// It is generated into the Kotlin rather than into the page's loader module because this
/// is the side that holds what the Host needs. The memory belongs to this module and only
/// this module can name it; the function the Host's frame request binds to is one of this
/// module's exports; and `wasmExports` is where the generated import object keeps both,
/// filled in before `main` runs. The page's part is the one thing this side cannot do,
/// which is to finish an asynchronous fetch first.
///
/// The instantiation is asynchronous and answers a promise. A browser refuses to
/// instantiate a module larger than 8MB synchronously on its main thread (Chromium throws
/// "WebAssembly.Instance is disallowed on the main thread, if the buffer size is larger
/// than 8MB"), and a Host that carries an HTML engine is larger than that. Only start-up
/// waits: nothing is in the table until the promise settles, and every call after it is the
/// same wasm to wasm call through the trampoline.
///
/// It is also where the trampoline's table is filled, and only once the Host has reported
/// its block inside its own region. Until then every slot is empty, and a boundary call
/// traps inside wasm rather than reaching a Host that could not start.
///
/// Keeping it in one place also means a test can drive it. The page a Kotlin/Wasm test runs
/// on is generated by the toolchain and cannot load a module of its own, so a test puts a
/// compiled module on the same global the loader would have used, and everything after
/// that is what a browser really runs.
///
/// The body uses string concatenation rather than template literals. This is a Kotlin raw
/// string, and a `${...}` in it would be read as Kotlin interpolation before JavaScript
/// ever saw it.
const INSTALL_HOST_KOTLIN: &str = r##"/**
* Instantiates the Host on this module's memory, points the trampoline at it, and answers
* with a promise of the address of the block it lends back: the record a call reports into,
* and the buffer an event is encoded in. Zero means there is no Host on this page.
*
* Called once, from `main`. That is the first moment at which both halves exist: this
* module's own instantiation created the memory the Host imports, and the page compiled the
* Host's module before that started.
*
* A promise because a browser will not instantiate a module over 8MB synchronously on its
* main thread. The wait is start-up only: the table stays empty until the Host has checked
* out, and no call goes through a promise.
*/
@JsFun(
"""() => {
const compiled = globalThis.MODULE_GLOBAL;
if (!compiled) return Promise.resolve(0);
const table = globalThis.TABLE_GLOBAL;
if (!table) {
throw new Error('compose-rust: the trampoline table is missing. The loader module ' +
'creates it, and this module imports the loader, so a page without it was not ' +
'built from the generated files.');
}
const memory = wasmExports.memory;
const pages = memory.buffer.byteLength / 65536;
// This module's memory starts at zero pages and the Host's import declares a minimum,
// so the two module types do not match until this has run.
if (pages < MEMORY_MIN_PAGES) memory.grow(MEMORY_MIN_PAGES - pages);
// The wasm-bindgen placeholders dioxus-core brings in through subsecond. A browser will
// not instantiate a module with an import nobody supplied, used or not, and their names
// carry a per-version hash, so this answers whatever is asked rather than a list that
// would go stale. Nothing on the boundary goes near one.
const unbound = (namespace) => new Proxy({}, {
get: (_, name) => () => {
throw new Error('compose-rust: the Host called ' + namespace + '.' + String(name) +
', which is a wasm-bindgen import this page does not provide. Nothing on the ' +
'boundary uses one, so a call here means the Host reached JavaScript through a ' +
'dependency rather than through the boundary.');
},
});
return WebAssembly.instantiate(compiled, {
env: { memory },
RENDERER_IMPORT_MODULE: {
// The exported function object itself, not a closure around it: bound this way the
// engine builds no JavaScript frame for the call.
compose_rust_renderer_request_frame:
wasmExports.compose_rust_renderer_request_frame,
compose_rust_renderer_measure:
wasmExports.compose_rust_renderer_measure,
},
__wbindgen_placeholder__: unbound('__wbindgen_placeholder__'),
__wbindgen_externref_xform__: unbound('__wbindgen_externref_xform__'),
}).then((instance) => {
const host = instance.exports;
const block = host.START_SYMBOL();
if (block < REGION_BASE) {
// Either the Host could not start, or its data landed in the half of the memory this
// module's allocator uses. The second draws a wrong screen instead of failing, so
// neither is allowed to become the first boundary call: the table stays empty.
throw new Error('compose-rust: the Host reported its boundary block at ' + block +
', which is not inside the region above REGION_BASE that it was linked into. ' +
'Check that it was linked with --import-memory and --global-base.');
}
// The trampoline's slots, in the order its functions call them. The exported function
// objects themselves, so a call through a slot is wasm to wasm.
TABLE_SLOTS return block;
});
}""",
)
external fun installHost(): kotlin.js.Promise<JsNumber>
"##;
/// The lines that put the Host's exports into the trampoline's table, one per slot.
fn web_table_slots() -> String {
let mut output = String::new();
for (slot, call) in web_calls().iter().enumerate() {
writeln!(output, " table.set({slot}, host.{});", call.symbol).unwrap();
}
output
}
/// Emits the Kotlin half of the web boundary: one import per operation, bound to the
/// trampoline, the shared memory constants both sides read the batch record with, and the
/// export a Host worker calls to ask for a frame.
pub fn generate_web_bridge_kotlin() -> String {
let mut output = String::new();
output.push_str("// Generated by `cargo run -p compose-rust --bin codegen`. DO NOT EDIT.\n");
output.push_str(
"@file:OptIn(\n \
kotlin.js.ExperimentalWasmJsInterop::class,\n \
kotlin.wasm.ExperimentalWasmInterop::class,\n)\n\n",
);
writeln!(output, "package {WEB_KOTLIN_PACKAGE}\n").unwrap();
output.push_str("import kotlin.wasm.WasmExport\nimport kotlin.wasm.WasmImport\n\n");
output.push_str(
r#"// The web boundary.
//
// One WebAssembly.Memory holds both modules. The Kotlin module defines and exports it,
// because a Kotlin/Wasm module cannot import one, and the Host's module is linked against
// it, so a batch is read where the Host wrote it and no byte of it is copied.
//
// Every call below is a wasm import, and no call has JavaScript on it. Each one is bound to
// a function of the generated trampoline module, which passes its arguments on with
// `call_indirect` through a table whose slots hold the Host's exports. The table is what
// lets this module be instantiated before the Host exists, which it has to be, because the
// Host imports this module's memory. The loader creates the table and the trampoline before
// this module is instantiated; `installHost` fills the slots once the Host is running.
// A call is one wasm `call` and one `call_indirect`: no encoding, no copy, no queue.
//
// The other direction needs no trampoline. The Host is instantiated second, so the page
// hands it the function object Kotlin exports below, and the engine binds that edge as a
// wasm call.
"#,
);
writeln!(
output,
"/**\n \
* The first address that belongs to the Host's module.\n \
*\n \
* Below it is this module's `kotlin.wasm.unsafe` allocator; at and above it are the\n \
* Host's data, stack and heap. Two allocators hand out addresses in one memory, and an\n \
* overlap does not crash, it draws the wrong screen, so every address that crosses is\n \
* checked against this line.\n \
*/\n\
const val RUST_REGION_BASE: Int = {WEB_RUST_REGION_BASE}\n"
)
.unwrap();
output.push_str(
"/**\n \
* The batch record the Host writes, field by field.\n \
*\n \
* A wasm32 `#[repr(C)]` layout: two four byte fields and then an eight byte one, which\n \
* the padding before it puts at 8. The Host's generated shims assert this against the\n \
* layout its compiler chose, so a disagreement stops that build.\n \
*/\n",
);
for field in WEB_BATCH_FIELDS {
writeln!(output, "/** {}. */", field.description).unwrap();
writeln!(
output,
"const val BATCH_{}_OFFSET: Int = {}",
screaming_snake_case(field.name),
field.offset
)
.unwrap();
}
writeln!(
output,
"\n/** How long that record is, padding included. */\nconst val BATCH_BYTES: Int = {WEB_BATCH_BYTES}\n"
)
.unwrap();
writeln!(
output,
"/**\n \
* Where the event buffer starts inside the block the Host lends this side.\n \
*\n \
* The out record comes first and the event buffer follows it. Both belong to the Host,\n \
* because `kotlin.wasm.unsafe` only hands out addresses inside a scope and this side\n \
* needs two buffers that outlive every scope it could open.\n \
*/\n\
const val EVENT_BUFFER_OFFSET: Int = {WEB_EVENT_BUFFER_OFFSET}\n"
)
.unwrap();
writeln!(
output,
"/**\n \
* How much room there is to encode one event into, before any has needed more.\n \
*\n \
* An event that does not fit is encoded into a larger buffer the Host lends instead.\n \
*/\n\
const val EVENT_BUFFER_BYTES: Int = {WEB_EVENT_BUFFER_BYTES}\n"
)
.unwrap();
writeln!(
output,
"/**\n \
* The largest event buffer the Host lends.\n \
*\n \
* The buffer doubles from [EVENT_BUFFER_BYTES] until an event fits and stops here. An\n \
* event larger than this is refused, never cut short.\n \
*/\n\
const val EVENT_BUFFER_MAX_BYTES: Int = {WEB_EVENT_BUFFER_MAX_BYTES}\n"
)
.unwrap();
for (slot, op) in BOUNDARY_SCHEMA.iter().enumerate() {
let declared: Vec<String> = web_parameters(op)
.iter()
.map(|(name, value)| format!("{name}: {}", value.kotlin()))
.collect();
writeln!(
output,
"/** `{}`, which calls `{}` through slot {slot} of the trampoline. */",
op.name, op.symbol
)
.unwrap();
writeln!(
output,
"@WasmImport(\"./{WEB_LOADER_FILE_NAME}\", \"{}\")",
web_symbol(op.name)
)
.unwrap();
writeln!(
output,
"external fun {}({}): Int\n",
web_kotlin_name(op.name),
declared.join(", ")
)
.unwrap();
}
writeln!(
output,
"/**\n \
* Borrows an event buffer of at least `minLength` bytes from the Host, for an event that\n \
* does not fit in the one this side has. The Host keeps it until the next call, so\n \
* this side goes on encoding into it. Zero means the Host refused.\n \
*\n \
* Setup, like starting the Host, rather than a boundary operation: it is called only\n \
* when an event outgrows the buffer, which steady state never does. It still goes\n \
* through slot {} of the trampoline, so it has no JavaScript on it either.\n \
*/\n\
@WasmImport(\"./{WEB_LOADER_FILE_NAME}\", \"{WEB_LEND_EVENT_BUFFER_SYMBOL}\")\n\
external fun hostLendEventBuffer(minLength: Int): Int\n",
BOUNDARY_SCHEMA.len()
)
.unwrap();
output.push_str(
INSTALL_HOST_KOTLIN
.replace("MODULE_GLOBAL", WEB_MODULE_GLOBAL)
.replace("TABLE_GLOBAL", WEB_TABLE_GLOBAL)
.replace("TABLE_SLOTS", &web_table_slots())
.replace("RENDERER_IMPORT_MODULE", WEB_RENDERER_IMPORT_MODULE)
.replace("START_SYMBOL", WEB_START_SYMBOL)
.replace("MEMORY_MIN_PAGES", &WEB_MEMORY_MIN_PAGES.to_string())
.replace("REGION_BASE", &WEB_RUST_REGION_BASE.to_string())
.as_str(),
);
writeln!(
output,
"/**\n \
* Called by the Host when work done off the frame loop needs one.\n \
*\n \
* A browser tab is one thread, so this arrives on the same thread that will answer it.\n \
* It only bumps a counter the frame clock observes, so any number of requests between\n \
* two frames become one frame. The page also calls it once after the Host is installed,\n \
* which is what gets the first tree drawn.\n \
*/\n\
@WasmExport(\"compose_rust_renderer_request_frame\")\n\
fun onFrameRequested() {{\n \
FrameRequests.request()\n\
}}\n\n\
/**\n \
* Called by the Host to measure, inside a call this side made. A browser tab is one\n \
* thread, so this is always the thread that answers. Both addresses are in the Host's\n \
* region of the shared memory, and the requests and results are read and written\n \
* where they lie.\n \
*/\n\
@WasmExport(\"compose_rust_renderer_measure\")\n\
fun onMeasure(requests: Int, length: Int, count: Int, results: Int): Int =\n \
measureInSharedMemory(requests, length, count, results)"
)
.unwrap();
output
}
/// Emits the page's half: the trampoline and its table, which have to exist before the
/// Renderer's module is instantiated, and the Host compiled ahead of the Renderer's `main`.
pub fn generate_web_loader_js() -> String {
let mut output = String::new();
output.push_str("// Generated by `cargo run -p compose-rust --bin codegen`. DO NOT EDIT.\n");
output.push_str(
r#"//
// The page's half of the web boundary.
//
// `WebAssembly.instantiate` wants every import before it will give you an instance, and
// the two modules each hold what the other needs. The Renderer's module defines the one
// linear memory, which the Host imports; the Host exports the functions the Renderer
// calls. A table breaks that cycle without putting JavaScript on any call:
//
// 1. This module creates the table and instantiates the trampoline on it. The trampoline
// exports one function per boundary call, each a `call_indirect` through its slot.
// The Renderer's module imports this one by name, so it is always evaluated first.
// 2. It compiles the Host. Compiling needs no imports.
// 3. The Renderer's module is instantiated with its boundary imports bound to the
// trampoline's functions, which is what creates the memory.
// 4. The Renderer's `main` instantiates the Host on that memory and puts the Host's
// exports in the table. The instantiation is asynchronous, because a browser refuses
// to instantiate a module over 8MB synchronously on its main thread; the Renderer
// starts drawing once it has settled.
//
// JavaScript wires the modules together here and is not on any call afterwards. Step 4
// needs the memory and the Renderer's own exports, and only the Renderer's module can name
// either, so it sits in the generated Kotlin beside the imports.
"#,
);
writeln!(output, "const HOST_WASM = './{WEB_HOST_WASM_NAME}';\n").unwrap();
writeln!(
output,
"// One slot per call into the Host: the boundary calls in the order of the boundary\n\
// schema, then the event buffer lend. Empty until the Host is running, so a call made\n\
// before then traps inside wasm.\n\
const table = new WebAssembly.Table({{ element: 'anyfunc', initial: {} }});\n\
globalThis.{WEB_TABLE_GLOBAL} = table;\n",
web_calls().len()
)
.unwrap();
output.push_str(
"// The trampoline module, assembled by the generator from the same schema.\n\
const trampoline = (\n await WebAssembly.instantiate(\n new Uint8Array([\n",
);
for chunk in generate_web_trampoline_wasm().chunks(12) {
let bytes: Vec<String> = chunk.iter().map(|byte| format!("0x{byte:02x}")).collect();
writeln!(output, " {},", bytes.join(", ")).unwrap();
}
output.push_str(" ]),\n { env: { table } },\n )\n).instance.exports;\n\n");
output.push_str(
"// What the Renderer's module imports. Each is a wasm function, so the engine binds the\n\
// Renderer's import to it as a wasm call.\n",
);
for call in web_calls() {
let symbol = call.symbol;
writeln!(output, "export const {symbol} = trampoline.{symbol};").unwrap();
}
output.push('\n');
writeln!(output, "globalThis.{WEB_MODULE_GLOBAL} = null;").unwrap();
output.push_str("try {\n globalThis.");
output.push_str(WEB_MODULE_GLOBAL);
output.push_str(
r#" = await WebAssembly.compileStreaming(
fetch(new URL(HOST_WASM, import.meta.url)),
);
} catch (error) {
// No Host on this page, which is a page serving the renderer on its own. The renderer
// falls back to its scripted development host, and this says why on the console rather
// than leaving an empty screen to be puzzled over.
console.info(
`compose-rust: no Host module beside this page (${HOST_WASM}: ${error}). ` +
'The renderer will draw its development host instead.',
);
}
"#,
);
output
}
/// Emits the Rust half of the web boundary: one wasm shim per operation, the block the
/// Host lends the Renderer, and the entry point a page uses in place of a library loader.
pub fn generate_wasm_rust() -> String {
let mut output = String::new();
output.push_str("// Generated by `cargo run -p compose-rust --bin codegen`. DO NOT EDIT.\n");
output.push_str(
r#"//! The wasm shims for the web boundary.
//!
//! The Renderer owns the one linear memory and this module imports it, so a batch is read
//! where it was written. That leaves the addresses: every address below is in that shared
//! memory, and both buffers a call names belong to this side, because the Renderer has no
//! allocator that can hold memory from one frame to the next.
//!
//! The Renderer reaches these through the generated trampoline, whose table holds them, so
//! every call arrives from wasm with no JavaScript in between. A value arrives as the wasm
//! type it is: an address or a length as an `i32`, a frame timestamp as one `i64`.
use crate::boundary::{
MutationBatch, RendererApi, STATUS_OK, STATUS_PROTOCOL_ERROR, install_renderer_api,
};
use crate::measure::MeasureResult;
use crate::schema::{
WEB_BATCH_BYTES, WEB_EVENT_BUFFER_BYTES, WEB_EVENT_BUFFER_OFFSET, WEB_RUST_REGION_BASE,
};
use crate::web_event_buffer::{LentEventBuffer, region_address};
use crate::{LaunchBuilder, LoopMode, Runtime};
use std::ffi::c_int;
use std::mem::{offset_of, size_of};
"#,
);
writeln!(
output,
"#[link(wasm_import_module = \"{WEB_RENDERER_IMPORT_MODULE}\")]"
)
.unwrap();
output.push_str(
r#"unsafe extern "C" {
/// Bound to the function the Renderer exports, with no JavaScript in between: the page
/// hands the exported function object straight to this module's instantiation, which it
/// can because this module is instantiated second.
fn compose_rust_renderer_request_frame();
/// Bound the same way, to the Renderer's measure export. The two buffers are addresses
/// in the shared memory, in this module's region, and the Renderer reads and writes
/// them where they lie.
fn compose_rust_renderer_measure(
requests: *const u8,
length: u32,
count: u32,
results: *mut MeasureResult,
) -> i32;
}
/// The record layout the generated Kotlin reads a reply out of.
///
/// Written down on the Kotlin side as constants and checked here against what this
/// compiler actually chose. A layout that disagreed would not fail anywhere else: the
/// Renderer would read four bytes at the wrong offset and draw whatever they happened to
/// mean.
const _: () = {
assert!(size_of::<MutationBatch>() == WEB_BATCH_BYTES as usize);
"#,
);
for field in WEB_BATCH_FIELDS {
let member = match field.name {
"Address" => "ptr",
"Length" => "len",
"Result" => "result",
other => panic!("no MutationBatch member is named {other}"),
};
writeln!(
output,
" assert!(offset_of!(MutationBatch, {member}) == {});",
field.offset
)
.unwrap();
}
output.push_str("};\n\n");
output.push_str(
r#"/// What the Host lends the Renderer, once, for the life of the page.
///
/// The Renderer cannot own either buffer. `kotlin.wasm.unsafe` hands out addresses that
/// are only valid inside the scope that asked for them, and opening a scope per call is
/// the steady-state allocation the frame budget does not have. So both sit here, in this
/// module's region, and the Renderer keeps the address.
#[repr(C)]
struct BoundaryBlock {
/// Where a call writes what it did. The Renderer reads it and releases it on the same
/// call stack.
out: MutationBatch,
/// Where the Renderer encodes one event before the call that carries it.
event: [u8; WEB_EVENT_BUFFER_BYTES as usize],
}
/// A browser tab is one thread, and the Renderer needs this address to stay where it is
/// between calls, so it is a static rather than a thread local.
static mut BLOCK: BoundaryBlock = BoundaryBlock {
out: MutationBatch {
ptr: std::ptr::null(),
len: 0,
result: 0,
},
event: [0; WEB_EVENT_BUFFER_BYTES as usize],
};
/// Where the Renderer is told the event buffer starts, against where it really starts.
const _: () = assert!(offset_of!(BoundaryBlock, event) == WEB_EVENT_BUFFER_OFFSET as usize);
/// The page owns the loop, so the Host never runs one.
extern "C" fn platform_run() -> c_int {
STATUS_OK as c_int
}
extern "C" fn request_frame() {
// SAFETY: the page supplied this import from the Renderer's exports before this
// module was instantiated, so there is a function here to call.
unsafe { compose_rust_renderer_request_frame() };
}
/// # Safety
/// `requests` must address `length` readable bytes and `results` room for `count` results.
unsafe extern "C" fn measure(
requests: *const u8,
length: u32,
count: u32,
results: *mut MeasureResult,
) -> i32 {
// SAFETY: supplied by the page from the Renderer's exports, like the frame request,
// and the caller's promise about the buffers is passed on unchanged.
unsafe { compose_rust_renderer_measure(requests, length, count, results) }
}
/// Whether an address the Renderer passed is one this side lent it.
///
/// Every buffer a call names is in this module's region. An address below the region is
/// either the Renderer allocator's, which would mean the two allocators have grown into
/// each other, or a stray number, and neither is worth reading or writing through.
fn lent(address: u32) -> bool {
address >= WEB_RUST_REGION_BASE
}
"#,
);
for op in BOUNDARY_SCHEMA {
write!(output, "{}", wasm_shim(op)).unwrap();
}
writeln!(
output,
r#"thread_local! {{
/// The larger event buffer, once an event has outgrown the one in [`BLOCK`].
///
/// Kept here rather than in the block because its size is only known when an event
/// needs it, and kept until the next request because the Renderer goes on encoding into
/// it. A browser tab is one thread, so the thread's own copy is the only one.
static LENT_EVENT_BUFFER: std::cell::RefCell<LentEventBuffer> =
const {{ std::cell::RefCell::new(LentEventBuffer::new()) }};
}}
/// Lends the Renderer an event buffer of at least `min_len` bytes and answers with its
/// address, or zero when the request is refused.
///
/// The Renderer calls this only when an event does not fit in the buffer it has, doubling
/// what it asks for each time up to {max} bytes, and keeps encoding into what it gets.
/// The buffer stays where it is until the next call, so a request it already satisfies
/// answers with the same address and allocates nothing. Zero is the answer for a request
/// past the ceiling, for memory that cannot be had, and for an address outside this
/// module's region, which the Renderer would have to refuse anyway. A refused request
/// leaves the buffer lent before it in place.
///
/// This is setup, like `{start}`, and not a boundary operation.
#[unsafe(no_mangle)]
pub extern "C" fn {lend}(min_len: u32) -> u32 {{
LENT_EVENT_BUFFER
.with_borrow_mut(|buffer| buffer.lend(min_len))
.map_or(0, |pointer| region_address(pointer.cast_const()))
}}
"#,
max = WEB_EVENT_BUFFER_MAX_BYTES,
start = WEB_START_SYMBOL,
lend = WEB_LEND_EVENT_BUFFER_SYMBOL,
)
.unwrap();
writeln!(
output,
r#"/// Starts the Host and reports where the block it lends the Renderer sits.
///
/// A page has no library loader, so this is where the work `JNI_OnLoad` does on Android
/// goes: install the renderer API, then register the application's runtime. Zero means the
/// block is not somewhere the Renderer may read, and the Renderer makes no boundary call at
/// all in that case.
///
/// The application exports this as `{WEB_START_SYMBOL}` through its authoring layer's
/// entry point (`web_main!` in dioxus-compose), and the export lives there rather than
/// here because a wasm module cannot be linked with an undefined symbol the way an ELF
/// shared library can: an import nobody satisfies stops the module from being
/// instantiated, so this crate's own module must not name a function only an application
/// can define.
///
/// The builder comes from the application rather than being made here, because
/// everything an application settles before it launches, its theme above all, is settled
/// on a builder. Making one here would mean a page ignored the theme its own desktop
/// binary uses and drew the same screens in a different design system.
pub fn web_start(
builder: LaunchBuilder,
runtime: impl Fn() -> Box<dyn Runtime> + Send + Sync + 'static,
) -> u32 {{
let _ = install_renderer_api(RendererApi {{
run: platform_run,
request_frame,
measure,
}});
let status = builder
.with_mode(LoopMode::Platform)
.try_launch_runtime(runtime);
if status != STATUS_OK {{
return 0;
}}
let address = (&raw const BLOCK) as usize as u32;
if lent(address) {{ address }} else {{ 0 }}
}}"#
)
.unwrap();
rustfmt(output)
}
fn wasm_shim(op: &BoundaryOp) -> String {
let mut output = String::new();
writeln!(output, "/// `{}`, which calls `{}`.", op.name, op.symbol).unwrap();
output.push_str("#[unsafe(no_mangle)]\npub extern \"C\" fn ");
write!(output, "{}(", web_symbol(op.name)).unwrap();
let declared: Vec<String> = web_parameters(op)
.iter()
.map(|(name, value)| format!("{}: {}", snake_case(name), value.rust()))
.collect();
writeln!(output, "{}) -> i32 {{", declared.join(", ")).unwrap();
// Anything that is an address has to be inside this module's region before it is read
// or written through, and a zero-length range names no address at all.
let mut guards: Vec<String> = Vec::new();
let mut arguments: Vec<String> = Vec::new();
for param in op.params {
match param {
BoundaryParam::Bytes { name } => {
let address = snake_case(name);
let length = snake_case(&format!("{name}Length"));
guards.push(format!("({length} == 0 || lent({address}))"));
arguments.push(format!("{address} as *const u8"));
arguments.push(length);
}
BoundaryParam::Nanos { name } => {
arguments.push(snake_case(name));
}
}
}
let takes_out = op.returns_batch || op.name == "ReleaseBatch";
if takes_out {
guards.push("lent(out)".to_owned());
arguments.push("out as *mut MutationBatch".to_owned());
}
// Refused before anything is worked out from the arguments, so that a call that will
// not happen costs nothing.
if !guards.is_empty() {
let condition = if guards.len() == 1 {
guards[0].clone()
} else {
guards.join(" && ")
};
writeln!(output, " if !({condition}) {{").unwrap();
output.push_str(" return STATUS_PROTOCOL_ERROR;\n }\n");
}
let call = format!("crate::boundary::{}({})", op.symbol, arguments.join(", "));
if op.symbol == "compose_rust_host_shutdown" {
writeln!(output, " {call};").unwrap();
output.push_str(" STATUS_OK\n}\n\n");
return output;
}
output.push_str(
" // SAFETY: every address above was checked to be inside this module's region,\n\
\x20 // which is where the only buffers the Renderer can name live.\n",
);
if op.returns_batch {
writeln!(output, " unsafe {{ {call} }}").unwrap();
} else {
writeln!(output, " unsafe {{ {call} }};").unwrap();
output.push_str(" STATUS_OK\n");
}
output.push_str("}\n\n");
output
}
// ---------------------------------------------------------------------------------------
// The Linux static renderer's reach into the Host.
//
// That renderer is a Kotlin/Native archive linked into the application, so the Host's
// functions are in the same executable as the code that calls them. They are reached the
// way any two halves of one program reach each other, by name at link time, rather than
// looked up at run time: a lookup reads the executable's dynamic symbol table, and nothing
// a dependency can ask of an application's link puts them there without a shared library
// beside the executable, which is exactly what one executable cannot have.
//
// The references are weak. A Kotlin/Native test executable for the renderer's own module
// links with no Host in it, and a strong reference would fail that link; a weak one
// resolves to nothing there, and the renderer falls back to the lookup it uses everywhere
// else. In an application the Host is linked, the references resolve to it, and nothing
// is looked up.
// ---------------------------------------------------------------------------------------
/// The cinterop definition the Linux module's `cinterop/` directory holds. The Kotlin
/// Toolchain picks up every definition there by convention.
pub const LINUX_HOST_DEF_RELATIVE_PATH: &str = "../renderer/linux/cinterop/host.def";
/// The C function the Linux renderer calls to find one Host function by name.
pub const LINKED_HOST_FUNCTION: &str = "dxc_linked_host_function";
/// Emits the cinterop definition that gives the Linux renderer the Host's addresses.
pub fn generate_linux_host_def() -> String {
let mut output = String::new();
output.push_str("# Generated by `cargo run -p compose-rust --bin codegen`. DO NOT EDIT.\n");
output.push_str(
r#"#
# Where the Linux renderer finds the Host's functions when it is linked into the
# application as a static archive.
#
# The renderer and the Host are one executable then, so the Host's functions are referred
# to by name and the link resolves them, the way any two halves of one program refer to each
# other. Looking them up at run time instead reads the executable's dynamic symbol table,
# and a Rust executable puts nothing there unless a shared library beside it asks for it.
#
# The references are weak. The renderer module's own test executable links with no Host in
# it, and a weak reference that nothing defines is a null address rather than a failed
# link. The renderer then falls back to looking the name up, which is also what it does on
# every other platform.
package = dxc_host
# The declarations below exist to be referred to, not called from Kotlin: the renderer
# calls through the addresses with the signatures its own boundary code declares.
"#,
);
output.push_str("excludedFunctions =");
for op in BOUNDARY_SCHEMA {
write!(output, " {}", op.symbol).unwrap();
}
output.push_str("\n\n---\n\n");
// The prototypes are deliberately not the real ones. Only addresses are taken here, so
// a signature that later changes cannot make this file disagree with the Host.
for op in BOUNDARY_SCHEMA {
writeln!(
output,
"extern void {}(void) __attribute__((weak));",
op.symbol
)
.unwrap();
}
output.push('\n');
writeln!(
output,
"static inline void* {LINKED_HOST_FUNCTION}(const char* name) {{"
)
.unwrap();
for op in BOUNDARY_SCHEMA {
writeln!(
output,
" if (__builtin_strcmp(name, \"{0}\") == 0) return (void*)&{0};",
op.symbol
)
.unwrap();
}
output.push_str(" return 0;\n}\n");
output
}