- executor: coroutines on MoonBit's async intrinsics (%async.suspend / run / capture_cancellation / raise_cancellation_signal), scheduled by a Dispatcher trait (the platform hook) instead of core/async's event loop; works on wasm, wasm-gc, js and native. - Task[T]: wait (re-raises task errors), cancel (unwinds at the next suspension point, running defers; waiters get TaskCancelled), ready, try_result, detach. Executor: spawn, timer, sleep, yield_now, now. - TestDispatcher: deterministic FIFO queue and virtual clock with GPUI's advance_clock semantics (run, then step to each due timer). - app: AsyncApp, App::spawn, Context::spawn (weak handle), foreground/background executors, run_until_parked / advance_clock; App::new() owns a TestDispatcher unless given a dispatcher. - Tests ported/adapted from the scheduler crate; app async tests; the counter example gains a ticker task. Docs: M4 status and deviations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
585 lines
34 KiB
Markdown
585 lines
34 KiB
Markdown
# Porting GPUI to MoonBit
|
|
|
|
This document is the plan for porting [GPUI](https://github.com/zed-industries/zed/tree/main/crates/gpui)
|
|
(Zed's UI framework, Apache-2.0) to MoonBit. It covers how GPUI is built,
|
|
how its modules map to MoonBit packages, which parts are pure logic and which
|
|
are platform code, the backend strategy, where Rust idioms need a different
|
|
design, and an ordered roadmap.
|
|
|
|
Reference snapshot: `zed-industries/zed` @ `f98c2c100d21` (2026-11-24). The
|
|
`gpui` crate is about 98k lines of Rust. Platform code lives in sibling
|
|
crates: `gpui_platform`, `gpui_macos`, `gpui_linux`, `gpui_windows`,
|
|
`gpui_web`, `gpui_wgpu`, and `gpui_macros`.
|
|
|
|
---
|
|
|
|
## 1. GPUI architecture in one page
|
|
|
|
```mermaid
|
|
flowchart TD
|
|
App["App (entities, globals, effects, keymap, actions)"] --> Window
|
|
Window["Window (frame loop, focus, dispatch tree, element state)"] --> Element
|
|
Element["Element tree: div(), text, img, list ... (Styled + Interactive)"] --> Taffy["Layout (taffy flexbox/grid)"]
|
|
Element --> Scene["Scene (Quad, Shadow, Path, Underline, Sprites)"]
|
|
Window --> TextSystem["Text system (shape, wrap, glyph atlas)"]
|
|
Scene --> PlatformWindow
|
|
App --> Platform["Platform trait: windows, executors, clipboard, text system"]
|
|
Platform --> PlatformWindow["PlatformWindow: draw(scene), input callbacks"]
|
|
PlatformWindow --> Renderer["Renderer (Metal / wgpu / Blade)"]
|
|
```
|
|
|
|
**App, Context and Entity** (`app.rs`, `app/entity_map.rs`, `app/context.rs`)
|
|
- All state lives in *entities* owned by `App`. `EntityMap` stores
|
|
`Box<dyn Any>` values in a slot map. An `Entity<T>` is a refcounted, typed
|
|
handle (an id plus `PhantomData<T>`), and `WeakEntity<T>` is its weak form.
|
|
- `update_entity` *leases* the value: it removes it from the map, runs the
|
|
closure with `&mut T` and `&mut Context<T>`, and puts it back. A re-entrant
|
|
update of the same entity panics.
|
|
- `Context<T>` derefs to `App` and adds entity-scoped helpers: `notify`,
|
|
`emit`, `observe`, `subscribe`, `spawn`, `listener`, `on_release`, and the
|
|
`*_in(window)` variants.
|
|
- Side effects go through an `Effect` queue (`Notify`, `Emit`,
|
|
`RefreshWindows`, `NotifyGlobalObservers`, `Defer`, `EntityCreated`). The
|
|
queue is flushed when the outermost `App::update` returns.
|
|
- Subscriptions are `SubscriberSet`s. A callback that returns `false`
|
|
unsubscribes itself.
|
|
- Globals are a `TypeId → Box<dyn Any>` map.
|
|
- `notify` marks individual views dirty. During a draw, each window records
|
|
which entities it read (`AccessedEntities`).
|
|
|
|
**Window** (`window.rs`, 11k lines)
|
|
- `draw()` runs three phases over the root view's element tree:
|
|
1. `request_layout`, then compute layout with taffy.
|
|
2. `prepaint`: hitboxes, the dispatch tree, focus, and element state.
|
|
3. `paint`: emits primitives into the `Scene`.
|
|
- Frames are double-buffered (`rendered_frame` and `next_frame`).
|
|
- Cached views reuse their prepaint and paint *ranges* from the previous
|
|
frame (`Scene::replay`).
|
|
- Element state is keyed by `(GlobalElementId, TypeId)`.
|
|
|
|
**Element** (`element.rs`, `elements/*`)
|
|
- The `Element` trait has two associated state types,
|
|
`RequestLayoutState` and `PrepaintState`, and three phase methods.
|
|
- `AnyElement` is a type-erased element in an arena.
|
|
- `IntoElement`, `ParentElement`, `Render`/`RenderOnce`, `View`, and `AnyView`
|
|
build the tree.
|
|
- `div()` (5.9k lines) carries an `Interactivity`: a base
|
|
`StyleRefinement`, state styles (hover, active, focus, group), about 20
|
|
listener lists, scrolling, drag and drop, and tooltips.
|
|
|
|
**Style and layout** (`style.rs`, `styled.rs`, `taffy.rs`)
|
|
- `Style` is a CSS-like struct.
|
|
- `#[derive(Refineable)]` generates `StyleRefinement`, a copy of the struct
|
|
with every field optional.
|
|
- `Styled` provides hundreds of Tailwind-style builder methods. Most are
|
|
macro-generated (`gpui_macros::style_helpers!`).
|
|
- Layout is taffy 0.15 (flexbox, block, and grid), wrapped by
|
|
`TaffyLayoutEngine` with measured leaves (text) and a cache.
|
|
|
|
**Scene** (`scene.rs`, `bounds_tree.rs`)
|
|
- Per-kind primitive arrays. Each primitive gets a draw `order` from an
|
|
R-tree: one more than the highest overlapping order, unless the kinds may
|
|
share a level.
|
|
- Layers group primitives into one ordering unit.
|
|
- `finish()` sorts the arrays. `batches()` merges them into
|
|
`PrimitiveBatch`es for the renderer.
|
|
|
|
**Platform** (`platform.rs`, plus one crate per OS)
|
|
- `Platform` has about 90 methods: windows, executors, the text system,
|
|
clipboard, menus, and paths.
|
|
- `PlatformWindow` has about 100 methods: `draw(&Scene)`, input and resize
|
|
callbacks, and the IME handler.
|
|
- Other platform traits: `PlatformDispatcher` (runs tasks), `PlatformTextSystem`
|
|
(font ids, shaping via `layout_line`, glyph rasterization), and
|
|
`PlatformAtlas` (glyph, SVG, and image tiles).
|
|
- The `gpui_web` crate already targets the browser. It uses a `<canvas>`, the
|
|
`gpui_wgpu` renderer (WebGPU with a WebGL2 fallback), cosmic-text for text,
|
|
and DOM event translation. It has a hidden `<textarea>` for IME and a
|
|
`setTimeout`-based dispatcher.
|
|
|
|
**Text** (`text_system.rs`, `text_system/*`)
|
|
- Fonts → `FontId`. The platform shapes a line into a `LineLayout` (runs of
|
|
positioned glyphs).
|
|
- GPUI itself wraps lines (`LineWrapper`), caches layouts per frame, and
|
|
paints glyphs as sprites from the atlas.
|
|
|
|
**Input** (`action.rs`, `keymap*.rs`, `key_dispatch.rs`, `interactive.rs`)
|
|
- Actions are `dyn Action` values. They are registered globally with the
|
|
`inventory` crate and dispatched by `TypeId`.
|
|
- The keymap maps keystroke sequences and a context predicate (`"Editor &&
|
|
mode == full"`) to actions.
|
|
- The dispatch tree is rebuilt every frame. Key events are tried in this
|
|
order: key listeners, then keymap bindings, then action listeners (capture,
|
|
then bubble), then global listeners, then the IME input handler.
|
|
|
|
**Executors** (`executor.rs`, `platform_scheduler.rs`, the `scheduler` crate)
|
|
- `BackgroundExecutor` and `ForegroundExecutor` spawn futures and return a
|
|
`Task<T>`. Dropping the task cancels the work.
|
|
- `AsyncApp` is a weak handle to the app that can be held across `.await`.
|
|
|
|
---
|
|
|
|
## 2. Module map: GPUI to MoonBit packages
|
|
|
|
The module is `experiments/gpui` with sources under `src/`. Packages are
|
|
fine-grained, so pure logic can be tested on every backend and platform code
|
|
stays isolated.
|
|
|
|
| MoonBit package | GPUI source | Kind | Status |
|
|
| --- | --- | --- | --- |
|
|
| `geometry` | `geometry.rs`, `ContentMask` (window.rs) | pure | **done** |
|
|
| `color` | `color.rs`, `colors.rs` | pure | **done** (`colors.rs` theme defaults pending) |
|
|
| `scene` | `scene.rs`, `bounds_tree.rs`, `AtlasTile` (platform.rs) | pure | **done** (see deviations) |
|
|
| `font` | `Font`, `FontWeight`, `FontStyle`, `FontFeatures`, `FontFallbacks` (text_system.rs) | pure | **done** (descriptors only) |
|
|
| `style` | `style.rs`, `styled.rs`, Refineable, gpui_macros style helpers | pure | **done** (generated by `tools/gen_style.py`) |
|
|
| `layout` | `taffy.rs` (engine on `Milky2018/chicle`, a taffy port) | pure | **done** (no cross-frame node cache yet) |
|
|
| `keymap` | `keymap.rs`, `keymap/*`, `platform/keystroke.rs` | pure | planned |
|
|
| `action` | `action.rs` | pure | planned |
|
|
| `app` | `app.rs`, `app/entity_map.rs`, `app/context.rs`, `subscription.rs`, `global.rs` | pure | **done** (no windows, executors or actions yet) |
|
|
| `executor` | `executor.rs`, `scheduler` crate (`executor.rs`, `test_scheduler.rs`) | pure core + `Dispatcher` platform hook | **done** (single thread) |
|
|
| `element` | `element.rs`, `view.rs`, `elements/div.rs`, `interactive.rs` | pure | planned |
|
|
| `window` | `window.rs`, `key_dispatch.rs`, `tab_stop.rs` | pure (talks to platform traits) | planned |
|
|
| `text` | `text_system.rs`, `text_system/*` | mixed: wrapping/caching pure, shaping platform | planned |
|
|
| `platform` | `platform.rs` (traits only), `interactive.rs` input types | pure (interfaces) | planned |
|
|
| `platform/test` | `platform/test/*` | pure | planned: headless platform for tests |
|
|
| `platform/web` | `gpui_web` | **js only** | planned |
|
|
| `renderer/canvas2d` | (new) | **js only** | planned |
|
|
| `renderer/software` | (new; optional) | pure | candidate |
|
|
| `renderer/wgpu` | `gpui_wgpu` | native (+ js WebGPU) | later |
|
|
| `platform/native/*` | `gpui_macos`, `gpui_linux`, `gpui_windows` | native only | later |
|
|
| `examples/*` | `examples/*` | executables | `card` (headless, prints a scene report) |
|
|
| `elements/*` | `elements/{text,img,svg,list,uniform_list,anchored,deferred,canvas,animation}.rs` | pure | later |
|
|
|
|
A facade package (`experiments/gpui` re-exporting the common API, similar to
|
|
GPUI's `prelude.rs`) should come once there are enough packages to make
|
|
`@gpui.div()` worth having.
|
|
|
|
### What is pure logic and what is platform code
|
|
|
|
```mermaid
|
|
flowchart LR
|
|
subgraph pure["Pure MoonBit: every backend, unit-testable without a GPU"]
|
|
geometry --> color --> scene
|
|
geometry --> style --> layout
|
|
keymap --> action
|
|
app --> executor_core[executor core]
|
|
element --> window
|
|
text_wrap[text: wrapping, line cache]
|
|
end
|
|
subgraph platform["Platform-specific"]
|
|
web["platform/web: DOM events, rAF, canvas (js)"]
|
|
r2d["renderer/canvas2d (js)"]
|
|
shaping["text shaping + rasterization: canvas measureText or moon_cosmic"]
|
|
native["native windowing + wgpu (native)"]
|
|
end
|
|
window --> platform_traits[platform traits] --> web & native
|
|
scene --> r2d
|
|
```
|
|
|
|
Pure, portable, and testable without a GPU:
|
|
- Geometry, color, and style resolution.
|
|
- Flexbox and grid layout.
|
|
- The entity, context, subscription, and effect model.
|
|
- The executor queue logic, driven by a fake clock in tests (GPUI's
|
|
`TestScheduler` is the model).
|
|
- Keystroke parsing, the keymap and context predicates, and action dispatch.
|
|
- Scene building, ordering, and batching.
|
|
- Element trees, hit-testing, focus, and the dispatch tree.
|
|
- Line wrapping and truncation.
|
|
- The whole `Window::draw` pipeline against a test platform. Assertions run
|
|
on the resulting `Scene`.
|
|
|
|
Platform-specific:
|
|
- Window creation and the event loop (the browser `requestAnimationFrame` or a
|
|
native event loop).
|
|
- Input event translation and IME.
|
|
- The GPU or Canvas2D renderer.
|
|
- Font loading, shaping, and glyph rasterization. These can also be pure;
|
|
see the text system below.
|
|
- Clipboard, cursors, menus, and file dialogs.
|
|
|
|
---
|
|
|
|
## 3. Existing MoonBit packages (mooncakes.io survey, 2026-11-24)
|
|
|
|
The **Backends** column is what each package declares
|
|
(`supported_targets` or FFI); "all" means no restriction. The check column
|
|
records what I verified with toolchain `moon 0.1.20261119`.
|
|
|
|
| Need | Package | Backends | Notes |
|
|
| --- | --- | --- | --- |
|
|
| Flexbox/grid layout | `Milky2018/moon_taffy@0.5.3` | all (pure) | Port of taffy 0.5.2 (GPUI uses 0.15). **Does not compile on the current toolchain**: 32 errors in `style/style_json.mbt` from the new explicit trait-method `extend` rule. Needs an upstream fix or a vendored patch. |
|
|
| Flexbox/grid layout (used) | `Milky2018/chicle@0.6.3` | all (pure) | Successor of `moon_taffy` from the same upstream repository; builds on the current toolchain. **All 1,038 of `moon_taffy`'s taffy fixtures pass against it on all four backends** (`conformance/chicle`). |
|
|
| Flexbox (alt.) | `NoahLiu/yoga-mbt@0.1.1` | pure | Yoga-style flexbox only, with no grid. |
|
|
| Text shaping/layout | `Milky2018/moon_cosmic@0.3.9` | all (pure) | Port of cosmic-text on `moon_swash`, `moon_skrifa`, and `moon_zeno`. **Checks on js and native.** It is what `gpui_web`/`gpui_wgpu` use upstream (cosmic-text), so it fits well. |
|
|
| Font parsing | `Milky2018/moon_skrifa`, `mizchi/font`, `bikallem/freetype` | pure | |
|
|
| 2D rasterizer | `Milky2018/moon_zeno`, `TryAndRun-TvT/tiny-skia-moon` (wasm/wasm-gc only), `mizchi/canvas` (pure, PNG out) | mixed | For a pure software renderer and golden-image tests. |
|
|
| Unicode | `moonbit-community/unicode-segmentation`, `unicode-bidi`, `kawaz/grapheme`, `moonbit-community/unicodewidth` | pure | For word boundaries in the line wrapper and for grapheme-aware cursor movement. |
|
|
| Browser APIs | `mizchi/js_browser@0.13.0` (MIT), `dijdzv/websys`, `peter-jerry-ye/canvas` | **js only** | DOM, Canvas2D, events, and rAF. |
|
|
| WebGPU | `Milky2018/wgpu_mbt@0.16.2` | **native only** | wgpu-native C API bindings; macOS is supported, Linux and Windows are experimental. `tonyfettes/webgpu` and `emadurandal/rhodonite_webgpu` cover browser WebGPU. |
|
|
| Windowing | `Milky2018/window@0.6.2` (winit port, **native, macOS only**), `mizchi/glfw`, `klaseca/sdl`, `laplaceliu/tycho_window` (Xlib) | native only | |
|
|
| Async | `moonbitlang/async@0.22.10`, `moonbitlang/core/async` | native, wasm; js partly; **not wasm-gc** | Not used. Both own the event loop (`async fn main`, task groups), which conflicts with a platform-driven executor, and neither supports wasm-gc. `executor` uses the same compiler intrinsics (`%async.suspend`/`%async.run`) directly; see M4. |
|
|
| Taffy-free layout ref | `Frank-III/onebit-tui` | native | Uses Yoga through FFI. Not useful here. |
|
|
|
|
Recommendation: depend on `moon_cosmic` for text when that milestone
|
|
arrives. For layout, the original plan was to **fork/vendor `moon_taffy`** (Apache-2.0) and fix it for
|
|
the toolchain, or send the fix upstream. Writing flexbox from scratch would
|
|
be the costlier path.
|
|
|
|
---
|
|
|
|
## 4. Backend recommendation
|
|
|
|
**Primary target: `js` (browser)**, with a Canvas2D renderer first.
|
|
|
|
1. Browser rendering needs no native toolchain: the result is a `<canvas>`
|
|
and a page. The upstream `gpui_web` crate shows that GPUI's platform traits
|
|
fit the browser: rAF frames, DOM events, and a hidden textarea for IME.
|
|
2. Canvas2D can draw every GPUI primitive closely enough for a first
|
|
milestone:
|
|
- Rounded rectangles with borders: `roundRect`, `fill`, `stroke`.
|
|
- Box shadows: `shadowBlur`, `shadowColor`, then fill.
|
|
- Gradients: `createLinearGradient`.
|
|
- Paths: `Path2D` with the even-odd or non-zero fill rule.
|
|
- Underlines: lines, or a wavy path.
|
|
- Sprites: `drawImage` from an atlas canvas.
|
|
- Clipping: `clip()` to the content mask.
|
|
|
|
Text can either go through Canvas2D `fillText`, with `measureText`
|
|
implementing `PlatformTextSystem.layout_line`, or be shaped by
|
|
`moon_cosmic` and drawn as atlas sprites. The first is fastest to build;
|
|
the second gives identical results on every backend.
|
|
3. All pure packages run on `js` as well as on wasm-gc and native. We test
|
|
them on all four targets (`moon test --target all`; there is no CI yet), so the core stays
|
|
backend-neutral.
|
|
4. A **WebGPU renderer** on js (reusing GPUI's WGSL shaders from
|
|
`gpui_wgpu/shaders.wgsl`) and a **native** platform (`wgpu_mbt` plus a
|
|
windowing binding) can follow. They plug in behind the same
|
|
`Platform`/`PlatformWindow`/`Renderer` interfaces.
|
|
|
|
Alternative considered: wasm-gc in the browser. It is faster and smaller, but
|
|
the FFI to JavaScript is clumsier and the browser-binding packages target js.
|
|
We can revisit this once the js platform works; the pure core already
|
|
compiles for wasm-gc.
|
|
|
|
The `Platform` interface is a MoonBit trait, or a record of closures, holding
|
|
the **core subset**:
|
|
- `open_window`, `run`, `quit`
|
|
- Executor hooks: `dispatch`, `dispatch_after`, `now`
|
|
- `text_system`
|
|
- Clipboard read and write
|
|
- `set_cursor_style`
|
|
|
|
`PlatformWindow` likewise holds only the core:
|
|
- `bounds`, `scale_factor`, `mouse_position`, `modifiers`
|
|
- `draw(scene)`, `request_frame`
|
|
- `on_input`, `on_resize`, `on_request_frame`
|
|
- `set_input_handler`, `sprite_atlas`
|
|
|
|
The other roughly 150 methods (menus, tabs, thermal state, credentials, and
|
|
so on) are added only when an element needs them. Unsupported operations
|
|
**fail loudly**: `abort` or `raise`, never a silent no-op.
|
|
|
|
---
|
|
|
|
## 5. Rust idioms that need a different MoonBit design
|
|
|
|
| Rust in GPUI | Problem in MoonBit | Proposed design |
|
|
| --- | --- | --- |
|
|
| `Box<dyn Any>` + `TypeId` + downcast (entities, globals, events, actions, element state, drag payloads) | No `Any` or `TypeId` | **Typed keys created at registration**: `EntityKey[T]`, `GlobalKey[T]`, and `EventKey[E]` each wrap a unique `Int` and are allocated once per type (`let counter_key : GlobalKey[Counter] = GlobalKey::new("Counter")`). Storage is `Map[Int, Erased]`, where `Erased` is a closure-captured value. Typed access goes through a key whose type parameter fixes `T`, with a runtime id check that aborts on mismatch. Events are delivered to closures registered against an `EventKey[E]`, so no downcast is needed at the call site. |
|
|
| `Entity<T>` with `PhantomData<T>`, refcount via `Clone`/`Drop` | GC, no `Drop` | `Entity[T]` holds an id and a reference to a typed cell (`Ref[T]`). Typed access needs no map lookup, and the map holds only erased bookkeeping. **Liveness:** with a GC there is no drop hook, so release is explicit (`App::release(entity)` or the window owning its views), and release listeners run then. Subscriptions return a `Subscription` with `unsubscribe()`. Decide this early; see the design questions. |
|
|
| `Context<'a, T>` derefs to `&mut App`; leasing for `&mut T` | No lifetimes, no `Deref` | `Context[T]` is a struct `{ app : App, entity : Entity[T] }` passed by reference, with App methods duplicated or forwarded explicitly. Leasing is unnecessary for memory safety, but **keep the re-entrancy check** (abort on a nested `update` of the same entity) so behavior matches GPUI. |
|
|
| `trait Element { type RequestLayoutState; type PrepaintState; ... }` | No associated types | Elements keep per-frame state in **their own mutable fields**, set in `request_layout` and read in `prepaint` and `paint`; `div` already works this way. The trait becomes `trait Element { request_layout(Self, Window, App) -> LayoutId; prepaint(Self, Bounds, Window, App) -> Unit; paint(Self, Bounds, Window, App) -> Unit }`, and `AnyElement` is `&Element`. |
|
|
| `impl IntoElement` returns, `IntoElement::Element` | No RPIT, no associated types | `render` returns `AnyElement`. `IntoElement` becomes `into_any_element(Self) -> AnyElement`, implemented for `Div`, `String`, and so on. |
|
|
| `Along::Unit`, `Refineable::Refinement`, `VisualContext::Result<T>` | Associated types | Plain generic methods (as done in `geometry`), hand-written or generated `StyleRefinement`, and concrete return types. |
|
|
| `impl Mul<f32> for Pixels` (heterogeneous operators) | `Mul` is `Self * Self` | A separate `MulScalar` trait with `mul_scalar(Double)`, as done in `geometry`. `Pixels / Pixels -> f32` becomes `Pixels::ratio`. |
|
|
| Trait methods callable as methods | The current toolchain requires an explicit `extend` | Packages add `pub extend T with Trait::{method}` for ergonomic calls, or call `Trait::method(x)`. |
|
|
| Proc macros: `Refineable`, `style_helpers!` and 8 other style macros, `actions!`, `#[derive(Action)]`, `IntoElement`, `Render` | No macros | **Code generation**: a small generator script (kept in `tools/`) emits `styled_generated.mbt` and the refinement structs, and its output is committed. `actions!` becomes explicit `Action` impls, or one enum per namespace plus a `register_actions(registry)` call. |
|
|
| `inventory::submit!` global action registry | No link-time registration | Explicit `ActionRegistry::register(name, build)` at app start-up. |
|
|
| `async`/`await`, `AsyncFnOnce`, `Task<T>` cancels on drop, `!Send` executors | MoonBit async is young; `moonbitlang/async` is native-only | Single-threaded **foreground executor** built on a run queue and a timer heap, driven by the platform (`setTimeout`/rAF on js). `Task[T]` has an explicit `cancel()` and a `detach()`. The background executor starts as an alias of the foreground one on js. Use MoonBit `async fn` where the toolchain supports it on the target, and callbacks otherwise. A deterministic `TestScheduler` drives tests. |
|
|
| `Rc<RefCell<..>>` sharing (scroll handles, focus maps, text layouts) | No borrow checker needed | Plain mutable structs / `Ref[T]`. |
|
|
| Arenas for elements and events | GC | Ordinary allocation. |
|
|
| `#[repr(C)]` primitives with padding for GPU upload | No layout control | Clean MoonBit records. Each renderer packs into `FixedArray[Float]` or bytes explicitly. |
|
|
| `f32` everywhere | `Float` is emulated on js; `Double` is native everywhere | Logical units use `Double`. Converting to f32 is the renderer's job. |
|
|
| `SmallVec`, `SharedString`, `Arc<str>` | Not needed | `Array`, `String`. |
|
|
|
|
---
|
|
|
|
## 6. Roadmap
|
|
|
|
Each milestone is a vertical slice merged as its own PR with tests on all
|
|
backends. Pure milestones come first so most of GPUI can be tested headless
|
|
before any pixels appear.
|
|
|
|
```mermaid
|
|
gantt
|
|
dateFormat X
|
|
axisFormat %s
|
|
section Pure core
|
|
M0 geometry/color/scene :done, m0, 0, 1
|
|
M1 style + refinement + Styled :m1, after m0, 2
|
|
M2 layout (taffy) bridge :m2, after m1, 2
|
|
M3 app/entity/effects :m3, after m0, 2
|
|
M4 executor + test scheduler :m4, after m3, 1
|
|
M5 keymap/actions/keystrokes :m5, after m0, 1
|
|
M6 element/div/window draw :m6, after m2, 3
|
|
section Platform
|
|
M7 test platform + headless draw :m7, after m6, 1
|
|
M8 web platform + canvas2d :m8, after m7, 3
|
|
M9 text system :m9, after m8, 3
|
|
M10 input, focus, IME :m10, after m9, 2
|
|
M11 more elements :m11, after m10, 3
|
|
M12 wgpu / native :m12, after m11, 4
|
|
```
|
|
|
|
- **M0 (this PR).** `geometry`, `color`, and `scene`: units, rects, colors,
|
|
primitives, the bounds tree, layers, batching, and replay.
|
|
- **M1: style (done).**
|
|
- `Style`, `TextStyle`, `Fill`, `BoxShadow`, and the enums (`Display`,
|
|
`Position`, `Overflow`, flex and alignment enums, `Visibility`,
|
|
`CursorStyle`, `WhiteSpace`, and so on).
|
|
- `StyleRefinement` and `TextStyleRefinement` with `refine`.
|
|
- The `Styled` trait and the generated Tailwind helpers (`p_2`, `w_full`,
|
|
`rounded_md`, `shadow_lg`, ...).
|
|
- Tests: refinement cascade semantics, and helper values matching GPUI's
|
|
(for example `p_2 == rems(0.5)`).
|
|
- **M2: layout (done).**
|
|
- Depends on `Milky2018/chicle` (see decision 3).
|
|
- `LayoutEngine` with `request_layout`, `request_measured_layout`,
|
|
`compute_layout`, `layout_bounds`, and `stretch_auto_size_to_fill`.
|
|
- `Style` → engine conversion with rem resolution and device-pixel
|
|
snapping.
|
|
- Tests: GPUI's rounding and stroke-snapping tests, plus layout
|
|
scenarios. The engine is checked separately by the 1,038-fixture
|
|
conformance suite in `conformance/chicle`.
|
|
- **M3: app model (done).**
|
|
- `App`, `Entity[T]`/`WeakEntity[T]`/`Reservation[T]`, and `Context[T]`.
|
|
- `notify`, `observe`, `subscribe`/`emit` with typed `EventKey`s,
|
|
globals with `GlobalKey`s, release listeners, and `defer_call`.
|
|
- The effect queue and `flush_effects` semantics: deferred activation of
|
|
new subscriptions, dedup of notifications, and cascading effects.
|
|
- Tests: GPUI's subscription tests are ported, plus app-model tests,
|
|
including the aborts expected on misuse.
|
|
- `src/examples/counter` shows the model end to end.
|
|
- **M4: executor (done).**
|
|
- `Executor` (spawn, timer, sleep, yield_now, now), and `Task[T]` (wait,
|
|
cancel with unwinding, try_result, ready, detach).
|
|
- A `Dispatcher` trait as the platform hook, plus `TestDispatcher`, a
|
|
deterministic dispatcher with a virtual clock (`tick`,
|
|
`run_until_parked`, `advance_clock`, with GPUI's timer semantics).
|
|
- `AsyncApp`, `App::spawn`, `Context::spawn` (weak entity), and the
|
|
app's `foreground_executor`/`background_executor`.
|
|
- `App::new()` uses its own `TestDispatcher` (like GPUI's
|
|
`TestAppContext`); a platform passes its own dispatcher.
|
|
- **M5: input model.**
|
|
- `Keystroke::parse`, `Modifiers`.
|
|
- `KeyContext` and the predicate parser and evaluator.
|
|
- `Keymap::bindings_for_input` with precedence, `NoAction`, and pending
|
|
multi-stroke matching.
|
|
- `ActionRegistry`.
|
|
- Tests ported from `keymap.rs` and `keymap/context.rs`.
|
|
- **M6: elements and window.**
|
|
- `Element`/`AnyElement`/`IntoElement`/`ParentElement`, `Render`, and
|
|
views.
|
|
- `div` with styles, hover and active styles, mouse listeners, and
|
|
scrolling.
|
|
- `Window::draw` (request_layout → prepaint → paint), element ids and
|
|
state, hitboxes, the content-mask stack, and the dispatch tree.
|
|
- Tests: build a tree, draw against the test platform, assert on the
|
|
Scene.
|
|
- **M7: test platform.** A headless `Platform`/`PlatformWindow` that records
|
|
scenes and injects input events, mirroring GPUI's `TestPlatform` and
|
|
`VisualTestContext`. This is the base for most later tests.
|
|
- **M8: web platform + Canvas2D renderer (first pixels).**
|
|
- A `<canvas>` window, rAF-driven frames, resize, and DPR.
|
|
- DOM pointer, wheel, and key events → `PlatformInput`.
|
|
- Canvas2D drawing of every primitive kind.
|
|
- An example app (`examples/hello_world`, after GPUI's) served by a tiny
|
|
HTML page.
|
|
- **M9: text.**
|
|
- The `PlatformTextSystem` interface, `LineLayout`, `ShapedLine`, and
|
|
`WrappedLine`.
|
|
- The pure `LineWrapper` port.
|
|
- Shaping through `moon_cosmic` (pure) or Canvas `measureText` (decision
|
|
below).
|
|
- The glyph atlas and `MonochromeSprite` painting.
|
|
- Text elements: `StyledText` and `&str` children.
|
|
- **M10: interaction.**
|
|
- Focus handles and tab stops.
|
|
- Key dispatch through the keymap to actions.
|
|
- `InputHandler` with a hidden-textarea IME on the web.
|
|
- Clipboard.
|
|
- Drag and drop of typed payloads.
|
|
- **M11: elements.** `img` and `svg` (atlas `PolychromeSprite`), `list` and
|
|
`uniform_list`, `anchored`, `deferred`, `canvas`, `animation`, and
|
|
tooltips.
|
|
- **M12: GPU and native.**
|
|
- A WebGPU renderer on js reusing GPUI's WGSL, with tiled path rasterization
|
|
replacing the simplified `PaintedPath`.
|
|
- A native platform on `wgpu_mbt` plus a windowing binding (macOS first).
|
|
|
|
### Deviations already taken in M0
|
|
- `Pixels`, `ScaledPixels`, `Rems`, and colors are `Double`-based (GPUI:
|
|
`f32`). `Pixels::round` keeps Rust's round-half-away-from-zero on every
|
|
backend.
|
|
- `PaintedPath` stores flattened polygon contours. GPUI stores tiled paths
|
|
built with lyon, which is renderer-milestone work.
|
|
- Not yet ported:
|
|
- `PaintSurface` (macOS video surfaces).
|
|
- `PaintNativeView` (embedded native views).
|
|
- Sprite animations (`TimedTransformation`).
|
|
- `Scene::batches()` returns an `Array` rather than a lazy iterator.
|
|
- `Hsla::fade_out` returns a new color instead of mutating.
|
|
- `Bounds::extend` is `Bounds::extend_by`, because `extend` is a keyword.
|
|
- `Corners::corner` aborts for side-center anchors instead of panicking in
|
|
`unreachable!`; the behavior is the same, failing loudly.
|
|
|
|
---
|
|
|
|
### Deviations taken in M1 (style)
|
|
- `Style`, `TextStyle` and all nested refinements are immutable values.
|
|
`Style::refined` returns a new style. Only `StyleRefinement` (what
|
|
`Styled::style()` returns) is mutable, because it is the builder.
|
|
Nested updates are written as `style.text = { ..style.text, color: ... }`.
|
|
- `Styled` is one trait with 3,213 methods: 132 hand-written in
|
|
`src/style/styled.mbt`, the rest generated as GPUI's macros would generate
|
|
them. GPUI's `text_style()` accessor (`&mut TextStyleRefinement`) is
|
|
omitted.
|
|
- `impl Into<X>` parameters became trait objects: `&IntoLength`,
|
|
`&IntoDefiniteLength`, `&IntoAbsoluteLength`, `&IntoHsla`, and `&IntoFill`.
|
|
- `AlignSelf`, `JustifyContent`, and the other alias types are not separate
|
|
types. Fields use `AlignItems` and `AlignContent` directly.
|
|
- `combine_highlights` takes and returns `Array[HighlightRange]` rather than
|
|
iterators. Ranges covered by several highlights combine them in the order
|
|
the highlights were given; GPUI uses HashSet iteration order.
|
|
- The refinement `Cascade` and `Style::paint` (which needs `Window`) wait for
|
|
M6. The conversion to taffy styles waits for M2.
|
|
|
|
### Deviations taken in M2 (layout)
|
|
- There is no cross-frame node cache yet. GPUI reuses taffy nodes keyed by
|
|
element path, and reuses measure closures by key. That cache depends on
|
|
element ids from the Window, so it comes in M6. Until then the engine is
|
|
rebuilt on `clear()`, as older GPUI versions did.
|
|
- `compute_layout` takes the scale factor instead of `&mut Window`.
|
|
- Measure functions are `(known, available) -> Size[Pixels]` closures. They
|
|
do not receive GPUI's `final_layout` flag, because chicle's measure
|
|
callback does not report the run mode.
|
|
- The engine keeps its own parent/child maps, because chicle has no
|
|
`parent`/`children` queries. Misuse fails loudly: an unknown or stale
|
|
`LayoutId`, or a child given two parents, aborts.
|
|
|
|
### Deviations taken in M3 (app model)
|
|
- **Type keys replace `TypeId`.** Events and globals are identified by
|
|
`EventKey[E]` and `GlobalKey[G]` values, created once per type (usually a
|
|
top-level `let`). The app stores values under the key's id as closures
|
|
that write into the key's typed slot. Reading one back through the same
|
|
key is type-safe and needs no downcast.
|
|
- `EventEmitter<E>` (a compile-time check that `T` may emit `E`) has no
|
|
equivalent: any entity may emit any `EventKey`.
|
|
- **Entities are not reference counted.** A handle points at a typed cell.
|
|
`App::release(entity)` plays the role of the last handle being dropped:
|
|
- Weak handles stop upgrading at once.
|
|
- At the next flush, observers and subscriptions are removed and release
|
|
listeners run.
|
|
- Double release is a no-op.
|
|
- Use after release, re-entrant updates, reads during an update, and using
|
|
an entity with another `App` all abort, as GPUI panics.
|
|
- **Subscriptions do not end when dropped.** A `Subscription` stays active
|
|
until `unsubscribe()` is called, or until the entity it belongs to is
|
|
released. GPUI unsubscribes on drop; `detach()` is kept for parity.
|
|
- **Entity state is passed by reference.** Update callbacks receive the
|
|
state; entity types should be structs with `mut` fields (GPUI's `&mut T`).
|
|
- **Renames.**
|
|
- Entity creation is `App::new_entity`, because `App::new` creates the app.
|
|
- `cx.defer` is `defer_call`, because `defer` is a MoonBit keyword.
|
|
- `Context<T>` does not deref to `App`; use `cx.app`.
|
|
- **Top-level `App` methods open an update.** Methods such as `notify`,
|
|
`set_global`, `release` and `defer_call` flush their effects when called
|
|
outside an update.
|
|
- `global_mut` and `default_global` return the global to be mutated, so
|
|
they must be called inside `App::update`; outside one they abort.
|
|
- **Not yet ported:**
|
|
- `observe_new` (needs a per-type key for entities).
|
|
- Accessed-entity tracking and window invalidation (M6).
|
|
- `spawn` and `AsyncApp` (M4).
|
|
- Actions (M5).
|
|
- Leak detection.
|
|
|
|
### Deviations taken in M4 (executor)
|
|
- **Coroutines come from MoonBit's experimental async intrinsics.**
|
|
`%async.suspend`, `%async.run`, `%async.capture_cancellation`, and
|
|
`%async.raise_cancellation_signal` are scheduled by our own `Dispatcher`.
|
|
This is what `moonbitlang/core/async` is built on, minus its event loop.
|
|
It works on all four backends, including wasm-gc.
|
|
- The package must set `experimental: true`, and packages importing it
|
|
need `"allow-experimental-packages": true`.
|
|
- Risk: the intrinsics may change with the toolchain. They are wrapped in
|
|
`src/executor/coroutine.mbt`.
|
|
- **One thread.** Background and foreground executors are the same executor
|
|
on the main thread, as in GPUI's single-threaded web backend. There are no
|
|
priorities, dedicated threads, `block_on`, or `scoped`.
|
|
- **Tasks are not cancelled on drop.** A GPUI `Task` cancels its future when
|
|
dropped. Here a task runs to completion unless `cancel()` is called.
|
|
- Cancellation resumes the task with a cancellation signal at its next
|
|
suspension point, running its `defer` blocks.
|
|
- Waiters get `TaskCancelled`; errors raised by a task are re-raised by
|
|
`wait`.
|
|
- **Durations are integer milliseconds.** `now()` returns `Int64`
|
|
milliseconds.
|
|
- **The test dispatcher is FIFO and deterministic.** GPUI's `TestScheduler`
|
|
can randomize the interleaving of sessions with a seed. That is not ported.
|
|
There is also no parking detection.
|
|
- **`AsyncApp` methods return values, not `Result`s.** An app is never
|
|
dropped while a task references it.
|
|
|
|
## 7. Design decisions
|
|
|
|
Decided on 2026-11-24, following the recommendations below.
|
|
|
|
1. **Entity liveness without `Drop`.** Entities with release listeners or
|
|
observers are released explicitly. Views are released when their window
|
|
closes.
|
|
2. **Text shaping on the web.** Shape with `moon_cosmic`, which is pure, the
|
|
same on every backend, and matches upstream `gpui_web`, using bundled
|
|
fonts. Canvas text is used only as an emoji/CJK fallback, as upstream does.
|
|
3. **Layout engine.** The decision was to vendor `moon_taffy`, fix it, and
|
|
upstream the fixes. Revised in M2: upstream had already moved on and
|
|
published the fixed successor `Milky2018/chicle` 0.6.3. We depend on it
|
|
instead of forking. `moon_taffy`'s 1,038 taffy fixtures, which chicle no
|
|
longer ships, all pass against it. They are kept in `conformance/chicle`
|
|
and must be rerun before any chicle upgrade.
|
|
4. **First renderer.** Canvas2D on js first, then WebGPU reusing GPUI's WGSL
|
|
shaders.
|
|
5. **API surface naming.** Keep GPUI names verbatim (`div()`, `px()`,
|
|
`rems()`, `.flex().p_2().bg(...)`), so GPUI code ports mechanically.
|
|
6. **Module name.** `experiments/gpui` for now. Publishing to mooncakes
|
|
needs an owner namespace; revisit before the first release.
|
|
|
|
## 8. Toolchain notes (moon 0.1.20261119)
|
|
|
|
- Trait methods are callable with dot syntax only after an explicit
|
|
`pub extend Type with Trait::{m1, m2}`. A type parameter with several
|
|
bounds needs `Trait::method(x)`. This is why every `Styled` implementor
|
|
needs the generated `extend` list.
|
|
- Derives use `#derive(...)` before the declaration.
|
|
- `extend` is a keyword (so `Bounds::extend` became `Bounds::extend_by`), and
|
|
`try?` was removed.
|
|
- `moon fmt` migrates code to the newest syntax: it writes `impl T with fn m`
|
|
and turns `Int` into `Int32`. Generators must accept the formatted form.
|
|
Always run `python3 tools/gen_style.py && moon fmt` together.
|
|
- A value converts implicitly to a trait object (`&IntoLength`) at a call
|
|
site. That is how GPUI's `impl Into<Length>` parameters are expressed.
|
|
- `defer` is a keyword (GPUI's `cx.defer` became `defer_call`).
|
|
- Closures are not allowed to raise implicitly: `assert_*` cannot be called
|
|
inside a callback in a test. Record values and assert afterwards. A test
|
|
whose name starts with `panic` passes only if it aborts; use this to test
|
|
the fail-loudly paths.
|
|
- `test` is a keyword, so a binding cannot be named `test`. Trait-object
|
|
coercion does not reach inside tuples: build `(&Trait, ...)` values
|
|
separately.
|
|
- Async code: `async fn` bodies that never suspend get an "unused async"
|
|
warning; a plain `fn` closure is accepted where an `async` one is
|
|
expected. Closures that raise must say so (`fn() raise { ... }`).
|
|
- `Ref(x)` builds a `Ref`; `{ val: x }` needs a type annotation.
|
|
- Test-only imports go in `import { ... } for "test"` in `moon.pkg`.
|