- input: MouseExitEvent, ModifiersChangedEvent, PlatformInput, and DispatchEventResult. - platform: core Platform and PlatformWindow traits plus WindowId, WindowBounds, WindowOptions, WindowParams, and ClipboardItem. - window: Application, AnyWindowHandle, WindowHandle[V], Window::from_platform, dispatch_input, prevent_default, close/activation hooks, and replace_root_view while keeping standalone Window::new; closing a window releases its root view; hit-testing runs between prepaint and paint gated by pointer containment. - platform/test: TestPlatform, TestWindow (recording Scenes and simulating frames, input, resize, scale factor, active/hover status, and close), TestAppContext, and VisualTestContext with automatic frame pumping and a runaway-redraw guard. - Tests & example: platform tests, TestPlatform/VisualTestContext unit and panic-on-misuse tests, elements visual integration tests, and src/examples/card updated to run on TestAppContext/VisualTestContext. - Docs: updated docs/PORTING.md and README.md.
39 KiB
Porting GPUI to MoonBit
This document is the plan for porting 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
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.EntityMapstoresBox<dyn Any>values in a slot map. AnEntity<T>is a refcounted, typed handle (an id plusPhantomData<T>), andWeakEntity<T>is its weak form. update_entityleases the value: it removes it from the map, runs the closure with&mut Tand&mut Context<T>, and puts it back. A re-entrant update of the same entity panics.Context<T>derefs toAppand adds entity-scoped helpers:notify,emit,observe,subscribe,spawn,listener,on_release, and the*_in(window)variants.- Side effects go through an
Effectqueue (Notify,Emit,RefreshWindows,NotifyGlobalObservers,Defer,EntityCreated). The queue is flushed when the outermostApp::updatereturns. - Subscriptions are
SubscriberSets. A callback that returnsfalseunsubscribes itself. - Globals are a
TypeId → Box<dyn Any>map. notifymarks 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:request_layout, then compute layout with taffy.prepaint: hitboxes, the dispatch tree, focus, and element state.paint: emits primitives into theScene.
- Frames are double-buffered (
rendered_frameandnext_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
Elementtrait has two associated state types,RequestLayoutStateandPrepaintState, and three phase methods. AnyElementis a type-erased element in an arena.IntoElement,ParentElement,Render/RenderOnce,View, andAnyViewbuild the tree.div()(5.9k lines) carries anInteractivity: a baseStyleRefinement, 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)
Styleis a CSS-like struct.#[derive(Refineable)]generatesStyleRefinement, a copy of the struct with every field optional.Styledprovides 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
TaffyLayoutEnginewith measured leaves (text) and a cache.
Scene (scene.rs, bounds_tree.rs)
- Per-kind primitive arrays. Each primitive gets a draw
orderfrom 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 intoPrimitiveBatches for the renderer.
Platform (platform.rs, plus one crate per OS)
Platformhas about 90 methods: windows, executors, the text system, clipboard, menus, and paths.PlatformWindowhas about 100 methods:draw(&Scene), input and resize callbacks, and the IME handler.- Other platform traits:
PlatformDispatcher(runs tasks),PlatformTextSystem(font ids, shaping vialayout_line, glyph rasterization), andPlatformAtlas(glyph, SVG, and image tiles). - The
gpui_webcrate already targets the browser. It uses a<canvas>, thegpui_wgpurenderer (WebGPU with a WebGL2 fallback), cosmic-text for text, and DOM event translation. It has a hidden<textarea>for IME and asetTimeout-based dispatcher.
Text (text_system.rs, text_system/*)
- Fonts →
FontId. The platform shapes a line into aLineLayout(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 Actionvalues. They are registered globally with theinventorycrate and dispatched byTypeId. - 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)
BackgroundExecutorandForegroundExecutorspawn futures and return aTask<T>. Dropping the task cancels the work.AsyncAppis 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) |
input |
mouse/window input of interactive.rs, Modifiers, PlatformInput, DispatchEventResult |
pure | done (mouse/modifiers; keys in M5) |
window |
window.rs, element.rs, view.rs, Style::paint, Application, window handles |
pure | done (PlatformWindow-backed + standalone headless; no focus/keys/caching yet) |
elements |
elements/div.rs (+ Interactivity), elements/canvas.rs |
pure | done (div, canvas) |
text |
text_system.rs, text_system/* |
mixed: wrapping/caching pure, shaping platform | planned |
platform |
platform.rs (core traits, WindowId, WindowOptions, WindowParams, ClipboardItem) |
pure (interfaces) | done (core subset; text/atlas/IME/displays later) |
platform/test |
platform/test/*, app/test_context.rs (TestAppContext, VisualTestContext) |
pure | done |
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 | counter (M3–M4), card (headless on TestPlatform, prints a scene report) |
elements/* |
elements/{text,img,svg,list,uniform_list,anchored,deferred,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
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
TestScheduleris 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::drawpipeline against a test platform. Assertions run on the resultingScene.
Platform-specific:
- Window creation and the event loop (the browser
requestAnimationFrameor 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.
-
Browser rendering needs no native toolchain: the result is a
<canvas>and a page. The upstreamgpui_webcrate shows that GPUI's platform traits fit the browser: rAF frames, DOM events, and a hidden textarea for IME. -
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:
Path2Dwith the even-odd or non-zero fill rule. - Underlines: lines, or a wavy path.
- Sprites:
drawImagefrom an atlas canvas. - Clipping:
clip()to the content mask.
Text can either go through Canvas2D
fillText, withmeasureTextimplementingPlatformTextSystem.layout_line, or be shaped bymoon_cosmicand drawn as atlas sprites. The first is fastest to build; the second gives identical results on every backend. - Rounded rectangles with borders:
-
All pure packages run on
jsas 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. -
A WebGPU renderer on js (reusing GPUI's WGSL shaders from
gpui_wgpu/shaders.wgsl) and a native platform (wgpu_mbtplus a windowing binding) can follow. They plug in behind the samePlatform/PlatformWindow/Rendererinterfaces.
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,modifiersdraw(scene),request_frameon_input,on_resize,on_request_frameset_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.
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, andscene: 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).StyleRefinementandTextStyleRefinementwithrefine.- The
Styledtrait 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). LayoutEnginewithrequest_layout,request_measured_layout,compute_layout,layout_bounds, andstretch_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.
- Depends on
- M3: app model (done).
App,Entity[T]/WeakEntity[T]/Reservation[T], andContext[T].notify,observe,subscribe/emitwith typedEventKeys, globals withGlobalKeys, release listeners, anddefer_call.- The effect queue and
flush_effectssemantics: 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/countershows the model end to end.
- M4: executor (done).
Executor(spawn, timer, sleep, yield_now, now), andTask[T](wait, cancel with unwinding, try_result, ready, detach).- A
Dispatchertrait as the platform hook, plusTestDispatcher, 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'sforeground_executor/background_executor.App::new()uses its ownTestDispatcher(like GPUI'sTestAppContext); a platform passes its own dispatcher.
- M5: input model.
Keystroke::parse,Modifiers.KeyContextand the predicate parser and evaluator.Keymap::bindings_for_inputwith precedence,NoAction, and pending multi-stroke matching.ActionRegistry.- Tests ported from
keymap.rsandkeymap/context.rs.
- M6: elements and window (done).
Element/AnyElement/IntoElement,Render,AnyView, views as elements,listener, andempty.Window:draw(render, then layout to fill the viewport, prepaint, paint,Scene::finish) with phase checks, anddraw_if_dirty.- The content-mask, element-offset, opacity, and element-id stacks.
- Element state across frames (
ElementStateKey), hitboxes and hit testing, occlusion, and mouse dispatch (capture and bubble,stop_propagation). - Hover-driven and notify-driven invalidation, with only rendered views
invalidating the window, plus
resize.
- Painting:
paint_quadwith device-pixel snapping, drop and inset shadows,paint_path, andpaint_style(a port ofStyle::paint). div():- Styles through the generated
Styledlist, plus children and hover styles. - Mouse down, up, move and scroll listeners, and clicks (with element state).
occlude, overflow clipping, and opacity.
- Styles through the generated
canvas().- Tests: end-to-end views to scene, clicks, hover, invalidation, nested views, bubbling, occlusion, shadows and borders, clipping, canvas, resize, and the aborts expected on misuse.
- M7: test platform (done).
input:MouseExitEvent,ModifiersChangedEvent,PlatformInput, andDispatchEventResult.platform: corePlatformandPlatformWindowtraits plusWindowId,WindowBounds,WindowOptions,WindowParams, andClipboardItem(text subset).window:Application,AnyWindowHandle,WindowHandle[V],Window::dispatch_input,prevent_default, close/activation hooks,replace_root_view, andPlatformWindowcallback/frame wiring (keeping standaloneWindow::new). Closing a window releases its root view.platform/test:TestPlatformandTestWindow(recording presentedScenes and simulating frames, input, resize, scale factor, active/hover status, and close requests), plusTestAppContextandVisualTestContextwhich pump tasks and scheduled frames together with a runaway-redraw guard.- Tests: platform types,
TestPlatform/TestWindow/TestAppContextunit tests,elementsvisual integration tests (VisualTestContext), panic tests on closed-window misuse and runaway redraws, andsrc/examples/cardupdated to run onTestPlatform/VisualTestContext.
- 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.
- A
- M9: text.
- The
PlatformTextSysteminterface,LineLayout,ShapedLine, andWrappedLine. - The pure
LineWrapperport. - Shaping through
moon_cosmic(pure) or CanvasmeasureText(decision below). - The glyph atlas and
MonochromeSpritepainting. - Text elements:
StyledTextand&strchildren.
- The
- M10: interaction.
- Focus handles and tab stops.
- Key dispatch through the keymap to actions.
InputHandlerwith a hidden-textarea IME on the web.- Clipboard.
- Drag and drop of typed payloads.
- M11: elements.
imgandsvg(atlasPolychromeSprite),listanduniform_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_mbtplus a windowing binding (macOS first).
- A WebGPU renderer on js reusing GPUI's WGSL, with tiled path rasterization
replacing the simplified
Deviations already taken in M0
Pixels,ScaledPixels,Rems, and colors areDouble-based (GPUI:f32).Pixels::roundkeeps Rust's round-half-away-from-zero on every backend.PaintedPathstores 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 anArrayrather than a lazy iterator.Hsla::fade_outreturns a new color instead of mutating.Bounds::extendisBounds::extend_by, becauseextendis a keyword.Corners::corneraborts for side-center anchors instead of panicking inunreachable!; the behavior is the same, failing loudly.
Deviations taken in M1 (style)
Style,TextStyleand all nested refinements are immutable values.Style::refinedreturns a new style. OnlyStyleRefinement(whatStyled::style()returns) is mutable, because it is the builder. Nested updates are written asstyle.text = { ..style.text, color: ... }.Styledis one trait with 3,213 methods: 132 hand-written insrc/style/styled.mbt, the rest generated as GPUI's macros would generate them. GPUI'stext_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 useAlignItemsandAlignContentdirectly.combine_highlightstakes and returnsArray[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
CascadeandStyle::paint(which needsWindow) 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_layouttakes the scale factor instead of&mut Window.- Measure functions are
(known, available) -> Size[Pixels]closures. They do not receive GPUI'sfinal_layoutflag, because chicle's measure callback does not report the run mode. - The engine keeps its own parent/child maps, because chicle has no
parent/childrenqueries. Misuse fails loudly: an unknown or staleLayoutId, or a child given two parents, aborts.
Deviations taken in M3 (app model)
- Type keys replace
TypeId. Events and globals are identified byEventKey[E]andGlobalKey[G]values, created once per type (usually a top-levellet). 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 thatTmay emitE) has no equivalent: any entity may emit anyEventKey.
- 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
Appall abort, as GPUI panics.
- Subscriptions do not end when dropped. A
Subscriptionstays active untilunsubscribe()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
mutfields (GPUI's&mut T). - Renames.
- Entity creation is
App::new_entity, becauseApp::newcreates the app. cx.deferisdefer_call, becausedeferis a MoonBit keyword.Context<T>does not deref toApp; usecx.app.
- Entity creation is
- Top-level
Appmethods open an update. Methods such asnotify,set_global,releaseanddefer_callflush their effects when called outside an update.global_mutanddefault_globalreturn the global to be mutated, so they must be called insideApp::update; outside one they abort.
- Not yet ported:
observe_new(needs a per-type key for entities).- Accessed-entity tracking and window invalidation (M6).
spawnandAsyncApp(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_signalare scheduled by our ownDispatcher. This is whatmoonbitlang/core/asyncis 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.
- The package must set
- 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, orscoped. - Tasks are not cancelled on drop. A GPUI
Taskcancels its future when dropped. Here a task runs to completion unlesscancel()is called.- Cancellation resumes the task with a cancellation signal at its next
suspension point, running its
deferblocks. - Waiters get
TaskCancelled; errors raised by a task are re-raised bywait.
- Cancellation resumes the task with a cancellation signal at its next
suspension point, running its
- Durations are integer milliseconds.
now()returnsInt64milliseconds. - The test dispatcher is FIFO and deterministic. GPUI's
TestSchedulercan randomize the interleaving of sessions with a seed. That is not ported. There is also no parking detection. AsyncAppmethods return values, notResults. An app is never dropped while a task references it.
Deviations taken in M6 (elements and window)
- Element state lives in the element.
Elementhas no associated state types. Elements keep per-frame state in their own fields and are rebuilt every frame.renderreturnsAnyElement. - Element ids are strings, and state is keyed by
ElementStateKey[S](the same key pattern as globals).Div::idmakes a div stateful, andon_clickaborts without an id. There is no separateStateful<Div>type. - Hover styles apply at paint time only. Hovering cannot change layout. Any change in the hovered hitboxes marks the window dirty, not only for elements with hover styles.
- The window is headless. It is created directly with a viewport size,
scale factor, and rem size, and
drawreturns theScene. There is no platform window or frame scheduling yet (M7/M8). - Invalidation without accessed-entity tracking. A window re-renders when
a view it rendered in the last frame is notified, through
App::observe_notifications. There is no view caching orScene::replayreuse yet; every frame renders everything. - Quads are not split. GPUI splits bordered quads into a fill and border strips; that renderer optimization is not ported.
- Not yet ported:
- Focus and the key dispatch tree (M5/M10).
- Active and group styles.
- Drag and drop, tooltips, scroll state, and deferred draws.
- Text (M9).
Deviations taken in M7 (test platform)
- Core platform subset.
PlatformandPlatformWindowinclude window lifecycle, frame scheduling/drawing, input/resize/focus/hover callbacks, executor dispatcher, cursor style, clipboard, andopen_url. Text system, glyph atlas, IME, displays, menus, and screen capture come in later milestones. - Explicit
PlatformWindow::close. MoonBit has noDrop, so app-driven window teardown callsPlatformWindow::closeexplicitly (without re-invokingon_close). Closing aWindowreleases its root view (Design Decision 1). TestWindowdefaults toscale_factor = 1.0. Matches M6'sWindow::new(GPUI historically defaults to2.0), configurable viaTestPlatform::new(default_scale_factor=...)orWindowOptions.Applicationlives inwindow.Applicationowns theApp,Platform, and open windows soappstays independent ofplatform,scene, andstyle;application_for(app)looks it up via a privateGlobalKey.- Automatic frame pumping in tests.
TestAppContext::run_until_parked()alternates draining ready tasks onTestDispatcherwith pumping scheduled frames, aborting after 100 consecutive redraws to catch runaway redraw loops.
7. Design decisions
Decided on 2026-11-24, following the recommendations below.
- Entity liveness without
Drop. Entities with release listeners or observers are released explicitly. Views are released when their window closes. - Text shaping on the web. Shape with
moon_cosmic, which is pure, the same on every backend, and matches upstreamgpui_web, using bundled fonts. Canvas text is used only as an emoji/CJK fallback, as upstream does. - 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 successorMilky2018/chicle0.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 inconformance/chicleand must be rerun before any chicle upgrade. - First renderer. Canvas2D on js first, then WebGPU reusing GPUI's WGSL shaders.
- API surface naming. Keep GPUI names verbatim (
div(),px(),rems(),.flex().p_2().bg(...)), so GPUI code ports mechanically. - Module name.
experiments/gpuifor 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 needsTrait::method(x). This is why everyStyledimplementor needs the generatedextendlist. - Derives use
#derive(...)before the declaration. extendis a keyword (soBounds::extendbecameBounds::extend_by), andtry?was removed.moon fmtmigrates code to the newest syntax: it writesimpl T with fn mand turnsIntintoInt32. Generators must accept the formatted form. Always runpython3 tools/gen_style.py && moon fmttogether.- A value converts implicitly to a trait object (
&IntoLength) at a call site. That is how GPUI'simpl Into<Length>parameters are expressed. deferis a keyword (GPUI'scx.deferbecamedefer_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 withpanicpasses only if it aborts; use this to test the fail-loudly paths. testis a keyword, so a binding cannot be namedtest. Trait-object coercion does not reach inside tuples: build(&Trait, ...)values separately.- Async code:
async fnbodies that never suspend get an "unused async" warning; a plainfnclosure is accepted where anasyncone is expected. Closures that raise must say so (fn() raise { ... }). Ref(x)builds aRef;{ val: x }needs a type annotation.- Test-only imports go in
import { ... } for "test"inmoon.pkg. - Package import aliases in
moon.pkgwrite"path/to/pkg" @alias,(withoutas). - Tuple destructuring cannot annotate element types inside the pattern
(
let (a : T, b)); annotate the whole tuple or bind afterwards (let a : T = a).