Files
moon-gpui/docs/PORTING.md
T
SpriteandClaude Opus 5.5 8c0685fe01 Add porting plan and first pure slice: geometry, color, scene
docs/PORTING.md maps GPUI's architecture onto MoonBit packages, separates
pure logic from platform code, surveys mooncakes packages and their backends,
recommends a js + Canvas2D first backend behind a small Platform trait, lists
the Rust idioms that need a different design, and gives an ordered roadmap.

First slice (pure, tested on wasm, wasm-gc, js and native):
- geometry: Pixels/ScaledPixels/DevicePixels/Rems, Absolute/Definite/Length
  with parsing, Point/Size/Bounds/Edges/Corners, Anchor, Axis, ContentMask
- color: Rgba/Hsla with conversions, hex parsing, blending, Background
  (solid, linear gradient, patterns)
- scene: primitives (Quad, Shadow, Path, Underline, sprites), transformation
  matrix, BoundsTree draw ordering, layers, finish/batches, replay

Derived from Zed's GPUI (Apache-2.0); see LICENSE and NOTICE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 21:23:48 +00:00

453 lines
26 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) |
| `style` | `style.rs`, `styled.rs`, Refineable | pure | next |
| `layout` | `taffy.rs` (+ a taffy port) | pure | next |
| `keymap` | `keymap.rs`, `keymap/*`, `platform/keystroke.rs` | pure | planned |
| `action` | `action.rs` | pure | planned |
| `app` | `app.rs`, `app/*`, `subscription.rs`, `global.rs`, `gpui.rs` traits | pure | planned |
| `executor` | `executor.rs`, `platform_scheduler.rs`, `scheduler` crate | pure core + platform hooks | planned |
| `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 |
| `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 (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` | **native** (some wasm) | Not usable on js. Core has a `moonbitlang/core/async` package; its js story needs checking before the executor milestone. |
| 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, **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.**
- `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.**
- Vendor and fix `moon_taffy`, or port the taffy flexbox, block, and grid
algorithms needed.
- `LayoutEngine` with `request_layout`, `request_measured_layout`,
`compute_layout`, and `layout_bounds`, plus `Style` → taffy conversion
with rem and scale resolution.
- Tests: a corpus of flexbox cases (taffy's generated tests).
- **M3: app model.**
- `App`, `Entity[T]`/`WeakEntity[T]`, and `Context[T]`.
- `notify`, `observe`, `subscribe`/`emit` with typed event keys, globals,
and observers.
- The effect queue and `flush_effects` semantics: deferral, and dedup of
notifications.
- Tests ported from GPUI's `app` tests.
- **M4: executor.**
- Foreground executor, timers, and `Task[T]` (cancel and detach).
- `TestScheduler` with a virtual clock and `run_until_parked`.
- `spawn` from `Context`.
- **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.
---
## 7. Open design questions
1. **Entity liveness without `Drop`.** Should entities be released explicitly
(`release()`, or ownership through windows and views)? The alternative is
for strong handles to be ordinary GC references and drop GPUI's release
semantics (`on_release`, dropped-entity cleanup), which is simpler but
diverges. *Recommendation: explicit release for entities that have release
listeners or are observed, with views released when their window closes.*
2. **Text shaping on the web.** Shape with `moon_cosmic`, which is pure,
deterministic, the same on every backend, matches upstream `gpui_web`, and
needs bundled fonts. Or use browser Canvas `measureText`/`fillText`, which
gives system fonts and is quick to build, but has no glyph-level shaping
output and cannot be tested headless. *Recommendation: `moon_cosmic`, with
Canvas text only as an emoji/CJK fallback, as upstream does.*
3. **Layout engine.** Vendor and fix `moon_taffy` 0.5 (which needs toolchain
fixes, and whose API differs from taffy 0.15), or port taffy 0.15's
algorithms directly. *Recommendation: vendor `moon_taffy` now and upstream
the fixes.*
4. **First renderer.** Canvas2D on js (fastest to pixels), WebGPU on js
(closest to GPUI, reusing the WGSL shaders), or a pure software rasterizer
(golden-image tests on every backend). *Recommendation: Canvas2D first,
WebGPU second.*
5. **API surface naming.** Keep GPUI names verbatim where possible (`div()`,
`px()`, `rems()`, `.flex().p_2().bg(...)`), so Rust GPUI code ports
mechanically? *Recommendation: yes.*
6. **Module name.** `experiments/gpui` for now; publishing to mooncakes would
need an owner namespace.