app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
[package]
name = "rune-luau"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "Sandboxed Luau scripting for Rune UIs, with direct element builders, async task scheduling, and hot reload."
[features]
default = ["wasi-allocator"]
# Luau native code generation for modules that open with `--!native` (Windows and Linux, x86-64 and
# arm64; enable it only for those targets). Off, they run in the interpreter. On, every VM makes
# a code generator as it starts: a 4 MiB committed code block per VM, used or not (21 VMs in
# OpenCode held 88 MB of commit this way with no native module among them).
native-code = ["mlua/luau-jit"]
# `Script::watch`: reload a script folder when a file in it is saved (notify; native only).
watch = ["dep:notify"]
# On wasm32-unknown-unknown, Rust allocates through WASI libc's malloc, which Luau's C++ uses,
# so one allocator owns linear memory. Off: the app installs such an allocator itself.
wasi-allocator = []
# Decoding script values into a host's own records: `Data::decode` (whole numbers decode into
# `i64` fields on every target), and mlua's `LuaSerdeExt`.
serde = ["mlua/serde", "dep:serde", "dep:serde_json"]
[dependencies]
rune = { workspace = true }
rustc-hash = { workspace = true }
serde = { workspace = true, optional = true }
serde_json = { workspace = true, optional = true }
# mlua is pinned to a rev on main: wasm32-unknown-unknown support landed after 0.12.2.
mlua = { git = "https://github.com/mlua-rs/mlua", rev = "a0ad4535fc72ba89967a931c5be57b162b5f0f3f", features = ["luau"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
notify = { version = "8.2", optional = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = { workspace = true }
wasm-bindgen-futures = { workspace = true }
js-sys = { workspace = true }
web-sys = { workspace = true, features = ["console"] }
[lints]
workspace = true
+115
View File
@@ -0,0 +1,115 @@
# rune-luau
Luau scripts that build Rune UI. A `Script` is one sandboxed Luau VM: its `init.luau` returns a
module whose `render(view)` builds nodes with `@rune/ui`, straight into `rune::El`s.
```rust
struct State { script: Script }
fn view(s: &State, cx: &mut Cx<State>) -> El { s.script.view(cx) }
fn poll(s: &mut State, now: f64, tx: &mut Tx) -> bool { s.script.poll(now, tx) }
fn setup(s: &mut State, waker: Waker) { s.script.set_waker(waker) }
let script = Script::new("panel", Sources::from_dir("scripts/panel")?);
script.watch("scripts/panel")?; // `watch` feature: save a file, the panel reloads
```
```luau
--!strict
local ui = require("@rune/ui")
local count = 0
return {
render = function(view)
return ui.col({ pad = 16, gap = 8 }, {
ui.text(`Pressed {count} times`),
ui.row({ key = "inc", px = 10, py = 4, radius = 6, fill = "control-off",
onPress = function() count += 1 end }, { "Press" }),
})
end,
}
```
## Host API
| Call | What it does |
| --- | --- |
| `Script::new(name, sources)`, `Script::with_options(..)` | Compiles and starts a script. One that fails to start still renders, as an error card. |
| `ScriptOptions::new().palette(..).setup(..).node(..).time_limit(..).memory_limit(..).on_log(..)` | Colour names, host bindings for each new VM, host-built `ui.*` nodes, the watchdog's CPU-time budget (250 ms), the heap limit (64 MB), and a log sink. |
| `ScriptOptions::start(..).around(..).around_read(..).shadows(..).text(..)` | A hook that runs with each new VM and the table its entry returned (call a setup function it hands over); hooks around entries from the UI with the app's state and transaction; elevation shadows; the base text style and the weights `regular`..`bold` name. |
| `Sources::entry(path)` | Starts from another module than `init.luau` (`app.luau` beside it). |
| `script.render_fn(id, version, dark, f, args)`, `script.spawn_fn(f, args, tx)`, `script.eval_fn(f, args)` | Functions a script handed the host: render one as a memoized surface, run one as a task, or call one at once without letting it wait. `script.version()` moves whenever script code runs. |
| `script.view(cx)`, `script.surface(cx, name)` | The module's `render(view)` (or `name(view)`), memoized on the script's version: a view rebuilt for other reasons reuses it without entering the VM. |
| `script.poll(now, tx)` | Runs finished host calls, due `task.wait`/`task.delay` deadlines and deferred tasks, then arms `Tx::wake_after` for the next deadline. With nothing due it never enters the VM. |
| `script.reload(sources)`, `script.watch(dir)` | Hot reload: the new VM gets `loadHotState(saveHotState())`. A compile or start error keeps the running VM. |
| `script.fire(name, data)`, `script.call(name, data)`, `script.query(name, data)` | Fires a host signal; runs an export as a task; calls an export and returns its result. |
| `Host::signal`, `Host::script_signal`, `Host::async_function`, `Host::register_module`, `Host::global` | What `ScriptOptions::setup` binds. An async function hands the host a `Completer`, finished from any thread; `spawn_blocking` runs work off the UI thread. |
| `script.error()`, `script.log()`, `script.metrics()`, `script.memory()` | Why it stopped, recent `print`/`warn`/error lines, VM entries and time, heap bytes. |
| `Data`, `Data::decode` (`serde` feature) | Plain values across the VM boundary. Whole numbers are `Data::Integer` and decode into `i64` fields on every target; mlua's own serde path gives wasm32 a float for whole numbers past 32 bits. |
## In Luau
- **`@rune/ui`**: `row`, `col`, `box`, `spacer`, `text(content, props)`, `virtualList`, `each`,
`hex`. Containers take `(props, children)`; a string child is text, and `nil` or `false`
children are skipped. A props table frozen with `table.freeze` is decoded once per VM and its
node copied after that; a node whose props are partly its own takes the frozen style first and
a small table of its own after it, laid over it (`ui.row(ROW, { key = id }, children)`,
`ui.text(words, LABEL, { color = ink })`, host nodes too), and only that table is decoded.
Values after a text's props fill `{1}`, `{2}`... in its content, straight into the string the
element keeps (`ui.text("{1} / {2}", VALUE, read, write)`). Props: `key`, `w`/`h` (points or `"full"`), `minW`..`maxH`, `grow`, `shrink`, `pad`,
`px`..`pl`, `m`..`ml`, `gap`, `align`, `justify`, `center`, `wrap`, `fill`, `hover`, `press`,
`border`, `borderWidth`, `radius`, `clip`, `scrollY`, `scrollX`, `opacity`, `role`, `label`,
`help`, `helpSide`, `helpOpen` (keeps the tooltip up while true, as a `Tooltip forceOpen`), `dir` (`"ltr"`, `"rtl"` or `"auto"`), `pin`, `corners`, `shadow`, `selected`, `focusable`, `disabled`, `hoverTransition`, `hoverGroup`, `hoverGroupColor`, `revealOnHover`, `onPress`, `onMiddlePress` (a middle click: a `middle-press` event), `menuTrigger` (its `onPress` opens a menu: a mouse runs it as the button goes down, as Kobalte's `Menu.Trigger`; a key, a screen reader's Invoke or a tap runs it on the click), `onHover`, and for text `size`, `weight`, `lineHeight`, `tracking`, `color`, `mono`,
`tabular`, `noWrap`, `truncate`, `fadeOut`, `selectable`, `textAlign`. Colours are palette names or
`ui.hex("#rrggbb")`.
- **`view:Memo(key, version, build)`** reuses the subtree while `version` (a string, number or
boolean) is unchanged, without calling `build`. Its memo id, and its root's key, is `key` under
the script's prefix (`luau:<name>:<key>`), so scripts in one window never share a memo. **`view:Handler(fn)`** returns `fn`; handlers
run as tasks and receive a `UiEvent` (`kind`, `key`, `shift`, `alt`, `mod`).
- **`ui.each(items, key, version, build)`** returns `build(item, index)` for each item as a list
of children, each a memo of its own on the item's key (also its node's key) and version, so a
render rebuilds only the items whose version moved. `key` and `version` are field names or
functions of `(item, index)`.
- **`ui.virtualList({ count, estimatedRowHeight, version, renderRow, rowKey?, rowVersions?, onVisibleRows?, gap?, scrollY? })`**
is `El::virtual_rows`: `renderRow(i)` (from 1) runs only for rows entering the window, and each
row is memoized on `version` and its entry in `rowVersions`. With `scrollY = false` it has no
viewport of its own: it sits in a scrolling column under or among other content and builds the
rows that column shows.
- **`task`**: `spawn`, `defer`, `delay`, `wait` and `cancel`, on the frame clock `poll` receives.
Waiting costs nothing; `wait` in a render is an error.
- **Signals**: a host's `Signal` has `Connect`, `Once` and `Wait`; a `ScriptSignal`
(`require("@rune/signal").new()`) adds `Fire` and `Version`. A `Connection` has `Connected`
and `Disconnect`. Connections run as tasks.
- **`require`** follows Luau's require-by-string rules inside the script's folder, so the host and
`luau-lsp` agree. `init.luau` stands for its folder: from it, `require("@self/x")` is `x.luau`
and `require("./x")` would be beside the folder. `.luaurc` aliases apply, including the one
above the folder (`Sources::parent_config`). Nothing outside the folder resolves; a cycle is an
error naming the chain. A module that starts with `--!native` compiles to native code with
the `native-code` feature (Windows and Linux).
## Errors
Nothing a script does panics the app. A render error shows an error card with a Reload button;
a task error is logged; the watchdog stops any entry that uses more than 250 ms of its thread's
CPU time (time spent waiting for a CPU or on a host call isn't charged; 20 times that in wall time
bounds it), at a Luau safepoint, and that script carries on with its next call.
## Platforms
Scripts run in Luau's interpreter. The `native-code` feature adds Luau's native code generation
for modules that open with `--!native`, on Windows and Linux (x86-64, arm64) only: enable it for
those targets alone. It costs every VM a 4 MiB committed code block as the VM starts, whether a
native module ever loads or not. On `wasm32-unknown-unknown`, Luau's C++ builds with
[WASI SDK](https://github.com/WebAssembly/wasi-sdk) 33 or newer and WebAssembly exception
handling: set `WASI_SDK_PATH` and `scripts/web-build.sh` sets the compilers up; this crate links
the SDK's C runtime and defines the few WASI calls it makes, so the page needs nothing extra.
On the web, `spawn_blocking` runs its job on the main thread after the current frame's work;
finish browser-async work (a `fetch`) from its own callback through the `Completer`.
`mlua` is pinned to a commit on its main branch: `wasm32-unknown-unknown` support landed after
0.12.2.
## Example
`examples/luau-panel`: a header, a pulse driven by `task.wait`, a signal and a 1,000-row virtual
list. `cargo run -p luau-panel`; `cargo run -p luau-panel --bin luau-bench --profile perf`
measures idle frames, memo hits, a 20-row rebuild, list scrolling and hot reload.
+31
View File
@@ -0,0 +1,31 @@
//! On `wasm32-unknown-unknown`, Luau's C++ is compiled by WASI SDK's clang against WASI libc with
//! WebAssembly exception handling (`scripts/web-build.sh` sets the compiler up). The C++ runtime,
//! the unwinder and libc come from the same SDK, so link them here: any app that depends on this
//! crate then links on the web without flags of its own.
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=WASI_SDK_PATH");
println!("cargo::rustc-check-cfg=cfg(luau_jit)");
let var = |name: &str| std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()).unwrap_or_default();
let (os, arch) = (var("CARGO_CFG_TARGET_OS"), var("CARGO_CFG_TARGET_ARCH"));
// The `native-code` feature, on the targets where Luau has a backend and a process may map
// executable memory without an entitlement.
if std::env::var_os("CARGO_FEATURE_NATIVE_CODE").is_some() && matches!(os.as_str(), "windows" | "linux") && matches!(arch.as_str(), "x86_64" | "aarch64") {
println!("cargo:rustc-cfg=luau_jit");
}
if var("TARGET") != "wasm32-unknown-unknown" {
return;
}
let Some(sdk) = std::env::var_os("WASI_SDK_PATH") else {
println!("cargo:warning=rune-luau on wasm32-unknown-unknown needs WASI SDK: set WASI_SDK_PATH (scripts/web-build.sh does)");
return;
};
let lib = std::path::Path::new(&sdk).join("share").join("wasi-sysroot").join("lib").join("wasm32-wasip1");
println!("cargo:rustc-link-search=native={}", lib.join("eh").display());
println!("cargo:rustc-link-search=native={}", lib.display());
// `clock()`, which `os.clock` reads, comes from the emulated process clocks.
for name in ["c++abi", "unwind", "wasi-emulated-process-clocks", "c"] {
println!("cargo:rustc-link-lib=static={name}");
}
}
+47
View File
@@ -0,0 +1,47 @@
//! The card a surface shows in place of a render that failed: the error's first line, its
//! traceback, and Reload, which runs the script again from its current sources.
use std::rc::Weak;
use rune::{Color, El, TextStyle, col, row, text};
use crate::script::Inner;
use crate::ui::{Attach, Palette};
pub(crate) fn error_card(message: &str, palette: &Palette, dark: bool, attach: &'static Attach, script: Weak<Inner>) -> El {
let color = |name: &str, fallback: Color| palette(name, dark).unwrap_or(fallback);
let fg = color("text", if dark { Color::WHITE } else { Color::BLACK });
let weak = color("text-secondary", fg.alpha(0.7));
let danger = rune::color::hex("#e5484d").unwrap_or(fg);
let mut lines = message.lines();
let first = lines.next().unwrap_or("script error");
let rest: Vec<&str> = lines.filter(|l| !l.trim().is_empty()).take(12).collect();
let reload = row()
.key("luau-reload")
.px(10.0)
.py(4.0)
.radius(6.0)
.fill(color("control-off", weak.alpha(0.2)))
.hover(color("hover", weak.alpha(0.1)))
.child(text("Reload").font(TextStyle::new(12.0, 500.0)).color(fg))
.label("Reload script");
let mut card = col()
.key("luau-error")
.w_full()
.padding(12.0)
.gap(8.0)
.radius(8.0)
.fill(color("card", Color::TRANSPARENT))
.border(1.0, danger)
.child(text(format!("Stopped drawing: {first}")).font(TextStyle::new(13.0, 500.0)).color(fg).wrap().w_full());
if !rest.is_empty() {
card = card.child(text(rest.join("\n")).font(TextStyle::new(11.0, 400.0).mono()).color(weak).wrap().w_full());
}
card.child(row().child((attach.reload)(reload, script)))
}
/// What a row shows when `renderRow` fails.
pub(crate) fn row_error(message: &str) -> El {
let danger = rune::color::hex("#e5484d").unwrap_or(Color::WHITE);
text(message.lines().next().unwrap_or("row failed").to_owned()).font(TextStyle::new(11.0, 400.0).mono()).color(danger).truncate().w_full()
}
+282
View File
@@ -0,0 +1,282 @@
//! [`Data`]: plain values that cross a VM boundary: from a worker thread into a script, from a
//! host into a [signal](crate::Script::fire), and from the old VM to the new one on a hot reload.
#![allow(unsafe_code)]
use std::collections::BTreeMap;
use mlua::{FromLua, IntoLua, Lua, Value};
/// A plain, owned value: what a script table holds, without functions, threads or userdata.
/// It is `Send`, so a worker thread can return one.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Data {
#[default]
Nil,
Bool(bool),
/// A whole number: Luau keeps every number as a double, and a whole one comes across as
/// this, so it decodes into an integer field.
Integer(i64),
Number(f64),
String(String),
/// A Luau array: keys `1..=n`.
List(Vec<Data>),
/// A Luau table with string keys.
Map(BTreeMap<String, Data>),
}
/// How deep [`Data`] follows nested tables; a deeper or cyclic table stops there as `nil`.
const MAX_DEPTH: usize = 64;
/// The largest whole number a double holds exactly (2^53 - 1).
const MAX_SAFE: f64 = 9_007_199_254_740_991.0;
impl Data {
/// The value as a number, if it is one.
pub fn as_f64(&self) -> Option<f64> {
match self {
Data::Number(n) => Some(*n),
Data::Integer(i) => Some(*i as f64),
_ => None,
}
}
/// The value as an integer, if it is a whole number.
pub fn as_i64(&self) -> Option<i64> {
match self {
Data::Integer(i) => Some(*i),
_ => None,
}
}
/// The value as a string, if it is one.
pub fn as_str(&self) -> Option<&str> {
if let Data::String(s) = self { Some(s) } else { None }
}
/// The field `key` of a map, or [`Data::Nil`].
pub fn get(&self, key: &str) -> &Data {
const NIL: Data = Data::Nil;
match self {
Data::Map(m) => m.get(key).unwrap_or(&NIL),
_ => &NIL,
}
}
/// Decodes into a host record through serde. Whole numbers decode into integer fields on
/// every target: mlua's own serde path hands wasm32 hosts a float for any whole number past
/// 32 bits, which an `i64` field refuses.
#[cfg(feature = "serde")]
pub fn decode<T: serde::de::DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
serde_json::from_value(self.to_json())
}
/// The value as JSON: lists as arrays, maps as objects, whole numbers as integers.
#[cfg(feature = "serde")]
pub fn to_json(&self) -> serde_json::Value {
use serde_json::Value as J;
match self {
Data::Nil => J::Null,
Data::Bool(b) => J::Bool(*b),
Data::Integer(i) => J::from(*i),
Data::Number(n) => serde_json::Number::from_f64(*n).map_or(J::Null, J::Number),
Data::String(s) => J::String(s.clone()),
Data::List(items) => J::Array(items.iter().map(Data::to_json).collect()),
Data::Map(fields) => J::Object(fields.iter().map(|(k, v)| (k.clone(), v.to_json())).collect()),
}
}
fn from_value(value: &Value, depth: usize) -> Data {
match value {
Value::Boolean(b) => Data::Bool(*b),
// `i32` on wasm32, `i64` elsewhere.
#[allow(clippy::useless_conversion)]
Value::Integer(i) => Data::Integer(i64::from(*i)),
// mlua's integers are isize: on wasm32 a whole number past 32 bits arrives as a
// float, so whole numbers are recognised here too.
Value::Number(n) if n.fract() == 0.0 && n.abs() <= MAX_SAFE => Data::Integer(*n as i64),
Value::Number(n) => Data::Number(*n),
Value::String(s) => Data::String(s.to_string_lossy()),
Value::Table(t) if depth < MAX_DEPTH => {
let len = t.raw_len();
if len > 0 {
return Data::List((1..=len).map(|i| Data::from_value(&t.raw_get(i).unwrap_or(Value::Nil), depth + 1)).collect());
}
Data::Map(
t.pairs::<Value, Value>()
.flatten()
.filter_map(|(k, v)| {
let key = match &k {
Value::String(s) => s.to_string_lossy(),
Value::Integer(i) => i.to_string(),
Value::Number(n) => n.to_string(),
_ => return None,
};
Some((key, Data::from_value(&v, depth + 1)))
})
.collect(),
)
}
_ => Data::Nil,
}
}
}
/// The value at stack slot `idx` as [`Data`], read with the C API inside a C function: whole
/// numbers as integers, arrays as lists, string-keyed tables as maps; functions and userdata as
/// `nil`.
pub(crate) unsafe fn from_stack(state: *mut mlua::ffi::lua_State, idx: std::os::raw::c_int) -> Data {
// SAFETY: the caller passes a valid slot.
unsafe { read_stack(state, mlua::ffi::lua_absindex(state, idx), 0) }
}
unsafe fn read_stack(state: *mut mlua::ffi::lua_State, idx: std::os::raw::c_int, depth: usize) -> Data {
use mlua::ffi;
// SAFETY: `idx` is an absolute slot; every value pushed below is popped before returning.
unsafe {
match ffi::lua_type(state, idx) {
ffi::LUA_TBOOLEAN => Data::Bool(ffi::lua_toboolean(state, idx) != 0),
ffi::LUA_TNUMBER => {
let n = ffi::lua_tonumberx(state, idx, std::ptr::null_mut());
if n.fract() == 0.0 && n.abs() <= MAX_SAFE { Data::Integer(n as i64) } else { Data::Number(n) }
}
ffi::LUA_TSTRING => {
let mut len = 0;
let p = ffi::lua_tolstring(state, idx, &mut len);
Data::String(String::from_utf8_lossy(std::slice::from_raw_parts(p.cast::<u8>(), len)).into_owned())
}
ffi::LUA_TTABLE if depth < MAX_DEPTH => {
let len = ffi::lua_objlen(state, idx);
if len > 0 {
let items = (1..=len)
.map(|i| {
ffi::lua_rawgeti(state, idx, i as ffi::lua_Integer);
let item = read_stack(state, ffi::lua_gettop(state), depth + 1);
ffi::lua_settop(state, -2);
item
})
.collect();
return Data::List(items);
}
let mut fields = BTreeMap::new();
let mut iter = 0;
while {
iter = ffi::lua_rawiter(state, idx, iter);
iter >= 0
} {
let top = ffi::lua_gettop(state);
let key = match ffi::lua_type(state, top - 1) {
ffi::LUA_TSTRING | ffi::LUA_TNUMBER => match read_stack(state, top - 1, MAX_DEPTH) {
Data::String(s) => Some(s),
Data::Integer(i) => Some(i.to_string()),
Data::Number(n) => Some(n.to_string()),
_ => None,
},
_ => None,
};
if let Some(key) = key {
fields.insert(key, read_stack(state, top, depth + 1));
}
ffi::lua_settop(state, -3);
}
Data::Map(fields)
}
_ => Data::Nil,
}
}
}
impl From<bool> for Data {
fn from(v: bool) -> Self {
Data::Bool(v)
}
}
impl From<f64> for Data {
fn from(v: f64) -> Self {
Data::Number(v)
}
}
impl From<i64> for Data {
fn from(v: i64) -> Self {
Data::Integer(v)
}
}
impl From<&str> for Data {
fn from(v: &str) -> Self {
Data::String(v.to_owned())
}
}
impl From<String> for Data {
fn from(v: String) -> Self {
Data::String(v)
}
}
impl<T: Into<Data>> From<Vec<T>> for Data {
fn from(v: Vec<T>) -> Self {
Data::List(v.into_iter().map(Into::into).collect())
}
}
impl IntoLua for Data {
fn into_lua(self, lua: &Lua) -> mlua::Result<Value> {
Ok(match self {
Data::Nil => Value::Nil,
Data::Bool(b) => Value::Boolean(b),
Data::Integer(i) => Value::Number(i as f64),
Data::Number(n) => Value::Number(n),
Data::String(s) => Value::String(lua.create_string(s)?),
// A table is built on the stack with the C API in one protected call, not a call
// through mlua's handles per field: props a host passes each render are tables.
Data::List(_) | Data::Map(_) => {
// SAFETY: `push_stack` leaves exactly the one table it builds on the stack.
unsafe { lua.exec_raw::<Value>((), |state| push_stack(state, &self, 0))? }
}
})
}
}
/// Pushes `data` with the C API. Inside a protected call: a failed allocation raises a Lua error.
unsafe fn push_stack(state: *mut mlua::ffi::lua_State, data: &Data, depth: usize) {
use mlua::ffi;
// SAFETY: each branch pushes exactly one value; a table's entries are pushed and set in turn.
unsafe {
match data {
Data::Nil => ffi::lua_pushnil(state),
Data::Bool(b) => ffi::lua_pushboolean(state, i32::from(*b)),
Data::Integer(i) => ffi::lua_pushnumber(state, *i as f64),
Data::Number(n) => ffi::lua_pushnumber(state, *n),
Data::String(s) => {
ffi::lua_pushlstring(state, s.as_ptr().cast(), s.len());
}
Data::List(_) | Data::Map(_) if depth >= MAX_DEPTH => ffi::lua_pushnil(state),
Data::List(items) => {
ffi::luaL_checkstack(state, 3, std::ptr::null());
ffi::lua_createtable(state, items.len().try_into().unwrap_or(0), 0);
for (i, item) in items.iter().enumerate() {
push_stack(state, item, depth + 1);
ffi::lua_rawseti(state, -2, (i + 1) as _);
}
}
Data::Map(fields) => {
ffi::luaL_checkstack(state, 4, std::ptr::null());
ffi::lua_createtable(state, 0, fields.len().try_into().unwrap_or(0));
for (k, v) in fields {
ffi::lua_pushlstring(state, k.as_ptr().cast(), k.len());
push_stack(state, v, depth + 1);
ffi::lua_rawset(state, -3);
}
}
}
}
}
impl FromLua for Data {
fn from_lua(value: Value, _: &Lua) -> mlua::Result<Self> {
Ok(Data::from_value(&value, 0))
}
}
+69
View File
@@ -0,0 +1,69 @@
//! [`ScriptError`]: what a failed script reports instead of panicking.
use std::fmt;
/// What went wrong.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorKind {
/// The source doesn't parse. A reload with a syntax error keeps the running VM.
Syntax,
/// The script raised an error, or called something with the wrong arguments.
Runtime,
/// One entry into the VM used up the watchdog's budget (250 ms of the thread's CPU time by default).
Timeout,
/// The VM reached its memory limit.
Memory,
/// The script has no entry module, or the entry module has no such function.
Missing,
}
/// A script error, with the Luau traceback when there is one.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScriptError {
pub kind: ErrorKind,
pub message: String,
}
/// The message the watchdog raises; [`ScriptError::from`] recognises it.
pub(crate) const WATCHDOG: &str = "script ran longer than its time limit (watchdog)";
impl ScriptError {
pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
ScriptError { kind, message: message.into() }
}
/// The first line of the message: `init.luau:12: attempt to index nil`.
pub fn summary(&self) -> &str {
self.message.lines().next().unwrap_or_default()
}
}
impl fmt::Display for ScriptError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ScriptError {}
impl From<mlua::Error> for ScriptError {
fn from(err: mlua::Error) -> Self {
match err {
mlua::Error::SyntaxError { message, .. } => ScriptError::new(ErrorKind::Syntax, message),
mlua::Error::MemoryError(message) => ScriptError::new(ErrorKind::Memory, message),
mlua::Error::CallbackError { traceback, cause } => {
let inner = ScriptError::from((*cause).clone());
ScriptError::new(inner.kind, format!("{}\n{traceback}", inner.message))
}
mlua::Error::WithContext { context, cause } => {
let inner = ScriptError::from((*cause).clone());
ScriptError::new(inner.kind, format!("{context}: {}", inner.message))
}
other => {
let message = other.to_string();
let kind = if message.contains(WATCHDOG) { ErrorKind::Timeout } else { ErrorKind::Runtime };
ScriptError::new(kind, message)
}
}
}
}
+153
View File
@@ -0,0 +1,153 @@
//! Running script functions a host holds: a host that takes callbacks from a script (a panel's
//! `render`, a command's `run`) renders, runs and queries them through these, under the same
//! watchdog, metrics and error handling as the script's own entries.
use std::time::Duration;
use mlua::{FromLuaMulti, Function, IntoLuaMulti, Table, Value};
use rune::{El, Tx};
use crate::card::error_card;
use crate::script::{Inner, LogLevel, Reload, take_root};
use crate::sources::{Compiled, Sources};
use crate::task;
use crate::ui::view::mix;
use crate::ui::{attach, with_frame};
use crate::{ErrorKind, Script, ScriptError};
impl Script {
/// Moves whenever script code runs (a handler, a task, a signal), and on a reload. A host
/// mixes it into the versions it passes [`Script::render_fn`], so a surface rebuilds after
/// the script ran and not otherwise.
pub fn version(&self) -> u64 {
self.inner.version.get()
}
/// The running VM's id, unique in the process; `None` when the script isn't running. It
/// changes with every VM a reload starts, and [`ScriptOptions::start`](crate::ScriptOptions::start)
/// receives the new one.
pub fn vm_id(&self) -> Option<u64> {
self.inner.vm().map(|vm| vm.id)
}
/// The table the entry module returned.
pub fn module(&self) -> Option<Table> {
self.inner.vm().map(|vm| vm.module.clone())
}
/// Renders `f(view, args...)`, memoized as `id` on `version`: while `version` holds (and
/// the script hasn't reloaded) the subtree is reused without entering the VM. A render
/// error shows the error card, with Reload.
pub fn render_fn<S: 'static>(&self, id: &str, version: u64, dark: bool, f: &Function, args: impl IntoLuaMulti) -> El {
let i = &self.inner;
i.dark.set(dark);
let id = format!("{}{id}", i.prefix);
rune::memo::memo_with_hash(id.clone(), mix(version, i.salt.get()), || i.render_with::<S>(dark, f, args).key(id))
}
/// Runs `f(args...)` as a task, so it may wait: a command's `run`, a signal from the host.
/// With `tx`, the deadline it sets arms on the transaction.
pub fn spawn_fn(&self, f: &Function, args: impl IntoLuaMulti, tx: Option<&mut Tx>) -> Result<(), ScriptError> {
let ran = self.inner.enter(tx, |vm| {
let thread = vm.lua.create_thread(f.clone())?;
task::run(&vm.lua, &thread, args);
Ok(())
});
ran.unwrap_or_else(|| Err(self.inner.not_running()))
}
/// Calls `f(args...)` and returns its result, at once and without letting it wait: a
/// query a host makes while it draws (a pill's `show`, a link handler's `match`). It leaves
/// the script's version where it was.
pub fn eval_fn<R: FromLuaMulti>(&self, f: &Function, args: impl IntoLuaMulti) -> Result<R, ScriptError> {
let Some(vm) = self.inner.vm() else { return Err(self.inner.not_running()) };
let out = self.inner.timed(&vm, |_| f.call::<R>(args));
self.inner.note_schedule(&vm);
out.map_err(|e| {
let e = ScriptError::from(e);
self.inner.log(LogLevel::Error, &e.message);
e
})
}
/// Builds, ahead of the next reload, the part of a VM that doesn't depend on the script's
/// files: the Luau state, the prelude, `@rune/ui` and the host's
/// [`ScriptOptions::setup`](crate::ScriptOptions::setup). The reload then only loads the
/// modules and runs them, so its swap on the UI thread is shorter. Call it once a reload is
/// coming (a file was saved and compiles off the UI thread meanwhile); with one built
/// already it does nothing. `setup` runs here rather than in the reload.
pub fn prewarm(&self) {
self.inner.prewarm();
}
/// [`Script::reload`] with sources the host compiled itself, off the UI thread (`compile` is
/// how long that took, for the report).
pub fn reload_compiled(&self, sources: Sources, compiled: Compiled, compile: Duration) -> Result<Reload, ScriptError> {
let mut report = self.inner.swap(compiled).inspect_err(|e| self.inner.log(LogLevel::Error, &e.message))?;
report.compile = compile;
*self.inner.sources.borrow_mut() = sources;
self.inner.note_reload(report);
Ok(report)
}
}
impl Inner {
pub(crate) fn not_running(&self) -> ScriptError {
self.failed.borrow().clone().unwrap_or_else(|| ScriptError::new(ErrorKind::Missing, "not running"))
}
/// Runs `f` inside the host's [`ScriptOptions::around`](crate::ScriptOptions::around) hook.
pub(crate) fn around_write<S: 'static>(&self, s: &mut S, tx: Option<&mut Tx>, f: impl FnOnce(Option<&mut Tx>)) {
let Some(hook) = self.options.around.clone() else { return f(tx) };
let mut f = Some(f);
hook(s, tx, &mut |tx| {
if let Some(f) = f.take() {
f(tx);
}
});
}
/// Runs `f` inside the host's [`ScriptOptions::around_read`](crate::ScriptOptions::around_read)
/// hook; `None` if the hook didn't run it.
pub(crate) fn around_read<S: 'static, R>(&self, s: &S, f: impl FnOnce() -> R) -> Option<R> {
let Some(hook) = self.options.around_read.clone() else { return Some(f()) };
let (mut f, mut out) = (Some(f), None);
hook(s, &mut || {
if let Some(f) = f.take() {
out = Some(f());
}
});
out
}
fn render_with<S: 'static>(&self, dark: bool, f: &Function, args: impl IntoLuaMulti) -> El {
let attach = attach::<S>();
let card = |message: &str| error_card(message, &self.options.palette, dark, attach, self.weak.clone());
if let Some(err) = self.failed.borrow().as_ref() {
return card(&err.message);
}
let Some(vm) = self.vm() else { return card("the script isn't running") };
let env = self.env(&vm, dark);
let built = with_frame(attach, env.clone(), || {
self.timed(&vm, |vm| {
vm.view.raw_set("dark", dark)?;
let mut args = args.into_lua_multi(&vm.lua)?;
args.push_front(Value::Table(vm.view.clone()));
take_root(f.call::<Value>(args)?)
})
});
let mut m = self.metrics.get();
m.renders += 1;
self.metrics.set(m);
self.note_schedule(&vm);
if env.memo_failed.get() {
self.salt.set(self.salt.get().wrapping_add(1));
}
built.unwrap_or_else(|err| {
let err = ScriptError::from(err);
self.log(LogLevel::Error, &err.message);
self.salt.set(self.salt.get().wrapping_add(1));
card(&err.message)
})
}
}
+84
View File
@@ -0,0 +1,84 @@
//! Luau scripts that build Rune UI.
//!
//! A [`Script`] is one sandboxed Luau VM. Its `init.luau` returns a module whose `render(view)`
//! builds nodes with `@rune/ui`:
//!
//! ```luau
//! --!strict
//! local ui = require("@rune/ui")
//! local count = 0
//! return {
//! render = function(view)
//! return ui.col({ pad = 16, gap = 8 }, {
//! ui.text(`Pressed {count} times`),
//! ui.row({ key = "inc", px = 10, py = 4, radius = 6, fill = "control-off",
//! onPress = function() count += 1 end }, { "Press" }),
//! })
//! end,
//! }
//! ```
//!
//! - **Nodes** are built straight into `rune::El`s by C functions, with no Lua tables or tree
//! diff in between. `view:Memo(key, version, build)` reuses a subtree without calling `build`;
//! `ui.virtualList` is `El::virtual_rows`, calling `renderRow(i)` only for rows entering the
//! window.
//! - **`task`** (`spawn`, `defer`, `delay`, `wait`, `cancel`) runs on the frame clock the app's
//! `poll` receives; an idle script never enters its VM. A host's **`Signal`** has `Connect`,
//! `Once` and `Wait`; a `ScriptSignal` adds `Fire` and `Version`. Connections run as tasks.
//! - **Errors never panic**: a failed render shows an error card, a failed task is logged, and a
//! watchdog stops any entry that uses more than 250 ms of its thread's CPU time.
//! - **Hot reload**: [`Script::reload`] (or `Script::watch` with the `watch` feature) swaps the
//! VM, carrying `saveHotState()` into `loadHotState(state)`.
//!
//! Luau runs with native code generation on Windows and Linux (x86-64, arm64), and as its
//! interpreter on macOS, iOS and the web. On `wasm32-unknown-unknown`, Luau's C++ builds with
//! WASI SDK: `scripts/web-build.sh` sets that up when `WASI_SDK_PATH` is set.
mod card;
mod data;
mod error;
mod functions;
mod options;
mod require;
mod script;
mod sources;
mod task;
mod ui;
mod vm;
mod watchdog;
#[cfg(all(feature = "watch", not(target_arch = "wasm32")))]
mod watch;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
mod web;
mod workers;
pub use data::Data;
pub use error::ErrorKind;
pub use error::ScriptError;
pub use mlua;
pub use options::ScriptOptions;
pub use options::Shadows;
pub use script::LogLevel;
pub use script::LogLine;
pub use script::Metrics;
pub use script::Reload;
pub use script::Script;
pub use sources::Compiled;
pub use sources::ENTRY;
pub use sources::Sources;
pub use sources::precompiled;
pub use ui::Palette;
pub use ui::default_palette;
pub use ui::host::Handler;
pub use ui::host::HostNode;
pub use ui::host::NodeArgs;
pub use ui::host::Press;
pub use ui::host::Prop;
pub use ui::props::prop_names;
pub use vm::Host;
pub use workers::Completer;
pub use workers::spawn_blocking;
/// Whether this build compiles `--!native` modules to native code (the `native-code` feature, on
/// Windows and Linux) rather than interpreting them.
pub const NATIVE_CODE: bool = cfg!(luau_jit);
+154
View File
@@ -0,0 +1,154 @@
//! [`ScriptOptions`]: how a host runs its scripts.
use std::any::Any;
use std::rc::Rc;
use std::time::Duration;
use mlua::{Lua, Table};
use rune::{Shadow, TextStyle, Tx};
use crate::script::LogLevel;
use crate::ui::host::HostNode;
use crate::ui::{Palette, default_palette};
use crate::vm::Host;
/// Receives log lines as they happen.
pub(crate) type LogFn = dyn Fn(LogLevel, &str);
/// Binds a host's API into a new VM.
pub(crate) type SetupFn = dyn Fn(&Host<'_>) -> mlua::Result<()>;
/// Runs once a new VM's entry module has returned.
pub(crate) type StartFn = dyn Fn(&Lua, &Table, u64) -> mlua::Result<()>;
/// Wraps an entry into the VM that comes from the UI (a press, a hover, a list's visible rows)
/// with the app's state and the transaction, when the UI hands one over.
pub(crate) type AroundFn = dyn Fn(&mut dyn Any, Option<&mut Tx>, &mut dyn FnMut(Option<&mut Tx>));
/// Wraps an entry that only reads the app's state: a virtual list building a row.
pub(crate) type AroundReadFn = dyn Fn(&dyn Any, &mut dyn FnMut());
/// Maps an elevation name (`raised`, `floating`, `overlay`) to its shadows, for the current light
/// or dark appearance.
pub type Shadows = Rc<dyn Fn(&str, bool) -> Option<Vec<Shadow>>>;
/// How a script is hosted. Build with [`ScriptOptions::new`] and its setters.
#[derive(Clone)]
pub struct ScriptOptions {
pub(crate) palette: Palette,
pub(crate) shadows: Option<Shadows>,
pub(crate) setup: Option<Rc<SetupFn>>,
pub(crate) start: Option<Rc<StartFn>>,
pub(crate) around: Option<Rc<AroundFn>>,
pub(crate) around_read: Option<Rc<AroundReadFn>>,
pub(crate) nodes: Vec<HostNode>,
pub(crate) time_limit: Duration,
pub(crate) memory_limit: usize,
pub(crate) on_log: Option<Rc<LogFn>>,
pub(crate) text: TextStyle,
/// `weight = "regular"`, `"medium"`, `"semibold"` and `"bold"`.
pub(crate) weights: [f32; 4],
}
impl Default for ScriptOptions {
fn default() -> Self {
ScriptOptions {
palette: default_palette(),
shadows: None,
setup: None,
start: None,
around: None,
around_read: None,
nodes: Vec::new(),
time_limit: Duration::from_millis(250),
memory_limit: 64 << 20,
on_log: None,
text: TextStyle::new(13.0, 400.0),
weights: [400.0, 500.0, 600.0, 700.0],
}
}
}
impl ScriptOptions {
pub fn new() -> Self {
ScriptOptions::default()
}
/// Colour names scripts may use (`fill = "card"`); [`default_palette`] otherwise.
pub fn palette(mut self, palette: Palette) -> Self {
self.palette = palette;
self
}
/// What `shadow = "<name>"` draws. Without it the prop draws nothing.
pub fn shadows(mut self, shadows: Shadows) -> Self {
self.shadows = Some(shadows);
self
}
/// Binds the host's modules, globals, signals and async functions into each new VM.
pub fn setup(mut self, setup: impl Fn(&Host<'_>) -> mlua::Result<()> + 'static) -> Self {
self.setup = Some(Rc::new(setup));
self
}
/// Runs with each new VM, the table its entry module returned and the VM's id (what
/// [Script::vm_id](crate::Script::vm_id) returns once it runs), after the module ran and
/// before `loadHotState`: a host that calls a setup function the module hands it does it
/// here, so hot state lands on what that setup made. An error fails the start, and a reload
/// keeps the running VM.
pub fn start(mut self, start: impl Fn(&Lua, &Table, u64) -> mlua::Result<()> + 'static) -> Self {
self.start = Some(Rc::new(start));
self
}
/// Wraps every entry the UI makes (a press, `onHover`, a list's `onVisibleRows`): the hook
/// gets the app's state and the transaction, and must call `run` once. A host whose
/// bindings reach its own state sets it up around `run`, then carries out what the script
/// asked for in the same transaction.
pub fn around(mut self, around: impl Fn(&mut dyn Any, Option<&mut Tx>, &mut dyn FnMut(Option<&mut Tx>)) + 'static) -> Self {
self.around = Some(Rc::new(around));
self
}
/// Wraps the entries the UI makes while it only reads the app's state: a virtual list's
/// rows and row keys. The hook must call `run` once.
pub fn around_read(mut self, around: impl Fn(&dyn Any, &mut dyn FnMut()) + 'static) -> Self {
self.around_read = Some(Rc::new(around));
self
}
/// Adds `ui.<name>`, a node the host builds.
pub fn node(mut self, node: HostNode) -> Self {
self.nodes.push(node);
self
}
/// The text style `ui.text` starts from (13 pt, weight 400), and the weights `regular`,
/// `medium`, `semibold` and `bold` name (400, 500, 600, 700): an app whose type runs on a
/// variable font names its own.
pub fn text(mut self, base: TextStyle, weights: [f32; 4]) -> Self {
self.text = base;
self.weights = weights;
self
}
/// The most of its thread's CPU time one entry into the VM may use before the watchdog stops it
/// (250 ms); waiting for a CPU or on a host call isn't charged, and 20 budgets of wall time bound it.
pub fn time_limit(mut self, limit: Duration) -> Self {
self.time_limit = limit;
self
}
/// The VM's heap limit in bytes (64 MB).
pub fn memory_limit(mut self, bytes: usize) -> Self {
self.memory_limit = bytes;
self
}
/// Receives `print`, `warn` and errors as they happen, besides [`Script::log`](crate::Script::log).
pub fn on_log(mut self, f: impl Fn(LogLevel, &str) + 'static) -> Self {
self.on_log = Some(Rc::new(f));
self
}
}
+145
View File
@@ -0,0 +1,145 @@
--!strict
-- Runs once in every VM before the sandbox freezes the globals. `task` arrives with spawn, defer,
-- delay and the host half of cancel; this adds wait and cancel, the signal types and the wrapper
-- that turns a host async function into one a task calls like a plain function.
local task, WAIT, PARK, JOB, forget = ...
local yield = coroutine.yield
local isyieldable = coroutine.isyieldable
local running = coroutine.running
local close = coroutine.close
local spawn = task.spawn
local function needTask(name: string)
if not isyieldable() then
error(`{name} can only be called from a task (task.spawn, a handler or a connection), not while rendering`, 3)
end
end
function task.wait(seconds: number?): number
needTask("task.wait")
return yield(WAIT, seconds or 0)
end
function task.cancel(thread: thread)
forget(thread)
if coroutine.status(thread) ~= "running" then
close(thread)
end
end
-- Signals are userdata with Luau methods. A `Signal` (a host's) has Connect, Once and Wait; a
-- `ScriptSignal` (one a script fires) adds Fire and Version. A `Connection` has Connected and
-- Disconnect. A connection's callback runs as a task, so it may wait.
type State = { list: { any }, waiting: { thread }, version: number }
local states: { [any]: State } = setmetatable({}, { __mode = "k" }) :: any
type Conn = { fn: (...any) -> (), once: boolean, connected: boolean, signal: any }
local connections: { [any]: Conn } = setmetatable({}, { __mode = "k" }) :: any
local Connection = {}
function Connection.Disconnect(self)
local c = connections[self]
if not c.connected then
return
end
c.connected = false
local list = states[c.signal].list
local i = table.find(list, self)
if i then
table.remove(list, i)
end
end
local function connectionIndex(self, key)
if key == "Connected" then
return connections[self].connected
end
return Connection[key]
end
local function connect(self, fn, once: boolean)
if type(fn) ~= "function" then
error("Connect and Once need a function", 3)
end
local proxy = newproxy(true)
local mt = getmetatable(proxy)
mt.__index = connectionIndex
mt.__type = "Connection"
connections[proxy] = { fn = fn, once = once, connected = true, signal = self }
table.insert(states[self].list, proxy)
return proxy
end
local function fire(self, ...)
local s = states[self]
s.version += 1
if #s.list > 0 then
for _, proxy in table.clone(s.list) do
local c = connections[proxy]
if c.connected then
if c.once then
Connection.Disconnect(proxy)
end
spawn(c.fn, ...)
end
end
end
if #s.waiting > 0 then
local waiting = s.waiting
s.waiting = {}
for _, thread in waiting do
spawn(thread, ...)
end
end
end
local Signal = {}
function Signal.Connect(self, fn)
return connect(self, fn, false)
end
function Signal.Once(self, fn)
return connect(self, fn, true)
end
function Signal.Wait(self)
needTask("Signal:Wait")
table.insert(states[self].waiting, (running()))
return yield(PARK)
end
local ScriptSignal = table.clone(Signal)
ScriptSignal.Fire = fire
-- How many times the signal fired: a cheap version for view:Memo.
function ScriptSignal.Version(self): number
return states[self].version
end
local function new(methods, name: string)
return function()
local proxy = newproxy(true)
local mt = getmetatable(proxy)
mt.__index = methods
mt.__type = name
states[proxy] = { list = {}, waiting = {}, version = 0 }
return proxy
end
end
local function async(submit: (...any) -> number, name: string)
return function(...)
needTask(name)
return yield(JOB, submit(...))
end
end
return {
signal = new(table.freeze(Signal), "Signal"),
scriptSignal = new(table.freeze(ScriptSignal), "ScriptSignal"),
fire = fire,
async = async,
}
+168
View File
@@ -0,0 +1,168 @@
//! `require` inside a script's folder, by Luau's require-by-string rules, so the host and
//! `luau-lsp` resolve the same module: Luau's own navigator walks the path, and this is its
//! view of the script's files.
//!
//! - A module's path drops `.luau`, and `x/init.luau` is module `x`: `init.luau` stands for its
//! folder. `./` and `../` start from the requiring module's parent, so from the script's
//! `init.luau` they leave the folder and fail; `@self/x` starts from the module itself and
//! reaches `x.luau` in the script's folder.
//! - `.luaurc` (or `.config.luau`) aliases in the script's folders apply, and so does the one
//! above the folder ([`Sources::parent_config`](crate::Sources::parent_config)). Built-in
//! modules (`@rune/ui`, `@rune/signal`, a host's) resolve before any of these.
//! - Nothing outside the folder resolves. Each module runs once per VM, and a cycle is an error
//! naming the chain.
use std::cell::RefCell;
use std::rc::Rc;
use std::result::Result as StdResult;
use mlua::chunk::ChunkMode;
use mlua::luau::{NavigateError, Require};
use mlua::{Function, Lua, MultiValue};
use crate::sources::{Compiled, ENTRY};
/// Modules running their top level, outermost first.
pub(crate) type Loading = Rc<RefCell<Vec<String>>>;
pub(crate) struct Requirer {
compiled: Rc<Compiled>,
loading: Loading,
/// The current module path, or `None` above the script's folder.
at: Option<Vec<String>>,
}
impl Requirer {
pub(crate) fn new(compiled: Rc<Compiled>, loading: Loading) -> Self {
Requirer { compiled, loading, at: Some(Vec::new()) }
}
/// The file of module `at`.
fn file(&self, at: &[String]) -> StdResult<Option<String>, NavigateError> {
if at.is_empty() {
return Ok(self.compiled.module(ENTRY).map(|_| ENTRY.to_owned()));
}
let base = at.join("/");
let found: Vec<String> =
[format!("{base}.luau"), format!("{base}/init.luau")].into_iter().filter(|p| self.compiled.module(p).is_some()).collect();
match found.len() {
0 => Ok(None),
1 => Ok(found.into_iter().next()),
_ => Err(NavigateError::Ambiguous),
}
}
fn resolved(&self) -> Option<String> {
self.at.as_deref().and_then(|at| self.file(at).ok().flatten())
}
}
impl Require for Requirer {
fn is_require_allowed(&self, chunk_name: &str) -> bool {
chunk_name.starts_with('@')
}
fn reset(&mut self, chunk_name: &str) -> StdResult<(), NavigateError> {
let path = chunk_name.strip_prefix('@').ok_or(NavigateError::NotFound)?;
let path = path.strip_suffix(".luau").unwrap_or(path);
let mut at: Vec<String> = path.split('/').filter(|c| !c.is_empty()).map(str::to_owned).collect();
if at.last().is_some_and(|c| c == "init") {
at.pop();
}
self.at = Some(at);
Ok(())
}
fn jump_to_alias(&mut self, _path: &str) -> StdResult<(), NavigateError> {
// An alias to an absolute path names something outside the script's folder.
Err(NavigateError::NotFound)
}
fn to_parent(&mut self) -> StdResult<(), NavigateError> {
match &mut self.at {
Some(at) if at.is_empty() => self.at = None,
Some(at) => {
at.pop();
}
None => return Err(NavigateError::NotFound),
}
Ok(())
}
fn to_child(&mut self, name: &str) -> StdResult<(), NavigateError> {
let Some(at) = &self.at else {
// Above the folder, only the folder itself is reachable.
if self.compiled.folder.as_deref() == Some(name) {
self.at = Some(Vec::new());
return Ok(());
}
return Err(NavigateError::NotFound);
};
let mut next = at.clone();
next.push(name.to_owned());
if self.file(&next)?.is_none() && !self.compiled.is_dir(&next.join("/")) {
return Err(NavigateError::NotFound);
}
self.at = Some(next);
Ok(())
}
fn has_module(&self) -> bool {
self.resolved().is_some()
}
fn cache_key(&self) -> String {
self.resolved().unwrap_or_default()
}
fn has_config(&self) -> bool {
self.config_text().is_some()
}
fn config(&self) -> std::io::Result<Vec<u8>> {
self.config_text().map(|s| s.as_bytes().to_vec()).ok_or_else(|| std::io::ErrorKind::NotFound.into())
}
fn loader(&self, lua: &Lua) -> mlua::Result<Function> {
let path = self.resolved().ok_or_else(|| mlua::Error::runtime("module not found"))?;
module_loader(lua, &self.compiled, &self.loading, &path)
}
}
impl Requirer {
/// The configuration of the folder navigation is at: a module path is a folder here.
fn config_text(&self) -> Option<&str> {
match &self.at {
None => self.compiled.config(None),
Some(at) => self.compiled.config(Some(&at.join("/"))),
}
}
}
/// A function that runs module `path` once, refusing to start it again while it is still
/// running (a `require` cycle). A module that opens with `--!native` compiles to native code
/// with the `native-code` feature (Windows and Linux).
pub(crate) fn module_loader(lua: &Lua, compiled: &Compiled, loading: &Loading, path: &str) -> mlua::Result<Function> {
let module = compiled.module(path).ok_or_else(|| mlua::Error::runtime(format!("no module {path}")))?;
#[cfg(luau_jit)]
lua.enable_jit(module.native);
#[cfg(not(luau_jit))]
let _ = module.native;
let chunk = lua.load(&*module.code).set_mode(ChunkMode::Binary).set_name(format!("@{path}")).into_function();
#[cfg(luau_jit)]
lua.enable_jit(false);
let chunk = chunk?;
let loading = loading.clone();
let path = path.to_owned();
lua.create_function(move |_, args: MultiValue| {
if loading.borrow().contains(&path) {
let mut chain = loading.borrow().clone();
chain.push(path.clone());
return Err(mlua::Error::runtime(format!("require cycle: {}", chain.join(" -> "))));
}
loading.borrow_mut().push(path.clone());
let out = chunk.call::<MultiValue>(args);
loading.borrow_mut().pop();
out
})
}
+579
View File
@@ -0,0 +1,579 @@
//! [`Script`]: one Luau VM a Rune app hosts, from `init.luau` to the `El`s it renders.
use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::time::Duration;
use mlua::{LightUserData, Value};
use rune::{Cx, El, Tx};
use rustc_hash::FxHashSet;
use crate::card::{error_card, row_error};
use crate::options::ScriptOptions;
use crate::sources::{Compiled, Sources};
use crate::task::{self, Sched};
use crate::ui::host::HostNode;
use crate::ui::rows::Spec;
use crate::ui::view::mix;
use crate::ui::{Callback, Env, Event, attach, top, with_frame};
use crate::vm::{Base, Setup, Vm};
use crate::watchdog;
use crate::workers::Shared;
use crate::{Data, ErrorKind, ScriptError};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LogLevel {
Info,
Warn,
Error,
}
#[derive(Clone, Debug)]
pub struct LogLine {
pub level: LogLevel,
pub message: String,
}
/// Counters for proof and profiling.
#[derive(Clone, Copy, Debug, Default)]
pub struct Metrics {
/// Entries from Rust into the VM: renders, rows, handlers, polls that resumed tasks.
pub vm_calls: u64,
/// Time spent inside those entries.
pub vm_time: Duration,
/// Surface renders that ran the script (memo misses).
pub renders: u64,
/// Rows `ui.virtualList` built by calling `renderRow`.
pub rows: u64,
pub reloads: u64,
pub last_reload: Option<Reload>,
}
/// How long a reload took.
#[derive(Clone, Copy, Debug, Default)]
pub struct Reload {
/// Parsing and compiling every file to bytecode (off the UI thread when watching).
pub compile: Duration,
/// Saving hot state, starting the new VM, running `init.luau`, restoring hot state.
pub swap: Duration,
}
/// A hosted Luau script: one VM. Keep it in the window's state and call [`Script::poll`] from
/// `AppSpec::poll` and [`Script::view`] from the view.
///
/// ```ignore
/// fn poll(s: &mut State, now: f64, tx: &mut Tx) -> bool { s.script.poll(now, tx) }
/// fn view(s: &State, cx: &mut Cx<State>) -> El { s.script.view(cx) }
/// ```
pub struct Script {
pub(crate) inner: Rc<Inner>,
}
pub(crate) struct Inner {
pub(crate) weak: Weak<Inner>,
name: Rc<str>,
pub(crate) prefix: Rc<str>,
pub(crate) options: ScriptOptions,
vm: RefCell<Option<Rc<Vm>>>,
pub(crate) sources: RefCell<Sources>,
pub(crate) failed: RefCell<Option<ScriptError>>,
pub(crate) version: Cell<u64>,
pub(crate) salt: Cell<u64>,
pub(crate) dark: Cell<bool>,
pub(crate) clock: Cell<f64>,
/// The earliest task deadline on the frame clock, or infinity.
deadline: Cell<f64>,
pub(crate) metrics: Cell<Metrics>,
log: RefCell<VecDeque<LogLine>>,
warned: Rc<RefCell<FxHashSet<String>>>,
nodes: Rc<[HostNode]>,
pub(crate) shared: Arc<Shared>,
/// A VM base built ahead of the next reload ([`Script::prewarm`]).
spare: RefCell<Option<Base>>,
#[cfg(all(feature = "watch", not(target_arch = "wasm32")))]
pub(crate) watch: RefCell<Option<crate::watch::Watch>>,
}
impl Script {
/// Compiles and starts `sources` with default options.
pub fn new(name: &str, sources: Sources) -> Self {
Script::with_options(name, sources, ScriptOptions::new())
}
/// Compiles and starts `sources`. A script that fails to start still exists: its surfaces
/// show the error, and [`Script::error`] returns it.
pub fn with_options(name: &str, sources: Sources, options: ScriptOptions) -> Self {
let nodes: Rc<[HostNode]> = options.nodes.clone().into();
let inner = Rc::new_cyclic(|weak| Inner {
weak: weak.clone(),
name: name.into(),
prefix: format!("luau:{name}:").into(),
options,
vm: RefCell::new(None),
sources: RefCell::new(sources.clone()),
failed: RefCell::new(None),
version: Cell::new(1),
salt: Cell::new(1),
dark: Cell::new(true),
clock: Cell::new(0.0),
deadline: Cell::new(f64::INFINITY),
metrics: Cell::new(Metrics::default()),
log: RefCell::new(VecDeque::new()),
warned: Rc::default(),
nodes,
shared: Arc::default(),
spare: RefCell::new(None),
#[cfg(all(feature = "watch", not(target_arch = "wasm32")))]
watch: RefCell::new(None),
});
let started = sources.compile().and_then(|c| inner.swap(c).map(|_| ()));
if let Err(err) = started {
inner.fail(err);
}
Script { inner }
}
pub fn name(&self) -> &str {
&self.inner.name
}
/// Gives the script the window's waker, so finished host work and `task.delay` deadlines
/// set outside a handler can ask for a frame. Call it from `AppSpec::setup`.
pub fn set_waker(&self, waker: rune::Waker) {
self.inner.shared.set_waker(waker);
}
/// Runs what is due: finished host calls, `task.wait`/`task.delay` deadlines up to `now`
/// (`AppSpec::poll`'s clock) and deferred tasks, then asks for a frame at the next deadline.
/// Returns true when script code ran. With nothing due it returns at once and never enters
/// the VM, so an idle script costs nothing.
pub fn poll(&self, now: f64, tx: &mut Tx) -> bool {
self.inner.poll(now, tx)
}
/// The `render` surface: what `init.luau`'s `render(view)` returns.
pub fn view<S: 'static>(&self, cx: &Cx<S>) -> El {
self.surface(cx, "render")
}
/// Surface `name`: what the module's function `name(view)` returns. The result is memoized
/// on the script's version, which moves only when script code runs, so a view rebuilt for
/// other reasons reuses it without entering the VM.
pub fn surface<S: 'static>(&self, cx: &Cx<S>, name: &str) -> El {
let i = &self.inner;
let dark = cx.system_dark();
i.dark.set(dark);
// The surface's root is keyed by its memo id, whatever key the script gave it.
let id = format!("{}{name}", i.prefix);
rune::memo::memo_with_hash(id.clone(), mix(i.version.get(), i.salt.get()), || i.render::<S>(name, dark).key(id))
}
/// Runs the surface's render function now, outside any memo: the cost of a rebuild.
pub fn render_uncached<S: 'static>(&self, name: &str, dark: bool) -> El {
self.inner.render::<S>(name, dark)
}
/// Recompiles from `sources` and swaps the VM. `saveHotState()` from the old VM is passed to
/// `loadHotState(state)` in the new one. A compile or start error keeps the old VM running.
pub fn reload(&self, sources: Sources) -> Result<Reload, ScriptError> {
let start = rune::time::now();
let compiled = sources.compile().inspect_err(|e| self.inner.log(LogLevel::Error, &e.message))?;
let compile = start.elapsed();
let mut report = self.inner.swap(compiled).inspect_err(|e| self.inner.log(LogLevel::Error, &e.message))?;
report.compile = compile;
*self.inner.sources.borrow_mut() = sources;
self.inner.note_reload(report);
Ok(report)
}
/// Fires the signal the host made with [`Host::signal`] as `name`.
pub fn fire(&self, name: &str, args: impl IntoIterator<Item = Data>) -> bool {
let args: Vec<Data> = args.into_iter().collect();
let fired = self.inner.enter(None, |vm| Ok(vm.fire(name, args)?));
fired.is_some_and(|f| f.unwrap_or(false))
}
/// Calls the module's function `name` with `args` in a new task.
pub fn call(&self, name: &str, args: impl IntoIterator<Item = Data>) -> Result<(), ScriptError> {
let args: Vec<Data> = args.into_iter().collect();
let ran = self.inner.enter(None, |vm| {
let f = vm.export(name).ok_or_else(|| ScriptError::new(ErrorKind::Missing, format!("no function {name}")))?;
let thread = vm.lua.create_thread(f)?;
task::run(&vm.lua, &thread, mlua::Variadic::from_iter(args));
Ok(())
});
ran.unwrap_or_else(|| Err(self.inner.failed.borrow().clone().unwrap_or_else(|| ScriptError::new(ErrorKind::Missing, "not running"))))
}
/// Calls the module's function `name` with `args` and returns its result. It runs to the
/// end at once: like a render, it can't wait.
pub fn query(&self, name: &str, args: impl IntoIterator<Item = Data>) -> Result<Data, ScriptError> {
let args: Vec<Data> = args.into_iter().collect();
let ran = self.inner.enter(None, |vm| {
let f = vm.export(name).ok_or_else(|| ScriptError::new(ErrorKind::Missing, format!("no function {name}")))?;
Ok(f.call::<Data>(mlua::Variadic::from_iter(args))?)
});
ran.unwrap_or_else(|| Err(self.inner.failed.borrow().clone().unwrap_or_else(|| ScriptError::new(ErrorKind::Missing, "not running"))))
}
/// Why the script isn't running, if it isn't.
pub fn error(&self) -> Option<ScriptError> {
self.inner.failed.borrow().clone()
}
/// Recent `print`, `warn` and error lines (up to 256).
pub fn log(&self) -> Vec<LogLine> {
self.inner.log.borrow().iter().cloned().collect()
}
pub fn metrics(&self) -> Metrics {
self.inner.metrics.get()
}
/// A full garbage collection now, for a window at rest (`App::on_rest`): the incremental
/// steps that follow script calls leave garbage behind once the calls stop, and Luau gives
/// back a page only once it's empty.
pub fn collect_garbage(&self) {
if let Some(vm) = self.inner.vm() {
vm.collect();
vm.lua.gc_collect().ok();
}
}
/// Bytes the VM's heap holds.
pub fn memory(&self) -> usize {
self.inner.vm().map_or(0, |vm| vm.lua.used_memory())
}
/// The prefix of every memo id this script's surfaces use, for
/// `Tx::invalidate_memos_by_prefix`.
pub fn memo_prefix(&self) -> &str {
&self.inner.prefix
}
/// The script's current sources.
pub fn sources(&self) -> Sources {
self.inner.sources.borrow().clone()
}
/// The Luau VM, for host bindings beyond [`Host`]. Changes here don't survive a reload.
pub fn with_lua<R>(&self, f: impl FnOnce(&mlua::Lua) -> R) -> Option<R> {
self.inner.vm().map(|vm| f(&vm.lua))
}
#[cfg(all(feature = "watch", not(target_arch = "wasm32")))]
pub(crate) fn inner(&self) -> &Rc<Inner> {
&self.inner
}
}
impl Inner {
pub(crate) fn vm(&self) -> Option<Rc<Vm>> {
self.vm.borrow().clone()
}
fn fail(&self, err: ScriptError) {
self.log(LogLevel::Error, &err.message);
*self.failed.borrow_mut() = Some(err);
self.bump();
}
fn bump(&self) {
self.version.set(self.version.get().wrapping_add(1));
}
pub(crate) fn log(&self, level: LogLevel, message: &str) {
if let Some(f) = &self.options.on_log {
f(level, message);
}
let mut log = self.log.borrow_mut();
if log.len() == 256 {
log.pop_front();
}
log.push_back(LogLine { level, message: message.to_owned() });
}
/// One entry into the VM under the watchdog, counted in the metrics. Errors are logged.
pub(crate) fn timed<R>(&self, vm: &Vm, f: impl FnOnce(&Vm) -> R) -> R {
vm.collect();
let _armed = watchdog::arm(self.options.time_limit);
let start = rune::time::now();
let out = f(vm);
let mut m = self.metrics.get();
m.vm_calls += 1;
m.vm_time += start.elapsed();
self.metrics.set(m);
out
}
/// Runs script code that may change state: afterwards the version moves, deferred tasks
/// run, task errors are logged and the next deadline is armed (on `tx`, or by waking).
pub(crate) fn enter<R>(&self, tx: Option<&mut Tx>, f: impl FnOnce(&Vm) -> Result<R, ScriptError>) -> Option<Result<R, ScriptError>> {
let vm = self.vm()?;
let out = self.timed(&vm, |vm| {
let out = f(vm);
task::drain_defers(&vm.lua);
out
});
if let Err(e) = &out {
self.log(LogLevel::Error, &e.message);
}
self.settle(&vm, tx);
Some(out)
}
/// After script code ran: logs task errors, moves the version and arms the next deadline.
fn settle(&self, vm: &Vm, tx: Option<&mut Tx>) {
self.bump();
// One incremental collection step while the VM is warm, so garbage from this batch is
// swept between frames rather than in the middle of a render. An idle script runs none.
vm.lua.gc_step().ok();
let Some((errors, deadline, wait, changed)) = vm.lua.app_data_mut::<Sched>().map(|mut s| {
let errors = std::mem::take(&mut s.errors);
let deadline = s.next_deadline();
(errors, deadline, s.wait_for(deadline), s.take_changed())
}) else {
return;
};
for e in errors {
self.log(LogLevel::Error, &e.message);
}
self.deadline.set(deadline.unwrap_or(f64::INFINITY));
match (tx, wait) {
(Some(tx), Some(wait)) => tx.wake_after(Duration::from_secs_f64(wait)),
(None, Some(_)) if changed => self.shared.wake(),
_ => {}
}
}
/// After a render, which has no `Tx`: a `task.delay` or `task.defer` it set asks for a
/// frame, whose poll runs it.
pub(crate) fn note_schedule(&self, vm: &Vm) {
let Some((changed, deadline, defers)) =
vm.lua.app_data_mut::<Sched>().map(|mut s| (s.take_changed(), s.next_deadline(), s.has_defers()))
else {
return;
};
if changed || defers {
self.deadline.set(if defers { self.clock.get() } else { deadline.unwrap_or(f64::INFINITY) });
self.shared.mark();
self.shared.wake();
}
}
fn poll(&self, now: f64, tx: &mut Tx) -> bool {
self.clock.set(now);
#[cfg(all(feature = "watch", not(target_arch = "wasm32")))]
let reloaded = crate::watch::apply(self);
#[cfg(not(all(feature = "watch", not(target_arch = "wasm32"))))]
let reloaded = false;
let arrived = self.shared.take_dirty();
if !arrived && now < self.deadline.get() {
return reloaded;
}
let Some(vm) = self.vm() else { return reloaded };
let resumed = self.timed(&vm, |vm| task::poll(&vm.lua, now));
self.settle(&vm, Some(tx));
if resumed == 0 {
// Nothing ran: the version needn't have moved.
self.version.set(self.version.get().wrapping_sub(1));
}
reloaded || resumed > 0
}
/// Runs a handler as a task with its `UiEvent`, so it may wait.
pub(crate) fn handle(&self, cb: &Callback, event: Event<'_>, tx: Option<&mut Tx>) {
if self.vm().is_none_or(|vm| vm.id != cb.vm) {
return;
}
let r = cb.func.r;
self.enter(tx, |vm| {
let f = vm.function(r)?;
let thread = vm.lua.create_thread(f)?;
task::run(&vm.lua, &thread, event.to_table(&vm.lua)?);
Ok(())
});
}
pub(crate) fn reload_from_card(&self, _tx: &mut Tx) {
let sources = self.sources.borrow().clone();
let start = rune::time::now();
let swapped = sources.compile().and_then(|c| {
let compile = start.elapsed();
self.swap(c).map(|r| Reload { compile, ..r })
});
match swapped {
Ok(report) => self.note_reload(report),
Err(err) => self.fail(err),
}
}
#[cfg(all(feature = "watch", not(target_arch = "wasm32")))]
pub(crate) fn set_sources(&self, sources: Sources) {
*self.sources.borrow_mut() = sources;
}
pub(crate) fn note_reload(&self, report: Reload) {
let mut m = self.metrics.get();
m.reloads += 1;
m.last_reload = Some(report);
self.metrics.set(m);
let ms = |d: Duration| d.as_secs_f64() * 1e3;
let (compile, swap) = (ms(report.compile), ms(report.swap));
self.log(LogLevel::Info, &format!("reloaded in {:.2} ms: compile {compile:.2} ms, swap {swap:.2} ms", compile + swap));
}
/// Starts a VM from `compiled`, carrying hot state over from the running one, and swaps it
/// in. On error the running VM stays.
pub(crate) fn swap(&self, compiled: Compiled) -> Result<Reload, ScriptError> {
let start = rune::time::now();
let old = self.vm();
let saved = old.as_ref().and_then(|vm| {
let save = vm.export("saveHotState")?;
self.timed(vm, |_| save.call::<Data>(())).inspect_err(|e| self.log(LogLevel::Warn, &format!("saveHotState: {e}"))).ok()
});
let base = match self.spare.take() {
Some(base) => base,
None => self.base()?,
};
let (mut vm, entry) = Vm::new(base, &Rc::new(compiled), self.clock.get())?;
let module = self.timed(&vm, |_| entry.call::<Value>(()))?;
vm.set_module(module)?;
if let Some(start) = self.options.start.clone() {
self.timed(&vm, |vm| start(&vm.lua, &vm.module, vm.id))?;
}
if let (Some(saved), Some(load)) = (saved, vm.export("loadHotState")) {
self.timed(&vm, |_| load.call::<()>(saved))?;
}
*self.vm.borrow_mut() = Some(Rc::new(vm));
*self.failed.borrow_mut() = None;
self.warned.borrow_mut().clear();
self.salt.set(self.salt.get().wrapping_add(1));
if let Some(vm) = self.vm() {
self.settle(&vm, None);
}
drop(old);
Ok(Reload { compile: Duration::ZERO, swap: start.elapsed() })
}
/// The part of a new VM that doesn't depend on the script's files.
fn base(&self) -> Result<Base, ScriptError> {
let weak = self.weak.clone();
let log: Rc<dyn Fn(LogLevel, String)> = Rc::new(move |level, message| {
if let Some(i) = weak.upgrade() {
i.log(level, &message);
}
});
Base::new(Setup { shared: &self.shared, memory_limit: self.options.memory_limit, nodes: &self.options.nodes, host: self.options.setup.as_deref(), log })
}
pub(crate) fn prewarm(&self) {
if self.spare.borrow().is_none() {
let base = self.base().ok();
*self.spare.borrow_mut() = base;
}
}
pub(crate) fn env(&self, vm: &Vm, dark: bool) -> Rc<Env> {
Rc::new(Env {
script: self.weak.clone(),
vm: vm.id,
render: crate::ui::next_render(),
salt: self.salt.get(),
version: self.version.get(),
dark,
memo_failed: Cell::new(false),
palette: self.options.palette.clone(),
shadows: self.options.shadows.clone(),
text: self.options.text,
weights: self.options.weights,
garbage: Rc::downgrade(&vm.garbage),
templates: vm.templates.clone(),
recording: RefCell::new(None),
prefix: self.prefix.clone(),
nodes: self.nodes.clone(),
warned: self.warned.clone(),
colors: RefCell::new(Vec::new()),
})
}
pub(crate) fn render<S: 'static>(&self, name: &str, dark: bool) -> El {
let attach = attach::<S>();
let card = |message: &str| error_card(message, &self.options.palette, dark, attach, self.weak.clone());
if let Some(err) = self.failed.borrow().as_ref() {
return card(&err.message);
}
let Some(vm) = self.vm() else { return card("the script isn't running") };
let Some(render) = vm.export(name) else {
return card(&format!("init.luau exports no {name} function"));
};
let env = self.env(&vm, dark);
let built = with_frame(attach, env.clone(), || {
self.timed(&vm, |vm| {
vm.view.raw_set("dark", dark)?;
let out = render.call::<Value>(vm.view.clone())?;
take_root(out)
})
});
let mut m = self.metrics.get();
m.renders += 1;
self.metrics.set(m);
self.note_schedule(&vm);
if env.memo_failed.get() {
self.salt.set(self.salt.get().wrapping_add(1));
}
match built {
Ok(el) => el,
Err(err) => {
let err = ScriptError::from(err);
self.log(LogLevel::Error, &err.message);
self.salt.set(self.salt.get().wrapping_add(1));
card(&err.message)
}
}
}
pub(crate) fn row<S: 'static>(&self, spec: &Spec, i: usize) -> El {
let Some(vm) = self.vm().filter(|vm| vm.id == spec.render.vm) else { return rune::el() };
let env = self.env(&vm, self.dark.get());
let r = spec.render.func.r;
let built = with_frame(attach::<S>(), env, || {
self.timed(&vm, |vm| {
let out = vm.function(r)?.call::<Value>(i + 1)?;
take_root(out)
})
});
let mut m = self.metrics.get();
m.rows += 1;
self.metrics.set(m);
self.note_schedule(&vm);
built.unwrap_or_else(|err| {
let err = ScriptError::from(err);
self.log(LogLevel::Error, &err.message);
row_error(&err.message)
})
}
pub(crate) fn row_key(&self, cb: &Callback, i: usize) -> String {
let Some(vm) = self.vm().filter(|vm| vm.id == cb.vm) else { return i.to_string() };
let r = cb.func.r;
let key = self.timed(&vm, |vm| vm.function(r)?.call::<Value>(i + 1));
match key {
Ok(Value::String(s)) => s.to_string_lossy(),
Ok(Value::Integer(n)) => n.to_string(),
Ok(Value::Number(n)) => crate::ui::props::format_num(n),
_ => i.to_string(),
}
}
}
/// The element behind the handle a render or row function returned.
pub(crate) fn take_root(out: Value) -> mlua::Result<El> {
match out {
Value::LightUserData(LightUserData(p)) => top(|f| f.take(p)).unwrap_or_else(|| Err("no render in progress".into())).map_err(mlua::Error::runtime),
Value::Nil => Ok(rune::el()),
other => Err(mlua::Error::runtime(format!("a render function must return a ui node, not a {}", other.type_name()))),
}
}
+255
View File
@@ -0,0 +1,255 @@
//! [`Sources`]: a script's files, held in memory so a script runs the same from a folder, from
//! files built into the binary, or on the web, where there is no file system.
use std::collections::BTreeMap;
use std::sync::Arc;
use crate::{ErrorKind, ScriptError};
/// The file a script starts from.
pub const ENTRY: &str = "init.luau";
/// Configuration files `require` reads aliases from.
const CONFIGS: [&str; 2] = [".luaurc", ".config.luau"];
/// A script's files by path relative to its folder (`init.luau`, `views/row.luau`,
/// `.luaurc`). `require` follows Luau's require-by-string rules among them and never reaches
/// outside the folder: from `init.luau`, `require("@self/row")` is `row.luau`, and
/// `require("./row")` would be a sibling of the folder, so it fails.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Sources {
files: BTreeMap<String, Input>,
parent_config: Option<Arc<str>>,
folder: Option<String>,
entry: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Input {
Text(Arc<str>),
Embedded { code: &'static [u8], native: bool },
}
impl Sources {
pub fn new() -> Self {
Sources::default()
}
/// One file, `init.luau`.
pub fn single(source: impl Into<Arc<str>>) -> Self {
Sources::new().with(ENTRY, source)
}
/// Adds or replaces the file at `path` (`/`-separated, relative to the script's folder).
pub fn with(mut self, path: impl AsRef<str>, source: impl Into<Arc<str>>) -> Self {
self.insert(path, source);
self
}
/// Adds or replaces the file at `path`.
pub fn insert(&mut self, path: impl AsRef<str>, source: impl Into<Arc<str>>) {
self.files.insert(normalize(path.as_ref()), Input::Text(source.into()));
}
/// Adds a built-in module by its original path. The bytecode retains its line table; no text
/// is needed for stack traces. `native` is the source file's `--!native` directive.
///
/// # Safety
/// `code` must be trusted output of this build's Luau compiler. Never pass downloaded bytes
/// or files from a plugin directory: the VM expects compiler output, not untrusted bytecode.
#[allow(unsafe_code)]
pub unsafe fn with_embedded(mut self, path: &str, code: &'static [u8], native: bool) -> Self {
self.files.insert(normalize(path), Input::Embedded { code, native });
self
}
/// The `.luaurc` of the folder holding the script's folder, as an editor finds it above a
/// plugin: its aliases resolve for every module. Aliases may only lead back into the
/// script's folder; built-in modules (`@rune/ui`) resolve before aliases.
pub fn parent_config(mut self, luaurc: impl Into<Arc<str>>) -> Self {
self.parent_config = Some(luaurc.into());
self
}
/// The module the script starts from, [`ENTRY`] (`init.luau`) unless set: a host with two
/// entry points in one folder (`app.luau` beside `init.luau`) starts each as its own script.
pub fn entry(mut self, path: impl AsRef<str>) -> Self {
self.entry = Some(normalize(path.as_ref()));
self
}
/// The module the script starts from.
pub fn entry_path(&self) -> &str {
self.entry.as_deref().unwrap_or(ENTRY)
}
/// The script folder's own name, so an alias in [`Sources::parent_config`] that leads to
/// `./<name>` resolves into it.
pub fn folder(mut self, name: impl Into<String>) -> Self {
self.folder = Some(name.into());
self
}
/// Every `.luau` file and `.luaurc` under `dir`, recursively, with the `.luaurc` of the
/// folder above it as [`Sources::parent_config`].
#[cfg(not(target_arch = "wasm32"))]
pub fn from_dir(dir: impl AsRef<std::path::Path>) -> std::io::Result<Self> {
fn walk(root: &std::path::Path, dir: &std::path::Path, out: &mut Sources) -> std::io::Result<()> {
for entry in std::fs::read_dir(dir)? {
let path = entry?.path();
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();
if path.is_dir() {
walk(root, &path, out)?;
} else if (name.ends_with(".luau") || CONFIGS.contains(&name))
&& let Ok(rel) = path.strip_prefix(root)
{
let rel: Vec<_> = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
out.insert(rel.join("/"), std::fs::read_to_string(&path)?);
}
}
Ok(())
}
let dir = dir.as_ref();
let mut out = Sources::new();
out.folder = dir.file_name().map(|n| n.to_string_lossy().into_owned());
walk(dir, dir, &mut out)?;
if let Some(parent) = dir.parent()
&& let Ok(luaurc) = std::fs::read_to_string(parent.join(".luaurc"))
{
out.parent_config = Some(luaurc.into());
}
Ok(out)
}
/// The text at `path`, if supplied as source rather than as an embedded module.
pub fn get(&self, path: &str) -> Option<&str> {
match self.files.get(path)? { Input::Text(s) => Some(s), Input::Embedded { .. } => None }
}
/// Every file's path, sorted.
pub fn paths(&self) -> impl Iterator<Item = &str> {
self.files.keys().map(String::as_str)
}
/// Compiles every `.luau` file to Luau bytecode (`-O2`, with type information for native
/// code). Runs on any thread; a watched script compiles off the UI thread.
pub fn compile(&self) -> Result<Compiled, ScriptError> {
self.compile_reusing(None)
}
/// [`Sources::compile`], reusing `previous`'s bytecode for every module whose source is
/// the same: a save recompiles only the files it changed.
pub fn compile_from(&self, previous: &Compiled) -> Result<Compiled, ScriptError> {
self.compile_reusing(Some(previous))
}
fn compile_reusing(&self, previous: Option<&Compiled>) -> Result<Compiled, ScriptError> {
let compiler = compiler();
let entry = self.entry_path();
if !self.files.contains_key(entry) {
return Err(ScriptError::new(ErrorKind::Missing, format!("the script has no {entry}")));
}
let mut modules = BTreeMap::new();
let mut configs = BTreeMap::new();
for (path, input) in &self.files {
let source = match input {
Input::Text(source) => source,
Input::Embedded { code, native } => {
modules.insert(path.clone(), Module { code: Arc::from(*code), native: *native, source: None });
continue;
}
};
if !path.ends_with(".luau") || path.ends_with(".config.luau") {
configs.insert(path.clone(), source.clone());
continue;
}
if let Some(same) = previous.and_then(|p| p.modules.get(path)).filter(|m| m.source.as_ref() == Some(source)) {
modules.insert(path.clone(), same.clone());
continue;
}
if let Some(code) = PRECOMPILED.get().and_then(|table| table.get(&**source)) {
modules.insert(path.clone(), Module { code: Arc::from(*code), native: is_native(source), source: Some(source.clone()) });
continue;
}
let code = compiler
.compile(source.as_bytes())
.map_err(|e| ScriptError::new(ErrorKind::Syntax, format!("{path}{}", ScriptError::from(e).message)))?;
modules.insert(path.clone(), Module { code: code.into(), native: is_native(source), source: Some(source.clone()) });
}
Ok(Compiled { modules, configs, parent_config: self.parent_config.clone(), folder: self.folder.clone(), entry: entry.to_owned() })
}
}
/// [`Sources`] compiled to bytecode, ready to load into a VM.
#[derive(Clone, Debug)]
pub struct Compiled {
modules: BTreeMap<String, Module>,
configs: BTreeMap<String, Arc<str>>,
parent_config: Option<Arc<str>>,
pub(crate) folder: Option<String>,
pub(crate) entry: String,
}
#[derive(Clone, Debug)]
pub(crate) struct Module {
pub(crate) code: Arc<[u8]>,
/// The file starts with `--!native`: compile it to native code with the `native-code` feature.
pub(crate) native: bool,
/// What it was compiled from, so a later compile of the same text reuses it.
source: Option<Arc<str>>,
}
impl Compiled {
pub(crate) fn module(&self, path: &str) -> Option<&Module> {
self.modules.get(path)
}
/// Whether folder `dir` ("" for the script's own) holds any file.
pub(crate) fn is_dir(&self, dir: &str) -> bool {
dir.is_empty() || {
let prefix = format!("{dir}/");
self.modules.keys().chain(self.configs.keys()).any(|k| k.starts_with(&prefix))
}
}
/// The configuration file in folder `dir` ("" for the script's own), or above the script's
/// folder for `None`.
pub(crate) fn config(&self, dir: Option<&str>) -> Option<&str> {
let Some(dir) = dir else { return self.parent_config.as_deref() };
CONFIGS.iter().find_map(|name| {
let path = if dir.is_empty() { (*name).to_owned() } else { format!("{dir}/{name}") };
self.configs.get(&path).map(|s| &**s)
})
}
}
/// Bytecode compiled ahead of time, by the source text it came from (`precompiled`).
static PRECOMPILED: std::sync::OnceLock<std::collections::HashMap<&'static str, &'static [u8]>> = std::sync::OnceLock::new();
/// Bytecode an app compiled ahead of time for the sources it ships, as `(source, bytecode)`, so a
/// script made from them starts without compiling: `Sources::compile` takes a module's bytecode from
/// here when its text is the same. Compile it as Rune does: optimisation level 2, type information
/// level 1, debug level 1 (`mlua::chunk::Compiler`, from the same Luau as this build). Compiling
/// is most of a script's start (a 100 KB plugin: about 28,000 µs of its 30,000 on a Windows
/// laptop). Call it once, before scripts start; later calls do nothing. A table from another Luau
/// bytecode version than this build's is ignored, and those scripts compile as before.
pub fn precompiled(modules: impl IntoIterator<Item = (&'static str, &'static [u8])>) {
let version = compiler().compile("return nil").ok().and_then(|code| code.first().copied());
let table = modules.into_iter().filter(|(_, code)| code.first().copied() == version).collect();
PRECOMPILED.set(table).ok();
}
pub(crate) fn compiler() -> mlua::chunk::Compiler {
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
crate::web::init();
mlua::chunk::Compiler::new().set_optimization_level(2).set_type_info_level(1).set_debug_level(1)
}
/// Whether a `--!native` hot comment opens the file (before any code).
fn is_native(source: &str) -> bool {
source.lines().map(str::trim).take_while(|l| l.is_empty() || l.starts_with("--")).any(|l| l.starts_with("--!native"))
}
fn normalize(path: &str) -> String {
path.replace('\\', "/").trim_start_matches("./").trim_start_matches('/').to_owned()
}
+296
View File
@@ -0,0 +1,296 @@
//! The `task` library on Rune's frame clock. `spawn` runs a coroutine at once until it yields;
//! `defer` queues one for the end of the current handler or poll; `delay` and `wait` park one
//! until a deadline on the clock `AppSpec::poll` receives (virtual in headless runs), which the
//! host turns into `Tx::wake_after`; a host async call parks one until its [`Completer`] fires.
//! Nothing polls: with no deadline due and no result waiting, a poll returns without entering
//! the VM.
//!
//! [`Completer`]: crate::Completer
use std::cmp::Reverse;
use std::collections::{BinaryHeap, VecDeque};
use std::ffi::c_void;
use std::sync::Arc;
use mlua::thread::ThreadStatus;
use mlua::{Function, LightUserData, Lua, MultiValue, Table, Thread, Value};
use rune::time::Instant;
use rustc_hash::FxHashMap;
use crate::ScriptError;
use crate::workers::Shared;
static WAIT: u8 = 0;
static PARK: u8 = 0;
static JOB: u8 = 0;
fn token(tag: &'static u8) -> LightUserData {
LightUserData(tag as *const u8 as *mut c_void)
}
/// A deadline, ordered by time then by when it was set.
#[derive(Clone, Copy, PartialEq)]
struct Due(f64, u64);
impl Eq for Due {}
impl PartialOrd for Due {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Due {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0.total_cmp(&other.0).then(self.1.cmp(&other.1))
}
}
/// A parked task: resumed with the seconds it waited, or with `delay`'s arguments.
struct Parked {
thread: Thread,
since: f64,
args: Option<MultiValue>,
}
/// One VM's scheduler, kept in the VM's app data.
pub(crate) struct Sched {
clock: f64,
read_at: Instant,
timers: BinaryHeap<Reverse<Due>>,
parked: FxHashMap<u64, Parked>,
by_thread: FxHashMap<*const c_void, u64>,
defers: VecDeque<(Thread, MultiValue)>,
jobs: FxHashMap<u64, Thread>,
next: u64,
/// A deadline was set since the host last read [`Sched::take_changed`].
changed: bool,
pub(crate) errors: Vec<ScriptError>,
pub(crate) shared: Arc<Shared>,
}
impl Sched {
pub(crate) fn new(shared: Arc<Shared>, clock: f64) -> Self {
Sched {
clock,
read_at: rune::time::now(),
timers: BinaryHeap::new(),
parked: FxHashMap::default(),
by_thread: FxHashMap::default(),
defers: VecDeque::new(),
jobs: FxHashMap::default(),
next: 0,
changed: false,
errors: Vec::new(),
shared,
}
}
/// Sets the frame clock to `clock` now (a VM built ahead of time starts on the clock of the
/// moment it runs).
pub(crate) fn set_clock(&mut self, clock: f64) {
self.clock = clock;
self.read_at = rune::time::now();
}
/// The frame clock now: the last poll's reading plus the wall time since.
fn now(&self) -> f64 {
self.clock + self.read_at.elapsed().as_secs_f64()
}
fn park(&mut self, thread: Thread, at: f64, args: Option<MultiValue>) {
self.next += 1;
let since = self.now();
self.by_thread.insert(thread.to_pointer(), self.next);
self.parked.insert(self.next, Parked { thread, since, args });
self.timers.push(Reverse(Due(at, self.next)));
self.changed = true;
}
fn forget(&mut self, thread: &Thread) {
if let Some(seq) = self.by_thread.remove(&thread.to_pointer()) {
self.parked.remove(&seq);
}
let ptr = thread.to_pointer();
self.defers.retain(|(t, _)| t.to_pointer() != ptr);
self.jobs.retain(|_, t| t.to_pointer() != ptr);
}
/// The earliest deadline still set.
pub(crate) fn next_deadline(&mut self) -> Option<f64> {
while let Some(Reverse(Due(at, seq))) = self.timers.peek().copied() {
if self.parked.contains_key(&seq) {
return Some(at);
}
self.timers.pop();
}
None
}
pub(crate) fn has_defers(&self) -> bool {
!self.defers.is_empty()
}
pub(crate) fn take_changed(&mut self) -> bool {
std::mem::take(&mut self.changed)
}
/// Seconds from now until `deadline` on the frame clock.
pub(crate) fn wait_for(&self, deadline: Option<f64>) -> Option<f64> {
deadline.map(|d| (d - self.now()).max(0.0))
}
}
/// Builds the `task` table (the prelude adds `wait` and `cancel`) and the host half of cancel.
pub(crate) fn install(lua: &Lua) -> mlua::Result<(Table, Function)> {
let task = lua.create_table()?;
task.raw_set(
"spawn",
lua.create_function(|lua, (target, args): (Value, MultiValue)| {
let thread = thread_of(lua, target, "task.spawn")?;
with(lua, |s| s.forget(&thread));
if thread.status() == ThreadStatus::Resumable {
run(lua, &thread, args);
}
Ok(thread)
})?,
)?;
task.raw_set(
"defer",
lua.create_function(|lua, (target, args): (Value, MultiValue)| {
let thread = thread_of(lua, target, "task.defer")?;
with(lua, |s| s.defers.push_back((thread.clone(), args)));
Ok(thread)
})?,
)?;
task.raw_set(
"delay",
lua.create_function(|lua, (seconds, target, args): (Option<f64>, Value, MultiValue)| {
let thread = thread_of(lua, target, "task.delay")?;
with(lua, |s| {
let at = s.now() + seconds.unwrap_or(0.0).max(0.0);
s.park(thread.clone(), at, Some(args));
});
Ok(thread)
})?,
)?;
let forget = lua.create_function(|lua, thread: Thread| {
with(lua, |s| s.forget(&thread));
Ok(())
})?;
Ok((task, forget))
}
/// The tokens the prelude yields: wait, park, job.
pub(crate) fn tokens() -> (LightUserData, LightUserData, LightUserData) {
(token(&WAIT), token(&PARK), token(&JOB))
}
fn thread_of(lua: &Lua, target: Value, name: &str) -> mlua::Result<Thread> {
match target {
Value::Function(f) => lua.create_thread(f),
Value::Thread(t) => Ok(t),
other => Err(mlua::Error::runtime(format!("{name} needs a function or a thread, got {}", other.type_name()))),
}
}
fn with<R>(lua: &Lua, f: impl FnOnce(&mut Sched) -> R) -> Option<R> {
lua.app_data_mut::<Sched>().map(|mut s| f(&mut s))
}
/// Resumes `thread` with `args` and parks it by what it yielded. An error in the task is
/// recorded, not raised: one failing task doesn't stop the code that started it.
pub(crate) fn run(lua: &Lua, thread: &Thread, args: impl mlua::IntoLuaMulti) {
match thread.resume::<MultiValue>(args) {
Ok(out) if thread.status() == ThreadStatus::Resumable => park(lua, thread, out),
Ok(_) => {}
Err(err) => {
let err = ScriptError::from(err);
with(lua, |s| s.errors.push(err));
}
}
}
fn park(lua: &Lua, thread: &Thread, out: MultiValue) {
let tag = match out.front() {
Some(Value::LightUserData(p)) => p.0,
_ => std::ptr::null_mut(),
};
// Whole numbers arrive as integers.
let arg = match out.get(1) {
Some(Value::Integer(i)) => Some(*i as f64),
Some(Value::Number(n)) => Some(*n),
_ => None,
};
with(lua, |s| {
if tag == token(&PARK).0 {
return;
}
if tag == token(&JOB).0 {
s.jobs.insert(arg.unwrap_or_default() as u64, thread.clone());
return;
}
// `task.wait(seconds)`, or a bare `coroutine.yield()` in a task: resume next frame.
let wait = if tag == token(&WAIT).0 { arg.unwrap_or(0.0).max(0.0) } else { 0.0 };
let at = s.now() + wait;
s.park(thread.clone(), at, None);
});
}
/// Runs what is due at frame time `now`: finished host calls, then deadlines that passed, then
/// deferred tasks. Tasks parked during this run wait for a later poll. Returns how many tasks
/// resumed.
pub(crate) fn poll(lua: &Lua, now: f64) -> usize {
let Some((done, due)) = with(lua, |s| {
s.clock = now;
s.read_at = rune::time::now();
let done: Vec<_> =
s.shared.take_completions().into_iter().filter_map(|(id, value)| Some((s.jobs.remove(&id)?, value))).collect();
let mut due = Vec::new();
while let Some(Reverse(Due(at, seq))) = s.timers.peek().copied() {
if at > now {
break;
}
s.timers.pop();
if let Some(p) = s.parked.remove(&seq) {
s.by_thread.remove(&p.thread.to_pointer());
due.push(p);
}
}
(done, due)
}) else {
return 0;
};
let mut resumed = done.len() + due.len();
for (thread, value) in done {
run(lua, &thread, value);
}
for p in due {
match p.args {
Some(args) => run(lua, &p.thread, args),
None => run(lua, &p.thread, (now - p.since).max(0.0)),
}
}
resumed += drain_defers(lua);
resumed
}
/// Runs deferred tasks until none are left, including ones they defer.
pub(crate) fn drain_defers(lua: &Lua) -> usize {
let mut n = 0;
while let Some((thread, args)) = with(lua, |s| s.defers.pop_front()).flatten() {
if thread.status() == ThreadStatus::Resumable {
run(lua, &thread, args);
}
n += 1;
if n >= 100_000 {
let err = ScriptError::new(crate::ErrorKind::Runtime, "task.defer: more than 100,000 deferred tasks in one batch");
with(lua, |s| {
s.defers.clear();
s.errors.push(err);
});
break;
}
}
n
}
+346
View File
@@ -0,0 +1,346 @@
//! Nodes an app adds to `ui`: `ui.<name>(props?, children?)`, `ui.<name>(content, props?)` or
//! `ui.<name>(props, node)`, built by the app from [`NodeArgs`]; a second props table after the
//! first lays its props over it (`ui.icon("copy", STYLE, { color = ink })`). The standard layout
//! props (`w`, `pad`, `key`, `label`, ...) apply after the app's build, except the ones it read.
#![allow(unsafe_code)]
use std::cell::Cell;
use std::os::raw::c_int;
use std::rc::Rc;
use mlua::ffi;
use rune::{Color, El};
use super::nodes::{keyed, take_children};
use super::props::{self, Atom, Props, Value};
use super::{Callback, Env, Frame, guard, top};
use crate::Data;
type BuildNode = dyn Fn(&mut NodeArgs) -> Result<El, String>;
/// A node an app adds to `ui`: `ui.<name>(props, children)` calls `build` with the props as
/// [`NodeArgs`]. Use it for native views a script places (a code view, a terminal) and for the
/// app's own controls (a button, a switch).
#[derive(Clone)]
pub struct HostNode {
pub(crate) name: String,
pub(crate) build: Rc<BuildNode>,
/// The props the node has ([`HostNode::props`]): a key that is neither one of them nor a
/// standard prop is unknown ([`super::unknown_prop`]).
known: Option<Rc<dyn Fn(&str) -> bool>>,
}
impl HostNode {
pub fn new(name: impl Into<String>, build: impl Fn(&mut NodeArgs) -> Result<El, String> + 'static) -> Self {
HostNode { name: name.into(), build: Rc::new(build), known: None }
}
/// The props the node has, as its contract lists them. With it, a script's prop that is
/// neither one of these nor a standard prop is an error in debug builds and a warning (once
/// per script) in release, instead of being dropped without a word. Without it the node's
/// unknown props go unreported, as a prop its build reads only sometimes can't be told apart.
pub fn props(mut self, known: impl Fn(&str) -> bool + 'static) -> Self {
self.known = Some(Rc::new(known));
self
}
}
/// A host node's arguments: a leading string (`ui.icon("copy", props)`), its props and its
/// children (an array, or one node: `ui.settingsRow(props, control)`).
pub struct NodeArgs {
content: Option<String>,
props: Vec<(Key, Prop)>,
pub children: Vec<El>,
attach: &'static super::Attach,
env: Rc<Env>,
/// Props the build read, by index in `props` (past 64 all count as read): the standard pass
/// leaves them alone.
used: Cell<u64>,
}
/// A prop's name: the bytes of the key string in the props table. The table sits on the Luau
/// stack for the whole host node call, which is a `NodeArgs`'s whole life, and keeps it alive.
struct Key(*const u8, usize);
impl Key {
fn as_str(&self) -> &str {
// SAFETY: as the type says; `host_props` only makes keys of UTF-8 strings.
unsafe { std::str::from_utf8_unchecked(std::slice::from_raw_parts(self.0, self.1)) }
}
}
/// One prop a host node received.
#[derive(Clone)]
pub enum Prop {
Bool(bool),
Number(f64),
String(String),
/// A table, as plain data.
Data(Data),
/// A function; [`NodeArgs::on_press`] attaches it.
Function(Handler),
}
/// A script function a host node can run on press.
#[derive(Clone)]
pub struct Handler(Rc<Callback>);
/// A script function a host node keeps past its build ([`NodeArgs::press_later`]): each element
/// it attaches to runs it on press, with that element's own event fields.
#[derive(Clone)]
pub struct Press {
cb: Rc<Callback>,
attach: &'static super::Attach,
key: Option<Rc<str>>,
}
impl Press {
/// Runs the function when `el` is pressed, with `fields` added to its `press` event.
pub fn attach(&self, el: El, fields: Vec<(&'static str, Data)>) -> El {
let mut el = el;
(self.attach.press)(&mut el, self.cb.clone(), self.key.clone(), fields.into());
el
}
}
impl NodeArgs {
/// The node's key, which the standard pass applies: reading it here leaves it there.
fn key(&self) -> Option<Rc<str>> {
self.props.iter().rev().find_map(|(k, v)| match v {
Prop::String(s) if k.as_str() == "key" => Some(s.as_str().into()),
_ => None,
})
}
/// The leading string argument, if the node was called with one.
pub fn content(&self) -> Option<&str> {
self.content.as_deref()
}
/// Prop `name`: from the props laid over a style, else from the style.
pub fn get(&self, name: &str) -> Option<&Prop> {
let i = self.props.iter().rposition(|(k, _)| k.as_str() == name)?;
if i < 64 {
self.used.set(self.used.get() | 1 << i);
}
Some(&self.props[i].1)
}
/// The names of the props the build read.
fn read(&self) -> impl Iterator<Item = &str> {
let used = self.used.get();
self.props.iter().enumerate().filter(move |(i, _)| *i >= 64 || used & (1 << i) != 0).map(|(_, (k, _))| k.as_str())
}
pub fn number(&self, name: &str) -> Option<f64> {
match self.get(name) {
Some(Prop::Number(n)) => Some(*n),
_ => None,
}
}
pub fn string(&self, name: &str) -> Option<&str> {
match self.get(name) {
Some(Prop::String(s)) => Some(s),
_ => None,
}
}
pub fn flag(&self, name: &str) -> bool {
matches!(self.get(name), Some(Prop::Bool(true)))
}
/// A table prop as plain data (a string or number prop too).
pub fn data(&self, name: &str) -> Option<Data> {
match self.get(name)? {
Prop::Data(d) => Some(d.clone()),
Prop::String(s) => Some(Data::String(s.clone())),
Prop::Number(n) => Some(Data::Number(*n)),
Prop::Bool(b) => Some(Data::Bool(*b)),
Prop::Function(_) => None,
}
}
/// The colour prop `name` names (a palette name or `ui.hex`), resolved for this render.
pub fn color(&self, name: &str) -> Option<Color> {
self.string(name).and_then(|c| self.env.resolve(c).ok())
}
/// Palette colour `name`, resolved for this render.
pub fn palette(&self, name: &str) -> Option<Color> {
self.env.color(name)
}
/// Whether the render is for the dark appearance.
pub fn dark(&self) -> bool {
self.env.dark
}
/// The script function in prop `name`.
pub fn handler(&self, name: &str) -> Option<Handler> {
match self.get(name) {
Some(Prop::Function(h)) => Some(h.clone()),
_ => None,
}
}
/// Runs the script function in prop `name` when `el` is pressed; with `menuTrigger = true`, a
/// mouse runs it as the button goes down (`El::press_on_down`), as on a `ui` node.
pub fn on_press(&self, el: El, name: &str) -> El {
let el = self.on_press_with(el, name, Vec::new());
if self.flag("menuTrigger") && self.handler(name).is_some() { el.press_on_down() } else { el }
}
/// Runs the script function in prop `name` when `el` is pressed, with `fields` added to its
/// event (`checked` for a switch).
pub fn on_press_with(&self, el: El, name: &str, fields: Vec<(&'static str, Data)>) -> El {
let key = self.key();
match self.handler(name) {
Some(h) => {
let mut el = el;
(self.attach.press)(&mut el, h.0, key, fields.into());
el
}
None => el,
}
}
/// The script function in prop `name`, kept to run on a press of elements the node builds
/// later, such as the rows of a virtual list it makes.
pub fn press_later(&self, name: &str) -> Option<Press> {
let key = self.key();
self.handler(name).map(|h| Press { cb: h.0, attach: self.attach, key })
}
/// Runs the script function in prop `name` as the pointer enters and leaves `el`.
pub fn on_hover(&self, el: El, name: &str) -> El {
let key = self.key();
match self.handler(name) {
Some(h) => (self.attach.hover)(el, h.0, key),
None => el,
}
}
}
/// `ui.<host node>(...)`: upvalue 1 is the node's index in the script's host nodes.
pub(crate) unsafe extern "C-unwind" fn ui_host(state: *mut ffi::lua_State) -> c_int {
// SAFETY: reads this C function's arguments and upvalue.
unsafe {
let index = ffi::lua_tointegerx(state, ffi::lua_upvalueindex(1), std::ptr::null_mut()) as usize;
let lead = ffi::lua_type(state, 1) == ffi::LUA_TSTRING;
let content = lead.then(|| match props::read(state, 1) {
Value::Str(s) => s.to_owned(),
_ => String::new(),
});
let first = if lead { 2 } else { 1 };
let props_at = if ffi::lua_type(state, first) == ffi::LUA_TTABLE { first } else { 0 };
// Props laid over a style: `ui.icon("copy", STYLE, { color = ink })`.
let over_at = if props_at > 0 && ffi::lua_type(state, first + 1) == ffi::LUA_TTABLE && keyed(state, first + 1) { first + 1 } else { 0 };
let next = if over_at > 0 { over_at + 1 } else { first + 1 };
let children_at = match ffi::lua_type(state, next) {
ffi::LUA_TTABLE | ffi::LUA_TLIGHTUSERDATA => next,
_ => 0,
};
guard(state, || {
let args = top(|frame| -> Result<NodeArgs, String> {
let mut props = if props_at > 0 { host_props(state, props_at, frame)? } else { Vec::new() };
if over_at > 0 {
props.extend(host_props(state, over_at, frame)?);
}
let children = match children_at {
0 => Vec::new(),
at if ffi::lua_type(state, at) == ffi::LUA_TLIGHTUSERDATA => vec![frame.take(ffi::lua_tolightuserdata(state, at))?],
at => take_children(state, at, frame)?,
};
Ok(NodeArgs { content, props, children, attach: frame.attach, env: frame.env.clone(), used: Cell::new(0) })
});
let mut args = args.ok_or("ui nodes can only be built while rendering")??;
let node = top(|frame| frame.env.nodes.get(index).cloned()).flatten().ok_or("unknown host node")?;
let el = (node.build)(&mut args).map_err(|e| format!("ui.{}: {e}", node.name))?;
// Standard layout props still apply, after the host's own.
build_from(state, el, [props_at, over_at], &args, &node)
})
}
}
unsafe fn build_from(state: *mut ffi::lua_State, el: El, tables: [c_int; 2], args: &NodeArgs, node: &HostNode) -> Result<c_int, String> {
top(|frame| {
let Frame { arena, attach, env } = frame;
let slot = arena.alloc(el)?;
let mut p = Props::new(env);
for props_at in tables.into_iter().filter(|&at| at > 0) {
let el = arena.get_mut(slot);
// SAFETY: walks the props table again, decoding the standard props the build left.
unsafe {
let mut iter = 0;
while {
iter = ffi::lua_rawiter(state, props_at, iter);
iter >= 0
} {
let key = match props::read(state, -2) {
Value::Str(k) => Some(k),
_ => None,
};
let own = key.is_some_and(|k| args.read().any(|u| u == k));
// Neither read by the build nor in the node's listed props.
let unknown = |name: &str| !own && node.known.as_ref().is_some_and(|known| !known(name));
match props::key_atom(state, -2) {
// The build attaches the handlers it takes; one it didn't read is unknown.
Ok(Atom::OnPress | Atom::OnHover | Atom::OnMiddlePress) => {
if let Some(k) = key
&& unknown(k)
{
super::unknown_prop(env, Some(&node.name), k)?;
}
}
Ok(atom) if !own => p.decode_at(el, state, atom, -1, env, false)?,
Err(name) if unknown(name) => super::unknown_prop(env, Some(&node.name), name)?,
_ => {}
}
ffi::lua_settop(state, -3);
}
}
}
p.finish(arena.get_mut(slot), env, false, None, *attach);
let handle = arena.handle(slot);
// SAFETY: pushes the handle as this C function's result.
unsafe { ffi::lua_pushlightuserdata(state, handle) };
Ok(1)
})
.unwrap_or_else(|| Err("ui nodes can only be built while rendering".into()))
}
unsafe fn host_props(state: *mut ffi::lua_State, idx: c_int, frame: &Frame) -> Result<Vec<(Key, Prop)>, String> {
let mut out = Vec::new();
// SAFETY: walks the table at `idx`, popping each value.
unsafe {
let mut iter = 0;
while {
iter = ffi::lua_rawiter(state, idx, iter);
iter >= 0
} {
let key = match props::read(state, -2) {
Value::Str(s) => Some(Key(s.as_ptr(), s.len())),
_ => None,
};
let value = match props::read(state, -1) {
Value::Bool(b) => Some(Prop::Bool(b)),
Value::Num(n) => Some(Prop::Number(n)),
Value::Str(s) => Some(Prop::String(s.to_owned())),
Value::Func => Some(Prop::Function(Handler(frame.env.reference(state, -1)))),
Value::Other("table") => Some(Prop::Data(crate::data::from_stack(state, -1))),
Value::Nil | Value::Other(_) => None,
};
if let (Some(k), Some(v)) = (key, value) {
out.push((k, v));
}
ffi::lua_settop(state, -3);
}
}
Ok(out)
}
#[cfg(test)]
#[path = "host_tests.rs"]
mod tests;
+38
View File
@@ -0,0 +1,38 @@
//! An app-defined node that lists its props (`HostNode::props`): a prop outside the list is an
//! unknown prop (the render fails in debug builds, a warning in release); a listed one is not.
use std::cell::RefCell;
use std::rc::Rc;
use crate::{HostNode, LogLevel, Script, ScriptOptions, Sources};
/// Renders `ui.probe(<props>)` from a script whose `probe` node lists only `text`, and returns
/// what the script logged.
fn render_probe(props: &str) -> Vec<(LogLevel, String)> {
let logged = Rc::new(RefCell::new(Vec::new()));
let sink = logged.clone();
let node = HostNode::new("probe", |args| Ok(rune::text(args.string("text").unwrap_or("")))).props(|name| name == "text");
let options = ScriptOptions::new().node(node).on_log(move |level, message| sink.borrow_mut().push((level, message.to_owned())));
let mut sources = Sources::new();
sources.insert("init.luau", format!("local ui = require(\"@rune/ui\")\nlocal M = {{}}\nfunction M.render(view)\n return ui.probe({props})\nend\nreturn M\n"));
let script = Script::with_options("probe", sources, options);
assert!(script.error().is_none(), "start: {:?}", script.error());
let _ = script.render_uncached::<()>("render", false);
logged.take()
}
#[test]
fn an_unlisted_prop_on_an_app_defined_node_is_an_error_in_debug_and_a_warning_in_release() {
let logged = render_probe(r#"{ text = "a", autofocus = true }"#);
let level = if cfg!(debug_assertions) { LogLevel::Error } else { LogLevel::Warn };
assert!(
logged.iter().any(|(l, m)| *l == level && m.contains("ui.probe: unknown prop `autofocus`")),
"expected a {level:?} naming the prop, got {logged:?}"
);
}
#[test]
fn a_listed_prop_on_an_app_defined_node_is_not_unknown() {
let logged = render_probe(r#"{ text = "a", key = "probe" }"#);
assert!(!logged.iter().any(|(l, m)| *l == LogLevel::Error || m.contains("unknown prop")), "got {logged:?}");
}
+502
View File
@@ -0,0 +1,502 @@
//! `UiArena`: Luau builds `rune::El`s directly. `ui.row(props, children)` and the other
//! constructors are plain C functions: they read props off the Luau stack, build the `El` into
//! this render's arena, and return a light-userdata handle (an index), so a node costs no Lua
//! table, no userdata and no tree diff. Rune's keyed elements and memo cache do the incremental
//! work: `view:Memo` wraps `rune::memo::memo_with_hash`, and `ui.virtualList` is
//! `El::virtual_rows`. A node whose props table is frozen (`table.freeze`) is decoded once and
//! copied after that ([`Templates`]).
pub(crate) mod host;
pub(crate) mod nodes;
pub(crate) mod props;
pub(crate) mod rows;
pub(crate) mod view;
use std::cell::{Cell, RefCell};
use std::ffi::c_void;
use std::os::raw::c_int;
use std::rc::{Rc, Weak};
use mlua::ffi;
use rune::{Color, El};
use rustc_hash::FxHashSet;
use crate::script::Inner;
/// Maps a colour name to a colour, for the current light or dark appearance. Names that start
/// with `#` are hex (`#rrggbb`, `#rrggbbaa`) and never reach it.
pub type Palette = Rc<dyn Fn(&str, bool) -> Option<Color>>;
/// Rune's own `tok::theme` colours under kebab-case names: `bg`, `card`, `card-border`, `text`,
/// `text-secondary`, `separator`, `hover`, `press`, `control-off`, `indicator`.
pub fn default_palette() -> Palette {
let themes = [rune::tok::theme(false), rune::tok::theme(true)];
Rc::new(move |name, dark| {
let t = &themes[usize::from(dark)];
Some(match name {
"bg" => t.bg,
"card" => t.card,
"card-border" => t.card_border,
"text" => t.text,
"text-secondary" => t.text_secondary,
"separator" => t.separator,
"hover" => t.hover,
"press" => t.press,
"control-off" => t.control_off,
"control-track" => t.control_track,
"indicator" => t.indicator,
_ => return None,
})
})
}
/// A Luau registry reference. Dropping it queues the slot for release at the VM's next entry,
/// since an element can drop while its VM is busy.
pub(crate) struct LuaRef {
pub(crate) r: c_int,
garbage: Weak<RefCell<Vec<c_int>>>,
}
impl Drop for LuaRef {
fn drop(&mut self) {
if let Some(g) = self.garbage.upgrade() {
g.borrow_mut().push(self.r);
}
}
}
/// A function a node handed the host: a press handler, a row builder.
pub(crate) struct Callback {
pub(crate) func: LuaRef,
pub(crate) vm: u64,
pub(crate) script: Weak<Inner>,
}
/// A prop a node doesn't have (a typo, or one wished for: `autofocus` on a button did nothing,
/// rune-desktop #664): an error in debug builds, so it can't pass unseen, and a warning once per
/// script in release, where the node still draws without it.
pub(crate) fn unknown_prop(env: &Env, node: Option<&str>, name: &str) -> Result<(), String> {
let message = match node {
Some(node) => format!("ui.{node}: unknown prop `{name}`"),
None => format!("unknown prop `{name}`"),
};
if cfg!(debug_assertions) {
return Err(message);
}
env.warn_once(format!("{message} (ignored)"));
Ok(())
}
/// What a render needs from its script.
pub(crate) struct Env {
pub(crate) script: Weak<Inner>,
pub(crate) vm: u64,
/// This render, unique on the thread ([`next_render`]).
pub(crate) render: u64,
pub(crate) salt: u64,
/// The script's version: it moves whenever script code runs.
pub(crate) version: u64,
pub(crate) dark: bool,
/// A `view:Memo` build failed this render, even if the script caught the error.
pub(crate) memo_failed: Cell<bool>,
pub(crate) palette: Palette,
pub(crate) shadows: Option<crate::options::Shadows>,
/// The text style `ui.text` starts from, and the weights `weight` names.
pub(crate) text: rune::TextStyle,
pub(crate) weights: [f32; 4],
pub(crate) garbage: Weak<RefCell<Vec<c_int>>>,
pub(crate) prefix: Rc<str>,
pub(crate) nodes: Rc<[host::HostNode]>,
pub(crate) warned: Rc<RefCell<FxHashSet<String>>>,
/// Colours this render resolved, by name: a render uses a handful, many times each.
pub(crate) colors: RefCell<Vec<(Box<str>, Color)>>,
/// The VM's nodes decoded from frozen props tables.
pub(crate) templates: Rc<RefCell<Templates>>,
/// While a frozen props table decodes: each colour it resolved, so its template knows
/// when a theme change has outdated it.
pub(crate) recording: RefCell<Option<Vec<(Box<str>, Color)>>>,
}
/// Nodes decoded from frozen props tables, by table and node kind. A frozen table can't change,
/// so a node built from one again starts from a copy of the first, its props already applied:
/// no table walk, no prop decoding, and the element's style shared until it is written. A script
/// gets this with `local STYLE = table.freeze({ ... })` passed as a node's props, or as the style
/// under a small table of its own props (`ui.row(STYLE, { key = id }, children)`): then only
/// those are decoded, onto a copy of the style's.
#[derive(Default)]
pub(crate) struct Templates(rustc_hash::FxHashMap<(usize, u8), Template>);
/// How many templates a VM keeps; past it the cache starts over.
const TEMPLATES: usize = 1024;
pub(crate) struct Template {
/// The finished node, without children, words or handlers.
el: El,
/// The node before its props were finished, and those props, for props laid over it.
under: El,
props: props::Props,
/// The appearance and colours it was decoded with.
dark: bool,
colors: Vec<(Box<str>, Color)>,
/// The render it last held in: a render checks its colours once.
checked: Cell<u64>,
/// Keeps the table alive, so its address isn't taken by another table.
_table: LuaRef,
}
/// A template as a node starts from.
pub(crate) enum Reuse {
/// The finished node: no props of its own.
Whole(El),
/// The node and its pending props, to decode the node's own props onto and finish.
Under(El, props::Props),
}
impl Templates {
/// A copy of the template for `key`, if it holds under `env`: finished, or ready for
/// `layered` props.
pub(crate) fn get(&self, key: (usize, u8), env: &Env, layered: bool) -> Option<Reuse> {
let t = self.0.get(&key)?;
if t.checked.get() != env.render {
let holds = t.dark == env.dark && t.colors.iter().all(|(name, c)| env.resolve(name).ok() == Some(*c));
if !holds {
return None;
}
t.checked.set(env.render);
}
Some(if layered { Reuse::Under(t.under.clone(), t.props.clone()) } else { Reuse::Whole(t.el.clone()) })
}
/// Keeps a node built from the frozen table at stack slot `idx` as `key`'s template: `under`
/// with its pending `props`, and `el`, the two finished.
#[allow(clippy::too_many_arguments, unsafe_code)]
pub(crate) unsafe fn put(&mut self, state: *mut ffi::lua_State, idx: c_int, key: (usize, u8), env: &Env, el: El, under: El, props: props::Props, colors: Vec<(Box<str>, Color)>) {
if self.0.len() >= TEMPLATES {
self.0.clear();
}
// SAFETY: the caller passes the props table's slot.
let r = unsafe { ffi::lua_ref(state, idx) };
let table = LuaRef { r, garbage: env.garbage.clone() };
self.0.insert(key, Template { el, under, props, dark: env.dark, colors, checked: Cell::new(env.render), _table: table });
}
}
/// Functions that need the window's state type, picked when a render starts.
pub(crate) struct Attach {
/// Runs the callback on press with a `press` event naming the element's key, and any
/// fields a host node adds (a switch's `checked`).
pub(crate) press: fn(&mut El, Rc<Callback>, Option<Rc<str>>, Fields),
/// Runs the callback on a middle click, with a `middle-press` event.
pub(crate) middle: fn(El, Rc<Callback>, Option<Rc<str>>) -> El,
/// Runs the callback as the pointer enters and leaves, with a `hover` event.
pub(crate) hover: fn(El, Rc<Callback>, Option<Rc<str>>) -> El,
pub(crate) rows: fn(El, rows::Spec) -> El,
pub(crate) reload: fn(El, Weak<Inner>) -> El,
}
/// Fields a host node adds to the events its handlers get.
pub(crate) type Fields = Rc<[(&'static str, crate::Data)]>;
pub(crate) fn attach<S: 'static>() -> &'static Attach {
const { &Attach { press: press::<S>, middle: middle::<S>, hover: hover::<S>, rows: rows::attach::<S>, reload: reload::<S> } }
}
fn press<S: 'static>(el: &mut El, cb: Rc<Callback>, key: Option<Rc<str>>, fields: Fields) {
el.set_on_press_tx(move |s: &mut S, tx| {
if let Some(script) = cb.script.upgrade() {
let mods = tx.mods();
let event = Event { fields: fields.clone(), ..Event::press(key.as_deref(), mods.shift, mods.alt, mods.cmd) };
script.around_write(s, Some(tx), |tx| script.handle(&cb, event, tx));
}
});
}
/// `onMiddlePress`: a middle click on the node (`El::on_middle_press`), as a `middle-press` event
/// with the modifier keys.
fn middle<S: 'static>(el: El, cb: Rc<Callback>, key: Option<Rc<str>>) -> El {
el.on_middle_press(move |s: &mut S, tx: &mut rune::Tx| {
if let Some(script) = cb.script.upgrade() {
let mods = tx.mods();
let event = Event { kind: "middle-press", ..Event::press(key.as_deref(), mods.shift, mods.alt, mods.cmd) };
script.around_write(s, Some(tx), |tx| script.handle(&cb, event, tx));
}
})
}
fn hover<S: 'static>(el: El, cb: Rc<Callback>, key: Option<Rc<str>>) -> El {
el.on_hover_change(move |s: &mut S, on: bool, tx: &mut rune::Tx| {
if let Some(script) = cb.script.upgrade() {
let event = Event { kind: "hover", key: key.as_deref(), mods: None, rows: None, entered: Some(on), fields: Rc::new([]) };
script.around_write(s, Some(tx), |tx| script.handle(&cb, event, tx));
}
})
}
/// A `UiEvent`: what a handler receives.
pub(crate) struct Event<'a> {
pub(crate) kind: &'static str,
pub(crate) key: Option<&'a str>,
pub(crate) mods: Option<(bool, bool, bool)>,
pub(crate) rows: Option<(usize, usize)>,
pub(crate) entered: Option<bool>,
pub(crate) fields: Fields,
}
impl<'a> Event<'a> {
pub(crate) fn press(key: Option<&'a str>, shift: bool, alt: bool, cmd: bool) -> Self {
Event { kind: "press", key, mods: Some((shift, alt, cmd)), rows: None, entered: None, fields: Rc::new([]) }
}
pub(crate) fn to_table(&self, lua: &mlua::Lua) -> mlua::Result<mlua::Table> {
let t = lua.create_table_with_capacity(0, 6 + self.fields.len())?;
t.raw_set("kind", self.kind)?;
if let Some(key) = self.key {
t.raw_set("key", key)?;
}
if let Some((shift, alt, cmd)) = self.mods {
t.raw_set("shift", shift)?;
t.raw_set("alt", alt)?;
t.raw_set("mod", cmd)?;
}
if let Some((first, last)) = self.rows {
t.raw_set("first", first)?;
t.raw_set("last", last)?;
}
if let Some(entered) = self.entered {
t.raw_set("entered", entered)?;
}
for (name, value) in self.fields.iter() {
t.raw_set(*name, value.clone())?;
}
Ok(t)
}
}
fn reload<S: 'static>(el: El, script: Weak<Inner>) -> El {
el.on_press_tx(move |s: &mut S, tx| {
if let Some(script) = script.upgrade() {
script.around_write(s, Some(tx), |tx| {
if let Some(tx) = tx {
script.reload_from_card(tx);
}
});
}
})
}
/// One render's built nodes, by handle.
pub(crate) struct Arena {
slots: Vec<Option<El>>,
generation: u32,
}
/// One render in progress: its arena and what it builds with.
pub(crate) struct Frame {
pub(crate) arena: Arena,
pub(crate) attach: &'static Attach,
pub(crate) env: Rc<Env>,
}
thread_local! {
static FRAMES: RefCell<Vec<Frame>> = const { RefCell::new(Vec::new()) };
static GENERATION: Cell<u32> = const { Cell::new(0) };
static POOL: RefCell<Vec<Vec<Option<El>>>> = const { RefCell::new(Vec::new()) };
static RENDERS: Cell<u64> = const { Cell::new(0) };
}
/// A number no earlier render on this thread had, for [`Env::render`].
pub(crate) fn next_render() -> u64 {
let n = RENDERS.get().wrapping_add(1);
RENDERS.set(n);
n
}
/// Handles are `generation << 20 | slot + 1`: a handle kept from an earlier render is refused,
/// not taken for whatever sits in its slot now. 32 bits, so they fit wasm32 pointers.
const SLOT_BITS: u32 = 20;
const SLOT_MASK: usize = (1 << SLOT_BITS) - 1;
/// Runs `f` with a fresh frame on top of this thread's stack.
pub(crate) fn with_frame<R>(attach: &'static Attach, env: Rc<Env>, f: impl FnOnce() -> R) -> R {
struct Pop;
impl Drop for Pop {
fn drop(&mut self) {
if let Some(frame) = FRAMES.with_borrow_mut(Vec::pop) {
let mut slots = frame.arena.slots;
slots.clear();
POOL.with_borrow_mut(|p| p.push(slots));
}
}
}
let generation = GENERATION.get().wrapping_add(1) & 0xfff;
GENERATION.set(generation);
let slots = POOL.with_borrow_mut(Vec::pop).unwrap_or_default();
FRAMES.with_borrow_mut(|f| f.push(Frame { arena: Arena { slots, generation }, attach, env }));
let _pop = Pop;
f()
}
/// Runs `f` on the innermost frame, or returns `None` outside a render.
pub(crate) fn top<R>(f: impl FnOnce(&mut Frame) -> R) -> Option<R> {
FRAMES.with_borrow_mut(|frames| frames.last_mut().map(f))
}
impl Frame {
pub(crate) fn put(&mut self, el: El) -> Result<*mut c_void, String> {
self.arena.put(el)
}
pub(crate) fn take(&mut self, handle: *mut c_void) -> Result<El, String> {
self.arena.take(handle)
}
}
impl Arena {
/// Stores `el` and returns its handle.
pub(crate) fn put(&mut self, el: El) -> Result<*mut c_void, String> {
let slot = self.alloc(el)?;
Ok(self.handle(slot))
}
/// Stores `el` and returns its slot, where props decode onto it in place.
pub(crate) fn alloc(&mut self, el: El) -> Result<usize, String> {
let slot = self.slots.len();
if slot >= SLOT_MASK {
return Err("more than a million nodes in one render".into());
}
self.slots.push(Some(el));
Ok(slot)
}
/// The handle a script holds for `slot`.
pub(crate) fn handle(&self, slot: usize) -> *mut c_void {
(((self.generation as usize) << SLOT_BITS) | (slot + 1)) as *mut c_void
}
/// The element `alloc` stored in `slot`.
pub(crate) fn get_mut(&mut self, slot: usize) -> &mut El {
self.slots[slot].as_mut().expect("a node keeps its slot until its handle is placed")
}
/// The element in `slot`, and the slots before it, where its children wait: a script
/// builds a node's children before the node.
pub(crate) fn split(&mut self, slot: usize) -> (Slots<'_>, &mut El) {
let (before, rest) = self.slots.split_at_mut(slot);
let el = rest[0].as_mut().expect("a node keeps its slot until its handle is placed");
(Slots { slots: before, generation: self.generation }, el)
}
/// Every slot, for children a host node takes.
pub(crate) fn all(&mut self) -> Slots<'_> {
Slots { slots: &mut self.slots, generation: self.generation }
}
/// Takes the element behind `handle`; each handle gives its element once.
pub(crate) fn take(&mut self, handle: *mut c_void) -> Result<El, String> {
self.all().slot(handle)?.take().ok_or_else(|| "a node can only be placed once".to_owned())
}
}
/// Arena slots that handles reach.
pub(crate) struct Slots<'a> {
slots: &'a mut [Option<El>],
generation: u32,
}
impl Slots<'_> {
/// The slot behind `handle`.
pub(crate) fn slot(&mut self, handle: *mut c_void) -> Result<&mut Option<El>, String> {
let raw = handle as usize;
let slot = (raw & SLOT_MASK).wrapping_sub(1);
if (raw >> SLOT_BITS) as u32 != self.generation {
return Err("a node from an earlier render can't be reused; build it again or use view:Memo".into());
}
self.slots.get_mut(slot).ok_or_else(|| "not a ui node".to_owned())
}
}
impl Env {
pub(crate) fn resolve(&self, name: &str) -> Result<Color, String> {
if let Some(c) = self.cached(name) {
self.note(name, c);
return Ok(c);
}
let c = if name.starts_with('#') {
rune::color::hex(name).ok_or_else(|| format!("{name} is not a #rrggbb or #rrggbbaa colour"))?
} else if let Some(c) = (self.palette)(name, self.dark) {
c
} else {
self.warn_once(format!("unknown colour {name}"));
Color::TRANSPARENT
};
self.colors.borrow_mut().push((name.into(), c));
self.note(name, c);
Ok(c)
}
fn note(&self, name: &str, c: Color) {
if let Some(r) = self.recording.borrow_mut().as_mut() {
r.push((name.into(), c));
}
}
fn cached(&self, name: &str) -> Option<Color> {
self.colors.borrow().iter().find(|(n, _)| &**n == name).map(|(_, c)| *c)
}
pub(crate) fn color(&self, name: &str) -> Option<Color> {
if let Some(c) = self.cached(name) {
self.note(name, c);
return Some(c);
}
let c = (self.palette)(name, self.dark)?;
self.colors.borrow_mut().push((name.into(), c));
self.note(name, c);
Some(c)
}
pub(crate) fn text_color(&self) -> Color {
self.color("text").unwrap_or(if self.dark { Color::WHITE } else { Color::BLACK })
}
/// Logs `message` once per script.
pub(crate) fn warn_once(&self, message: String) {
if self.warned.borrow_mut().insert(message.clone())
&& let Some(script) = self.script.upgrade()
{
script.log(crate::LogLevel::Warn, &message);
}
}
/// A registry reference to the function at stack slot `idx`.
#[allow(unsafe_code)]
pub(crate) unsafe fn reference(&self, state: *mut ffi::lua_State, idx: c_int) -> Rc<Callback> {
// SAFETY: the caller checked slot `idx` holds a function.
let r = unsafe { ffi::lua_ref(state, idx) };
Rc::new(Callback {
func: LuaRef { r, garbage: self.garbage.clone() },
vm: self.vm,
script: self.script.clone(),
})
}
}
/// Runs a C function body: its error becomes a Lua error once every Rust value it held is
/// dropped, and a Rust panic becomes an error too, where the target can catch one.
#[allow(unsafe_code)]
pub(crate) unsafe fn guard(state: *mut ffi::lua_State, body: impl FnOnce() -> Result<c_int, String>) -> c_int {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(body));
let message = match result {
Ok(Ok(n)) => return n,
Ok(Err(message)) => message,
Err(_) => "the host panicked while building this node".to_owned(),
};
// SAFETY: the message string is moved onto the Lua stack before raising.
unsafe {
ffi::lua_pushlstring(state, message.as_ptr().cast(), message.len());
drop(message);
ffi::lua_error(state)
}
}
+396
View File
@@ -0,0 +1,396 @@
//! The `ui.*` constructors, and host nodes an app adds to them.
#![allow(unsafe_code)]
use std::os::raw::c_int;
use std::rc::Rc;
use mlua::ffi;
use rune::{El, col, el, row, spacer, text};
use super::props::{self, Atom, Props, Value};
use super::{Callback, Env, Frame, Reuse, Slots, guard, top};
/// The built-in constructors, as `(name, C function)`.
pub(crate) const BUILTINS: &[(&str, ffi::lua_CFunction)] = &[
("row", ui_row),
("col", ui_col),
("box", ui_box),
("text", ui_text),
("spacer", ui_spacer),
("virtualList", super::rows::ui_virtual_list),
("each", super::view::ui_each),
("hex", ui_hex),
];
/// `ui.hex("#RRGGBB")` or `ui.hex("#RRGGBBAA")`: a literal colour. It checks the string and
/// returns it; colour props read `#` strings as hex.
unsafe extern "C-unwind" fn ui_hex(state: *mut ffi::lua_State) -> c_int {
// SAFETY: reads argument 1 and returns it.
unsafe {
let ok = matches!(props::read(state, 1), Value::Str(s) if s.starts_with('#') && matches!(s.len(), 7 | 9) && rune::color::hex(s).is_some());
if !ok {
return guard(state, || Err("ui.hex needs \"#RRGGBB\" or \"#RRGGBBAA\"".into()));
}
ffi::lua_pushvalue(state, 1);
1
}
}
unsafe extern "C-unwind" fn ui_row(state: *mut ffi::lua_State) -> c_int {
// SAFETY: Luau calls this as a C function with its arguments on `state`'s stack.
unsafe { container(state, row, 0) }
}
unsafe extern "C-unwind" fn ui_col(state: *mut ffi::lua_State) -> c_int {
// SAFETY: Luau calls this as a C function with its arguments on `state`'s stack.
unsafe { container(state, col, 1) }
}
unsafe extern "C-unwind" fn ui_box(state: *mut ffi::lua_State) -> c_int {
// SAFETY: Luau calls this as a C function with its arguments on `state`'s stack.
unsafe { container(state, el, 2) }
}
unsafe extern "C-unwind" fn ui_spacer(state: *mut ffi::lua_State) -> c_int {
// SAFETY: Luau calls this as a C function with its arguments on `state`'s stack.
unsafe { container(state, spacer, 3) }
}
/// What a node starts from: a box (and which kind, for its template) or a text.
enum Base {
Box(fn() -> El, u8),
Text(String),
}
/// Where a node's props tables sit on the stack, 0 for none: its style, decoded once when
/// frozen, and its own props laid over it.
#[derive(Clone, Copy)]
struct Layers {
style: c_int,
props: c_int,
}
impl Layers {
const NONE: Layers = Layers { style: 0, props: 0 };
fn one(at: c_int) -> Layers {
Layers { style: at, props: 0 }
}
}
/// `ui.row(props?, children?)`, `ui.row(style, props?, children?)`, or `ui.row(children)`.
unsafe fn container(state: *mut ffi::lua_State, base: fn() -> El, kind: u8) -> c_int {
// SAFETY: every call below reads or pushes on this C function's own stack.
unsafe {
let (layers, children) = match (ffi::lua_type(state, 1), ffi::lua_type(state, 2), ffi::lua_type(state, 3)) {
(ffi::LUA_TTABLE, ffi::LUA_TTABLE, ffi::LUA_TTABLE) => (Layers { style: 1, props: 2 }, 3),
(ffi::LUA_TTABLE, ffi::LUA_TNIL, ffi::LUA_TTABLE) => (Layers::one(1), 3),
(ffi::LUA_TTABLE, ffi::LUA_TTABLE, _) if keyed(state, 2) => (Layers { style: 1, props: 2 }, 0),
(ffi::LUA_TTABLE, ffi::LUA_TTABLE, _) => (Layers::one(1), 2),
(ffi::LUA_TTABLE, _, _) if keyed(state, 1) => (Layers::one(1), 0),
(ffi::LUA_TTABLE, _, _) => (Layers::NONE, 1),
(ffi::LUA_TNIL | ffi::LUA_TNONE, ffi::LUA_TTABLE, _) => (Layers::NONE, 2),
_ => (Layers::NONE, 0),
};
guard(state, || build(state, Base::Box(base, kind), layers, children))
}
}
/// `ui.text(content, props?)` or `ui.text(content, style, props?)`, and values after them (or
/// straight after `content`), which `{1}`, `{2}`... in `content` stand for.
unsafe extern "C-unwind" fn ui_text(state: *mut ffi::lua_State) -> c_int {
// SAFETY: as for `container`.
unsafe {
let (layers, values) = match (ffi::lua_type(state, 2), ffi::lua_type(state, 3)) {
(ffi::LUA_TTABLE, ffi::LUA_TTABLE) => (Layers { style: 2, props: 3 }, 4),
(ffi::LUA_TTABLE, ffi::LUA_TNIL) => (Layers::one(2), 4),
(ffi::LUA_TTABLE, _) => (Layers::one(2), 3),
(ffi::LUA_TNIL, ffi::LUA_TTABLE) => (Layers::one(3), 4),
(ffi::LUA_TNIL, _) => (Layers::NONE, 3),
_ => (Layers::NONE, 2),
};
let content = match words(state, values) {
Ok(content) => content,
Err(message) => return guard(state, || Err(message)),
};
guard(state, move || build(state, Base::Text(content), layers, 0))
}
}
/// A text's words: argument 1, with `{n}` filled from the `n`th value from stack slot
/// `values` on, straight into the string the element keeps.
unsafe fn words(state: *mut ffi::lua_State, values: c_int) -> Result<String, String> {
// SAFETY: reads this C function's own arguments.
let (content, last) = unsafe { (props::read(state, 1), ffi::lua_gettop(state)) };
let template = match content {
Value::Str(s) => s,
Value::Num(n) => return Ok(props::format_num(n)),
other => return Err(format!("ui.text needs a string, got {}", props::name(other))),
};
if last < values {
return Ok(template.to_owned());
}
let mut out = String::with_capacity(template.len() + 8 * (last - values + 1) as usize);
let mut rest = template;
while let Some(open) = rest.find('{') {
out.push_str(&rest[..open]);
let after = &rest[open + 1..];
let digits = after.bytes().take_while(u8::is_ascii_digit).count();
if digits == 0 || after.as_bytes().get(digits) != Some(&b'}') {
out.push('{');
rest = after;
continue;
}
let n: c_int = after[..digits].parse().unwrap_or(0);
let at = values + n - 1;
if n < 1 || at > last {
return Err(format!("ui.text: {{{n}}} has no value"));
}
// SAFETY: `at` is one of this C function's arguments.
match unsafe { props::read(state, at) } {
Value::Str(s) => out.push_str(s),
Value::Num(n) => props::push_num(&mut out, n),
other => return Err(format!("ui.text: {{{n}}} must be a string or a number, got {}", props::name(other))),
}
rest = &after[digits + 1..];
}
out.push_str(rest);
Ok(out)
}
/// Whether the table at `idx` is keyed by names, as props are, rather than a list: its first
/// key is a string. A list's entries come first, even with `nil` before them.
pub(crate) unsafe fn keyed(state: *mut ffi::lua_State, idx: c_int) -> bool {
// SAFETY: `idx` is a table on this stack; the first pair is popped.
unsafe {
if ffi::lua_objlen(state, idx) > 0 || ffi::lua_rawiter(state, idx, 0) < 0 {
return false;
}
let named = ffi::lua_type(state, -2) == ffi::LUA_TSTRING;
ffi::lua_settop(state, -3);
named
}
}
/// Builds a node from its props tables and the children array at `children` (0 for none) and
/// pushes its handle. The element is made in its arena slot first; each prop then sets it there
/// as it is read, and its children move from their slots straight into its list, so it is never
/// copied whole. A frozen style is decoded once per VM: after that the node starts from a copy,
/// and only the props laid over it are read.
unsafe fn build(state: *mut ffi::lua_State, base: Base, layers: Layers, children: c_int) -> Result<c_int, String> {
top(|frame| {
let is_text = matches!(base, Base::Text(_));
let kind = match base {
Base::Box(_, kind) => kind,
Base::Text(_) => u8::MAX,
};
let Frame { arena, attach, env } = frame;
// SAFETY: `layers.style` is 0 or a table on this stack.
let template = (layers.style > 0 && unsafe { ffi::lua_getreadonly(state, layers.style) } != 0)
// SAFETY: as above.
.then(|| (unsafe { ffi::lua_topointer(state, layers.style) } as usize, kind));
let reused = template.and_then(|key| env.templates.borrow().get(key, env, layers.props > 0));
// The node's props still to apply once its children are in: none for a whole template.
let (slot, pending) = match reused {
Some(Reuse::Whole(mut el)) => {
if let Base::Text(s) = base {
el.set_content(s);
}
(arena.alloc(el)?, None)
}
Some(Reuse::Under(mut el, mut p)) => {
if let Base::Text(s) = base {
el.set_content(s);
}
let slot = arena.alloc(el)?;
// SAFETY: `layers.props` is a table on `state`'s stack and decoding does not re-enter Luau.
let press = unsafe { decode_props(state, layers.props, env, is_text, &mut p, arena.get_mut(slot)) }?;
(slot, Some((p, press)))
}
None => {
let slot = arena.alloc(match base {
Base::Box(f, _) => f(),
// A plugin's words read the way they're written (dir="auto"), an English
// label in an Arabic window included, unless the node sets `dir`.
Base::Text(s) => text(s).dir(rune::Direction::Auto),
})?;
let mut p = Props::new(env);
if template.is_some() {
*env.recording.borrow_mut() = Some(Vec::new());
}
// SAFETY: `layers.style` is 0 or a table on `state`'s stack and decoding does not re-enter Luau.
let decoded = unsafe { decode_props(state, layers.style, env, is_text, &mut p, arena.get_mut(slot)) };
let colors = env.recording.take();
let mut press = decoded?;
// The template is the node without children, words or handlers, finished and not.
if let (Some(key), Some(colors), None, None, false) = (template, colors, &press, p.on_hover.as_ref().or(p.on_middle_press.as_ref()), p.uncacheable) {
let mut under = arena.get_mut(slot).clone();
if is_text {
under.set_content(String::new());
}
let mut el = under.clone();
p.clone().finish(&mut el, env, is_text, None, *attach);
// SAFETY: `layers.style` is the frozen table's slot.
unsafe { env.templates.borrow_mut().put(state, layers.style, key, env, el, under, p.clone(), colors) };
}
// SAFETY: `layers.props` is 0 or a table on `state`'s stack and decoding does not re-enter Luau.
if let Some(own) = unsafe { decode_props(state, layers.props, env, is_text, &mut p, arena.get_mut(slot)) }? {
press = Some(own);
}
(slot, Some((p, press)))
}
};
if children > 0 {
let (slots, el) = arena.split(slot);
let mut failed = None;
// SAFETY: `children` is a table on this stack.
el.extend_children(unsafe { Children::new(state, children, slots, env, &mut failed) });
if let Some(message) = failed {
return Err(message);
}
}
if let Some((p, press)) = pending {
p.finish(arena.get_mut(slot), env, is_text, press, *attach);
}
// SAFETY: pushes the handle as this C function's result.
unsafe { ffi::lua_pushlightuserdata(state, arena.handle(slot)) };
Ok(1)
})
.unwrap_or_else(|| Err("ui nodes can only be built while rendering".into()))
}
/// Decodes the props table at `props` (0 for none) onto `el`, and returns the `onPress`
/// function in it.
unsafe fn decode_props(state: *mut ffi::lua_State, props: c_int, env: &Env, is_text: bool, p: &mut Props, el: &mut El) -> Result<Option<Rc<Callback>>, String> {
let mut press = None;
if props > 0 {
// SAFETY: walks the table at `props` with `lua_rawiter`, popping each pair.
unsafe {
let mut iter = 0;
while {
iter = ffi::lua_rawiter(state, props, iter);
iter >= 0
} {
let v = props::read(state, -1);
match props::key_atom(state, -2) {
Ok(Atom::OnPress) => match v {
Value::Func => press = Some(env.reference(state, -1)),
Value::Nil => {}
other => return Err(format!("onPress must be a function, got {}", props::name(other))),
},
Ok(Atom::OnHover) => match v {
Value::Func => p.on_hover = Some(env.reference(state, -1)),
Value::Nil => {}
other => return Err(format!("onHover must be a function, got {}", props::name(other))),
},
Ok(Atom::OnMiddlePress) => match v {
Value::Func => p.on_middle_press = Some(env.reference(state, -1)),
Value::Nil => {}
other => return Err(format!("onMiddlePress must be a function, got {}", props::name(other))),
},
Ok(atom) => p.decode_at(el, state, atom, -1, env, is_text)?,
Err(name) => super::unknown_prop(env, None, name)?,
}
ffi::lua_settop(state, -3);
}
}
}
Ok(press)
}
/// Takes the elements of the children array at `idx`. Strings become text; `nil` and `false`
/// entries are skipped, so `cond and ui.text(...)` works.
pub(crate) unsafe fn take_children(state: *mut ffi::lua_State, idx: c_int, frame: &mut Frame) -> Result<Vec<El>, String> {
let mut failed = None;
let Frame { arena, env, .. } = frame;
// SAFETY: as `Children` documents.
let out: Vec<El> = unsafe { Children::new(state, idx, arena.all(), env, &mut failed) }.collect();
failed.map_or(Ok(out), Err)
}
/// The children in the array at stack slot `idx`, taken from their arena slots as they are
/// read. The first bad entry ends the walk and lands in `failed`.
pub(crate) struct Children<'a> {
state: *mut ffi::lua_State,
idx: c_int,
next: usize,
len: usize,
slots: Slots<'a>,
env: &'a Env,
failed: &'a mut Option<String>,
}
impl<'a> Children<'a> {
/// SAFETY: `idx` is a table on `state`'s stack, which the walk leaves as it found it.
unsafe fn new(state: *mut ffi::lua_State, idx: c_int, slots: Slots<'a>, env: &'a Env, failed: &'a mut Option<String>) -> Self {
// SAFETY: as this function's contract says.
let len = unsafe { ffi::lua_objlen(state, idx) };
Children { state, idx, next: 1, len, slots, env, failed }
}
}
impl Iterator for Children<'_> {
type Item = El;
fn next(&mut self) -> Option<El> {
while self.next <= self.len && self.failed.is_none() {
let i = self.next;
self.next += 1;
let state = self.state;
// SAFETY: reads one array slot, then pops it below.
let kind = unsafe { ffi::lua_rawgeti(state, self.idx, i as ffi::lua_Integer) };
let child = match kind {
ffi::LUA_TLIGHTUSERDATA => {
// SAFETY: the slot holds a light userdata.
let handle = unsafe { ffi::lua_tolightuserdata(state, -1) };
match self.slots.slot(handle) {
// Moved straight out of its slot into the parent's list.
Ok(slot) if slot.is_some() => slot.take(),
Ok(_) => {
*self.failed = Some("a node can only be placed once".into());
None
}
Err(message) => {
*self.failed = Some(message);
None
}
}
}
ffi::LUA_TSTRING | ffi::LUA_TNUMBER => {
// SAFETY: reads the slot pushed above.
let s = match unsafe { props::read(state, -1) } {
Value::Str(s) => s.to_owned(),
Value::Num(n) => props::format_num(n),
_ => String::new(),
};
let mut t = text(s);
t.set_color(self.env.text_color());
Some(t)
}
ffi::LUA_TNIL => None,
// SAFETY: reads the slot pushed above.
ffi::LUA_TBOOLEAN if unsafe { ffi::lua_toboolean(state, -1) } == 0 => None,
_ => {
// SAFETY: reads the slot pushed above.
let what = props::name(unsafe { props::read(state, -1) });
*self.failed = Some(format!("child {i} is a {what}, not a ui node"));
None
}
};
// SAFETY: pops the slot pushed above.
unsafe { ffi::lua_settop(state, -2) };
if child.is_some() {
return child;
}
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
// Holes (`nil`, `false`) are rare; counting every slot reserves the list once.
let left = self.len + 1 - self.next;
(left, Some(left))
}
}
+724
View File
@@ -0,0 +1,724 @@
//! `ui.*` props: names Luau interns as atoms, read straight off the stack and applied to an `El`.
//! A prop table is walked with `lua_rawiter`; each key's atom (a small integer Luau stores in the
//! string when it is interned) picks the setter, so a prop costs a switch, not a string compare.
//!
//! The names are layout (`w`, `pad`, `gap`, `align`), box (`fill`, `border`, `radius`,
//! `onPress`), text (`size`, `weight`, `color`) and list props (`count`, `renderRow`); colours are
//! palette names or `ui.hex(...)`.
#![allow(unsafe_code)]
use std::ffi::CStr;
use std::os::raw::{c_char, c_int};
use std::rc::Rc;
use mlua::ffi;
use rune::{Align, Color, El, ScrollSpec, TextStyle};
use super::{Attach, Callback, Env};
macro_rules! atoms {
($($atom:ident = $name:literal,)*) => {
/// Prop names, by atom.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i16)]
pub(crate) enum Atom { $($atom,)* }
const NAMES: &[(&str, Atom)] = &[$(($name, Atom::$atom),)*];
fn by_name(bytes: &[u8]) -> Option<Atom> {
match bytes {
$(b if b == $name.as_bytes() => Some(Atom::$atom),)*
_ => None,
}
}
};
}
atoms! {
Key = "key",
W = "w",
H = "h",
MinW = "minW",
MinH = "minH",
MaxW = "maxW",
MaxH = "maxH",
Grow = "grow",
Shrink = "shrink",
Pad = "pad",
Px = "px",
Py = "py",
Pt = "pt",
Pr = "pr",
Pb = "pb",
Pl = "pl",
M = "m",
Mx = "mx",
My = "my",
Mt = "mt",
Mr = "mr",
Mb = "mb",
Ml = "ml",
Opacity = "opacity",
Role = "role",
Label = "label",
Help = "help",
Gap = "gap",
Align = "align",
Justify = "justify",
Center = "center",
Wrap = "wrap",
Fill = "fill",
Hover = "hover",
Press = "press",
Border = "border",
BorderWidth = "borderWidth",
Radius = "radius",
Clip = "clip",
ScrollY = "scrollY",
ScrollX = "scrollX",
StickBottom = "stickBottom",
OnPress = "onPress",
MenuTrigger = "menuTrigger",
Color = "color",
Size = "size",
Weight = "weight",
LineHeight = "lineHeight",
Tracking = "tracking",
Mono = "mono",
Tabular = "tabular",
NoWrap = "noWrap",
Truncate = "truncate",
Selectable = "selectable",
TextAlign = "textAlign",
Count = "count",
EstimatedRowHeight = "estimatedRowHeight",
Version = "version",
RenderRow = "renderRow",
RowKey = "rowKey",
RowVersions = "rowVersions",
OnVisibleRows = "onVisibleRows",
OnHover = "onHover",
OnMiddlePress = "onMiddlePress",
HoverTransition = "hoverTransition",
HoverGroup = "hoverGroup",
HoverGroupColor = "hoverGroupColor",
RevealOnHover = "revealOnHover",
Corners = "corners",
Pin = "pin",
Shadow = "shadow",
Selected = "selected",
Focusable = "focusable",
Disabled = "disabled",
HelpSide = "helpSide",
HelpOpen = "helpOpen",
FadeOut = "fadeOut",
Dir = "dir",
}
/// Every prop name the built-in nodes read.
pub fn prop_names() -> impl Iterator<Item = &'static str> {
NAMES.iter().map(|(n, _)| *n)
}
fn by_id(id: c_int) -> Option<Atom> {
usize::try_from(id).ok().and_then(|i| NAMES.get(i)).map(|(_, a)| *a)
}
/// Luau's `useratom` callback: gives each prop name its atom when the string is first interned.
pub(crate) unsafe extern "C-unwind" fn useratom(_: *mut ffi::lua_State, s: *const c_char, len: usize) -> i16 {
if len > 18 {
return -1;
}
// SAFETY: Luau passes the new string's bytes and length.
let bytes = unsafe { std::slice::from_raw_parts(s.cast::<u8>(), len) };
by_name(bytes).map_or(-1, |a| a as i16)
}
/// A prop value on the stack. Strings borrow the Lua string, which the table keeps alive.
#[derive(Clone, Copy)]
pub(crate) enum Value<'a> {
Nil,
Bool(bool),
Num(f64),
Str(&'a str),
Func,
Other(&'static str),
}
/// Reads stack slot `idx`.
pub(crate) unsafe fn read<'a>(state: *mut ffi::lua_State, idx: c_int) -> Value<'a> {
// SAFETY: the caller passes a valid slot; strings stay alive while their table is on the stack.
unsafe {
match ffi::lua_type(state, idx) {
ffi::LUA_TNIL => Value::Nil,
ffi::LUA_TBOOLEAN => Value::Bool(ffi::lua_toboolean(state, idx) != 0),
ffi::LUA_TNUMBER => Value::Num(ffi::lua_tonumberx(state, idx, std::ptr::null_mut())),
ffi::LUA_TSTRING => {
let mut len = 0;
let p = ffi::lua_tolstring(state, idx, &mut len);
Value::Str(std::str::from_utf8(std::slice::from_raw_parts(p.cast::<u8>(), len)).unwrap_or(""))
}
ffi::LUA_TFUNCTION => Value::Func,
t => Value::Other(CStr::from_ptr(ffi::lua_typename(state, t)).to_str().unwrap_or("value")),
}
}
}
/// The key at stack slot `idx` as an atom, or its text when it isn't a prop name.
pub(crate) unsafe fn key_atom<'a>(state: *mut ffi::lua_State, idx: c_int) -> Result<Atom, &'a str> {
// SAFETY: the caller passes a valid slot.
unsafe {
if ffi::lua_type(state, idx) != ffi::LUA_TSTRING {
return Err("(non-string key)");
}
let mut atom: c_int = -1;
let p = ffi::lua_tostringatom(state, idx, &mut atom);
if let Some(a) = by_id(atom) {
return Ok(a);
}
let bytes = CStr::from_ptr(p).to_bytes();
by_name(bytes).ok_or(std::str::from_utf8(bytes).unwrap_or("?"))
}
}
/// A size prop: points, or the parent's whole side.
#[derive(Clone, Copy)]
pub(crate) enum Size {
Points(f32),
Full,
}
/// Padding sides a prop set on its own (`pt`, `px`, ...), which `pad` leaves alone.
const TOP: u8 = 1;
const RIGHT: u8 = 2;
const BOTTOM: u8 = 4;
const LEFT: u8 = 8;
/// A node's props, read straight onto its element in the arena: most set it as they're read.
/// The rest wait here for the whole table, so the result doesn't depend on the order Luau walks
/// it: the press handler needs the key, `pad` yields to the sides set beside it, a text node's
/// style and colour land together, and `center`, `corners`, `selected` and `disabled` overrule
/// the props they overlap.
#[derive(Clone)]
pub(crate) struct Props {
pub(crate) key: Option<String>,
pub(crate) on_hover: Option<Rc<Callback>>,
pub(crate) on_middle_press: Option<Rc<Callback>>,
pad: Option<f32>,
sides: u8,
role: Option<&'static str>,
center: bool,
corners: Option<[f32; 4]>,
selected: bool,
pub(crate) disabled: bool,
/// `menuTrigger`: the `onPress` opens a menu, so a mouse runs it as its button goes down.
menu_trigger: bool,
text: TextStyle,
color: Option<Color>,
truncate: bool,
fade_out: bool,
single_line: bool,
wrap: bool,
selectable: bool,
text_align: Option<Align>,
border: (Option<f32>, Option<Color>),
pub(crate) scroll: Option<(bool, bool)>,
stick_bottom: bool,
/// A prop whose effect depends on more than its value and the colours (`shadow`): the node
/// can't be a template.
pub(crate) uncacheable: bool,
}
impl Props {
/// A node's props before any are read: text starts from the host's text style.
pub(crate) fn new(env: &Env) -> Self {
Props {
key: None,
on_hover: None,
on_middle_press: None,
pad: None,
sides: 0,
role: None,
center: false,
corners: None,
selected: false,
disabled: false,
menu_trigger: false,
text: env.text,
color: None,
truncate: false,
fade_out: false,
single_line: false,
wrap: false,
selectable: false,
text_align: None,
border: (None, None),
scroll: None,
stick_bottom: false,
uncacheable: false,
}
}
/// Applies what waited for the whole table: the press, middle-click and hover handlers (`press`
/// is the node's `onPress`), then the props that depend on others, the text style and the key.
pub(crate) fn finish(self, e: &mut El, env: &Env, is_text: bool, press: Option<Rc<Callback>>, attach: &'static Attach) {
let press = press.filter(|_| !self.disabled);
let middle = self.on_middle_press.filter(|_| !self.disabled);
let key: Option<Rc<str>> = (press.is_some() || middle.is_some() || self.on_hover.is_some()).then(|| self.key.as_deref().map(Into::into)).flatten();
if let Some(cb) = press {
(attach.press)(e, cb, key.clone(), Rc::new([]));
// Kobalte's `Menu.Trigger` opens on a mouse's `pointerdown`; keys and taps on the click.
if self.menu_trigger {
with(e, El::press_on_down);
}
}
if let Some(cb) = middle {
with(e, |e| (attach.middle)(e, cb, key.clone()));
}
if let Some(cb) = self.on_hover {
with(e, |e| (attach.hover)(e, cb, key));
}
match (self.pad, self.sides) {
(Some(p), 0) => _ = e.set_padding(p),
(Some(p), s) => {
if s & TOP == 0 {
e.set_pt(p);
}
if s & RIGHT == 0 {
e.set_pr(p);
}
if s & BOTTOM == 0 {
e.set_pb(p);
}
if s & LEFT == 0 {
e.set_pl(p);
}
}
(None, _) => {}
}
if let Some(r) = self.role {
e.set_role(r);
}
if self.center {
e.set_center();
}
if let Some(r) = self.corners {
with(e, |e| e.corners(r));
}
if self.selected {
if let Some(c) = env.color("selected") {
e.set_fill(c);
}
with(e, |e| e.focus_selected(true));
}
if self.disabled {
with(e, |e| e.disabled(true));
}
if is_text {
e.set_font(self.text).set_color(self.color.unwrap_or_else(|| env.text_color()));
if self.truncate {
e.set_truncate();
}
if self.fade_out {
with(e, El::truncate_fade);
}
if self.single_line {
with(e, El::single_line);
}
if self.wrap {
e.set_wrap();
}
if self.selectable {
e.set_selectable(true);
}
if let Some(a) = self.text_align {
e.set_align(a);
}
} else if let Some(c) = self.color {
e.set_color(c);
}
if self.border != (None, None) {
let c = self.border.1.unwrap_or_else(|| env.color("separator").unwrap_or(Color::TRANSPARENT));
e.set_border(self.border.0.unwrap_or(1.0), c);
}
match self.scroll {
Some((true, true)) => e.set_scroll_xy(),
Some((true, false)) => e.set_scroll_x(),
Some((false, _)) => e.set_scroll(ScrollSpec { stick_bottom: self.stick_bottom }),
None => e,
};
if let Some(k) = self.key {
e.set_key(k);
}
}
/// Decodes one prop onto `e`, or keeps it for `finish`, or says what was wrong with its
/// value.
pub(crate) fn decode(&mut self, e: &mut El, atom: Atom, v: Value<'_>, env: &Env, is_text: bool) -> Result<(), String> {
let name = NAMES[atom as usize].0;
let num = |v: Value<'_>| match v {
Value::Num(n) => Ok(n as f32),
other => Err(format!("{name} must be a number, got {}", self::name(other))),
};
let flag = |v: Value<'_>| match v {
Value::Bool(b) => Ok(b),
Value::Nil => Ok(false),
other => Err(format!("{name} must be a boolean, got {}", self::name(other))),
};
let color = |v: Value<'_>| match v {
Value::Str(s) => env.resolve(s),
other => Err(format!("{name} must be a color token or ui.hex(...), got {}", self::name(other))),
};
let string = |v| as_str(atom, v);
let size = |v: Value<'_>| match v {
Value::Num(n) => Ok(Size::Points(n as f32)),
Value::Str("full") => Ok(Size::Full),
other => Err(format!("{name} must be a number or \"full\", got {}", self::name(other))),
};
match atom {
Atom::Key => {
self.key = Some(match v {
Value::Num(n) => format_num(n),
v => string(v)?.to_owned(),
})
}
Atom::W => {
match size(v)? {
Size::Points(n) => e.set_w(n),
Size::Full => e.set_w_full(),
};
}
Atom::H => {
match size(v)? {
Size::Points(n) => e.set_h(n),
Size::Full => e.set_h_full(),
};
}
Atom::MinW => _ = e.set_min_w(num(v)?),
Atom::MaxW => _ = e.set_max_w(num(v)?),
Atom::MinH => _ = e.set_min_h(num(v)?),
Atom::MaxH => _ = e.set_max_h(num(v)?),
Atom::Grow => _ = e.set_grow(num(v)?),
Atom::Shrink => {
if flag(v)? {
e.set_shrink();
}
}
Atom::Pad => self.pad = Some(num(v)?),
Atom::Px => {
let n = num(v)?;
e.set_pl(n).set_pr(n);
self.sides |= LEFT | RIGHT;
}
Atom::Py => {
let n = num(v)?;
e.set_pt(n).set_pb(n);
self.sides |= TOP | BOTTOM;
}
Atom::Pt => {
e.set_pt(num(v)?);
self.sides |= TOP;
}
Atom::Pr => {
e.set_pr(num(v)?);
self.sides |= RIGHT;
}
Atom::Pb => {
e.set_pb(num(v)?);
self.sides |= BOTTOM;
}
Atom::Pl => {
e.set_pl(num(v)?);
self.sides |= LEFT;
}
Atom::M => {
let n = num(v)?;
e.set_mt(n).set_mr(n).set_mb(n).set_ml(n);
}
Atom::Mx => {
let n = num(v)?;
e.set_ml(n).set_mr(n);
}
Atom::My => {
let n = num(v)?;
e.set_mt(n).set_mb(n);
}
Atom::Mt => _ = e.set_mt(num(v)?),
Atom::Mr => _ = e.set_mr(num(v)?),
Atom::Mb => _ = e.set_mb(num(v)?),
Atom::Ml => _ = e.set_ml(num(v)?),
Atom::Opacity => _ = e.set_opacity(num(v)?),
Atom::Role => {
let s = string(v)?;
self.role = Some(role(s).ok_or_else(|| format!("unknown role {s}"))?);
}
Atom::Label => _ = e.set_label(string(v)?),
Atom::Help => _ = e.set_help(string(v)?),
Atom::Gap => _ = e.set_gap(num(v)?),
Atom::Align => {
match v {
Value::Str("start") => e.set_items_start(),
Value::Str("center") => e.set_items_center(),
Value::Str("end") => e.set_items_end(),
Value::Str("stretch") => e.set_items_stretch(),
other => return Err(format!("align must be start, center, end or stretch, got {}", self::name(other))),
};
}
Atom::Justify => {
match v {
Value::Str("start") => e.set_justify_start(),
Value::Str("center") => e.set_justify_center(),
Value::Str("end") => e.set_justify_end(),
Value::Str("between") => e.set_justify_between(),
other => return Err(format!("justify must be start, center, end or between, got {}", self::name(other))),
};
}
Atom::Center => self.center = flag(v)?,
Atom::Wrap if is_text => self.wrap = flag(v)?,
Atom::Wrap => {
if flag(v)? {
e.set_flex_wrap();
}
}
Atom::Fill => _ = e.set_fill(color(v)?),
Atom::Hover => _ = e.set_hover(color(v)?),
Atom::Press => _ = e.set_press(color(v)?),
Atom::Border => self.border.1 = Some(color(v)?),
Atom::BorderWidth => self.border.0 = Some(num(v)?),
Atom::Radius => _ = e.set_radius(num(v)?),
Atom::Clip => {
if flag(v)? {
e.set_clip_soft(0.0);
}
}
Atom::ScrollY | Atom::ScrollX => {
if flag(v)? {
let (x, y) = self.scroll.unwrap_or((false, false));
self.scroll = Some(if atom == Atom::ScrollX { (true, y) } else { (x, true) });
}
}
Atom::StickBottom => self.stick_bottom = flag(v)?,
Atom::Color => self.color = Some(color(v)?),
Atom::Size => self.text.size = num(v)?,
Atom::Weight => {
self.text.weight = match v {
Value::Str("regular") => env.weights[0],
Value::Str("medium") => env.weights[1],
Value::Str("semibold") => env.weights[2],
Value::Str("bold") => env.weights[3],
Value::Num(n) => n as f32,
other => return Err(format!("weight must be regular, medium, semibold or bold, got {}", self::name(other))),
}
}
Atom::HoverTransition => match v {
Value::Str("instant") => with(e, |e| e.hover_motion(rune::Anim::INSTANT, rune::Anim::INSTANT)),
Value::Str("default") | Value::Nil => {}
other => return Err(format!("hoverTransition must be default or instant, got {}", self::name(other))),
},
Atom::HoverGroup => {
if flag(v)? {
with(e, El::hover_group);
}
}
Atom::HoverGroupColor => {
let c = color(v)?;
with(e, |e| e.group_color(c));
}
Atom::RevealOnHover => {
if flag(v)? {
with(e, |e| e.group_opacity(0.0, 1.0));
}
}
Atom::Shadow => match v {
Value::Str(s) => {
self.uncacheable = true;
if let Some(shadows) = env.shadows.as_ref().and_then(|f| f(s, env.dark)) {
// In CSS order, the first on top.
with(e, |e| shadows.into_iter().rev().fold(e, El::box_shadow));
}
}
Value::Nil => {}
other => return Err(format!("shadow must be an elevation name, got {}", self::name(other))),
},
Atom::Selected => self.selected = flag(v)?,
Atom::Focusable => {
if flag(v)? {
with(e, |e| e.focusable(true));
}
}
Atom::Disabled => self.disabled = flag(v)?,
Atom::MenuTrigger => self.menu_trigger = flag(v)?,
Atom::HelpSide => {
let side = match v {
Value::Str("top") => Some(rune::Side::Top),
Value::Str("left") => Some(rune::Side::Left),
Value::Str("right") => Some(rune::Side::Right),
_ => None,
};
if let Some(side) = side {
with(e, |e| e.help_side(side));
}
}
// A Copy button's "Copied" held up after the press (`El::help_open`).
Atom::HelpOpen => {
if flag(v)? {
with(e, |e| e.help_open(true));
}
}
Atom::FadeOut => self.fade_out = flag(v)?,
// HTML's `dir`: `ltr` or `rtl` lays the subtree out that way whatever the window's
// direction, `auto` takes a text's first strong direction.
Atom::Dir => {
let dir = match string(v)? {
"ltr" => rune::Direction::Ltr,
"rtl" => rune::Direction::Rtl,
"auto" => rune::Direction::Auto,
s => return Err(format!("unknown dir {s}")),
};
with(e, |e| e.dir(dir));
}
// Tables, read off the stack by `decode_at`.
Atom::Corners | Atom::Pin => return Err(format!("{name} must be a table, got {}", self::name(v))),
Atom::LineHeight => self.text = self.text.lh(num(v)?),
Atom::Tracking => self.text = self.text.tracking(num(v)?),
Atom::Mono => {
if flag(v)? {
self.text = self.text.mono();
}
}
Atom::Tabular => {
if flag(v)? {
self.text = self.text.features("'tnum' 1");
}
}
Atom::NoWrap => {
if flag(v)? {
self.wrap = false;
self.single_line = true;
}
}
Atom::Truncate => self.truncate = flag(v)?,
Atom::Selectable => self.selectable = flag(v)?,
Atom::TextAlign => {
self.text_align = Some(match v {
Value::Str("start") => Align::Start,
Value::Str("center") => Align::Center,
Value::Str("end") => Align::End,
other => return Err(format!("textAlign must be start, center or end, got {}", self::name(other))),
})
}
// Read by the node that takes them; elsewhere they mean nothing.
Atom::OnPress | Atom::OnHover | Atom::OnMiddlePress | Atom::Count | Atom::EstimatedRowHeight | Atom::Version | Atom::RenderRow | Atom::RowKey | Atom::RowVersions | Atom::OnVisibleRows => {
super::unknown_prop(env, None, name)?;
}
}
Ok(())
}
/// Decodes the prop whose value is at stack slot `idx` onto `e`, reading the table-valued
/// ones (`corners`, `pin`) off the stack.
pub(crate) unsafe fn decode_at(&mut self, e: &mut El, state: *mut ffi::lua_State, atom: Atom, idx: c_int, env: &Env, is_text: bool) -> Result<(), String> {
// SAFETY: the caller passes a valid slot.
let v = unsafe { read(state, idx) };
match (atom, v) {
(Atom::Corners | Atom::Pin, Value::Nil) => Ok(()),
(Atom::Corners, Value::Other("table")) => {
// SAFETY: slot `idx` holds a table.
let r = unsafe { numbers::<4>(state, idx, &[]) };
self.corners = Some(r.map(|n| n.unwrap_or(0.0)));
Ok(())
}
(Atom::Pin, Value::Other("table")) => {
// SAFETY: slot `idx` holds a table.
let [l, t, r, b] = unsafe { numbers::<4>(state, idx, &["left", "top", "right", "bottom"]) };
e.set_pin(l, t, r, b);
Ok(())
}
_ => self.decode(e, atom, v, env, is_text),
}
}
}
/// Runs a by-value builder on `e` in place, for the props Rune has no in-place setter for.
fn with(e: &mut El, f: impl FnOnce(El) -> El) {
let taken = std::mem::replace(e, rune::el());
*e = f(taken);
}
/// `N` numbers from the table at `idx`: by name when `names` are given, else items `1..=N`.
unsafe fn numbers<const N: usize>(state: *mut ffi::lua_State, idx: c_int, names: &[&str]) -> [Option<f32>; N] {
let mut out = [None; N];
// SAFETY: `idx` is a table; each lookup pushes one value, popped right after.
unsafe {
let idx = ffi::lua_absindex(state, idx);
for (i, slot) in out.iter_mut().enumerate() {
let kind = match names.get(i) {
Some(name) => {
ffi::lua_pushlstring(state, name.as_ptr().cast(), name.len());
ffi::lua_rawget(state, idx)
}
None => ffi::lua_rawgeti(state, idx, i as ffi::lua_Integer + 1),
};
if kind == ffi::LUA_TNUMBER {
*slot = Some(ffi::lua_tonumberx(state, -1, std::ptr::null_mut()) as f32);
}
ffi::lua_settop(state, -2);
}
}
out
}
fn as_str(atom: Atom, v: Value<'_>) -> Result<&str, String> {
match v {
Value::Str(s) => Ok(s),
other => Err(format!("{} must be a string, got {}", NAMES[atom as usize].0, name(other))),
}
}
fn role(s: &str) -> Option<&'static str> {
Some(match s {
"none" => "none",
"group" => "group",
"region" => "region",
"button" => "button",
"link" => "link",
"switch" => "switch",
"checkbox" => "checkbox",
"radio" => "radio",
"tab" => "tab",
"list" => "list",
"listitem" => "listitem",
"heading" => "heading",
"img" => "img",
"status" => "status",
"timer" => "timer",
"alert" => "alert",
_ => return None,
})
}
pub(crate) fn name(v: Value<'_>) -> &'static str {
match v {
Value::Nil => "nil",
Value::Bool(_) => "boolean",
Value::Num(_) => "number",
Value::Str(_) => "string",
Value::Func => "function",
Value::Other(t) => t,
}
}
/// A number as Luau prints it: `3`, not `3.0`.
pub(crate) fn format_num(n: f64) -> String {
let mut s = String::new();
push_num(&mut s, n);
s
}
/// [`format_num`] onto the end of `out`.
pub(crate) fn push_num(out: &mut String, n: f64) {
use std::fmt::Write;
if n.fract() == 0.0 && n.abs() < 1e15 { write!(out, "{}", n as i64).ok(); } else { write!(out, "{n}").ok(); }
}
+186
View File
@@ -0,0 +1,186 @@
//! `ui.virtualList({ count, estimatedRowHeight, renderRow, rowKey?, version?, key, ... })`: a
//! vertical scroll viewport over `El::virtual_rows`. Layout asks for rows only as they enter the
//! mounted window, and each row is memoized by its key and the list's `version`, so scrolling
//! calls `renderRow(i)` (1-based) only for rows coming in, and a frame that scrolls nothing new
//! into the window calls no Luau at all. Without `rowKey`, row `i` is keyed by its index.
//! `rowVersions` gives each row a version of its own beside the list's, so a row rebuilds only
//! when the list's or its own moves. With `scrollY = false` the list has no viewport of its own: it is a stack inside a scrolling
//! column, under or among other content, and windows against that column's viewport.
#![allow(unsafe_code)]
use std::os::raw::c_int;
use std::rc::{Rc, Weak};
use mlua::ffi;
use rune::{El, GrowthSpec, col};
use super::props::{self, Atom, Props, Value};
use super::view::{mix, version_hash};
use super::{Callback, Event, guard, top};
use crate::script::Inner;
/// A list's rows, as layout asks for them.
#[derive(Clone)]
pub(crate) struct Spec {
pub(crate) count: usize,
pub(crate) estimate: f32,
pub(crate) render: Rc<Callback>,
pub(crate) key: Option<Rc<Callback>>,
/// The list's version mixed with the script's salt: rows rebuild when it changes. Without
/// a `version` prop it is the script's own, which moves whenever script code runs.
pub(crate) version: u64,
/// `rowVersions`: each row's own version, mixed with `version`, so a row rebuilds when
/// either moves. Rows past its end take `version` alone.
pub(crate) row_versions: Option<Rc<[u64]>>,
/// What `virtual_rows_version` gets: rows keyed by index never change keys; rows keyed by
/// `rowKey` change keys when `version` does.
pub(crate) keys_version: Option<u64>,
pub(crate) id: Rc<str>,
pub(crate) visible: Option<Rc<Callback>>,
pub(crate) gap: f32,
/// The rows stack in the list's own element, inside a scrolling ancestor, rather than in a
/// viewport of their own.
pub(crate) inline: bool,
}
pub(crate) unsafe extern "C-unwind" fn ui_virtual_list(state: *mut ffi::lua_State) -> c_int {
// SAFETY: argument 1 is the props table on this C function's stack.
unsafe {
if ffi::lua_type(state, 1) != ffi::LUA_TTABLE {
return guard(state, || Err("ui.virtualList needs a props table".into()));
}
guard(state, || {
top(|frame| {
let mut p = Props::new(&frame.env);
let mut list = col();
list.set_w_full();
let (mut count, mut estimate, mut version, mut key) = (0usize, 32.0f32, None, None::<String>);
let (mut render, mut row_key, mut visible, mut gap, mut own) = (None, None, None, 0.0f32, true);
let mut row_versions: Option<Vec<u64>> = None;
let mut iter = 0;
while {
iter = ffi::lua_rawiter(state, 1, iter);
iter >= 0
} {
let v = props::read(state, -1);
match (props::key_atom(state, -2), v) {
(Ok(Atom::Count), Value::Num(n)) => count = n.max(0.0) as usize,
(Ok(Atom::EstimatedRowHeight), Value::Num(n)) => estimate = n.max(1.0) as f32,
(Ok(Atom::RowVersions), Value::Other("table")) => row_versions = Some(versions(state)?),
(Ok(Atom::Version), _) => version = Some(version_hash(state, -1)?),
(Ok(Atom::RenderRow), Value::Func) => render = Some(frame.env.reference(state, -1)),
(Ok(Atom::RowKey), Value::Func) => row_key = Some(frame.env.reference(state, -1)),
(Ok(Atom::OnVisibleRows), Value::Func) => visible = Some(frame.env.reference(state, -1)),
(Ok(Atom::Gap), Value::Num(n)) => gap = n as f32,
(Ok(Atom::ScrollY), Value::Bool(b)) => own = b,
(Ok(Atom::Key), Value::Str(s)) => key = Some(s.to_owned()),
(Ok(Atom::Key), Value::Num(n)) => key = Some(props::format_num(n)),
(Ok(atom @ (Atom::Count | Atom::EstimatedRowHeight | Atom::RenderRow | Atom::RowKey | Atom::RowVersions | Atom::OnVisibleRows | Atom::Gap)), other) => {
return Err(format!("ui.virtualList {atom:?} can't be a {}", props::name(other)));
}
(Ok(Atom::OnPress), _) => super::unknown_prop(&frame.env, Some("virtualList"), "onPress")?,
(Ok(atom), _) => p.decode_at(&mut list, state, atom, -1, &frame.env, false)?,
(Err(name), _) => super::unknown_prop(&frame.env, Some("virtualList"), name)?,
}
ffi::lua_settop(state, -3);
}
let render = render.ok_or("ui.virtualList needs renderRow")?;
let key = key.unwrap_or_else(|| "list".to_owned());
let env = &frame.env;
let version = mix(version.unwrap_or(env.version), env.salt);
let spec = Spec {
count,
estimate,
keys_version: if row_key.is_none() { Some(env.salt) } else { Some(version) },
version,
row_versions: row_versions.map(|vs| vs.into_iter().map(|v| mix(v, version)).collect()),
render,
key: row_key,
visible,
gap,
id: format!("{}{key}", env.prefix).into(),
inline: !own,
};
if own {
p.scroll = Some((false, true));
}
p.finish(&mut list, env, false, None, frame.attach);
list.set_key(key);
let el = (frame.attach.rows)(list, spec);
let handle = frame.put(el)?;
ffi::lua_pushlightuserdata(state, handle);
Ok(1)
})
.unwrap_or_else(|| Err("ui nodes can only be built while rendering".into()))
})
}
}
/// The versions in the list on top of the stack, one per row.
unsafe fn versions(state: *mut ffi::lua_State) -> Result<Vec<u64>, String> {
// SAFETY: the top slot holds a table; each entry is pushed, hashed and popped.
unsafe {
let at = ffi::lua_absindex(state, -1);
let len = ffi::lua_objlen(state, at);
(1..=len)
.map(|i| {
ffi::lua_rawgeti(state, at, i as ffi::lua_Integer);
let v = version_hash(state, -1);
ffi::lua_settop(state, -2);
v.map_err(|e| format!("ui.virtualList rowVersions {i}: {e}"))
})
.collect()
}
}
/// Makes `list` (the node its props built) a virtual list: the rows' stack inside it as its
/// viewport, or itself when the list is inline.
pub(crate) fn attach<S: 'static>(list: El, spec: Spec) -> El {
let keys = spec.clone();
let rows = spec.clone();
let (stack, viewport) = if spec.inline { (list, None) } else { (col().key("rows").w_full(), Some(list)) };
let mut stack = stack.gap(spec.gap).growth(GrowthSpec::default()).virtual_rows(
spec.count,
spec.estimate,
move |s: &S, i| match &keys.key {
Some(cb) => upgrade(&cb.script).and_then(|script| script.around_read(s, || script.row_key(cb, i))).unwrap_or_else(|| i.to_string()).into(),
None => i.to_string().into(),
},
move |s: &S, i| {
let Some(script) = upgrade(&rows.render.script) else { return rune::el() };
script
.around_read(s, || {
let key = match &rows.key {
Some(cb) => script.row_key(cb, i),
None => i.to_string(),
};
// Rune keys the row by `key` whatever its memo id; keying the root by that id
// keeps memo from reporting a replaced key.
let id = format!("{}/{key}", rows.id);
let version = rows.row_versions.as_ref().and_then(|vs| vs.get(i).copied()).unwrap_or(rows.version);
rune::memo::memo_with_hash(id.clone(), version, || script.row::<S>(&rows, i).key(id))
})
.unwrap_or_else(rune::el)
},
);
if let Some(v) = spec.keys_version {
stack = stack.virtual_rows_version(v);
}
if let Some(cb) = spec.visible {
stack = stack.on_visible_rows(move |s: &mut S, range| {
let Some(script) = cb.script.upgrade() else { return false };
let event = Event { kind: "visible-rows", key: None, mods: None, rows: Some((range.start + 1, range.end)), entered: None, fields: Rc::new([]) };
script.around_write(s, None, |tx| script.handle(&cb, event, tx));
true
});
}
match viewport {
Some(viewport) => viewport.child(stack),
None => stack,
}
}
fn upgrade(script: &Weak<Inner>) -> Option<Rc<Inner>> {
script.upgrade()
}
+220
View File
@@ -0,0 +1,220 @@
//! The `view` a render function receives: `view:Memo(key, version, build)` and
//! `view:Handler(fn)`, plus `view.dark`; and `ui.each(items, key, version, build)`, a memo per
//! item of a list.
//!
//! `Memo` is a C function: it hashes `version` straight off the stack (a number's bits, a
//! string's bytes) and calls `rune::memo::memo_with_hash`. On a hit Rune hands back the subtree
//! it built before, and `build` is never called.
#![allow(unsafe_code)]
use std::hash::{Hash, Hasher};
use std::os::raw::c_int;
use mlua::ffi;
use rune::El;
use super::props::{self, Value};
use super::{guard, top};
pub(crate) unsafe extern "C-unwind" fn view_memo(state: *mut ffi::lua_State) -> c_int {
// SAFETY: arguments are (view, key, version, build) on this C function's stack.
unsafe {
let num;
let key = match props::read(state, 2) {
Value::Str(s) => s,
Value::Num(n) => {
num = props::format_num(n);
num.as_str()
}
other => {
let message = format!("view:Memo key must be a string or number, got {}", props::name(other));
return guard(state, || Err(message));
}
};
let version = match version_hash(state, 3) {
Ok(v) => v,
Err(message) => return guard(state, || Err(message)),
};
if ffi::lua_type(state, 4) != ffi::LUA_TFUNCTION {
return guard(state, || Err("view:Memo needs a build function".into()));
}
let Some((salt, prefix)) = top(|f| (f.env.salt, f.env.prefix.clone())) else {
return guard(state, || Err("view:Memo can only be called while rendering".into()));
};
let mut failed: Option<String> = None;
// Memo ids are the window's: under the script's prefix, two scripts' "panel" memos are
// two entries. The subtree's root takes the memo's id, as `rune::memo` keys it.
let key = format!("{prefix}{key}");
let id = key.clone();
let el = rune::memo::memo_with_hash(key, mix(version, salt), || build(state, &mut failed).key(id));
if let Some(message) = failed {
// The salt bump after this render keeps the empty placeholder the memo stored from
// being reused, even if the script catches the error.
top(|f| f.env.memo_failed.set(true));
drop(el);
return guard(state, || Err(message));
}
guard(state, || {
let handle = top(|f| f.put(el)).ok_or("view:Memo can only be called while rendering")??;
ffi::lua_pushlightuserdata(state, handle);
Ok(1)
})
}
}
/// Calls the build function at slot 4 under `lua_pcall`, so an error in it comes back here
/// instead of unwinding through Rune's memo code.
fn build(state: *mut ffi::lua_State, failed: &mut Option<String>) -> El {
// SAFETY: pushes a copy of the function, calls it protected and pops what it left.
unsafe {
ffi::lua_pushvalue(state, 4);
let status = ffi::lua_pcall(state, 0, 1, 0);
built(state, status, failed, "view:Memo build")
}
}
/// The node a protected build call (`status`) left on the stack, which it pops; on an error,
/// an empty element and the message in `failed`.
unsafe fn built(state: *mut ffi::lua_State, status: c_int, failed: &mut Option<String>, what: &str) -> El {
// SAFETY: the call's one result is on top of the stack.
unsafe {
if status != ffi::LUA_OK {
*failed = Some(match props::read(state, -1) {
Value::Str(s) => s.to_owned(),
_ => format!("{what} failed"),
});
ffi::lua_settop(state, -2);
return rune::el();
}
let handle = ffi::lua_tolightuserdata(state, -1);
ffi::lua_settop(state, -2);
if handle.is_null() {
*failed = Some(format!("{what} must return a ui node"));
return rune::el();
}
match top(|f| f.take(handle)) {
Some(Ok(el)) => el,
Some(Err(message)) => {
*failed = Some(message);
rune::el()
}
None => rune::el(),
}
}
}
/// `ui.each(items, key, version, build)`: a list of nodes, `build(item, index)` for each item,
/// each a memo of its own (as `view:Memo`) on the item's key and version, so a render rebuilds
/// only the items whose version moved. `key` and `version` are field names or functions of
/// `(item, index)`. Returns the nodes as a list, to pass as children.
pub(crate) unsafe extern "C-unwind" fn ui_each(state: *mut ffi::lua_State) -> c_int {
// SAFETY: arguments are (items, key, version, build) on this C function's stack; slot 5 is
// the result list and slot 6 the item being built, popped after each.
unsafe {
let pick = |i| matches!(ffi::lua_type(state, i), ffi::LUA_TSTRING | ffi::LUA_TFUNCTION);
if ffi::lua_type(state, 1) != ffi::LUA_TTABLE || !pick(2) || !pick(3) || ffi::lua_type(state, 4) != ffi::LUA_TFUNCTION {
return guard(state, || Err("ui.each needs items, a key and a version (field names or functions) and a build function".into()));
}
ffi::lua_settop(state, 4);
let len = ffi::lua_objlen(state, 1);
ffi::lua_createtable(state, len as c_int, 0);
guard(state, || {
// An item's key is its node's key and its memo's id; memos nest under the surface's,
// which carries the script's prefix, so two scripts' keys never meet.
let salt = top(|f| f.env.salt).ok_or("ui.each can only be called while rendering")?;
for i in 1..=len {
ffi::lua_rawgeti(state, 1, i as ffi::lua_Integer);
let key = match field(state, 2, i)? {
Value::Str(s) => s.to_owned(),
Value::Num(n) => props::format_num(n),
other => return Err(format!("ui.each: item {i}'s key must be a string or a number, got {}", props::name(other))),
};
ffi::lua_settop(state, 6);
field(state, 3, i)?;
let version = version_hash(state, 7).map_err(|e| format!("ui.each: item {i}: {e}"))?;
ffi::lua_settop(state, 6);
let mut failed: Option<String> = None;
let id = key.clone();
let el = rune::memo::memo_with_hash(key, mix(version, salt), || item(state, i, &mut failed).key(id));
if let Some(message) = failed {
top(|f| f.env.memo_failed.set(true));
return Err(message);
}
let handle = top(|f| f.put(el)).ok_or("ui.each can only be called while rendering")??;
ffi::lua_settop(state, 5);
ffi::lua_pushlightuserdata(state, handle);
ffi::lua_rawseti(state, 5, i as ffi::lua_Integer);
}
Ok(1)
})
}
}
/// Pushes the item at slot 6's key or version: its field named by the string at `by`, or what
/// the function at `by` returns for `(item, i)`.
unsafe fn field<'a>(state: *mut ffi::lua_State, by: c_int, i: usize) -> Result<Value<'a>, String> {
// SAFETY: slot 6 is the item; `by` is a string or a function.
unsafe {
if ffi::lua_type(state, by) == ffi::LUA_TSTRING {
if ffi::lua_type(state, 6) != ffi::LUA_TTABLE {
return Err(format!("ui.each: item {i} is a {}, not a table with fields", props::name(props::read(state, 6))));
}
ffi::lua_pushvalue(state, by);
ffi::lua_rawget(state, 6);
} else {
ffi::lua_pushvalue(state, by);
ffi::lua_pushvalue(state, 6);
ffi::lua_pushinteger(state, i as ffi::lua_Integer);
if ffi::lua_pcall(state, 2, 1, 0) != ffi::LUA_OK {
return Err(match props::read(state, -1) {
Value::Str(s) => s.to_owned(),
_ => format!("ui.each: item {i}'s key or version failed"),
});
}
}
Ok(props::read(state, -1))
}
}
/// Calls the build function (slot 4) for the item at slot 6, protected.
fn item(state: *mut ffi::lua_State, i: usize, failed: &mut Option<String>) -> El {
// SAFETY: pushes the function and its arguments, calls it protected and pops what it left.
unsafe {
ffi::lua_pushvalue(state, 4);
ffi::lua_pushvalue(state, 6);
ffi::lua_pushinteger(state, i as ffi::lua_Integer);
let status = ffi::lua_pcall(state, 2, 1, 0);
built(state, status, failed, "ui.each build")
}
}
/// `view:Handler(fn)`: returns `fn`. Handlers are plain functions; this keeps scripts written
/// against hosts that wrap them working.
pub(crate) unsafe extern "C-unwind" fn view_handler(state: *mut ffi::lua_State) -> c_int {
// SAFETY: returns argument 2 as is.
unsafe {
ffi::lua_pushvalue(state, 2);
1
}
}
/// A memo version straight off the stack: nil, a boolean, a number's bits or a string's bytes.
pub(crate) unsafe fn version_hash(state: *mut ffi::lua_State, idx: c_int) -> Result<u64, String> {
let mut h = rustc_hash::FxHasher::default();
// SAFETY: reads slot `idx`.
match unsafe { props::read(state, idx) } {
Value::Nil => 0u8.hash(&mut h),
Value::Bool(b) => (1u8, b).hash(&mut h),
Value::Num(n) => (2u8, n.to_bits()).hash(&mut h),
Value::Str(s) => (3u8, s).hash(&mut h),
other => return Err(format!("a memo version must be nil, a boolean, a number or a string, got {}", props::name(other))),
}
Ok(h.finish())
}
pub(crate) fn mix(version: u64, salt: u64) -> u64 {
let mut h = rustc_hash::FxHasher::default();
(version, salt).hash(&mut h);
h.finish()
}
+284
View File
@@ -0,0 +1,284 @@
//! One Luau VM: a script's sandboxed globals (`task`, `Signal`, `require`), its `@rune/ui`
//! module, the host's own bindings, and the module its `init.luau` returned.
#![allow(unsafe_code)]
use std::cell::RefCell;
use std::os::raw::c_int;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use mlua::chunk::ChunkMode;
use mlua::{Function, IntoLua, Lua, MultiValue, Table, Value, ffi};
use rustc_hash::FxHashMap;
use crate::require::{Loading, Requirer, module_loader};
use crate::sources::{Compiled, compiler};
use crate::task::{self, Sched};
use crate::ui::host::{HostNode, ui_host};
use crate::ui::nodes::BUILTINS;
use crate::ui::props::useratom;
use crate::ui::view::{view_handler, view_memo};
use crate::workers::Shared;
use crate::{Completer, LogLevel, ScriptError};
const PRELUDE: &str = include_str!("prelude.luau");
/// The prelude, compiled once per thread.
fn prelude_bytecode() -> mlua::Result<Rc<[u8]>> {
thread_local! {
static CODE: RefCell<Option<Rc<[u8]>>> = const { RefCell::new(None) };
}
if let Some(code) = CODE.with_borrow(Clone::clone) {
return Ok(code);
}
let code: Rc<[u8]> = compiler().compile(PRELUDE)?.into();
CODE.set(Some(code.clone()));
Ok(code)
}
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
pub(crate) struct Vm {
pub(crate) lua: Lua,
/// Unique across every VM this process made: callbacks from an earlier VM are refused.
pub(crate) id: u64,
pub(crate) module: Table,
pub(crate) view: Table,
pub(crate) garbage: Rc<RefCell<Vec<c_int>>>,
/// Nodes decoded from frozen props tables, reused while this VM runs.
pub(crate) templates: Rc<RefCell<crate::ui::Templates>>,
signals: Rc<RefCell<FxHashMap<String, Value>>>,
fire: Function,
}
/// What a host binds into each new VM, in [`ScriptOptions::setup`](crate::ScriptOptions::setup).
/// It runs again for each new VM: in every reload, or ahead of one ([`Script::prewarm`](crate::Script::prewarm)).
pub struct Host<'a> {
lua: &'a Lua,
shared: &'a Arc<Shared>,
signals: &'a Rc<RefCell<FxHashMap<String, Value>>>,
prelude: &'a Table,
}
impl Host<'_> {
pub fn lua(&self) -> &Lua {
self.lua
}
/// Makes `require("@name")` return `value` (`@app/sessions`, say).
pub fn register_module(&self, name: &str, value: impl IntoLua) -> mlua::Result<()> {
self.lua.register_module(name, value)
}
/// Sets global `name` before the sandbox freezes the globals.
pub fn global(&self, name: &str, value: impl IntoLua) -> mlua::Result<()> {
self.lua.globals().raw_set(name, value)
}
/// A `Signal` (Connect, Once, Wait) the host fires with
/// [`Script::fire`](crate::Script::fire) as `name`. Expose it to the script in a module.
pub fn signal(&self, name: &str) -> mlua::Result<Value> {
let signal: Value = self.prelude.get::<Function>("signal")?.call(())?;
self.signals.borrow_mut().insert(name.to_owned(), signal.clone());
Ok(signal)
}
/// A new `ScriptSignal`, which the script fires itself (Fire, Version), for a host's
/// `CreateSignal`. Scripts also get one from `require("@rune/signal").new()`.
pub fn script_signal(&self) -> mlua::Result<Function> {
self.prelude.get::<Function>("scriptSignal")
}
/// A function a task calls like a plain one, which `start` finishes later: `start` gets
/// the arguments and a [`Completer`], and the task resumes with what the completer is given.
/// Called outside a task (while rendering), it raises an error.
pub fn async_function(
&self,
name: &str,
start: impl Fn(&Lua, MultiValue, Completer) -> mlua::Result<()> + 'static,
) -> mlua::Result<Function> {
let shared = self.shared.clone();
let submit = self.lua.create_function(move |lua, args: MultiValue| {
let done = shared.job();
let id = done.id;
start(lua, args, done)?;
Ok(id)
})?;
self.prelude.get::<Function>("async")?.call((submit, name))
}
}
pub(crate) struct Setup<'a> {
pub(crate) shared: &'a Arc<Shared>,
pub(crate) memory_limit: usize,
pub(crate) nodes: &'a [HostNode],
pub(crate) host: Option<&'a crate::options::SetupFn>,
pub(crate) log: Rc<dyn Fn(LogLevel, String)>,
}
/// A VM before its script: the Luau state with the prelude, `@rune/ui` and the host's bindings,
/// none of which depend on the script's files, so it can be built ahead of a reload
/// ([`Script::prewarm`](crate::Script::prewarm)).
pub(crate) struct Base {
lua: Lua,
prelude: Table,
view: Table,
signals: Rc<RefCell<FxHashMap<String, Value>>>,
}
impl Base {
pub(crate) fn new(setup: Setup<'_>) -> Result<Base, ScriptError> {
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
crate::web::init();
let lua = Lua::new();
// SAFETY: the callback table lives as long as the VM; `useratom` is a plain function.
unsafe { lua.exec_raw::<()>((), |state| (*ffi::lua_callbacks(state)).useratom = Some(useratom))? };
lua.set_memory_limit(setup.memory_limit)?;
lua.set_compiler(compiler());
crate::watchdog::install(&lua)?;
lua.set_app_data(Sched::new(setup.shared.clone(), 0.0));
let (task, forget) = task::install(&lua)?;
let (wait, park, job) = task::tokens();
#[cfg(luau_jit)]
lua.enable_jit(false);
let prelude: Table = lua
.load(&*prelude_bytecode()?)
.set_mode(ChunkMode::Binary)
.set_name("=rune-luau")
.call((task.clone(), wait, park, job, forget))?;
let globals = lua.globals();
globals.raw_set("task", task)?;
let signal = lua.create_table()?;
signal.raw_set("new", prelude.get::<Function>("scriptSignal")?)?;
lua.register_module("@rune/signal", signal)?;
for (name, level) in [("print", LogLevel::Info), ("warn", LogLevel::Warn)] {
let log = setup.log.clone();
let f = lua.create_function(move |_, args: MultiValue| {
let parts: Vec<String> = args.iter().map(|v| v.to_string().unwrap_or_else(|_| v.type_name().to_owned())).collect();
log(level, parts.join("\t"));
Ok(())
})?;
globals.raw_set(name, f)?;
}
let ui = lua.create_table()?;
for (name, f) in BUILTINS {
// SAFETY: each builtin follows the C function protocol and raises only through `guard`.
ui.raw_set(*name, unsafe { lua.create_c_function(*f)? })?;
}
for (i, node) in setup.nodes.iter().enumerate() {
// SAFETY: pushes `ui_host` with the node's index as its one upvalue.
let f: Function = unsafe {
lua.exec_raw((), |state| {
ffi::lua_pushinteger(state, i as ffi::lua_Integer);
ffi::lua_pushcclosurek(state, ui_host, c"ui.host".as_ptr(), 1, None);
})?
};
ui.raw_set(node.name.as_str(), f)?;
}
lua.register_module("@rune/ui", &ui)?;
let view = lua.create_table()?;
// SAFETY: as for the builtins.
unsafe {
view.raw_set("Memo", lua.create_c_function(view_memo)?)?;
view.raw_set("Handler", lua.create_c_function(view_handler)?)?;
}
view.raw_set("dark", false)?;
let signals = Rc::new(RefCell::new(FxHashMap::default()));
if let Some(host) = setup.host {
host(&Host { lua: &lua, shared: setup.shared, signals: &signals, prelude: &prelude })?;
}
Ok(Base { lua, prelude, view, signals })
}
}
impl Vm {
/// A new VM from `base` running `compiled`, sandboxed, before its entry module runs; its
/// task clock starts at `clock`.
pub(crate) fn new(base: Base, compiled: &Rc<Compiled>, clock: f64) -> Result<(Vm, Function), ScriptError> {
let Base { lua, prelude, view, signals } = base;
if let Some(mut sched) = lua.app_data_mut::<Sched>() {
sched.set_clock(clock);
}
let loading: Loading = Rc::default();
lua.globals().raw_set("require", lua.create_require_function(Requirer::new(compiled.clone(), loading.clone()))?)?;
lua.sandbox(true)?;
let entry = module_loader(&lua, compiled, &loading, &compiled.entry)?;
let fire = prelude.get::<Function>("fire")?;
let vm = Vm {
module: lua.create_table()?,
lua,
id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
view,
garbage: Rc::default(),
templates: Rc::default(),
signals,
fire,
};
Ok((vm, entry))
}
/// Takes what `init.luau` returned: a table of functions, or one function (`render`).
pub(crate) fn set_module(&mut self, value: Value) -> Result<(), ScriptError> {
self.module = match value {
Value::Table(t) => t,
Value::Function(f) => {
let t = self.lua.create_table()?;
t.raw_set("render", f)?;
t
}
other => {
return Err(ScriptError::new(
crate::ErrorKind::Missing,
format!("the entry module must return a table of functions or a render function, not a {}", other.type_name()),
));
}
};
Ok(())
}
/// The exported function `name`, if the module has one.
pub(crate) fn export(&self, name: &str) -> Option<Function> {
self.module.raw_get::<Option<Function>>(name).ok().flatten()
}
/// The function behind registry reference `r`.
pub(crate) fn function(&self, r: c_int) -> mlua::Result<Function> {
// SAFETY: pushes the registry slot `r`, which this VM's `lua_ref` filled.
unsafe { self.lua.exec_raw((), |state| { ffi::lua_rawgeti(state, ffi::LUA_REGISTRYINDEX, r as ffi::lua_Integer); }) }
}
/// Releases registry slots of elements dropped since the last entry.
pub(crate) fn collect(&self) {
let refs = std::mem::take(&mut *self.garbage.borrow_mut());
if refs.is_empty() {
return;
}
// SAFETY: each slot came from this VM's `lua_ref` and is released once. Releasing
// can't fail short of memory, and then the slots only stay taken.
let released: mlua::Result<()> = unsafe {
self.lua.exec_raw::<()>((), |state| {
for r in &refs {
ffi::lua_unref(state, *r);
}
})
};
released.ok();
}
/// Fires the host signal `name` with `args`; false when there is no such signal.
pub(crate) fn fire(&self, name: &str, args: Vec<crate::Data>) -> mlua::Result<bool> {
let Some(signal) = self.signals.borrow().get(name).cloned() else { return Ok(false) };
let mut values = MultiValue::new();
values.push_back(signal);
for a in args {
values.push_back(a.into_lua(&self.lua)?);
}
self.fire.call::<()>(values)?;
Ok(true)
}
}
+107
View File
@@ -0,0 +1,107 @@
//! [`Script::watch`]: save a `.luau` file and the script reloads. The OS file watcher's own
//! thread reads the folder and compiles the files that changed, while the UI thread builds the
//! next VM's base ([`Script::prewarm`]); the next poll after that only swaps the VM.
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use notify::{RecursiveMode, Watcher};
use crate::script::{Inner, LogLevel, Reload};
use crate::sources::{Compiled, Sources};
use crate::{Script, ScriptError};
type Ready = Arc<Mutex<Slot>>;
#[derive(Default)]
pub(crate) struct Slot {
/// A save is compiling.
saving: bool,
ready: Option<Result<(Sources, Compiled, Duration), ScriptError>>,
}
pub(crate) struct Watch {
_watcher: notify::RecommendedWatcher,
ready: Ready,
}
impl Script {
/// Reloads from `dir` whenever a `.luau` file under it changes. Compiling happens on the
/// watcher's thread; the swap happens in the next [`Script::poll`].
pub fn watch(&self, dir: impl AsRef<Path>) -> notify::Result<()> {
let dir: PathBuf = dir.as_ref().to_owned();
let ready: Ready = Arc::default();
let shared = self.inner().shared.clone();
let slot = ready.clone();
let root = dir.clone();
let entry = self.inner().sources.borrow().entry_path().to_owned();
let mut last: Option<(Sources, Compiled)> = None;
let mut watcher = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
let Ok(event) = event else { return };
if !event.kind.is_modify() && !event.kind.is_create() && !event.kind.is_remove() {
return;
}
if !event.paths.iter().any(|p| p.extension().is_some_and(|e| e == "luau")) {
return;
}
let sources = Sources::from_dir(&root).map(|s| s.entry(&entry)).map_err(|e| ScriptError::new(crate::ErrorKind::Missing, e.to_string()));
// One save is often several events (truncate, write): the same files compile once.
if let (Ok(sources), Some((seen, _))) = (&sources, &last)
&& sources == seen
{
return;
}
if let Ok(mut slot) = slot.lock() {
slot.saving = true;
}
shared.mark();
shared.wake();
let start = rune::time::now();
let result = sources.and_then(|sources| {
let compiled = match &last {
Some((_, previous)) => sources.compile_from(previous),
None => sources.compile(),
}?;
last = Some((sources.clone(), compiled.clone()));
Ok((sources, compiled, start.elapsed()))
});
if let Ok(mut slot) = slot.lock() {
*slot = Slot { saving: false, ready: Some(result) };
}
shared.mark();
shared.wake();
})?;
watcher.watch(&dir, RecursiveMode::Recursive)?;
*self.inner().watch.borrow_mut() = Some(Watch { _watcher: watcher, ready });
Ok(())
}
}
/// Swaps in what the watcher compiled, if anything. True when the VM changed.
pub(crate) fn apply(inner: &Inner) -> bool {
let (saving, next) = inner.watch.borrow().as_ref().and_then(|w| w.ready.lock().ok().map(|mut s| (s.saving, s.ready.take()))).unwrap_or_default();
match next {
None => {
if saving {
inner.prewarm();
}
false
}
Some(Err(err)) => {
inner.log(LogLevel::Error, &err.message);
false
}
Some(Ok((sources, compiled, compile))) => match inner.swap(compiled) {
Ok(report) => {
inner.set_sources(sources);
inner.note_reload(Reload { compile, ..report });
true
}
Err(err) => {
inner.log(LogLevel::Error, &err.message);
false
}
},
}
}
+150
View File
@@ -0,0 +1,150 @@
//! The watchdog: every entry into a VM gets a budget (250 ms by default) of the thread's own CPU
//! time, and Luau's interrupt safepoints (loop back edges, calls) raise an error once it is spent,
//! so `while true do end` stops that script without touching the rest of the app. The check reads
//! the clocks every 256 safepoints, which keeps it off the profile of ordinary code.
//!
//! CPU time, not the wall clock: on a loaded machine the thread may wait for a CPU, and a host call
//! may wait on the disk or another thread, for longer than the budget, and neither is the script's
//! doing. A wall-clock deadline charged that time to the script and stopped plugins that ran fine
//! (a plugin's start-up dying while a build ran, 22 Nov). A wall-clock backstop of
//! [`WALL_BACKSTOP`] budgets still bounds an entry that a starved CPU stretches out, and says so on
//! stderr when it is what stops a script (wall and CPU time, file and line). Where the
//! thread has no CPU clock (the browser, Windows on ARM, the first 20 ms of a Windows process while
//! the clock's rate is measured), or the clock can't be read mid-entry, the budget is wall time, as
//! before.
#![allow(unsafe_code)]
use std::cell::Cell;
use std::io::Write;
use std::os::raw::c_int;
use std::time::Duration;
use mlua::{Lua, ffi};
use rune::time::Instant;
use crate::error::WATCHDOG;
/// The wall-clock bound on one entry, in budgets.
const WALL_BACKSTOP: u32 = 20;
#[derive(Clone, Copy)]
struct Deadline {
/// The thread's CPU clock when the entry was armed; `None` without one. Converted at each
/// check, so an entry armed before Windows knows the cycles' rate is charged from its start
/// once it does (the first plugin's start-up included).
mark: Option<rune::ThreadCpuMark>,
/// The budget in nanoseconds of CPU time.
limit_ns: f64,
/// The budget in wall time: the deadline while there's no CPU reading.
budget: Option<Instant>,
/// The wall-clock bound with a CPU clock: [`WALL_BACKSTOP`] budgets.
backstop: Option<Instant>,
/// When the entry was armed: what a backstop stop reports.
armed: Instant,
/// The backstop's stop was logged (a script that catches it is stopped again at each check).
told: bool,
}
/// What stopped an entry.
#[derive(Clone, Copy, PartialEq)]
enum Stop {
/// Its CPU budget, or its wall-clock budget without a CPU clock.
Budget,
/// The wall-clock backstop, with CPU budget left: the thread was starved, not looping.
Backstop,
}
thread_local! {
static DEADLINE: Cell<Option<Deadline>> = const { Cell::new(None) };
static TICKS: Cell<u32> = const { Cell::new(0) };
}
/// Installs the interrupt on `lua`. It never yields and never calls back into Rust code that
/// could hold the VM, so it is safe at every safepoint.
pub(crate) fn install(lua: &Lua) -> mlua::Result<()> {
// SAFETY: `lua_callbacks` returns the VM's callback table, which lives as long as the VM; the
// interrupt slot is a plain function pointer mlua leaves unset.
unsafe { lua.exec_raw::<()>((), |state| (*ffi::lua_callbacks(state)).interrupt = Some(interrupt)) }
}
/// Arms the budget for one entry into a VM, unless an outer entry already did; dropping the
/// guard disarms what it armed.
pub(crate) fn arm(limit: Duration) -> Armed {
let outer = DEADLINE.get().is_some();
if !outer {
let at = rune::time::now();
let mark = rune::thread_cpu_mark();
// A limit too large to add is no wall-clock limit (`None`), never a panic.
let budget = at.checked_add(limit);
let backstop = mark.and_then(|_| at.checked_add(limit.saturating_mul(WALL_BACKSTOP)));
DEADLINE.set(Some(Deadline { mark, limit_ns: limit.as_nanos() as f64, budget, backstop, armed: at, told: false }));
}
Armed(!outer)
}
pub(crate) struct Armed(bool);
impl Drop for Armed {
fn drop(&mut self) {
if self.0 {
DEADLINE.set(None);
}
}
}
/// What stops deadline `d`'s entry, if anything yet: its CPU budget spent, its backstop, or without
/// a CPU reading its budget in wall time. Never panics: it runs inside Luau's interrupt.
fn stop(d: Deadline) -> Option<Stop> {
let now = rune::time::now();
let past = |at: Option<Instant>| at.is_some_and(|at| now >= at);
match d.mark.and_then(rune::thread_cpu_since) {
Some(used) if used >= d.limit_ns => Some(Stop::Budget),
Some(_) => past(d.backstop).then_some(Stop::Backstop),
None => past(d.budget).then_some(Stop::Budget),
}
}
/// One line on stderr when the backstop, not the CPU budget, stops a script: its wall and CPU time
/// and where it was, so a backstop that fires on a real machine is seen and its factor can be tuned.
fn tell_backstop(state: *mut ffi::lua_State, d: Deadline) {
// SAFETY: a zeroed `lua_Debug` is a valid out-parameter; level 0 is the function running at
// this safepoint, and the strings it points to live while it does.
let at = unsafe {
let mut ar: ffi::lua_Debug = std::mem::zeroed();
if ffi::lua_getinfo(state, 0, c"sl".as_ptr(), &mut ar) != 0 && !ar.short_src.is_null() {
format!("{}:{}", std::ffi::CStr::from_ptr(ar.short_src).to_string_lossy(), ar.currentline)
} else {
"?".to_owned()
}
};
let wall = rune::time::now().saturating_duration_since(d.armed).as_secs_f64() * 1e3;
let cpu = d.mark.and_then(rune::thread_cpu_since).map_or(0.0, |ns| ns / 1e6);
// Not `eprintln!`: it panics when stderr is a closed pipe, and this runs inside Luau's interrupt.
let _ = writeln!(std::io::stderr().lock(), "luau: watchdog backstop stopped {at} after {wall:.3} ms wall with {cpu:.3} ms CPU charged (starved, not looping)");
}
unsafe extern "C-unwind" fn interrupt(state: *mut ffi::lua_State, gc: c_int) {
if gc >= 0 {
return;
}
let ticks = TICKS.get().wrapping_add(1);
TICKS.set(ticks);
if ticks & 255 != 0 {
return;
}
// The deadline stays set past the first error, so a script that catches it with `pcall`
// gets it again at the next check, until control is back in the host.
let Some(d) = DEADLINE.get() else { return };
let Some(why) = stop(d) else { return };
if why == Stop::Backstop && !d.told {
tell_backstop(state, d);
DEADLINE.set(Some(Deadline { told: true, ..d }));
}
// SAFETY: raised at a safepoint inside a protected call that this crate made; no Rust
// frame with destructors lies between here and that call.
unsafe { ffi::luaL_error(state, c"%s".as_ptr(), WATCHDOG_C.as_ptr()) }
}
const WATCHDOG_C: &std::ffi::CStr = c"script ran longer than its time limit (watchdog)";
const _: () = assert!(WATCHDOG_C.to_bytes().len() == WATCHDOG.len());
+211
View File
@@ -0,0 +1,211 @@
//! The web build's C runtime. Luau links against WASI libc (`build.rs`), whose allocator then
//! shares linear memory with Rust's: Rust allocates through libc's `malloc` here, so one
//! allocator owns the heap. Turn off the `wasi-allocator` feature only to install an allocator
//! of your own that does the same.
//!
//! WASI libc calls a handful of WASI functions (write, clocks, environment, exit). They are
//! defined here, in the module, under the names libc imports them by, so the linker binds them
//! inside the wasm: the page needs no WASI shim, and `web-build.sh` output loads as any other
//! Rune app's. Writes to stdout and stderr go to the browser console a line at a time.
//!
//! Luau's C++ has static constructors. Left alone, the linker would wrap every export of the
//! module in a call to them (its "command" mode), running them again on each call into the wasm;
//! referencing them here makes it link them once, and [`init`] runs them before the first VM.
#![allow(unsafe_code)]
unsafe extern "C" {
fn __wasm_call_ctors();
}
/// Runs the C and C++ static constructors, once.
pub(crate) fn init() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
// SAFETY: the linker's constructor list, run once before any Luau code.
unsafe { __wasm_call_ctors() }
});
}
mod wasi {
use std::cell::RefCell;
use wasm_bindgen::prelude::wasm_bindgen;
#[wasm_bindgen]
extern "C" {
/// `performance.now()`, bound statically: the clocks below may run before anything
/// else in the module has looked up the global object.
#[wasm_bindgen(js_namespace = performance, js_name = now)]
fn performance_now() -> f64;
}
const SUCCESS: i32 = 0;
const BADF: i32 = 8;
const INVAL: i32 = 28;
const SPIPE: i32 = 70;
thread_local! {
static LINES: RefCell<[Vec<u8>; 2]> = const { RefCell::new([Vec::new(), Vec::new()]) };
}
/// SAFETY (for every function here): libc passes addresses in this module's own linear
/// memory, sized as the WASI ABI says.
unsafe fn put<T>(at: i32, value: T) {
// SAFETY: caller guarantees `at` is a valid writable wasm32 linear-memory address for `T`.
unsafe { std::ptr::write_unaligned(at as usize as *mut T, value) }
}
#[unsafe(no_mangle)]
unsafe extern "C" fn __imported_wasi_snapshot_preview1_fd_write(fd: i32, iovs: i32, len: i32, written: i32) -> i32 {
if fd != 1 && fd != 2 {
return BADF;
}
let mut total = 0u32;
for i in 0..len.max(0) as usize {
// SAFETY: `iovs` holds `len` (pointer, length) pairs of u32.
let bytes = unsafe {
let iov = (iovs as usize as *const u32).add(i * 2);
std::slice::from_raw_parts(iov.read_unaligned() as usize as *const u8, iov.add(1).read_unaligned() as usize)
};
total += bytes.len() as u32;
LINES.with_borrow_mut(|lines| {
let line = &mut lines[(fd - 1) as usize];
for &b in bytes {
if b != b'\n' {
line.push(b);
continue;
}
let text = String::from_utf8_lossy(line).into_owned();
line.clear();
if fd == 1 {
web_sys::console::log_1(&text.into());
} else {
web_sys::console::error_1(&text.into());
}
}
});
}
// SAFETY: WASI `fd_write` ABI guarantees `written` points to a writable `u32` in linear memory.
unsafe { put(written, total) };
SUCCESS
}
#[unsafe(no_mangle)]
unsafe extern "C" fn __imported_wasi_snapshot_preview1_fd_close(_fd: i32) -> i32 {
BADF
}
#[unsafe(no_mangle)]
unsafe extern "C" fn __imported_wasi_snapshot_preview1_fd_seek(_fd: i32, _offset: i64, _whence: i32, _new: i32) -> i32 {
SPIPE
}
#[unsafe(no_mangle)]
unsafe extern "C" fn __imported_wasi_snapshot_preview1_fd_fdstat_get(fd: i32, stat: i32) -> i32 {
if !(0..=2).contains(&fd) {
return BADF;
}
// `fdstat`: a character device (2), no flags, every right.
// SAFETY: WASI `fd_fdstat_get` ABI guarantees `stat` points to a 24-byte writable `fdstat` struct in linear memory.
unsafe {
put::<[u8; 8]>(stat, [2, 0, 0, 0, 0, 0, 0, 0]);
put::<u64>(stat + 8, u64::MAX);
put::<u64>(stat + 16, u64::MAX);
}
SUCCESS
}
#[unsafe(no_mangle)]
unsafe extern "C" fn __imported_wasi_snapshot_preview1_environ_sizes_get(count: i32, size: i32) -> i32 {
// SAFETY: WASI `environ_sizes_get` ABI guarantees `count` and `size` point to writable `u32`s in linear memory.
unsafe {
put::<u32>(count, 0);
put::<u32>(size, 0);
}
SUCCESS
}
#[unsafe(no_mangle)]
unsafe extern "C" fn __imported_wasi_snapshot_preview1_environ_get(_environ: i32, _buf: i32) -> i32 {
SUCCESS
}
#[unsafe(no_mangle)]
unsafe extern "C" fn __imported_wasi_snapshot_preview1_clock_time_get(id: i32, _precision: i64, time: i32) -> i32 {
let ns = match id {
// The real-time clock: the wall clock.
0 => (js_sys::Date::now() * 1e6) as u64,
// Monotonic and CPU-time clocks: the page's monotonic clock.
1..=3 => (performance_now() * 1e6) as u64,
_ => return INVAL,
};
// SAFETY: WASI `clock_time_get` ABI guarantees `time` points to a writable `u64` in linear memory.
unsafe { put(time, ns) };
SUCCESS
}
#[unsafe(no_mangle)]
unsafe extern "C" fn __imported_wasi_snapshot_preview1_proc_exit(code: i32) -> ! {
web_sys::console::error_1(&format!("Luau runtime exited with code {code}").into());
std::process::abort()
}
}
#[cfg(feature = "wasi-allocator")]
mod allocator {
use std::alloc::{GlobalAlloc, Layout};
use std::ffi::c_void;
unsafe extern "C" {
fn posix_memalign(ptr: *mut *mut c_void, align: usize, size: usize) -> i32;
fn malloc(size: usize) -> *mut c_void;
fn realloc(ptr: *mut c_void, size: usize) -> *mut c_void;
fn free(ptr: *mut c_void);
}
/// WASI libc's `malloc` aligns to 16 bytes.
const MALLOC_ALIGN: usize = 16;
struct LibcAlloc;
// SAFETY: forwards to libc's allocator, which returns memory aligned as asked or null.
unsafe impl GlobalAlloc for LibcAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
if layout.align() <= MALLOC_ALIGN {
// SAFETY: `layout.size()` is non-zero per `GlobalAlloc::alloc` and WASI `malloc` guarantees `MALLOC_ALIGN` alignment.
return unsafe { malloc(layout.size()) }.cast();
}
let mut ptr = std::ptr::null_mut();
// SAFETY: `layout.align()` is a power of two > `MALLOC_ALIGN` (multiple of `size_of::<*mut c_void>()`) and `&mut ptr` is valid.
if unsafe { posix_memalign(&mut ptr, layout.align(), layout.size()) } != 0 {
return std::ptr::null_mut();
}
ptr.cast()
}
unsafe fn dealloc(&self, ptr: *mut u8, _: Layout) {
// SAFETY: `GlobalAlloc::dealloc` guarantees `ptr` came from `malloc` or `posix_memalign` and is no longer used.
unsafe { free(ptr.cast()) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
if layout.align() <= MALLOC_ALIGN {
// SAFETY: `ptr` came from `malloc` with alignment `<= MALLOC_ALIGN` and `new_size` is valid per `GlobalAlloc::realloc`.
return unsafe { realloc(ptr.cast(), new_size) }.cast();
}
// SAFETY: as `GlobalAlloc::realloc`'s default: allocate, copy, free.
unsafe {
let new = self.alloc(Layout::from_size_align_unchecked(new_size, layout.align()));
if !new.is_null() {
std::ptr::copy_nonoverlapping(ptr, new, layout.size().min(new_size));
self.dealloc(ptr, layout);
}
new
}
}
}
#[global_allocator]
static ALLOCATOR: LibcAlloc = LibcAlloc;
}
+129
View File
@@ -0,0 +1,129 @@
//! Work off the UI thread, and the handle that brings its result back to the script.
//!
//! Natively, [`spawn_blocking`] runs a job on a pool of four threads shared by every script,
//! started on first use; idle threads block and cost nothing. The web has no threads by default,
//! so there a job runs on the browser's main thread as a microtask, after the current frame's
//! work: keep web jobs short, and finish browser-async work (a `fetch`) from its own callback
//! through the [`Completer`] instead.
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use rune::Waker;
use crate::Data;
/// What a script shares with other threads: results waiting for the next poll, and the waker
/// that asks for that poll.
#[derive(Default)]
pub(crate) struct Shared {
dirty: AtomicBool,
completions: Mutex<Vec<(u64, Data)>>,
waker: Mutex<Option<Waker>>,
next_job: AtomicU64,
}
impl Shared {
pub(crate) fn set_waker(&self, waker: Waker) {
if let Ok(mut w) = self.waker.lock() {
*w = Some(waker);
}
}
/// Asks for a frame, so the next poll runs.
pub(crate) fn wake(&self) {
let waker = self.waker.lock().ok().and_then(|w| w.clone());
if let Some(waker) = waker {
waker();
}
}
pub(crate) fn mark(&self) {
self.dirty.store(true, Ordering::Release);
}
/// Whether anything arrived since the last call.
pub(crate) fn take_dirty(&self) -> bool {
self.dirty.swap(false, Ordering::AcqRel)
}
pub(crate) fn take_completions(&self) -> Vec<(u64, Data)> {
self.completions.lock().map(|mut c| std::mem::take(&mut *c)).unwrap_or_default()
}
pub(crate) fn job(self: &Arc<Self>) -> Completer {
Completer { id: self.next_job.fetch_add(1, Ordering::Relaxed) + 1, shared: self.clone(), done: false }
}
}
/// Finishes one call of a host async function: the task that called it resumes on the next poll
/// with the value given to [`Completer::complete`]. `Send`, so any thread can finish it.
/// Dropping it unfinished resumes the task with `nil`.
pub struct Completer {
pub(crate) id: u64,
shared: Arc<Shared>,
done: bool,
}
impl Completer {
pub fn complete(mut self, value: impl Into<Data>) {
self.finish(value.into());
}
fn finish(&mut self, value: Data) {
if std::mem::replace(&mut self.done, true) {
return;
}
if let Ok(mut c) = self.shared.completions.lock() {
c.push((self.id, value));
}
self.shared.mark();
self.shared.wake();
}
}
impl Drop for Completer {
fn drop(&mut self) {
self.finish(Data::Nil);
}
}
/// Runs `job` off the UI thread (natively) or after the current frame's work (on the web).
#[cfg(not(target_arch = "wasm32"))]
pub fn spawn_blocking(job: impl FnOnce() + Send + 'static) {
use std::sync::OnceLock;
use std::sync::mpsc::{Sender, channel};
type Job = Box<dyn FnOnce() + Send>;
static POOL: OnceLock<Mutex<Sender<Job>>> = OnceLock::new();
let pool = POOL.get_or_init(|| {
let (tx, rx) = channel::<Job>();
let rx = Arc::new(Mutex::new(rx));
for i in 0..4 {
let rx = rx.clone();
let spawned = std::thread::Builder::new().name(format!("rune-luau-worker-{i}")).spawn(move || {
loop {
let job = rx.lock().ok().and_then(|r| r.recv().ok());
match job {
Some(job) => job(),
None => break,
}
}
});
if spawned.is_err() {
break;
}
}
Mutex::new(tx)
});
let sent = pool.lock().map(|tx| tx.send(Box::new(job)));
if let Ok(Err(failed)) = sent {
(failed.0)();
}
}
/// Runs `job` off the UI thread (natively) or as `rune::task` work (on the web), where a job that
/// waits on the network doesn't hold the page.
#[cfg(target_arch = "wasm32")]
pub fn spawn_blocking(job: impl FnOnce() + Send + 'static) {
let _ = rune::task::spawn("rune-luau-worker", job);
}