Author SHA1 Message Date
nandiandClaude Opus 5.5 30bd8b86b2 Merge feat/geometry-color-scene into feat/window
CI / moon fmt, check, test (pull_request) Successful in 23s
The squash of M1 there is already contained here in unsquashed form, so this
keeps this branch's tree and adds only the CI workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:11:48 -08:00
nandiandClaude Opus 5.5 6d8389a97c ci: run moon fmt, check and test on pull requests
CI / moon fmt, check, test (pull_request) Successful in 17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:11:46 -08:00
nandi 73c67825b2 M7: test platform — Platform traits, Application, TestPlatform, VisualTestContext (#7) 2026-11-24 23:54:56 +00:00
SpriteandClaude Opus 5.5 fbe4c081e6 M6 elements and window: Element/Render/views, headless Window, div, canvas
- input: mouse events, modifiers, dispatch phases.
- window: Element / AnyElement / IntoElement, Render / AnyView (entities
  render as elements), listener(), empty(); Window with the draw cycle
  (render, layout to fill the viewport, prepaint, paint, finish) and phase
  checks; content-mask / element-offset / opacity / element-id stacks;
  element state across frames (ElementStateKey); hitboxes, hit testing,
  occlusion; mouse dispatch (capture + bubble, stop_propagation); hover-
  and notify-driven invalidation of rendered views; painting: paint_quad
  with device-pixel snapping, drop/inset shadows, paint_path, paint_style
  (port of Style::paint).
- elements: div() (Styled, children, hover, mouse down/up/move/scroll,
  clicks with element state, occlude, overflow clipping, opacity) and
  canvas(); Styled extend lists generated by tools/gen_style.py.
- app: observe_notifications hook used by windows.
- Tests: end-to-end views -> scene, clicks, hover, invalidation, nested
  views, bubbling, occlusion, shadows/borders/clipping, canvas, resize,
  and aborts on misuse. The card example now renders a real view and
  simulates hover and click.
- Docs: PORTING.md M6 status and deviations; README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:55:17 +00:00
SpriteandClaude Opus 5.5 eeab51348e M4 executors: coroutine executor, tasks, timers, test dispatcher, AsyncApp
- 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>
2026-11-24 22:36:23 +00:00
SpriteandClaude Opus 5.5 64bf747047 M3 app model: App, Entity, Context, subscriptions, events, globals
- app: port of GPUI's App effect cycle (update / flush_effects with
  deferred subscription activation and notification dedup), EntityMap
  (typed cells, leasing, explicit release), Context<T> (notify, emit,
  observe, subscribe, observe_self/subscribe_self, on_release,
  observe_release, observe_global, defer_call), SubscriberSet and
  Subscription.
- TypeId-keyed maps become EventKey[E] / GlobalKey[G]: values cross the
  app's untyped maps as closures writing into the key's typed slot.
- No Drop: App::release replaces the last-handle drop; subscriptions end
  with unsubscribe() or when their entity is released.
- Fail loudly on re-entrant updates, reads during updates, use after
  release, cross-app use, missing globals, global_mut outside an update.
- Tests: GPUI's subscription tests ported, plus app-model and panic tests.
- examples/counter; PORTING.md M3 status, deviations, toolchain notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 22:23:03 +00:00
nandi ae3fd7da55 M1: style — Style/StyleRefinement, generated Styled API, font, card example (#2) 2026-11-24 21:53:38 +00:00
58 changed files with 22122 additions and 227 deletions

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
name: CI
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
jobs:
moon:
name: moon fmt, check, test
runs-on: depot-ubuntu-24.04-4
# bookworm: glibc >= 2.34 is needed to link moon native tests; the image also provides
# node for actions/checkout and the js backend, and cc for the native backend.
container: node:20-bookworm
steps:
- uses: actions/checkout@v4
- name: Install MoonBit CLI
run: |
curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
echo "$HOME/.moon/bin" >> "$GITHUB_PATH"
- name: moon fmt --check, check, test
run: |
set -eu
moon version --all
moon update
moon fmt --check
moon check --target all
moon test --target all
+25 -8
View File
@@ -15,35 +15,52 @@ roadmap.
| `experiments/gpui/scene` | `scene.rs`, `bounds_tree.rs` | Ported (primitives, draw ordering, layers, batching, replay) | | `experiments/gpui/scene` | `scene.rs`, `bounds_tree.rs` | Ported (primitives, draw ordering, layers, batching, replay) |
| `experiments/gpui/font` | font descriptors in `text_system.rs` | Ported (`Font`, weights, styles, features, fallbacks) | | `experiments/gpui/font` | font descriptors in `text_system.rs` | Ported (`Font`, weights, styles, features, fallbacks) |
| `experiments/gpui/style` | `style.rs`, `styled.rs`, Refineable, gpui_macros style helpers | Ported (`Style`/`StyleRefinement`, the full `Styled` fluent API) | | `experiments/gpui/style` | `style.rs`, `styled.rs`, Refineable, gpui_macros style helpers | Ported (`Style`/`StyleRefinement`, the full `Styled` fluent API) |
| `experiments/gpui/app` | `app.rs`, `entity_map.rs`, `context.rs`, `subscription.rs` | Ported (entities, contexts, notify/observe, typed events and globals, effect flushing) |
| `experiments/gpui/executor` | `executor.rs`, `scheduler` crate | Ported (tasks, timers, cancellation, deterministic test dispatcher; single thread) |
| `experiments/gpui/input` | mouse/window input of `interactive.rs` | Ported (mouse events, modifiers, `PlatformInput`, `DispatchEventResult`) |
| `experiments/gpui/window` | `window.rs`, `element.rs`, `view.rs`, `app.rs` | Ported, headless (`Application`, `PlatformWindow` integration, frame lifecycle, views, hitboxes, mouse dispatch, painting) |
| `experiments/gpui/elements` | `elements/div.rs`, `elements/canvas.rs` | Ported (`div` with styles, hover, clicks and mouse listeners; `canvas`) |
| `experiments/gpui/layout` | `taffy.rs` | Ported on [`Milky2018/chicle`](https://mooncakes.io/docs/Milky2018/chicle) (flexbox, grid, block) | | `experiments/gpui/layout` | `taffy.rs` | Ported on [`Milky2018/chicle`](https://mooncakes.io/docs/Milky2018/chicle) (flexbox, grid, block) |
| `experiments/gpui/platform` | `platform.rs` | Ported (core `Platform`/`PlatformWindow` traits, window options/params, clipboard) |
| `experiments/gpui/platform/test` | `platform/test/*`, `app/test_context.rs` | Ported (`TestPlatform`, `TestWindow`, `TestAppContext`, `VisualTestContext`) |
## Example ## Example
Nothing renders yet. `src/examples/card` resolves a style written with Nothing is shown on screen yet (the renderer comes with M8). `src/examples/card`
GPUI's fluent API, lays the card and its (fake-measured) text out with the is a view rendering a `div()` card with GPUI's fluent API inside a
layout engine, paints it into a `Scene`, and prints the layout and the draw `TestPlatform` window; `VisualTestContext` simulates a hover and click while
batches: pumping frames automatically, and prints the scene's draw batches and quads:
```sh ```sh
moon run src/examples/card --target js moon run src/examples/card --target js
``` ```
```moonbit ```moonbit
@style.StyleRefinement::new() @elements.div()
.id("card")
.flex().flex_col().gap_2().p_4() .flex().flex_col().gap_2().p_4()
.w(@geometry.px(320.0)) .w(@geometry.px(320.0))
.rounded_lg().border_1().border_color(@color.rgb(0xd0d7de)) .rounded_lg().border_1().border_color(@color.rgb(0xd0d7de))
.bg(@color.rgb(0xffffff)).shadow_md() .bg(@color.rgb(0xffffff)).shadow_md()
.text_color(@color.rgb(0x1f2328)).text_sm() .hover(fn(style) { style.border_color(@color.rgb(0x0969da)) })
.on_click(@window.listener(cx, fn(card, _, _, cx) {
card.expanded = !card.expanded
cx.notify()
}))
``` ```
`src/examples/counter` shows the app model and executors: two entities
talking through notifications, a typed event and a global, and a task
ticking on a simulated clock (`moon run src/examples/counter --target js`).
The first example that renders in the browser comes with milestone M8; see The first example that renders in the browser comes with milestone M8; see
the roadmap. the roadmap.
## Generated code ## Generated code
`src/style/style_generated.mbt`, `styled_generated.mbt` and `src/style/style_generated.mbt`, `styled_generated.mbt`,
`styled_extend_generated.mbt` are generated by `tools/gen_style.py`, which `styled_extend_generated.mbt`, and the `*_styled_generated.mbt` files in
`src/elements` are generated by `tools/gen_style.py`, which
stands in for GPUI's Rust macros. Do not edit them by hand; change the stands in for GPUI's Rust macros. Do not edit them by hand; change the
script or `src/style/styled.mbt`, then run: script or `src/style/styled.mbt`, then run:
+200 -32
View File
@@ -135,20 +135,21 @@ stays isolated.
| `layout` | `taffy.rs` (engine on `Milky2018/chicle`, a taffy port) | pure | **done** (no cross-frame node cache yet) | | `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 | | `keymap` | `keymap.rs`, `keymap/*`, `platform/keystroke.rs` | pure | planned |
| `action` | `action.rs` | pure | planned | | `action` | `action.rs` | pure | planned |
| `app` | `app.rs`, `app/*`, `subscription.rs`, `global.rs`, `gpui.rs` traits | 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`, `platform_scheduler.rs`, `scheduler` crate | pure core + platform hooks | planned | | `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 | | `input` | mouse/window input of `interactive.rs`, `Modifiers`, `PlatformInput`, `DispatchEventResult` | pure | **done** (mouse/modifiers; keys in M5) |
| `window` | `window.rs`, `key_dispatch.rs`, `tab_stop.rs` | pure (talks to platform traits) | planned | | `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 | | `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` | `platform.rs` (core traits, `WindowId`, `WindowOptions`, `WindowParams`, `ClipboardItem`) | pure (interfaces) | **done** (core subset; text/atlas/IME/displays later) |
| `platform/test` | `platform/test/*` | pure | planned: headless platform for tests | | `platform/test` | `platform/test/*`, `app/test_context.rs` (`TestAppContext`, `VisualTestContext`) | pure | **done** |
| `platform/web` | `gpui_web` | **js only** | planned | | `platform/web` | `gpui_web` | **js only** | planned |
| `renderer/canvas2d` | (new) | **js only** | planned | | `renderer/canvas2d` | (new) | **js only** | planned |
| `renderer/software` | (new; optional) | pure | candidate | | `renderer/software` | (new; optional) | pure | candidate |
| `renderer/wgpu` | `gpui_wgpu` | native (+ js WebGPU) | later | | `renderer/wgpu` | `gpui_wgpu` | native (+ js WebGPU) | later |
| `platform/native/*` | `gpui_macos`, `gpui_linux`, `gpui_windows` | native only | later | | `platform/native/*` | `gpui_macos`, `gpui_linux`, `gpui_windows` | native only | later |
| `examples/*` | `examples/*` | executables | `card` (headless, prints a scene report) | | `examples/*` | `examples/*` | executables | `counter` (M3–M4), `card` (headless on `TestPlatform`, prints a scene report) |
| `elements/*` | `elements/{text,img,svg,list,uniform_list,anchored,deferred,canvas,animation}.rs` | pure | later | | `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 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's `prelude.rs`) should come once there are enough packages to make
@@ -218,7 +219,7 @@ records what I verified with toolchain `moon 0.1.20261119`.
| Browser APIs | `mizchi/js_browser@0.13.0` (MIT), `dijdzv/websys`, `peter-jerry-ye/canvas` | **js only** | DOM, Canvas2D, events, and rAF. | | 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. | | 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 | | | 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. | | 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. | | 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 Recommendation: depend on `moon_cosmic` for text when that milestone
@@ -352,17 +353,25 @@ gantt
- Tests: GPUI's rounding and stroke-snapping tests, plus layout - Tests: GPUI's rounding and stroke-snapping tests, plus layout
scenarios. The engine is checked separately by the 1,038-fixture scenarios. The engine is checked separately by the 1,038-fixture
conformance suite in `conformance/chicle`. conformance suite in `conformance/chicle`.
- **M3: app model.** - **M3: app model (done).**
- `App`, `Entity[T]`/`WeakEntity[T]`, and `Context[T]`. - `App`, `Entity[T]`/`WeakEntity[T]`/`Reservation[T]`, and `Context[T]`.
- `notify`, `observe`, `subscribe`/`emit` with typed event keys, globals, - `notify`, `observe`, `subscribe`/`emit` with typed `EventKey`s,
and observers. globals with `GlobalKey`s, release listeners, and `defer_call`.
- The effect queue and `flush_effects` semantics: deferral, and dedup of - The effect queue and `flush_effects` semantics: deferred activation of
notifications. new subscriptions, dedup of notifications, and cascading effects.
- Tests ported from GPUI's `app` tests. - Tests: GPUI's subscription tests are ported, plus app-model tests,
- **M4: executor.** including the aborts expected on misuse.
- Foreground executor, timers, and `Task[T]` (cancel and detach). - `src/examples/counter` shows the model end to end.
- `TestScheduler` with a virtual clock and `run_until_parked`. - **M4: executor (done).**
- `spawn` from `Context`. - `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.** - **M5: input model.**
- `Keystroke::parse`, `Modifiers`. - `Keystroke::parse`, `Modifiers`.
- `KeyContext` and the predicate parser and evaluator. - `KeyContext` and the predicate parser and evaluator.
@@ -370,18 +379,49 @@ gantt
multi-stroke matching. multi-stroke matching.
- `ActionRegistry`. - `ActionRegistry`.
- Tests ported from `keymap.rs` and `keymap/context.rs`. - Tests ported from `keymap.rs` and `keymap/context.rs`.
- **M6: elements and window.** - **M6: elements and window (done).**
- `Element`/`AnyElement`/`IntoElement`/`ParentElement`, `Render`, and - `Element`/`AnyElement`/`IntoElement`, `Render`, `AnyView`, views as
views. elements, `listener`, and `empty`.
- `div` with styles, hover and active styles, mouse listeners, and - `Window`:
scrolling. - `draw` (render, then layout to fill the viewport, prepaint, paint,
- `Window::draw` (request_layout → prepaint → paint), element ids and `Scene::finish`) with phase checks, and `draw_if_dirty`.
state, hitboxes, the content-mask stack, and the dispatch tree. - The content-mask, element-offset, opacity, and element-id stacks.
- Tests: build a tree, draw against the test platform, assert on the - Element state across frames (`ElementStateKey`), hitboxes and hit
Scene. testing, occlusion, and mouse dispatch (capture and bubble,
- **M7: test platform.** A headless `Platform`/`PlatformWindow` that records `stop_propagation`).
scenes and injects input events, mirroring GPUI's `TestPlatform` and - Hover-driven and notify-driven invalidation, with only rendered views
`VisualTestContext`. This is the base for most later tests. invalidating the window, plus `resize`.
- Painting: `paint_quad` with device-pixel snapping, drop and inset
shadows, `paint_path`, and `paint_style` (a port of `Style::paint`).
- `div()`:
- Styles through the generated `Styled` list, plus children and hover
styles.
- Mouse down, up, move and scroll listeners, and clicks (with element
state).
- `occlude`, overflow clipping, and opacity.
- `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`, and
`DispatchEventResult`.
- `platform`: core `Platform` and `PlatformWindow` traits plus `WindowId`,
`WindowBounds`, `WindowOptions`, `WindowParams`, and `ClipboardItem`
(text subset).
- `window`: `Application`, `AnyWindowHandle`, `WindowHandle[V]`,
`Window::dispatch_input`, `prevent_default`, close/activation hooks,
`replace_root_view`, and `PlatformWindow` callback/frame wiring (keeping
standalone `Window::new`). Closing a window releases its root view.
- `platform/test`: `TestPlatform` and `TestWindow` (recording presented
`Scene`s and simulating frames, input, resize, scale factor, active/hover
status, and close requests), plus `TestAppContext` and `VisualTestContext`
which pump tasks and scheduled frames together with a runaway-redraw
guard.
- Tests: platform types, `TestPlatform`/`TestWindow`/`TestAppContext` unit
tests, `elements` visual integration tests (`VisualTestContext`), panic
tests on closed-window misuse and runaway redraws, and `src/examples/card`
updated to run on `TestPlatform`/`VisualTestContext`.
- **M8: web platform + Canvas2D renderer (first pixels).** - **M8: web platform + Canvas2D renderer (first pixels).**
- A `<canvas>` window, rAF-driven frames, resize, and DPR. - A `<canvas>` window, rAF-driven frames, resize, and DPR.
- DOM pointer, wheel, and key events → `PlatformInput`. - DOM pointer, wheel, and key events → `PlatformInput`.
@@ -460,6 +500,117 @@ gantt
`parent`/`children` queries. Misuse fails loudly: an unknown or stale `parent`/`children` queries. Misuse fails loudly: an unknown or stale
`LayoutId`, or a child given two parents, aborts. `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.
### Deviations taken in M6 (elements and window)
- **Element state lives in the element.** `Element` has no associated state
types. Elements keep per-frame state in their own fields and are rebuilt
every frame. `render` returns `AnyElement`.
- **Element ids are strings, and state is keyed by `ElementStateKey[S]`**
(the same key pattern as globals). `Div::id` makes a div stateful, and
`on_click` aborts without an id. There is no separate `Stateful<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 `draw` returns the `Scene`. 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 or `Scene::replay`
reuse 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.** `Platform` and `PlatformWindow` include window
lifecycle, frame scheduling/drawing, input/resize/focus/hover callbacks,
executor dispatcher, cursor style, clipboard, and `open_url`. Text
system, glyph atlas, IME, displays, menus, and screen capture come in
later milestones.
- **Explicit `PlatformWindow::close`.** MoonBit has no `Drop`, so
app-driven window teardown calls `PlatformWindow::close` explicitly (without
re-invoking `on_close`). Closing a `Window` releases its root view
(Design Decision 1).
- **`TestWindow` defaults to `scale_factor = 1.0`.** Matches M6's
`Window::new` (GPUI historically defaults to `2.0`), configurable via
`TestPlatform::new(default_scale_factor=...)` or `WindowOptions`.
- **`Application` lives in `window`.** `Application` owns the `App`,
`Platform`, and open windows so `app` stays independent of `platform`,
`scene`, and `style`; `application_for(app)` looks it up via a private
`GlobalKey`.
- **Automatic frame pumping in tests.** `TestAppContext::run_until_parked()`
alternates draining ready tasks on `TestDispatcher` with pumping scheduled
frames, aborting after 100 consecutive redraws to catch runaway redraw
loops.
## 7. Design decisions ## 7. Design decisions
Decided on 2026-11-24, following the recommendations below. Decided on 2026-11-24, following the recommendations below.
@@ -497,4 +648,21 @@ Decided on 2026-11-24, following the recommendations below.
Always run `python3 tools/gen_style.py && moon fmt` together. Always run `python3 tools/gen_style.py && moon fmt` together.
- A value converts implicitly to a trait object (`&IntoLength`) at a call - A value converts implicitly to a trait object (`&IntoLength`) at a call
site. That is how GPUI's `impl Into<Length>` parameters are expressed. 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`. - Test-only imports go in `import { ... } for "test"` in `moon.pkg`.
- Package import aliases in `moon.pkg` write `"path/to/pkg" @alias,` (without
`as`).
- Tuple destructuring cannot annotate element types inside the pattern
(`let (a : T, b)`); annotate the whole tuple or bind afterwards
(`let a : T = a`).
+521
View File
@@ -0,0 +1,521 @@
// The application state and effect cycle, ported from gpui/src/app.rs.
//
// All state lives in entities owned by the `App`. Updates run inside
// `App::update`; side effects (notifications, events, global changes,
// deferred callbacks, releases) are queued and flushed when the outermost
// update returns, exactly like GPUI's `flush_effects`.
//
// Not ported yet: windows and view invalidation (M6), executors and `spawn`
// (M4), actions and keymaps (M5), `observe_new` (needs a per-type key for
// entities), and the platform services.
///|
let next_app_id : Ref[Int32] = { val: 0, }
///|
priv enum Effect {
Notify(EntityId)
Emit(emitter~ : EntityId, event_key~ : Int32, payload~ : () -> Unit)
NotifyGlobalObservers(Int32)
Defer((App) -> Unit)
}
///|
/// A typed event listener stored without its type: `handler` reads the
/// payload back through the listener's own `EventKey`.
priv struct EventListener {
event_key : Int32
handler : (() -> Unit, App) -> Bool
}
///|
priv struct EntityRecord {
/// Drops the state once release listeners have run.
free : () -> Unit
}
///|
/// The application: owner of all entities and globals (GPUI: `App`).
pub struct App {
priv id : Int32
priv mut next_entity_id : Int32
priv entities : Map[EntityId, EntityRecord]
priv mut pending_updates : Int32
priv mut flushing_effects : Bool
priv pending_effects : @deque.Deque[Effect]
priv pending_notifications : @hashset.HashSet[EntityId]
priv pending_global_notifications : @hashset.HashSet[Int32]
priv dropped_entities : Array[EntityId]
priv observers : SubscriberSet[EntityId, (App) -> Bool]
priv event_listeners : SubscriberSet[EntityId, EventListener]
priv release_listeners : SubscriberSet[EntityId, (App) -> Unit]
priv global_observers : SubscriberSet[Int32, (App) -> Bool]
priv globals : Map[Int32, () -> Unit]
/// Called synchronously by `notify` (windows invalidate views with it).
priv notify_hooks : SubscriberSet[Unit, (EntityId) -> Unit]
priv executor : @executor.Executor
/// Set when the app drives its own deterministic dispatcher (tests).
priv test_dispatcher : @executor.TestDispatcher?
}
///|
/// A new, empty application. GPUI creates its `App` through `Application`
/// with a platform; there is no platform layer yet (M7/M8).
///
/// Async work runs on `dispatcher`. Without one, the app gets a
/// deterministic `TestDispatcher` that runs nothing until driven with
/// `run_until_parked` or `advance_clock` (like GPUI's `TestAppContext`).
pub fn App::new(dispatcher? : &@executor.Dispatcher) -> App {
let id = next_app_id.val
next_app_id.val = id + 1
let test_dispatcher = match dispatcher {
Some(_) => None
None => Some(@executor.TestDispatcher::new())
}
let executor = match (dispatcher, test_dispatcher) {
(Some(dispatcher), _) => @executor.Executor::new(dispatcher)
(None, Some(own)) => @executor.Executor::new(own)
(None, None) => abort("unreachable")
}
{
executor,
test_dispatcher,
id,
next_entity_id: 1,
entities: {},
pending_updates: 0,
flushing_effects: false,
pending_effects: @deque.Deque([]),
pending_notifications: @hashset.HashSet([]),
pending_global_notifications: @hashset.HashSet([]),
dropped_entities: [],
observers: SubscriberSet::new(),
event_listeners: SubscriberSet::new(),
release_listeners: SubscriberSet::new(),
global_observers: SubscriberSet::new(),
globals: {},
notify_hooks: SubscriberSet::new(),
}
}
///|
/// Runs `f`; queued effects are flushed when the outermost update returns.
pub fn[R] App::update(self : App, f : (App) -> R) -> R {
self.pending_updates = self.pending_updates + 1
let result = f(self)
if self.pending_updates == 1 && !self.flushing_effects {
self.flush_effects()
}
self.pending_updates = self.pending_updates - 1
result
}
///|
fn App::push_effect(self : App, effect : Effect) -> Unit {
match effect {
Notify(emitter) =>
if !self.pending_notifications.add_and_check(emitter) {
return
}
NotifyGlobalObservers(key) =>
if !self.pending_global_notifications.add_and_check(key) {
return
}
_ => ()
}
self.pending_effects.push_back(effect)
}
///|
/// Applies queued effects until none remain (GPUI: `flush_effects`).
fn App::flush_effects(self : App) -> Unit {
self.flushing_effects = true
while true {
self.release_dropped_entities()
match self.pending_effects.pop_front() {
Some(Notify(emitter)) => {
self.pending_notifications.remove(emitter)
self.observers.retain(emitter, fn(handler) { handler(self) })
}
Some(Emit(emitter~, event_key~, payload~)) =>
self.event_listeners.retain(emitter, fn(listener) {
if listener.event_key == event_key {
(listener.handler)(payload, self)
} else {
true
}
})
Some(NotifyGlobalObservers(key)) => {
self.pending_global_notifications.remove(key)
self.global_observers.retain(key, fn(observer) { observer(self) })
}
Some(Defer(callback)) => callback(self)
None => if self.dropped_entities.is_empty() { break }
}
}
self.flushing_effects = false
}
///|
/// Removes released entities' observers and subscriptions, then runs their
/// release listeners (GPUI: `release_dropped_entities`).
fn App::release_dropped_entities(self : App) -> Unit {
while !self.dropped_entities.is_empty() {
let dropped = self.dropped_entities.copy()
self.dropped_entities.clear()
for entity_id in dropped {
ignore(self.observers.remove(entity_id))
ignore(self.event_listeners.remove(entity_id))
for callback in self.release_listeners.remove(entity_id) {
callback(self)
}
if self.entities.get(entity_id) is Some(record) {
(record.free)()
self.entities.remove(entity_id)
}
}
}
}
///|
/// Queues `f` to run after the current effects (GPUI: `App::defer`;
/// renamed because `defer` is a MoonBit keyword).
pub fn App::defer_call(self : App, f : (App) -> Unit) -> Unit {
self.update(fn(app) { app.push_effect(Defer(f)) })
}
// ---------------------------------------------------------------------------
// Entities
// ---------------------------------------------------------------------------
///|
/// Hands out an id for an entity whose state is created later with
/// `insert_entity` (GPUI: `reserve_entity`).
pub fn[T] App::reserve_entity(self : App) -> Reservation[T] {
let id = EntityId(self.next_entity_id)
self.next_entity_id = self.next_entity_id + 1
{
cell: { app_id: self.id, id, value: None, leased: false, released: false, },
}
}
///|
/// Builds the state of a reserved entity (GPUI: `insert_entity`).
pub fn[T] App::insert_entity(
self : App,
reservation : Reservation[T],
build : (Context[T]) -> T,
) -> Entity[T] {
let cell = reservation.cell
cell.check_app(self, "insert")
guard cell.value is None && !self.entities.contains(cell.id) else {
abort("cannot insert \{cell.id}: the reservation was already used")
}
self.update(fn(app) {
let value = build({ app, weak: { cell, }, })
cell.value = Some(value)
app.entities[cell.id] = { free: fn() { cell.value = None }, }
{ cell, }
})
}
///|
/// Creates an entity whose state is built by `build` (GPUI: `App::new`;
/// renamed because `App::new` is the app's constructor here).
pub fn[T] App::new_entity(self : App, build : (Context[T]) -> T) -> Entity[T] {
self.insert_entity(self.reserve_entity(), build)
}
///|
/// Updates an entity's state; effects flush afterwards
/// (GPUI: `update_entity`). Fails loudly if the entity is already being
/// updated or has been released.
pub fn[T, R] App::update_entity(
self : App,
entity : Entity[T],
f : (T, Context[T]) -> R,
) -> R {
let cell = entity.cell
cell.check_app(self, "update")
self.update(fn(app) {
let value = cell.lease("update")
let result = f(value, { app, weak: { cell, }, })
cell.end_lease()
result
})
}
///|
/// Reads an entity's state (GPUI: `read_entity`). The state must not be
/// mutated through the returned value.
pub fn[T] App::read_entity(self : App, entity : Entity[T]) -> T {
entity.cell.check_app(self, "read")
entity.cell.read()
}
///|
/// Releases an entity: its observers and subscriptions are removed and its
/// release listeners run during the next effect flush. Weak handles stop
/// upgrading immediately. Releasing twice is a no-op.
pub fn[T] App::release(self : App, entity : Entity[T]) -> Unit {
let cell = entity.cell
cell.check_app(self, "release")
guard !cell.released else { return }
guard !cell.leased else {
abort("cannot release \{cell.id} while it is being updated")
}
cell.released = true
self.update(fn(app) { app.dropped_entities.push(cell.id) })
}
///|
/// Number of live (inserted, not yet released) entities.
pub fn App::entity_count(self : App) -> Int32 {
self.entities.length()
}
///|
/// Marks an entity as changed: its observers run during the next flush
/// (GPUI: `App::notify`). Repeated notifications before the flush coalesce.
/// Notification hooks (windows rendering the entity) run immediately.
pub fn App::notify(self : App, entity_id : EntityId) -> Unit {
self.notify_hooks.retain((), fn(hook) {
hook(entity_id)
true
})
self.update(fn(app) { app.push_effect(Notify(entity_id)) })
}
///|
/// Calls `hook` synchronously whenever any entity is notified. Used by
/// windows to invalidate the views they rendered (GPUI keeps per-window
/// invalidators for this).
pub fn App::observe_notifications(
self : App,
hook : (EntityId) -> Unit,
) -> Subscription {
self.notify_hooks.insert((), hook)
}
///|
fn[T] App::emit_event(
self : App,
emitter : EntityId,
key : EventKey[T],
event : T,
) -> Unit {
self.update(fn(app) {
app.push_effect(Emit(emitter~, event_key=key.id, payload=key.erase(event)))
})
}
///|
fn App::new_observer(
self : App,
entity_id : EntityId,
handler : (App) -> Bool,
) -> Subscription {
let (subscription, activate) = self.observers.insert_pending(
entity_id, handler,
)
// New observers start after the effects already queued (GPUI semantics).
self.defer_call(fn(_) { activate() })
subscription
}
///|
fn[T] App::observe_internal(
self : App,
entity : Entity[T],
on_notify : (Entity[T], App) -> Bool,
) -> Subscription {
let weak = entity.downgrade()
self.new_observer(entity.entity_id(), fn(app) {
match weak.upgrade() {
Some(entity) => on_notify(entity, app)
None => false
}
})
}
///|
/// Calls `on_notify` whenever `entity` is notified.
pub fn[T] App::observe(
self : App,
entity : Entity[T],
on_notify : (Entity[T], App) -> Unit,
) -> Subscription {
self.observe_internal(entity, fn(entity, app) {
on_notify(entity, app)
true
})
}
///|
fn[T, E] App::subscribe_internal(
self : App,
entity : Entity[T],
key : EventKey[E],
on_event : (Entity[T], E, App) -> Bool,
) -> Subscription {
let weak = entity.downgrade()
let listener : EventListener = {
event_key: key.id,
handler: fn(payload, app) {
let event = key.unerase(payload)
match weak.upgrade() {
Some(entity) => on_event(entity, event, app)
None => false
}
},
}
let (subscription, activate) = self.event_listeners.insert_pending(
entity.entity_id(),
listener,
)
self.defer_call(fn(_) { activate() })
subscription
}
///|
/// Calls `on_event` for every event of kind `key` that `entity` emits.
pub fn[T, E] App::subscribe(
self : App,
entity : Entity[T],
key : EventKey[E],
on_event : (Entity[T], E, App) -> Unit,
) -> Subscription {
self.subscribe_internal(entity, key, fn(entity, event, app) {
on_event(entity, event, app)
true
})
}
///|
/// Calls `on_release` with the entity's state when it is released
/// (GPUI: `observe_release`).
pub fn[T] App::observe_release(
self : App,
entity : Entity[T],
on_release : (T, App) -> Unit,
) -> Subscription {
let cell = entity.cell
self.release_listeners.insert(cell.id, fn(app) {
guard cell.value is Some(value) else { return }
on_release(value, app)
})
}
// ---------------------------------------------------------------------------
// Globals
// ---------------------------------------------------------------------------
///|
pub fn[G] App::has_global(self : App, key : GlobalKey[G]) -> Bool {
self.globals.contains(key.id)
}
///|
/// The global for `key`; fails loudly if it is not set (GPUI: `global`).
pub fn[G] App::global(self : App, key : GlobalKey[G]) -> G {
match self.globals.get(key.id) {
Some(erased) => key.unerase(erased)
None => abort("no global of type \{key.name} exists")
}
}
///|
pub fn[G] App::try_global(self : App, key : GlobalKey[G]) -> G? {
match self.globals.get(key.id) {
Some(erased) => Some(key.unerase(erased))
None => None
}
}
///|
/// The global for `key`, to be mutated by the caller; its observers run when
/// the enclosing update finishes (GPUI: `global_mut`). Must be called inside
/// `App::update` (or an entity update), so that the mutation happens before
/// observers run; fails loudly otherwise.
pub fn[G] App::global_mut(self : App, key : GlobalKey[G]) -> G {
guard self.pending_updates > 0 else {
abort(
"global_mut(\{key.name}) must be called inside App::update; use update_global or set_global outside",
)
}
let value = self.global(key)
self.push_effect(NotifyGlobalObservers(key.id))
value
}
///|
/// The global for `key`, created with `init` if missing (GPUI:
/// `default_global`). Like `global_mut`, must be called inside an update.
pub fn[G] App::default_global(
self : App,
key : GlobalKey[G],
init : () -> G,
) -> G {
if !self.has_global(key) {
self.globals[key.id] = key.erase(init())
}
self.global_mut(key)
}
///|
/// Sets the global for `key` and notifies its observers.
pub fn[G] App::set_global(self : App, key : GlobalKey[G], value : G) -> Unit {
self.update(fn(app) {
app.push_effect(NotifyGlobalObservers(key.id))
app.globals[key.id] = key.erase(value)
})
}
///|
/// Removes and returns the global for `key`; fails loudly if missing.
pub fn[G] App::remove_global(self : App, key : GlobalKey[G]) -> G {
let value = self.global(key)
self.update(fn(app) {
app.push_effect(NotifyGlobalObservers(key.id))
app.globals.remove(key.id)
})
value
}
///|
/// Updates the global for `key` (GPUI: `update_global`). The global is
/// leased: reading it inside `f` fails loudly, as in GPUI.
pub fn[G, R] App::update_global(
self : App,
key : GlobalKey[G],
f : (G, App) -> R,
) -> R {
self.update(fn(app) {
guard app.globals.get(key.id) is Some(erased) else {
abort("no global of type \{key.name} exists")
}
let value = key.unerase(erased)
app.globals.remove(key.id)
let result = f(value, app)
app.globals[key.id] = key.erase(value)
app.push_effect(NotifyGlobalObservers(key.id))
result
})
}
///|
/// Calls `f` whenever the global for `key` changes.
pub fn[G] App::observe_global(
self : App,
key : GlobalKey[G],
f : (App) -> Unit,
) -> Subscription {
let (subscription, activate) = self.global_observers.insert_pending(key.id, fn(
app,
) {
f(app)
true
})
self.defer_call(fn(_) { activate() })
subscription
}
+461
View File
@@ -0,0 +1,461 @@
///|
struct Counter {
mut count : Int32
}
///|
struct Log {
entries : Array[String]
}
///|
let changed : @app.EventKey[Int32] = @app.EventKey::new("Changed")
///|
let renamed : @app.EventKey[String] = @app.EventKey::new("Renamed")
///|
struct Settings {
mut theme : String
}
///|
let settings_key : @app.GlobalKey[Settings] = @app.GlobalKey::new("Settings")
///|
let marker_key : @app.GlobalKey[Int32] = @app.GlobalKey::new("Marker")
///|
fn new_counter(app : @app.App, count~ : Int32 = 0) -> @app.Entity[Counter] {
app.new_entity(fn(_) { { count, } })
}
///|
test "entities are created, read and updated" {
let app = @app.App::new()
let counter = new_counter(app, count=1)
assert_eq(counter.read(app).count, 1)
let context_ok = Ref(false)
let result = counter.update(app, fn(state, cx) {
state.count += 1
context_ok.val = cx.entity_id() == counter.entity_id() &&
cx.entity() == counter
state.count * 10
})
assert_eq(result, 20)
assert_true(context_ok.val)
assert_eq(app.read_entity(counter).count, 2)
assert_eq(app.entity_count(), 1)
let other = new_counter(app)
assert_not_eq(other.entity_id(), counter.entity_id())
assert_false(other == counter)
}
///|
test "reserve then insert" {
let app = @app.App::new()
let reservation : @app.Reservation[Counter] = app.reserve_entity()
let id = reservation.entity_id()
let seen_id : Ref[@app.EntityId?] = Ref(None)
let entity = app.insert_entity(reservation, fn(cx) {
seen_id.val = Some(cx.entity_id())
{ count: 7, }
})
assert_eq(seen_id.val, Some(id))
assert_eq(entity.entity_id(), id)
assert_eq(entity.read(app).count, 7)
}
///|
test "observers run after the update and notifications coalesce" {
let app = @app.App::new()
let counter = new_counter(app)
let seen = []
let during = Ref(-1)
let subscription = app.observe(counter, fn(entity, app) {
seen.push(entity.read(app).count)
})
counter.update(app, fn(state, cx) {
state.count = 1
cx.notify()
state.count = 2
cx.notify()
// Nothing runs until the outermost update returns.
during.val = seen.length()
})
assert_eq(during.val, 0)
assert_eq(seen, [2])
subscription.unsubscribe()
counter.update(app, fn(_, cx) { cx.notify() })
assert_eq(seen, [2])
}
///|
test "nested updates flush once at the end" {
let app = @app.App::new()
let counter = new_counter(app)
let seen = []
app.observe(counter, fn(_, _) { seen.push("notified") }).detach()
let during = Ref(-1)
app.update(fn(app) {
counter.update(app, fn(_, cx) { cx.notify() })
during.val = seen.length()
counter.update(app, fn(_, cx) { cx.notify() })
})
assert_eq(during.val, 0)
assert_eq(seen, ["notified"])
}
///|
test "observers registered during an update see effects queued after them" {
let app = @app.App::new()
let counter = new_counter(app)
let seen = []
app.update(fn(app) {
// Notified before the observer exists: not delivered to it.
app.notify(counter.entity_id())
app.observe(counter, fn(_, _) { seen.push("first") }).detach()
})
assert_eq(seen, [])
app.update(fn(app) {
app.observe(counter, fn(_, _) { seen.push("second") }).detach()
// Queued after the observer's activation: delivered.
app.notify(counter.entity_id())
})
assert_eq(seen, ["first", "second"])
}
///|
test "events are delivered by kind" {
let app = @app.App::new()
let counter = new_counter(app)
let ints = []
let strings = []
app.subscribe(counter, changed, fn(_, value, _) { ints.push(value) }).detach()
app
.subscribe(counter, renamed, fn(_, value, _) { strings.push(value) })
.detach()
counter.update(app, fn(state, cx) {
state.count = 5
cx.emit(changed, state.count)
cx.emit(renamed, "five")
cx.emit(changed, 6)
})
assert_eq(ints, [5, 6])
assert_eq(strings, ["five"])
}
///|
test "entities observe and subscribe to each other" {
let app = @app.App::new()
let source = new_counter(app)
let log : @app.Entity[Log] = app.new_entity(fn(cx) {
cx
.observe(source, fn(log, source, cx) {
log.entries.push("notified \{source.read(cx.app).count}")
})
.detach()
cx
.subscribe(source, changed, fn(log, _, value, _) {
log.entries.push("changed \{value}")
})
.detach()
{ entries: [], }
})
source.update(app, fn(state, cx) {
state.count = 3
cx.emit(changed, 3)
cx.notify()
})
assert_eq(log.read(app).entries, ["changed 3", "notified 3"])
}
///|
test "self observation and self subscription" {
let app = @app.App::new()
let counter : @app.Entity[Counter] = app.new_entity(fn(cx) {
cx.observe_self(fn(state, _) { state.count += 100 }).detach()
cx
.subscribe_self(changed, fn(state, value, _) { state.count += value })
.detach()
{ count: 0, }
})
counter.update(app, fn(_, cx) {
cx.emit(changed, 2)
cx.notify()
})
assert_eq(counter.read(app).count, 102)
}
///|
test "observers cascade within one flush" {
let app = @app.App::new()
let a = new_counter(app)
let b = new_counter(app)
let order = []
app
.observe(a, fn(_, app) {
order.push("a")
b.update(app, fn(_, cx) { cx.notify() })
})
.detach()
app.observe(b, fn(_, _) { order.push("b") }).detach()
a.update(app, fn(_, cx) { cx.notify() })
assert_eq(order, ["a", "b"])
}
///|
test "release removes observers, runs release listeners, stops weak handles" {
let app = @app.App::new()
let counter : @app.Entity[Counter] = app.new_entity(fn(cx) {
cx.on_release(fn(state, _) { state.count = -1 }).detach()
{ count: 4, }
})
let released = []
app
.observe_release(counter, fn(state, _) { released.push(state.count) })
.detach()
let notified = []
app.observe(counter, fn(_, _) { notified.push(1) }).detach()
let weak = counter.downgrade()
assert_true(weak.upgrade() is Some(_))
let upgraded_during = Ref(true)
let released_during = Ref(-1)
app.update(fn(app) {
app.release(counter)
// Weak handles stop upgrading immediately, listeners run at the flush.
upgraded_during.val = weak.upgrade() is Some(_)
released_during.val = released.length()
})
assert_false(upgraded_during.val)
assert_eq(released_during.val, 0)
// Listeners run in registration order: on_release first.
assert_eq(released, [-1])
assert_true(counter.is_released())
assert_eq(app.entity_count(), 0)
assert_eq(weak.update(app, fn(_, _) { 1 }), None)
// Releasing again is a no-op.
app.release(counter)
assert_eq(released, [-1])
}
///|
test "observer entities stop observing when released" {
let app = @app.App::new()
let source = new_counter(app)
let seen = []
let watcher : @app.Entity[Log] = app.new_entity(fn(cx) {
cx.observe(source, fn(_, _, _) { seen.push("seen") }).detach()
{ entries: [], }
})
source.update(app, fn(_, cx) { cx.notify() })
assert_eq(seen, ["seen"])
app.release(watcher)
source.update(app, fn(_, cx) { cx.notify() })
assert_eq(seen, ["seen"])
}
///|
test "observe_release between entities" {
let app = @app.App::new()
let child = new_counter(app, count=9)
let parent : @app.Entity[Log] = app.new_entity(fn(cx) {
cx
.observe_release(child, fn(log, child_state, _) {
log.entries.push("child released with \{child_state.count}")
})
.detach()
{ entries: [], }
})
app.release(child)
assert_eq(parent.read(app).entries, ["child released with 9"])
}
///|
test "globals" {
let app = @app.App::new()
assert_false(app.has_global(settings_key))
assert_true(app.try_global(settings_key) is None)
app.set_global(settings_key, { theme: "light", })
assert_eq(app.global(settings_key).theme, "light")
let changes = []
app
.observe_global(settings_key, fn(app) {
changes.push(app.global(settings_key).theme)
})
.detach()
app.update_global(settings_key, fn(settings, _) { settings.theme = "dark" })
assert_eq(changes, ["dark"])
app.update(fn(app) { app.global_mut(settings_key).theme = "solarized" })
assert_eq(changes, ["dark", "solarized"])
// Different keys hold different types independently.
app.set_global(marker_key, 42)
assert_eq(app.global(marker_key), 42)
assert_eq(
app.update(fn(app) { app.default_global(marker_key, fn() { 0 }) }),
42,
)
let removed = app.remove_global(marker_key)
assert_eq(removed, 42)
assert_false(app.has_global(marker_key))
assert_eq(
app.update(fn(app) { app.default_global(marker_key, fn() { 7 }) }),
7,
)
// Globals are per app.
assert_false(@app.App::new().has_global(settings_key))
}
///|
test "entities observe globals until released" {
let app = @app.App::new()
app.set_global(marker_key, 0)
let counter : @app.Entity[Counter] = app.new_entity(fn(cx) {
cx.observe_global(marker_key, fn(state, _) { state.count += 1 }).detach()
{ count: 0, }
})
app.set_global(marker_key, 1)
app.set_global(marker_key, 2)
assert_eq(counter.read(app).count, 2)
let weak = counter.downgrade()
app.release(counter)
app.set_global(marker_key, 3)
assert_true(weak.upgrade() is None)
}
///|
/// Port of GPUI's `test_unsubscribe_during_callback_with_insert`.
test "unsubscribe during callback with insert" {
let app = @app.App::new()
app.set_global(marker_key, 0)
let a_count = Ref(0)
let b_count = Ref(0)
let sub_a : Ref[@app.Subscription?] = Ref(None)
let sub_b : Ref[@app.Subscription?] = Ref(None)
sub_a.val = Some(
app.observe_global(marker_key, fn(app) {
a_count.val += 1
sub_a.val.unwrap().unsubscribe()
app.observe_global(marker_key, fn(_) { }).detach()
}),
)
sub_b.val = Some(
app.observe_global(marker_key, fn(_) {
b_count.val += 1
sub_b.val.unwrap().unsubscribe()
}),
)
app.set_global(marker_key, 1)
assert_eq(a_count.val, 1)
assert_eq(b_count.val, 1)
app.set_global(marker_key, 2)
assert_eq(a_count.val, 1)
assert_eq(b_count.val, 1)
}
///|
/// Port of GPUI's `test_callback_dropped_by_earlier_callback_does_not_fire`.
test "callback unsubscribed by an earlier callback does not fire" {
let app = @app.App::new()
app.set_global(marker_key, 0)
let b_count = Ref(0)
let sub_b : Ref[@app.Subscription?] = Ref(None)
app
.observe_global(marker_key, fn(_) {
if sub_b.val is Some(sub) {
sub.unsubscribe()
}
})
.detach()
sub_b.val = Some(app.observe_global(marker_key, fn(_) { b_count.val += 1 }))
app.set_global(marker_key, 1)
assert_eq(b_count.val, 0)
}
///|
/// Port of GPUI's `test_self_drop_during_callback` and
/// `test_subscription_drop`.
test "self unsubscribe and unsubscribe before firing" {
let app = @app.App::new()
app.set_global(marker_key, 0)
let count = Ref(0)
let sub : Ref[@app.Subscription?] = Ref(None)
sub.val = Some(
app.observe_global(marker_key, fn(_) {
count.val += 1
sub.val.unwrap().unsubscribe()
}),
)
app.set_global(marker_key, 1)
app.set_global(marker_key, 2)
assert_eq(count.val, 1)
let other = Ref(0)
let subscription = app.observe_global(marker_key, fn(_) { other.val += 1 })
subscription.unsubscribe()
app.set_global(marker_key, 3)
assert_eq(other.val, 0)
}
///|
test "defer_call runs after current effects" {
let app = @app.App::new()
let order = []
app.update(fn(app) {
app.defer_call(fn(_) { order.push("deferred") })
order.push("update")
})
assert_eq(order, ["update", "deferred"])
let counter = new_counter(app)
counter.update(app, fn(_, cx) {
cx.defer_call(fn(app) { order.push("count \{counter.read(app).count}") })
})
assert_eq(order, ["update", "deferred", "count 0"])
}
///|
test "panic on re-entrant update" {
let app = @app.App::new()
let counter = new_counter(app)
counter.update(app, fn(_, cx) { counter.update(cx.app, fn(_, _) { }) })
}
///|
test "panic on reading an entity while it is updated" {
let app = @app.App::new()
let counter = new_counter(app)
counter.update(app, fn(_, cx) { ignore(counter.read(cx.app)) })
}
///|
test "panic on updating a released entity" {
let app = @app.App::new()
let counter = new_counter(app)
app.release(counter)
counter.update(app, fn(_, _) { })
}
///|
test "panic on using an entity with another app" {
let app = @app.App::new()
let counter = new_counter(app)
ignore(counter.read(@app.App::new()))
}
///|
test "panic on reading a missing global" {
ignore(@app.App::new().global(settings_key))
}
///|
test "panic on reading a global while it is being updated" {
let app = @app.App::new()
app.set_global(marker_key, 1)
app.update_global(marker_key, fn(_, app) { ignore(app.global(marker_key)) })
}
///|
test "panic on global_mut outside an update" {
let app = @app.App::new()
app.set_global(marker_key, 1)
ignore(app.global_mut(marker_key))
}
+121
View File
@@ -0,0 +1,121 @@
// Async integration, ported from gpui/src/app/async_context.rs and the
// `spawn` methods of App and Context.
//
// Deviation from GPUI: `AsyncApp` methods return plain values. GPUI's return
// `Result`s because the app may have been dropped while a task was
// suspended; a MoonBit `App` is never dropped while referenced.
///|
/// A handle to the app that async tasks hold across suspension points
/// (GPUI: `AsyncApp`). Each call runs as its own update and flushes effects.
pub struct AsyncApp {
app : App
}
///|
pub fn App::to_async(self : App) -> AsyncApp {
{ app: self, }
}
///|
/// The executor for work that must run on the main thread (GPUI:
/// `ForegroundExecutor`). There is one thread, so it is the same executor as
/// `background_executor`.
pub fn App::foreground_executor(self : App) -> @executor.Executor {
self.executor
}
///|
/// The executor for work off the main thread (GPUI: `BackgroundExecutor`).
/// Shares the main thread here; see `foreground_executor`.
pub fn App::background_executor(self : App) -> @executor.Executor {
self.executor
}
///|
/// Runs `f` as a task with an `AsyncApp` (GPUI: `cx.spawn`).
pub fn[R] App::spawn(
self : App,
f : async (AsyncApp) -> R,
) -> @executor.Task[R] {
let cx = self.to_async()
self.executor.spawn(async fn() { f(cx) })
}
///|
fn App::expect_test_dispatcher(
self : App,
operation : String,
) -> @executor.TestDispatcher {
match self.test_dispatcher {
Some(dispatcher) => dispatcher
None =>
abort(
"App::\{operation} needs the app's own TestDispatcher (App::new() without a dispatcher)",
)
}
}
///|
/// Runs ready tasks until none is left (tests; GPUI:
/// `TestAppContext::run_until_parked`).
pub fn App::run_until_parked(self : App) -> Unit {
self.expect_test_dispatcher("run_until_parked").run_until_parked()
}
///|
/// Advances the virtual clock, running timers and tasks (tests; GPUI:
/// `BackgroundExecutor::advance_clock`).
pub fn App::advance_clock(self : App, ms : Int32) -> Unit {
self.expect_test_dispatcher("advance_clock").advance_clock(ms)
}
///|
/// Runs `f` as an update (GPUI: `AsyncApp::update`).
pub fn[R] AsyncApp::update(self : AsyncApp, f : (App) -> R) -> R {
self.app.update(f)
}
///|
pub fn[T, R] AsyncApp::update_entity(
self : AsyncApp,
entity : Entity[T],
f : (T, Context[T]) -> R,
) -> R {
self.app.update_entity(entity, f)
}
///|
pub fn[T] AsyncApp::read_entity(self : AsyncApp, entity : Entity[T]) -> T {
self.app.read_entity(entity)
}
///|
pub fn[R] AsyncApp::spawn(
self : AsyncApp,
f : async (AsyncApp) -> R,
) -> @executor.Task[R] {
self.app.spawn(f)
}
///|
pub fn AsyncApp::foreground_executor(self : AsyncApp) -> @executor.Executor {
self.app.executor
}
///|
pub fn AsyncApp::background_executor(self : AsyncApp) -> @executor.Executor {
self.app.executor
}
///|
/// Runs `f` as a task with a weak handle to this entity (GPUI: `cx.spawn`).
/// The task does not keep the entity alive: update it through the weak
/// handle, which yields `None` once the entity is released.
pub fn[T, R] Context::spawn(
self : Context[T],
f : async (WeakEntity[T], AsyncApp) -> R,
) -> @executor.Task[R] {
let weak = self.weak
self.app.spawn(async fn(cx) { f(weak, cx) })
}
+118
View File
@@ -0,0 +1,118 @@
///|
struct Status {
mut text : String
mut loads : Int32
}
///|
fn new_status(app : @app.App) -> @app.Entity[Status] {
app.new_entity(fn(_) { { text: "idle", loads: 0, } })
}
///|
test "app tasks update entities and flush effects per update" {
let app = @app.App::new()
let status = new_status(app)
let seen = []
app
.observe(status, fn(status, app) { seen.push(status.read(app).text) })
.detach()
let task = app.spawn(async fn(cx) {
cx.update_entity(status, fn(status, cx) {
status.text = "loading"
cx.notify()
})
cx.background_executor().sleep(100)
cx.update_entity(status, fn(status, cx) {
status.text = "done"
status.loads += 1
cx.notify()
})
cx.read_entity(status).loads
})
// Nothing runs until the test drives the app's dispatcher.
assert_eq(seen, [])
app.run_until_parked()
assert_eq(seen, ["loading"])
app.advance_clock(99)
assert_eq(seen, ["loading"])
app.advance_clock(1)
assert_eq(seen, ["loading", "done"])
assert_eq(task.try_result(), Some(1))
}
///|
test "entity tasks hold weak handles" {
let app = @app.App::new()
let results = []
let status : @app.Entity[Status] = app.new_entity(fn(cx) {
cx
.spawn(async fn(weak, cx) {
cx.foreground_executor().sleep(10)
let first = weak.update(cx.app, fn(status, _) { status.loads += 1 })
results.push(first is Some(_))
cx.foreground_executor().sleep(10)
// Released in between: the weak handle no longer upgrades.
let second = weak.update(cx.app, fn(status, _) { status.loads += 1 })
results.push(second is Some(_))
})
.detach()
{ text: "", loads: 0, }
})
app.advance_clock(10)
assert_eq(results, [true])
assert_eq(status.read(app).loads, 1)
app.release(status)
app.advance_clock(10)
assert_eq(results, [true, false])
}
///|
test "cancelling a spawned task stops it" {
let app = @app.App::new()
let status = new_status(app)
let task = app.spawn(async fn(cx) {
cx.background_executor().sleep(50)
cx.update_entity(status, fn(status, _) { status.text = "should not happen" })
})
app.run_until_parked()
task.cancel()
app.advance_clock(100)
assert_true(task.is_cancelled())
assert_eq(status.read(app).text, "idle")
}
///|
test "tasks spawned from AsyncApp and executor clock" {
let app = @app.App::new()
let order = []
app
.spawn(async fn(cx) {
let child = cx.spawn(async fn(cx) {
cx.background_executor().sleep(5)
order.push("child")
7
})
order.push("parent waits")
let value = child.wait()
order.push("parent got \{value} at \{cx.background_executor().now()}")
})
.detach()
app.advance_clock(5)
assert_eq(order, ["parent waits", "child", "parent got 7 at 5"])
}
///|
test "apps can run on a caller-provided dispatcher" {
let dispatcher = @executor.TestDispatcher::new()
let app = @app.App::new(dispatcher~)
let task = app.spawn(fn(_) { "ran" })
dispatcher.run_until_parked()
assert_eq(task.try_result(), Some("ran"))
}
///|
test "panic on run_until_parked without the app's own dispatcher" {
let app = @app.App::new(dispatcher=@executor.TestDispatcher::new())
app.run_until_parked()
}
+199
View File
@@ -0,0 +1,199 @@
// Port of gpui/src/app/context.rs: the context passed to entity callbacks.
//
// GPUI's `Context<T>` derefs to `App`; here the app is the public `app`
// field (`cx.app.set_global(...)`). Window-related methods (`listener`,
// `observe_in`, focus) come with the Window (M6), `spawn` with the executors
// (M4).
///|
/// The context of an update to entity `T` (GPUI: `Context<'_, T>`).
pub struct Context[T] {
app : App
priv weak : WeakEntity[T]
}
///|
pub fn[T] Context::entity_id(self : Context[T]) -> EntityId {
self.weak.entity_id()
}
///|
/// The entity being updated.
pub fn[T] Context::entity(self : Context[T]) -> Entity[T] {
match self.weak.upgrade() {
Some(entity) => entity
None => abort("the entity must be alive if we have an entity context")
}
}
///|
pub fn[T] Context::weak_entity(self : Context[T]) -> WeakEntity[T] {
self.weak
}
///|
/// Marks this entity as changed (GPUI: `cx.notify()`).
pub fn[T] Context::notify(self : Context[T]) -> Unit {
self.app.notify(self.weak.entity_id())
}
///|
/// Emits `event` to subscribers of this entity's `key` events
/// (GPUI: `cx.emit(event)`).
pub fn[T, E] Context::emit(
self : Context[T],
key : EventKey[E],
event : E,
) -> Unit {
self.app.emit_event(self.weak.entity_id(), key, event)
}
///|
/// Queues `f` to run after the current effects.
pub fn[T] Context::defer_call(self : Context[T], f : (App) -> Unit) -> Unit {
self.app.defer_call(f)
}
///|
/// Runs `f` on this entity's state, if it is still alive.
fn[T] invoke_on(
weak : WeakEntity[T],
app : App,
f : (T, Context[T]) -> Unit,
) -> Bool {
match weak.upgrade() {
Some(entity) => {
app.update_entity(entity, f)
true
}
None => false
}
}
///|
/// Calls `on_notify` on this entity whenever `entity` is notified. Stops when
/// either entity is released (GPUI: `cx.observe`).
pub fn[T, W] Context::observe(
self : Context[T],
entity : Entity[W],
on_notify : (T, Entity[W], Context[T]) -> Unit,
) -> Subscription {
let observer = self.weak
self.app.observe_internal(entity, fn(entity, app) {
invoke_on(observer, app, fn(this, cx) { on_notify(this, entity, cx) })
})
}
///|
/// Calls `on_notify` whenever this entity is notified.
pub fn[T] Context::observe_self(
self : Context[T],
on_notify : (T, Context[T]) -> Unit,
) -> Subscription {
let observer = self.weak
self.app.observe_internal(self.entity(), fn(_, app) {
invoke_on(observer, app, on_notify)
})
}
///|
/// Calls `on_event` on this entity for every `key` event `entity` emits.
/// Stops when either entity is released (GPUI: `cx.subscribe`).
pub fn[T, W, E] Context::subscribe(
self : Context[T],
entity : Entity[W],
key : EventKey[E],
on_event : (T, Entity[W], E, Context[T]) -> Unit,
) -> Subscription {
let subscriber = self.weak
self.app.subscribe_internal(entity, key, fn(entity, event, app) {
invoke_on(subscriber, app, fn(this, cx) {
on_event(this, entity, event, cx)
})
})
}
///|
/// Calls `on_event` for every `key` event this entity emits.
pub fn[T, E] Context::subscribe_self(
self : Context[T],
key : EventKey[E],
on_event : (T, E, Context[T]) -> Unit,
) -> Subscription {
let subscriber = self.weak
self.app.subscribe_internal(self.entity(), key, fn(_, event, app) {
invoke_on(subscriber, app, fn(this, cx) { on_event(this, event, cx) })
})
}
///|
/// Calls `on_release` with this entity's state when it is released
/// (GPUI: `cx.on_release`).
pub fn[T] Context::on_release(
self : Context[T],
on_release : (T, App) -> Unit,
) -> Subscription {
self.app.observe_release({ cell: self.weak.cell, }, on_release)
}
///|
/// Calls `on_release` on this entity when `entity` is released
/// (GPUI: `cx.observe_release`).
pub fn[T, W] Context::observe_release(
self : Context[T],
entity : Entity[W],
on_release : (T, W, Context[T]) -> Unit,
) -> Subscription {
let observer = self.weak
self.app.observe_release(entity, fn(released, app) {
ignore(
invoke_on(observer, app, fn(this, cx) { on_release(this, released, cx) }),
)
})
}
///|
/// Calls `f` on this entity whenever the global for `key` changes. Stops when
/// this entity is released (GPUI: `cx.observe_global`).
pub fn[T, G] Context::observe_global(
self : Context[T],
key : GlobalKey[G],
f : (T, Context[T]) -> Unit,
) -> Subscription {
let observer = self.weak
let (subscription, activate) = self.app.global_observers.insert_pending(
key.id,
fn(app) { invoke_on(observer, app, f) },
)
self.app.defer_call(fn(_) { activate() })
subscription
}
///|
/// Updates this entity's state from a weak handle, if it is still alive.
pub fn[T, R] WeakEntity::update(
self : WeakEntity[T],
app : App,
f : (T, Context[T]) -> R,
) -> R? {
match self.upgrade() {
Some(entity) => Some(app.update_entity(entity, f))
None => None
}
}
///|
/// `app.update_entity(self, f)`.
pub fn[T, R] Entity::update(
self : Entity[T],
app : App,
f : (T, Context[T]) -> R,
) -> R {
app.update_entity(self, f)
}
///|
/// `app.read_entity(self)`.
pub fn[T] Entity::read(self : Entity[T], app : App) -> T {
app.read_entity(self)
}
+152
View File
@@ -0,0 +1,152 @@
// Entities, ported from gpui/src/app/entity_map.rs.
//
// Deviations from GPUI:
// - A handle points directly at a typed cell holding the state; there is no
// `Box<dyn Any>` map to downcast from.
// - Handles are not reference counted (no `Drop`). An entity lives until
// `App::release` is called; then its observers and event subscriptions are
// removed and its release listeners run, as when the last GPUI handle
// drops. `WeakEntity::upgrade` returns `None` from the moment of release.
// - State is passed to update callbacks by reference (MoonBit structs with
// `mut` fields), playing the role of GPUI's `&mut T`.
///|
/// Identifies an entity within its app.
#derive(Eq, Hash, Compare, Debug)
pub(all) struct EntityId(Int32)
///|
pub impl Show for EntityId with fn output(self, logger) {
logger.write_string("EntityId(\{self.0})")
}
///|
priv struct EntityCell[T] {
app_id : Int32
id : EntityId
mut value : T?
/// True while an update callback holds the state.
mut leased : Bool
mut released : Bool
}
///|
/// A strong handle to state owned by the app (GPUI: `Entity<T>`).
pub struct Entity[T] {
priv cell : EntityCell[T]
}
///|
/// A handle that does not keep the entity alive (GPUI: `WeakEntity<T>`).
pub struct WeakEntity[T] {
priv cell : EntityCell[T]
}
///|
/// An entity id handed out before the entity's state exists
/// (GPUI: `Reservation<T>`).
pub struct Reservation[T] {
priv cell : EntityCell[T]
}
///|
pub fn[T] Entity::entity_id(self : Entity[T]) -> EntityId {
self.cell.id
}
///|
pub fn[T] Entity::downgrade(self : Entity[T]) -> WeakEntity[T] {
{ cell: self.cell, }
}
///|
/// Whether `App::release` has been called for this entity.
pub fn[T] Entity::is_released(self : Entity[T]) -> Bool {
self.cell.released
}
///|
pub impl[T] Eq for Entity[T] with fn equal(self, other) {
physical_equal(self.cell, other.cell)
}
///|
pub impl[T] Hash for Entity[T] with fn hash_combine(self, hasher) {
hasher.combine(self.cell.id)
}
///|
pub impl[T] Show for Entity[T] with fn output(self, logger) {
logger.write_string("Entity(\{self.cell.id.0})")
}
///|
pub fn[T] WeakEntity::entity_id(self : WeakEntity[T]) -> EntityId {
self.cell.id
}
///|
/// The strong handle, unless the entity has been released.
pub fn[T] WeakEntity::upgrade(self : WeakEntity[T]) -> Entity[T]? {
if self.cell.released {
None
} else {
Some({ cell: self.cell, })
}
}
///|
pub fn[T] Reservation::entity_id(self : Reservation[T]) -> EntityId {
self.cell.id
}
///|
fn[T] EntityCell::check_app(
self : EntityCell[T],
app : App,
operation : String,
) -> Unit {
guard self.app_id == app.id else {
abort("cannot \{operation} \{self.id}: it belongs to a different App")
}
}
///|
/// Takes the state for an update, failing loudly on re-entrancy or use after
/// release (GPUI: `EntityMap::lease`).
fn[T] EntityCell::lease(self : EntityCell[T], operation : String) -> T {
guard !self.released else {
abort("cannot \{operation} \{self.id}: the entity has been released")
}
guard !self.leased else {
abort("cannot \{operation} \{self.id} while it is already being updated")
}
guard self.value is Some(value) else {
abort(
"cannot \{operation} \{self.id}: the entity has not been inserted yet",
)
}
self.leased = true
value
}
///|
fn[T] EntityCell::end_lease(self : EntityCell[T]) -> Unit {
self.leased = false
}
///|
/// Reads the state. Fails if the entity is being updated or was released
/// (GPUI: `EntityMap::read`).
fn[T] EntityCell::read(self : EntityCell[T]) -> T {
guard !self.released else {
abort("cannot read \{self.id}: the entity has been released")
}
guard !self.leased else {
abort("cannot read \{self.id} while it is already being updated")
}
guard self.value is Some(value) else {
abort("cannot read \{self.id}: the entity has not been inserted yet")
}
value
}
+81
View File
@@ -0,0 +1,81 @@
// Type keys: MoonBit's replacement for GPUI's `TypeId`-keyed maps of
// `Box<dyn Any>` (globals, events).
//
// A key is created once per type, usually as a top-level `let`:
//
// let theme_key : @app.GlobalKey[Theme] = @app.GlobalKey::new("Theme")
//
// The app stores values under the key's id without knowing their type. A
// stored value is a closure that writes the value into its key's typed slot,
// so reading it back through the same key is type-safe without downcasts.
///|
let next_key_id : Ref[Int32] = { val: 0, }
///|
fn fresh_key_id() -> Int32 {
let id = next_key_id.val
next_key_id.val = id + 1
id
}
///|
/// Identifies one kind of global state (GPUI: `TypeId::of::<G>()` for a
/// `G: Global`).
pub struct GlobalKey[G] {
id : Int32
name : String
priv slot : Ref[G?]
}
///|
pub fn[G] GlobalKey::new(name : String) -> GlobalKey[G] {
{ id: fresh_key_id(), name, slot: { val: None, }, }
}
///|
/// A type-erased value that can only be read back through `key`.
fn[G] GlobalKey::erase(self : GlobalKey[G], value : G) -> () -> Unit {
fn() { self.slot.val = Some(value) }
}
///|
fn[G] GlobalKey::unerase(self : GlobalKey[G], erased : () -> Unit) -> G {
self.slot.val = None
erased()
guard self.slot.val is Some(value) else {
abort("global \{self.name}: stored value has the wrong key")
}
self.slot.val = None
value
}
///|
/// Identifies one kind of event (GPUI: `TypeId::of::<E>()` for events
/// declared with `impl EventEmitter<E> for T`).
pub struct EventKey[E] {
id : Int32
name : String
priv slot : Ref[E?]
}
///|
pub fn[E] EventKey::new(name : String) -> EventKey[E] {
{ id: fresh_key_id(), name, slot: { val: None, }, }
}
///|
fn[E] EventKey::erase(self : EventKey[E], event : E) -> () -> Unit {
fn() { self.slot.val = Some(event) }
}
///|
fn[E] EventKey::unerase(self : EventKey[E], erased : () -> Unit) -> E {
self.slot.val = None
erased()
guard self.slot.val is Some(event) else {
abort("event \{self.name}: payload has the wrong key")
}
self.slot.val = None
event
}
+11
View File
@@ -0,0 +1,11 @@
import {
"experiments/gpui/executor",
"moonbitlang/core/deque",
"moonbitlang/core/hashset",
}
// experiments/gpui/executor uses MoonBit's experimental async intrinsics.
options(
"allow-experimental-packages": true,
)
+132
View File
@@ -0,0 +1,132 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/app"
import {
"experiments/gpui/executor",
"moonbitlang/core/debug",
}
// Values
// Errors
// Types and methods
pub struct App {
// private fields
}
pub fn App::advance_clock(Self, Int32) -> Unit
pub fn App::background_executor(Self) -> @executor.Executor
pub fn[G] App::default_global(Self, GlobalKey[G], () -> G) -> G
pub fn App::defer_call(Self, (Self) -> Unit) -> Unit
pub fn App::entity_count(Self) -> Int32
pub fn App::foreground_executor(Self) -> @executor.Executor
pub fn[G] App::global(Self, GlobalKey[G]) -> G
pub fn[G] App::global_mut(Self, GlobalKey[G]) -> G
pub fn[G] App::has_global(Self, GlobalKey[G]) -> Bool
pub fn[T] App::insert_entity(Self, Reservation[T], (Context[T]) -> T) -> Entity[T]
pub fn App::new(dispatcher? : &@executor.Dispatcher) -> Self
pub fn[T] App::new_entity(Self, (Context[T]) -> T) -> Entity[T]
pub fn App::notify(Self, EntityId) -> Unit
pub fn[T] App::observe(Self, Entity[T], (Entity[T], Self) -> Unit) -> Subscription
pub fn[G] App::observe_global(Self, GlobalKey[G], (Self) -> Unit) -> Subscription
pub fn App::observe_notifications(Self, (EntityId) -> Unit) -> Subscription
pub fn[T] App::observe_release(Self, Entity[T], (T, Self) -> Unit) -> Subscription
pub fn[T] App::read_entity(Self, Entity[T]) -> T
pub fn[T] App::release(Self, Entity[T]) -> Unit
pub fn[G] App::remove_global(Self, GlobalKey[G]) -> G
pub fn[T] App::reserve_entity(Self) -> Reservation[T]
pub fn App::run_until_parked(Self) -> Unit
pub fn[G] App::set_global(Self, GlobalKey[G], G) -> Unit
pub fn[R] App::spawn(Self, async (AsyncApp) -> R) -> @executor.Task[R]
pub fn[T, E] App::subscribe(Self, Entity[T], EventKey[E], (Entity[T], E, Self) -> Unit) -> Subscription
pub fn App::to_async(Self) -> AsyncApp
pub fn[G] App::try_global(Self, GlobalKey[G]) -> G?
pub fn[R] App::update(Self, (Self) -> R) -> R
pub fn[T, R] App::update_entity(Self, Entity[T], (T, Context[T]) -> R) -> R
pub fn[G, R] App::update_global(Self, GlobalKey[G], (G, Self) -> R) -> R
pub struct AsyncApp {
app : App
}
pub fn AsyncApp::background_executor(Self) -> @executor.Executor
pub fn AsyncApp::foreground_executor(Self) -> @executor.Executor
pub fn[T] AsyncApp::read_entity(Self, Entity[T]) -> T
pub fn[R] AsyncApp::spawn(Self, async (Self) -> R) -> @executor.Task[R]
pub fn[R] AsyncApp::update(Self, (App) -> R) -> R
pub fn[T, R] AsyncApp::update_entity(Self, Entity[T], (T, Context[T]) -> R) -> R
pub struct Context[T] {
app : App
// private fields
}
pub fn[T] Context::defer_call(Self[T], (App) -> Unit) -> Unit
pub fn[T, E] Context::emit(Self[T], EventKey[E], E) -> Unit
pub fn[T] Context::entity(Self[T]) -> Entity[T]
pub fn[T] Context::entity_id(Self[T]) -> EntityId
pub fn[T] Context::notify(Self[T]) -> Unit
pub fn[T, W] Context::observe(Self[T], Entity[W], (T, Entity[W], Self[T]) -> Unit) -> Subscription
pub fn[T, G] Context::observe_global(Self[T], GlobalKey[G], (T, Self[T]) -> Unit) -> Subscription
pub fn[T, W] Context::observe_release(Self[T], Entity[W], (T, W, Self[T]) -> Unit) -> Subscription
pub fn[T] Context::observe_self(Self[T], (T, Self[T]) -> Unit) -> Subscription
pub fn[T] Context::on_release(Self[T], (T, App) -> Unit) -> Subscription
pub fn[T, R] Context::spawn(Self[T], async (WeakEntity[T], AsyncApp) -> R) -> @executor.Task[R]
pub fn[T, W, E] Context::subscribe(Self[T], Entity[W], EventKey[E], (T, Entity[W], E, Self[T]) -> Unit) -> Subscription
pub fn[T, E] Context::subscribe_self(Self[T], EventKey[E], (T, E, Self[T]) -> Unit) -> Subscription
pub fn[T] Context::weak_entity(Self[T]) -> WeakEntity[T]
pub struct Entity[T] {
// private fields
}
pub fn[T] Entity::downgrade(Self[T]) -> WeakEntity[T]
pub fn[T] Entity::entity_id(Self[T]) -> EntityId
pub fn[T] Entity::is_released(Self[T]) -> Bool
pub fn[T] Entity::read(Self[T], App) -> T
pub fn[T, R] Entity::update(Self[T], App, (T, Context[T]) -> R) -> R
pub impl[T] Eq for Entity[T]
pub impl[T] Hash for Entity[T]
pub impl[T] Show for Entity[T]
#derive(Compare, Eq, Hash, @debug.Debug)
pub(all) struct EntityId(Int32)
pub impl Show for EntityId
pub struct EventKey[E] {
id : Int32
name : String
// private fields
}
pub fn[E] EventKey::new(String) -> Self[E]
pub struct GlobalKey[G] {
id : Int32
name : String
// private fields
}
pub fn[G] GlobalKey::new(String) -> Self[G]
pub struct Reservation[T] {
// private fields
}
pub fn[T] Reservation::entity_id(Self[T]) -> EntityId
type SubscriberSet[K, C]
pub struct Subscription {
// private fields
}
pub fn Subscription::detach(Self) -> Unit
pub fn Subscription::is_active(Self) -> Bool
pub fn Subscription::join(Self, Self) -> Self
pub fn Subscription::new(() -> Unit) -> Self
pub fn Subscription::unsubscribe(Self) -> Unit
pub struct WeakEntity[T] {
// private fields
}
pub fn[T] WeakEntity::entity_id(Self[T]) -> EntityId
pub fn[T, R] WeakEntity::update(Self[T], App, (T, Context[T]) -> R) -> R?
pub fn[T] WeakEntity::upgrade(Self[T]) -> Entity[T]?
// Type aliases
// Traits
+179
View File
@@ -0,0 +1,179 @@
// Port of gpui/src/subscription.rs.
//
// Deviation from GPUI: a Rust `Subscription` unsubscribes when dropped. There
// is no `Drop` in MoonBit, so a `Subscription` stays active until
// `unsubscribe()` is called, or until the entity it belongs to is released.
// `detach()` is kept for API parity; it only documents intent.
///|
#derive(Eq)
priv enum SubscriberState {
Pending
Active
Dropped
}
///|
priv struct Subscriber[C] {
id : Int32
mut state : SubscriberState
callback : C
}
///|
/// A set of callbacks keyed by emitter. Callbacks run in subscription order;
/// subscriptions created while callbacks run are pending until activated.
struct SubscriberSet[K, C] {
subscribers : Map[K, Array[Subscriber[C]]]
mut next_subscriber_id : Int32
}
///|
fn[K : Hash + Eq, C] SubscriberSet::new() -> SubscriberSet[K, C] {
{ subscribers: {}, next_subscriber_id: 0, }
}
///|
/// Inserts an active subscriber.
fn[K : Hash + Eq, C] SubscriberSet::insert(
self : SubscriberSet[K, C],
key : K,
callback : C,
) -> Subscription {
let (subscription, activate) = self.insert_pending(key, callback)
activate()
subscription
}
///|
/// Inserts a subscriber that does not run until `activate` is called.
fn[K : Hash + Eq, C] SubscriberSet::insert_pending(
self : SubscriberSet[K, C],
key : K,
callback : C,
) -> (Subscription, () -> Unit) {
let id = self.next_subscriber_id
self.next_subscriber_id = id + 1
let subscriber = { id, state: Pending, callback, }
match self.subscribers.get(key) {
Some(list) => list.push(subscriber)
None => self.subscribers[key] = [subscriber]
}
let subscription = Subscription::new(fn() {
subscriber.state = Dropped
if self.subscribers.get(key) is Some(list) {
let remaining = list.filter(fn(s) { s.id != id })
if remaining.is_empty() {
self.subscribers.remove(key)
} else {
self.subscribers[key] = remaining
}
}
})
let activate = fn() {
if subscriber.state == Pending {
subscriber.state = Active
}
}
(subscription, activate)
}
///|
/// Removes every subscriber of `key`, returning the active callbacks.
fn[K : Hash + Eq, C] SubscriberSet::remove(
self : SubscriberSet[K, C],
key : K,
) -> Array[C] {
match self.subscribers.get(key) {
None => []
Some(list) => {
self.subscribers.remove(key)
list.filter(fn(s) { s.state == Active }).map(fn(s) { s.callback })
}
}
}
///|
/// Calls `f` on every active subscriber of `key`, in order; a subscriber is
/// removed when `f` returns false or when it was unsubscribed meanwhile.
/// Subscribers added during the iteration are kept but not visited.
fn[K : Hash + Eq, C] SubscriberSet::retain(
self : SubscriberSet[K, C],
key : K,
f : (C) -> Bool,
) -> Unit {
guard self.subscribers.get(key) is Some(list) else { return }
// Detach the list so that insertions during callbacks go to a fresh list.
self.subscribers.remove(key)
let kept : Array[Subscriber[C]] = []
for subscriber in list {
let keep = match subscriber.state {
Pending => true
Dropped => false
Active => f(subscriber.callback) && subscriber.state != Dropped
}
if keep && subscriber.state != Dropped {
kept.push(subscriber)
}
}
match self.subscribers.get(key) {
Some(added) =>
// Ids only grow, so newly added subscribers come after the kept ones.
self.subscribers[key] = [
..kept,
..added.filter(fn(s) { s.state != Dropped }),
]
None => if !kept.is_empty() { self.subscribers[key] = kept }
}
}
///|
/// A handle to a registered callback. Call `unsubscribe` to stop it.
pub struct Subscription {
priv mut unsubscribe_fn : (() -> Unit)?
}
///|
/// A subscription that runs `unsubscribe` once when unsubscribed.
pub fn Subscription::new(unsubscribe : () -> Unit) -> Subscription {
{ unsubscribe_fn: Some(unsubscribe), }
}
///|
/// Stops the callback. Idempotent.
pub fn Subscription::unsubscribe(self : Subscription) -> Unit {
if self.unsubscribe_fn is Some(f) {
self.unsubscribe_fn = None
f()
}
}
///|
/// Keeps the callback registered for as long as its entities live. In
/// MoonBit this is the default (there is no drop); kept for GPUI parity.
pub fn Subscription::detach(self : Subscription) -> Unit {
self.unsubscribe_fn = None
}
///|
/// Whether `unsubscribe` has not been called (and `detach` neither).
pub fn Subscription::is_active(self : Subscription) -> Bool {
self.unsubscribe_fn is Some(_)
}
///|
/// One subscription that unsubscribes both.
pub fn Subscription::join(a : Subscription, b : Subscription) -> Subscription {
let a_fn = a.unsubscribe_fn
let b_fn = b.unsubscribe_fn
a.unsubscribe_fn = None
b.unsubscribe_fn = None
Subscription::new(fn() {
if a_fn is Some(f) {
f()
}
if b_fn is Some(f) {
f()
}
})
}
+98
View File
@@ -0,0 +1,98 @@
///|
/// Number of subscribers (pending or active) of `key`.
fn[K : Hash + Eq, C] SubscriberSet::count(
self : SubscriberSet[K, C],
key : K,
) -> Int32 {
match self.subscribers.get(key) {
Some(list) => list.length()
None => 0
}
}
///|
/// Port of GPUI's `test_immediate_and_pending_insertions`.
test "immediate and pending insertions" {
let subscribers : SubscriberSet[Int32, Int32] = SubscriberSet::new()
let first = subscribers.insert(1, 10)
let (second, activate_second) = subscribers.insert_pending(1, 20)
let visited = []
subscribers.retain(1, fn(callback) {
visited.push(callback)
subscribers.insert(1, 30).detach()
true
})
// Pending (20) and newly inserted (30) subscribers are not visited.
assert_eq(visited, [10])
activate_second()
assert_eq(subscribers.remove(1), [10, 20, 30])
first.unsubscribe()
second.unsubscribe()
let (pending, _activate) = subscribers.insert_pending(1, 40)
assert_eq(subscribers.remove(1).length(), 0)
pending.unsubscribe()
}
///|
/// Port of GPUI's `test_activation_after_drop_during_retain`.
test "activation after unsubscribe during retain" {
let subscribers : SubscriberSet[Int32, Int32] = SubscriberSet::new()
let (first, activate_first) = subscribers.insert_pending(1, 10)
let (second, activate_second) = subscribers.insert_pending(1, 20)
subscribers.retain(1, fn(_) { abort("pending subscriber invoked") })
activate_first()
let mut second_taken = false
let visited = []
subscribers.retain(1, fn(callback) {
visited.push(callback)
guard !second_taken else { abort("only the first callback runs") }
second_taken = true
// Unsubscribing then activating must not revive the subscriber.
second.unsubscribe()
activate_second()
true
})
assert_eq(visited, [10])
assert_eq(subscribers.remove(1), [10])
first.unsubscribe()
}
///|
test "retain removes callbacks returning false and keeps order" {
let subscribers : SubscriberSet[String, Int32] = SubscriberSet::new()
for i in 0..<5 {
subscribers.insert("k", i).detach()
}
subscribers.retain("k", fn(i) { i % 2 == 0 })
let seen = []
subscribers.retain("k", fn(i) {
seen.push(i)
true
})
assert_eq(seen, [0, 2, 4])
// A subscriber unsubscribed by an earlier callback does not run.
let later = subscribers.insert("k", 9)
let seen = []
subscribers.retain("k", fn(i) {
seen.push(i)
later.unsubscribe()
true
})
assert_eq(seen, [0, 2, 4])
assert_eq(subscribers.count("k"), 3)
assert_eq(subscribers.count("none"), 0)
}
///|
test "subscription join and is_active" {
let log = []
let a = Subscription::new(fn() { log.push("a") })
let b = Subscription::new(fn() { log.push("b") })
let joined = Subscription::join(a, b)
assert_false(a.is_active())
assert_true(joined.is_active())
joined.unsubscribe()
joined.unsubscribe()
assert_eq(log, ["a", "b"])
assert_false(joined.is_active())
}
+72
View File
@@ -0,0 +1,72 @@
// `canvas()`, ported from gpui/src/elements/canvas.rs: an element laid out by
// its style that paints with a closure.
///|
/// An element that paints itself with a closure (GPUI: `Canvas`).
pub struct Canvas {
priv base_style : @style.StyleRefinement
priv prepaint_fn : (
@geometry.Bounds[@geometry.Pixels],
@window.Window,
@app.App,
) -> Unit
priv paint_fn : (@geometry.Bounds[@geometry.Pixels], @window.Window, @app.App) -> Unit
priv mut layout_style : @style.Style?
}
///|
/// A canvas that runs `paint` with its bounds during the paint phase, and
/// `prepaint` (if given) during prepaint. Size it with style methods, e.g.
/// `canvas(paint).size_full()`.
pub fn canvas(
paint : (@geometry.Bounds[@geometry.Pixels], @window.Window, @app.App) -> Unit,
prepaint~ : (@geometry.Bounds[@geometry.Pixels], @window.Window, @app.App) -> Unit = fn(
_,
_,
_,
) {
},
) -> Canvas {
{
base_style: @style.StyleRefinement::new(),
prepaint_fn: prepaint,
paint_fn: paint,
layout_style: None,
}
}
///|
pub impl @style.Styled for Canvas with fn style(self) {
self.base_style
}
///|
pub impl @window.IntoElement for Canvas with fn into_any_element(self) {
@window.AnyElement::new(self)
}
///|
pub extend Canvas with @window.IntoElement::{into_any_element}
///|
impl @window.Element for Canvas with fn request_layout(self, window, _app) {
let style = (Default::default() : @style.Style).refined(self.base_style)
self.layout_style = Some(style)
window.request_layout(style, [])
}
///|
impl @window.Element for Canvas with fn prepaint(self, bounds, window, app) {
(self.prepaint_fn)(bounds, window, app)
}
///|
impl @window.Element for Canvas with fn paint(self, bounds, window, app) {
guard self.layout_style is Some(style) else {
abort("canvas painted before layout")
}
window.paint_style(style, bounds, fn() {
(self.paint_fn)(bounds, window, app)
})
}
File diff suppressed because it is too large. Load diff
+355
View File
@@ -0,0 +1,355 @@
// `div()`, ported from gpui/src/elements/div.rs (`Div` and the parts of
// `Interactivity` that need neither focus nor actions).
//
// Ported: styles (via `Styled`), children, hover styles, mouse down/up/move
// and scroll listeners, clicks (which need an element id), hitbox
// occlusion, overflow clipping and opacity.
//
// Not ported yet: focus and key listeners and actions (M5/M10), active and
// group styles, drag and drop, tooltips, scrolling state, and the
// `Stateful<Div>` split (an id is set with `.id(...)` on `Div` itself, and
// `on_click` fails loudly without one).
//
// Deviation: hover styles apply at paint time only. GPUI also lays out with
// them (using the previous frame's hover state); here hovering cannot change
// an element's layout.
///|
/// A flexible container: GPUI's workhorse element (`div()`).
pub struct Div {
priv base_style : @style.StyleRefinement
priv mut hover_style : @style.StyleRefinement?
priv mut element_id : String?
priv mut occlude_mouse : Bool
priv children : Array[@window.AnyElement]
priv mouse_down_listeners : Array[
(
@input.MouseButton,
(@input.MouseDownEvent, @window.Window, @app.App) -> Unit,
),
]
priv mouse_up_listeners : Array[
(
@input.MouseButton,
(@input.MouseUpEvent, @window.Window, @app.App) -> Unit,
),
]
priv mouse_move_listeners : Array[
(@input.MouseMoveEvent, @window.Window, @app.App) -> Unit,
]
priv scroll_listeners : Array[
(@input.ScrollWheelEvent, @window.Window, @app.App) -> Unit,
]
priv click_listeners : Array[
(@input.ClickEvent, @window.Window, @app.App) -> Unit,
]
// Per-frame state.
priv mut layout_style : @style.Style?
priv mut hitbox : @window.Hitbox?
}
///|
/// A new, empty `div`.
pub fn div() -> Div {
{
base_style: @style.StyleRefinement::new(),
hover_style: None,
element_id: None,
occlude_mouse: false,
children: [],
mouse_down_listeners: [],
mouse_up_listeners: [],
mouse_move_listeners: [],
scroll_listeners: [],
click_listeners: [],
layout_style: None,
hitbox: None,
}
}
///|
pub impl @style.Styled for Div with fn style(self) {
self.base_style
}
///|
pub impl @window.IntoElement for Div with fn into_any_element(self) {
@window.AnyElement::new(self)
}
///|
pub extend Div with @window.IntoElement::{into_any_element}
///|
/// Gives the element an id, which makes it stateful (needed for clicks).
/// Ids are scoped to the parent's id (GPUI: `.id(...)`).
pub fn Div::id(self : Div, id : String) -> Div {
self.element_id = Some(id)
self
}
///|
/// Adds a child (GPUI: `ParentElement::child`).
pub fn[E : @window.IntoElement] Div::child(self : Div, child : E) -> Div {
self.children.push(child.into_any_element())
self
}
///|
/// Adds children (GPUI: `ParentElement::children`).
pub fn[E : @window.IntoElement] Div::children(
self : Div,
children : Array[E],
) -> Div {
for child in children {
self.children.push(child.into_any_element())
}
self
}
///|
/// Styles applied while the mouse is over the element (GPUI: `.hover(...)`).
pub fn Div::hover(
self : Div,
f : (@style.StyleRefinement) -> @style.StyleRefinement,
) -> Div {
let current = match self.hover_style {
Some(style) => style
None => @style.StyleRefinement::new()
}
self.hover_style = Some(f(current))
self
}
///|
/// Hitboxes painted below this element are not hovered (GPUI:
/// `.occlude()`).
pub fn Div::occlude(self : Div) -> Div {
self.occlude_mouse = true
self
}
///|
/// Called when `button` is pressed over the element (bubble phase).
pub fn Div::on_mouse_down(
self : Div,
button : @input.MouseButton,
listener : (@input.MouseDownEvent, @window.Window, @app.App) -> Unit,
) -> Div {
self.mouse_down_listeners.push((button, listener))
self
}
///|
/// Called when `button` is released over the element (bubble phase).
pub fn Div::on_mouse_up(
self : Div,
button : @input.MouseButton,
listener : (@input.MouseUpEvent, @window.Window, @app.App) -> Unit,
) -> Div {
self.mouse_up_listeners.push((button, listener))
self
}
///|
/// Called when the mouse moves over the element (bubble phase).
pub fn Div::on_mouse_move(
self : Div,
listener : (@input.MouseMoveEvent, @window.Window, @app.App) -> Unit,
) -> Div {
self.mouse_move_listeners.push(listener)
self
}
///|
/// Called on scroll-wheel events over the element (bubble phase).
pub fn Div::on_scroll_wheel(
self : Div,
listener : (@input.ScrollWheelEvent, @window.Window, @app.App) -> Unit,
) -> Div {
self.scroll_listeners.push(listener)
self
}
///|
/// Called when the left button is pressed and released over the element.
/// The element needs an id (GPUI: `StatefulInteractiveElement::on_click`).
pub fn Div::on_click(
self : Div,
listener : (@input.ClickEvent, @window.Window, @app.App) -> Unit,
) -> Div {
self.click_listeners.push(listener)
self
}
///|
fn Div::is_interactive(self : Div) -> Bool {
self.hover_style is Some(_) ||
self.occlude_mouse ||
!self.mouse_down_listeners.is_empty() ||
!self.mouse_up_listeners.is_empty() ||
!self.mouse_move_listeners.is_empty() ||
!self.scroll_listeners.is_empty() ||
!self.click_listeners.is_empty()
}
///|
/// The pending press of a click, kept across frames.
priv struct ClickState {
mut pending : @input.MouseDownEvent?
}
///|
let click_state_key : @window.ElementStateKey[ClickState] = @window.ElementStateKey::new(
"ClickState",
)
///|
impl @window.Element for Div with fn request_layout(self, window, app) {
let style = (Default::default() : @style.Style).refined(self.base_style)
self.layout_style = Some(style)
window.with_element_id(self.element_id, fn() {
let child_ids = self.children.map(fn(child) {
child.request_layout(window, app)
})
window.request_layout(style, child_ids)
})
}
///|
impl @window.Element for Div with fn prepaint(self, bounds, window, app) {
guard self.layout_style is Some(style) else {
abort("div prepainted before layout")
}
window.with_element_id(self.element_id, fn() {
if self.is_interactive() {
let behavior : @window.HitboxBehavior = if self.occlude_mouse {
BlockMouse
} else {
Normal
}
self.hitbox = Some(window.insert_hitbox(bounds, behavior))
}
window.with_content_mask(style.overflow_mask(bounds, window.rem_size()), fn() {
for child in self.children {
child.prepaint(window, app)
}
})
})
}
///|
impl @window.Element for Div with fn paint(self, bounds, window, app) {
guard self.layout_style is Some(layout_style) else {
abort("div painted before layout")
}
let hovered = match self.hitbox {
Some(hitbox) => hitbox.is_hovered(window)
None => false
}
let style = match (self.hover_style, hovered) {
(Some(hover), true) => layout_style.refined(hover)
_ => layout_style
}
window.with_element_id(self.element_id, fn() {
if self.hitbox is Some(hitbox) {
self.register_listeners(hitbox, window)
}
window.with_element_opacity(style.opacity, fn() {
window.paint_style(style, bounds, fn() {
window.with_content_mask(
style.overflow_mask(bounds, window.rem_size()),
fn() {
for child in self.children {
child.paint(window, app)
}
},
)
})
})
})
}
///|
fn Div::register_listeners(
self : Div,
hitbox : @window.Hitbox,
window : @window.Window,
) -> Unit {
for entry in self.mouse_down_listeners {
let (button, listener) = entry
window.on_mouse_event(fn(event, phase, window, app) {
if phase == Bubble &&
event is MouseDown(down) &&
down.button == button &&
hitbox.is_hovered(window) {
listener(down, window, app)
}
})
}
for entry in self.mouse_up_listeners {
let (button, listener) = entry
window.on_mouse_event(fn(event, phase, window, app) {
if phase == Bubble &&
event is MouseUp(up) &&
up.button == button &&
hitbox.is_hovered(window) {
listener(up, window, app)
}
})
}
for listener in self.mouse_move_listeners {
window.on_mouse_event(fn(event, phase, window, app) {
if phase == Bubble &&
event is MouseMove(moved) &&
hitbox.is_hovered(window) {
listener(moved, window, app)
}
})
}
for listener in self.scroll_listeners {
window.on_mouse_event(fn(event, phase, window, app) {
if phase == Bubble &&
event is ScrollWheel(scroll) &&
hitbox.is_hovered(window) {
listener(scroll, window, app)
}
})
}
if !self.click_listeners.is_empty() {
guard window.global_element_id() is Some(_) else {
abort("on_click requires an element id: call .id(...) on the div")
}
// The pending press lives in element state so it survives redraws
// between mouse down and mouse up.
let state = window.with_element_state(click_state_key, fn(previous) {
let state = match previous {
Some(state) => state
None => { pending: None, }
}
(state, state)
})
let listeners = self.click_listeners
window.on_mouse_event(fn(event, phase, window, app) {
match (event, phase) {
(MouseDown(down), Bubble) =>
if down.button == Left && hitbox.is_hovered(window) {
state.pending = Some(down)
}
(MouseUp(up), Capture) =>
if up.button == Left {
match state.pending {
Some(down) if hitbox.is_hovered(window) => {
state.pending = None
for listener in listeners {
listener({ down, up, }, window, app)
}
}
_ => state.pending = None
}
}
_ => ()
}
})
}
}
File diff suppressed because it is too large. Load diff
+427
View File
@@ -0,0 +1,427 @@
///|
fn px(v : Double) -> @geometry.Pixels {
@geometry.px(v)
}
///|
fn pt(x : Double, y : Double) -> @geometry.Point[@geometry.Pixels] {
@geometry.point(px(x), px(y))
}
///|
fn mouse_down(x : Double, y : Double) -> @input.MouseEvent {
MouseDown({ ..Default::default(), position: pt(x, y), click_count: 1, })
}
///|
fn mouse_up(x : Double, y : Double) -> @input.MouseEvent {
MouseUp({ ..Default::default(), position: pt(x, y), click_count: 1, })
}
///|
fn mouse_move(x : Double, y : Double) -> @input.MouseEvent {
MouseMove({ ..Default::default(), position: pt(x, y), })
}
///|
fn sp(v : Double) -> @geometry.ScaledPixels {
@geometry.ScaledPixels(v)
}
///|
fn sbounds(
x : Double,
y : Double,
w : Double,
h : Double,
) -> @geometry.Bounds[@geometry.ScaledPixels] {
@geometry.bounds(@geometry.point(sp(x), sp(y)), @geometry.size(sp(w), sp(h)))
}
// A counter view: a row with a decrement button, a value bar and an
// increment button.
///|
struct Counter {
mut count : Int32
mut renders : Int32
}
///|
impl @window.Render for Counter with fn render(self, _window, cx) {
self.renders += 1
@elements.div()
.flex()
.flex_row()
.gap(px(10.0))
.p(px(10.0))
.size_full()
.bg(@color.rgb(0xffffff))
.child(
@elements.div()
.id("minus")
.size(px(20.0))
.bg(@color.rgb(0xcc0000))
.on_click(
@window.listener(cx, fn(counter, _, _, cx) {
counter.count -= 1
cx.notify()
}),
),
)
.child(
@elements.div()
.w(px((self.count * 10).to_double()))
.h(px(20.0))
.bg(@color.rgb(0x0000cc)),
)
.child(
@elements.div()
.id("plus")
.size(px(20.0))
.bg(@color.rgb(0x00cc00))
.hover(fn(style) { style.bg(@color.rgb(0x00ff00)) })
.on_click(
@window.listener(cx, fn(counter, _, _, cx) {
counter.count += 1
cx.notify()
}),
),
)
.into_any_element()
}
///|
fn setup_counter(
count~ : Int32 = 3,
scale_factor~ : Double = 1.0,
) -> (@app.App, @window.Window, @app.Entity[Counter]) {
let app = @app.App::new()
let window = @window.Window::new(
app,
@geometry.size(px(200.0), px(40.0)),
scale_factor~,
)
let counter : @app.Entity[Counter] = app.new_entity(fn(_) {
{ count, renders: 0, }
})
window.set_root_view(counter)
(app, window, counter)
}
///|
test "a view renders a laid-out div tree into the scene" {
let (_, window, _) = setup_counter()
let scene = window.draw()
// Root background, minus, value bar (3 * 10px) and plus.
assert_eq(scene.quads.length(), 4)
let bounds = scene.quads.map(fn(q) { q.bounds })
assert_eq(bounds, [
sbounds(0.0, 0.0, 200.0, 40.0),
sbounds(10.0, 10.0, 20.0, 20.0),
sbounds(40.0, 10.0, 30.0, 20.0),
sbounds(80.0, 10.0, 20.0, 20.0),
])
assert_eq(scene.quads[1].background, @color.rgb(0xcc0000).to_background())
assert_eq(scene.batches().map(fn(b) { b.label() }), ["quads (4)"])
assert_eq(window.frame_count(), 1)
assert_false(window.is_dirty())
}
///|
test "device pixels at 2x" {
let (_, window, _) = setup_counter(scale_factor=2.0)
let scene = window.draw()
assert_eq(scene.quads[3].bounds, sbounds(160.0, 20.0, 40.0, 40.0))
}
///|
test "clicks update the view and invalidate the window" {
let (app, window, counter) = setup_counter()
ignore(window.draw())
// Click "plus" (80..100, 10..30).
ignore(window.dispatch_mouse_event(mouse_down(90.0, 20.0)))
ignore(window.dispatch_mouse_event(mouse_up(90.0, 20.0)))
assert_eq(counter.read(app).count, 4)
assert_true(window.is_dirty())
let scene = window.draw()
// The value bar grew to 40px and pushed "plus" to the right.
assert_eq(scene.quads[2].bounds.size.width, sp(40.0))
assert_eq(scene.quads[3].bounds.origin.x, sp(90.0))
// Click "minus" twice.
for _ in 0..<2 {
ignore(window.dispatch_mouse_event(mouse_down(15.0, 15.0)))
ignore(window.dispatch_mouse_event(mouse_up(15.0, 15.0)))
ignore(window.draw())
}
assert_eq(counter.read(app).count, 2)
}
///|
test "a click needs press and release over the same element" {
let (app, window, counter) = setup_counter()
ignore(window.draw())
// Press on "plus", release elsewhere: no click.
ignore(window.dispatch_mouse_event(mouse_down(90.0, 20.0)))
ignore(window.dispatch_mouse_event(mouse_up(150.0, 20.0)))
assert_eq(counter.read(app).count, 3)
// Press elsewhere, release on "plus": no click either.
ignore(window.dispatch_mouse_event(mouse_down(150.0, 20.0)))
ignore(window.dispatch_mouse_event(mouse_up(90.0, 20.0)))
assert_eq(counter.read(app).count, 3)
}
///|
test "hover styles apply under the mouse" {
let (_, window, _) = setup_counter()
ignore(window.draw())
ignore(window.dispatch_mouse_event(mouse_move(90.0, 20.0)))
// Entering a hitbox marks the window dirty.
assert_true(window.is_dirty())
let scene = window.draw()
assert_eq(scene.quads[3].background, @color.rgb(0x00ff00).to_background())
ignore(window.dispatch_mouse_event(mouse_move(150.0, 20.0)))
let scene = window.draw()
assert_eq(scene.quads[3].background, @color.rgb(0x00cc00).to_background())
// Moving within nothing interactive does not dirty the window.
ignore(window.dispatch_mouse_event(mouse_move(151.0, 20.0)))
assert_false(window.is_dirty())
}
///|
test "only rendered views invalidate the window" {
let (app, window, counter) = setup_counter()
ignore(window.draw())
let unrelated : @app.Entity[Counter] = app.new_entity(fn(_) {
{ count: 0, renders: 0, }
})
unrelated.update(app, fn(_, cx) { cx.notify() })
assert_false(window.is_dirty())
assert_false(window.draw_if_dirty())
counter.update(app, fn(_, cx) { cx.notify() })
assert_true(window.draw_if_dirty())
assert_eq(counter.read(app).renders, 2)
}
///|
struct Panel {
child : @app.Entity[Counter]
log : Array[String]
}
///|
impl @window.Render for Panel with fn render(self, _window, _cx) {
let log = self.log
@elements.div()
.size_full()
.p(px(4.0))
.on_mouse_down(Left, fn(_, _, _) { log.push("panel down") })
.child(self.child)
.into_any_element()
}
///|
test "nested views and event bubbling" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(208.0), px(48.0)))
let child : @app.Entity[Counter] = app.new_entity(fn(_) {
{ count: 0, renders: 0, }
})
let panel : @app.Entity[Panel] = app.new_entity(fn(_) { { child, log: [], } })
window.set_root_view(panel)
let scene = window.draw()
// The child view is laid out inside the panel's padding.
assert_eq(scene.quads[0].bounds.origin, @geometry.point(sp(4.0), sp(4.0)))
// With a count of 0 the value bar is empty: "plus" spans x 54..74.
// A press on it reaches the button first, then bubbles to the panel.
ignore(window.dispatch_mouse_event(mouse_down(64.0, 24.0)))
ignore(window.dispatch_mouse_event(mouse_up(64.0, 24.0)))
assert_eq(child.read(app).count, 1)
assert_eq(panel.read(app).log, ["panel down"])
// Notifying the nested view invalidates the window too.
ignore(window.draw())
child.update(app, fn(_, cx) { cx.notify() })
assert_true(window.is_dirty())
}
///|
struct Layers {
log : Array[String]
}
///|
impl @window.Render for Layers with fn render(self, _window, _cx) {
let log = self.log
@elements.div()
.size_full()
.relative()
.on_mouse_down(Left, fn(_, _, _) { log.push("background") })
.child(
@elements.div()
.absolute()
.size(px(50.0))
.occlude()
.on_mouse_down(Left, fn(_, window, _) {
log.push("overlay")
window.stop_propagation()
}),
)
.into_any_element()
}
///|
test "occlusion and stop_propagation" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(100.0), px(100.0)))
let view : @app.Entity[Layers] = app.new_entity(fn(_) { { log: [], } })
window.set_root_view(view)
ignore(window.draw())
let propagated = window.dispatch_mouse_event(mouse_down(10.0, 10.0))
assert_false(propagated)
ignore(window.dispatch_mouse_event(mouse_down(80.0, 80.0)))
assert_eq(view.read(app).log, ["overlay", "background"])
}
///|
struct Styled {
opacity : Double
}
///|
impl @window.Render for Styled with fn render(self, _window, _cx) {
@elements.div()
.size_full()
.overflow_hidden()
.opacity(self.opacity)
.shadow_sm()
.rounded_md()
.border_2()
.border_color(@color.black())
.bg(@color.rgb(0x336699))
.child(@elements.div().w(px(500.0)).h(px(10.0)).bg(@color.red()))
.into_any_element()
}
///|
test "shadows, borders, opacity and overflow clipping" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(100.0), px(100.0)))
let view : @app.Entity[Styled] = app.new_entity(fn(_) { { opacity: 0.5, } })
window.set_root_view(view)
let scene = window.draw()
assert_eq(scene.shadows.length(), 2)
// Background, child, border.
assert_eq(scene.quads.length(), 3)
let background = scene.quads[0]
assert_eq(background.background.solid.a, 0.5)
assert_eq(background.corner_radii.top_left, sp(6.0))
let border = scene.quads.filter(fn(q) { q.border_widths.top == sp(2.0) })
assert_eq(border.length(), 1)
assert_eq(border[0].border_color.a, 0.5)
// The wide child is clipped to the inside of the border.
let child = scene.quads.filter(fn(q) { q.bounds.size.width == sp(500.0) })
assert_eq(child[0].content_mask.bounds, sbounds(2.0, 2.0, 96.0, 96.0))
// Quads overlapping quads share a draw order and form one batch, drawn in
// insertion order: background, child, then the border on top.
assert_eq(scene.batches().map(fn(b) { b.label() }), [
"shadows (2)", "quads (3)",
])
assert_eq(scene.quads[2].border_widths.top, sp(2.0))
}
///|
enum Drawing {
Drawing
}
///|
impl @window.Render for Drawing with fn render(_self, _window, _cx) {
@elements.div()
.size_full()
.p(px(10.0))
.child(
@elements.canvas(fn(bounds, window, _) {
window.paint_path(
[[bounds.origin, bounds.top_right(), bounds.bottom_left()]],
@color.blue().to_background(),
)
}).size(px(30.0)),
)
.into_any_element()
}
///|
test "canvas paints with its bounds" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(100.0), px(100.0)))
let view : @app.Entity[Drawing] = app.new_entity(fn(_) { Drawing })
window.set_root_view(view)
let scene = window.draw()
assert_eq(scene.paths.length(), 1)
assert_eq(scene.paths[0].bounds, sbounds(10.0, 10.0, 30.0, 30.0))
}
///|
test "resizing relayouts" {
let (_, window, _) = setup_counter()
ignore(window.draw())
window.resize(@geometry.size(px(300.0), px(60.0)), scale_factor=2.0)
assert_true(window.is_dirty())
let scene = window.draw()
assert_eq(scene.quads[0].bounds, sbounds(0.0, 0.0, 600.0, 120.0))
}
///|
enum Broken {
Broken
}
///|
impl @window.Render for Broken with fn render(_self, _window, _cx) {
@elements.div().on_click(fn(_, _, _) { }).into_any_element()
}
///|
test "panic on on_click without an id" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(10.0), px(10.0)))
let view : @app.Entity[Broken] = app.new_entity(fn(_) { Broken })
window.set_root_view(view)
ignore(window.draw())
}
///|
test "panic on drawing without a root view" {
let window = @window.Window::new(
@app.App::new(),
@geometry.size(px(10.0), px(10.0)),
)
ignore(window.draw())
}
///|
enum PaintsDuringLayout {
PaintsDuringLayout
}
///|
impl @window.Render for PaintsDuringLayout with fn render(_self, window, _cx) {
window.paint_quad(
@window.fill(
@geometry.bounds(pt(0.0, 0.0), @geometry.size(px(1.0), px(1.0))),
@color.red().to_background(),
),
)
@window.empty()
}
///|
test "panic on painting outside the paint phase" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(10.0), px(10.0)))
let view : @app.Entity[PaintsDuringLayout] = app.new_entity(fn(_) {
PaintsDuringLayout
})
window.set_root_view(view)
ignore(window.draw())
}
+16
View File
@@ -0,0 +1,16 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/style",
"experiments/gpui/input",
"experiments/gpui/app",
"experiments/gpui/window",
}
options(
"allow-experimental-packages": true,
)
import {
"experiments/gpui/color",
"experiments/gpui/platform/test" @test_platform,
} for "test"
File diff suppressed because it is too large. Load diff
+187
View File
@@ -0,0 +1,187 @@
///|
struct VisualCounter {
mut count : Int32
}
///|
impl @window.Render for VisualCounter with fn render(self, _window, cx) {
@elements.div()
.flex()
.flex_row()
.gap(px(10.0))
.p(px(10.0))
.size_full()
.bg(@color.rgb(0xffffff))
.child(
@elements.div()
.id("minus")
.size(px(20.0))
.bg(@color.rgb(0xcc0000))
.on_click(
@window.listener(cx, fn(counter, _, _, cx) {
counter.count -= 1
cx.notify()
}),
),
)
.child(
@elements.div()
.w(px((self.count * 10).to_double()))
.h(px(20.0))
.bg(@color.rgb(0x0000cc)),
)
.child(
@elements.div()
.id("plus")
.size(px(20.0))
.bg(@color.rgb(0x00cc00))
.hover(fn(style) { style.bg(@color.rgb(0x00ff00)) })
.on_click(
@window.listener(cx, fn(counter, _, _, cx) {
counter.count += 1
cx.notify()
}),
),
)
.into_any_element()
}
///|
test "VisualTestContext renders div counter and tracks scene history" {
let cx = @test_platform.TestAppContext::new()
let (counter, vcx) = cx.add_window_view(
size=@geometry.size(px(200.0), px(40.0)),
fn(_, _) { { count: 3, } },
)
assert_eq(vcx.draw_count(), 1)
assert_eq(vcx.scene().quads.length(), 4)
assert_eq(vcx.scene().quads[2].bounds.size.width, sp(30.0))
assert_eq(
vcx.scene().quads[3].background,
@color.rgb(0x00cc00).to_background(),
)
// Moving onto "plus" triggers hover redraw automatically.
ignore(vcx.simulate_mouse_move(pt(90.0, 20.0)))
assert_eq(vcx.draw_count(), 2)
assert_eq(
vcx.scene().quads[3].background,
@color.rgb(0x00ff00).to_background(),
)
// Clicking "plus" updates the view and draws the expanded value bar.
vcx.simulate_click(pt(90.0, 20.0))
assert_eq(cx.read_entity(counter).count, 4)
assert_eq(vcx.draw_count(), 3)
assert_eq(vcx.drawn_scenes().length(), 3)
assert_eq(vcx.scene().quads[2].bounds.size.width, sp(40.0))
assert_eq(vcx.scene().quads[3].bounds.origin.x, sp(90.0))
}
///|
enum VisualCanvasView {
VisualCanvasView
}
///|
impl @window.Render for VisualCanvasView with fn render(_self, _window, _cx) {
@elements.div()
.flex()
.size_full()
.p(px(10.0))
.child(
@elements.canvas(fn(bounds, window, _) {
window.paint_path(
[[bounds.origin, bounds.top_right(), bounds.bottom_left()]],
@color.blue().to_background(),
)
}).size_full(),
)
.into_any_element()
}
///|
test "VisualTestContext resize, scale factor, and canvas view" {
let cx = @test_platform.TestAppContext::new()
let (_, vcx) = cx.add_window_view(size=@geometry.size(px(100.0), px(80.0)), fn(
_,
_,
) {
VisualCanvasView
})
assert_eq(vcx.scene().paths.length(), 1)
assert_eq(vcx.scene().paths[0].bounds, sbounds(10.0, 10.0, 80.0, 60.0))
vcx.simulate_resize(@geometry.size(px(150.0), px(100.0)))
vcx.simulate_scale_factor_change(2.0)
assert_eq(vcx.scene().paths[0].bounds, sbounds(20.0, 20.0, 260.0, 160.0))
}
///|
struct VisualTicker {
mut ticks : Int32
}
///|
impl @window.Render for VisualTicker with fn render(self, _window, _cx) {
@elements.div()
.size_full()
.child(
@elements.div()
.w(px((self.ticks * 20).to_double()))
.h(px(10.0))
.bg(@color.red()),
)
.into_any_element()
}
///|
test "VisualTestContext async ticker updates div layout on virtual clock" {
let cx = @test_platform.TestAppContext::new()
let (ticker, vcx) = cx.add_window_view(
size=@geometry.size(px(200.0), px(40.0)),
fn(_, ctx) {
let weak : @app.WeakEntity[VisualTicker] = ctx.weak_entity()
ctx
.spawn(async fn(_, async_app) {
while true {
async_app.background_executor().sleep(100)
let alive = weak.update(async_app.app, fn(t : VisualTicker, cx) {
t.ticks = t.ticks + 1
cx.notify()
})
if alive is None {
break
}
}
})
.detach()
{ ticks: 0, }
},
)
assert_eq(vcx.draw_count(), 1)
assert_eq(vcx.scene().quads.length(), 0)
cx.advance_clock(250)
assert_eq(cx.read_entity(ticker).ticks, 2)
assert_true(vcx.draw_count() >= 2)
assert_eq(vcx.scene().quads.length(), 1)
assert_eq(vcx.scene().quads[0].bounds.size.width, sp(40.0))
}
///|
test "closing VisualTestContext window releases rendered div view" {
let cx = @test_platform.TestAppContext::new()
let released = Ref(false)
let (counter, vcx) = cx.add_window_view(
size=@geometry.size(px(100.0), px(40.0)),
fn(_, ctx) {
ctx.on_release(fn(_, _) { released.val = true }).detach()
{ count: 1, }
},
)
assert_false(released.val)
assert_true(vcx.simulate_close())
assert_true(counter.is_released())
assert_true(released.val)
}
+82 -162
View File
@@ -1,187 +1,107 @@
// A headless example of what exists so far (M0-M2): describe a "card" with // A headless example of what exists so far (M0-M7): a view renders a card
// GPUI's fluent style API, lay it out with the layout engine (text is a fake // with GPUI's `div()` and fluent styles inside a `TestPlatform` window,
// fixed-width measure until the text system lands), and paint it into a // and `VisualTestContext` simulates a hover and click while pumping frames
// Scene. There is no renderer yet, so the output is a text report. // automatically. There is no renderer or text yet (text lines are
// placeholder bars), so the output is a report of the scene's draw batches
// and quads.
// //
// Run with: moon run src/examples/card --target js // Run with: moon run src/examples/card --target js
///| ///|
/// The card's style, written exactly as in GPUI: struct Card {
/// `div().flex().p_4().rounded_lg().border_1().shadow_md().bg(...)`. mut expanded : Bool
fn card_style() -> @style.StyleRefinement { mut clicks : Int32
@style.StyleRefinement::new()
.flex()
.flex_col()
.gap_2()
.p_4()
.w(@geometry.px(320.0))
.rounded_lg()
.border_1()
.border_color(@color.rgb(0xd0d7de))
.bg(@color.rgb(0xffffff))
.shadow_md()
.text_color(@color.rgb(0x1f2328))
.text_sm()
} }
///| ///|
/// Paints the resolved style's background, border and shadows, the way /// A placeholder for a line of text (the text system arrives in M9).
/// GPUI's `Style::paint` will once the Window exists (M6). fn text_bar(width : Double, color : UInt32) -> @elements.Div {
fn paint_card( @elements.div()
scene : @scene.Scene, .w(@geometry.px(width))
style : @style.Style, .h(@geometry.px(10.0))
bounds : @geometry.Bounds[@geometry.Pixels], .rounded_sm()
rem_size : @geometry.Pixels, .bg(@color.rgb(color))
scale_factor : Double, }
) -> Unit {
let corner_radii = style.corner_radii ///|
.absolute_to_pixels(rem_size) impl @window.Render for Card with fn render(self, _window, cx) {
.clamp_radii_for_quad_size(bounds.size) let body_lines = if self.expanded { 4 } else { 1 }
let mask : @geometry.ContentMask[@geometry.Pixels] = { let card = @elements.div()
bounds: bounds.dilate(@geometry.px(64.0)), .id("card")
} .flex()
for shadow in style.box_shadow { .flex_col()
let shadow_bounds = bounds .gap_2()
.translate(shadow.offset) .p_4()
.dilate(shadow.spread_radius) .w(@geometry.px(320.0))
scene.insert_primitive( .rounded_lg()
Shadow({ .border_1()
order: 0, .border_color(@color.rgb(0xd0d7de))
blur_radius: shadow.blur_radius.scale(scale_factor), .bg(@color.rgb(0xffffff))
bounds: shadow_bounds.scale(scale_factor), .shadow_md()
corner_radii: corner_radii.scale(scale_factor), .hover(fn(style) { style.border_color(@color.rgb(0x0969da)) })
content_mask: mask.scale(scale_factor), .on_click(
color: shadow.color, @window.listener(cx, fn(card, _, _, cx) {
shape_bounds: bounds.scale(scale_factor), card.expanded = !card.expanded
shape_corner_radii: corner_radii.scale(scale_factor), card.clicks += 1
inset: false, cx.notify()
}), }),
) )
.child(text_bar(160.0, 0x1f2328))
for _ in 0..<body_lines {
ignore(card.child(text_bar(280.0, 0x656d76)))
} }
let background = match style.background { @elements.div()
Some(fill) => fill.color().unwrap() .size_full()
None => Default::default() .flex()
} .items_start()
scene.insert_primitive( .p(@geometry.px(40.0))
Quad({ .bg(@color.rgb(0xf6f8fa))
order: 0, .child(card)
border_style: style.border_style, .into_any_element()
bounds: bounds.scale(scale_factor),
content_mask: mask.scale(scale_factor),
background,
border_color: style.border_color.unwrap_or(@color.transparent_black()),
corner_radii: corner_radii.scale(scale_factor),
border_widths: style.border_widths
.absolute_to_pixels(rem_size)
.scale(scale_factor),
}),
)
} }
///| ///|
/// A stand-in for text measurement (M9): `char_width` per character, wrapping fn describe(
/// at the available width, one `line_height` per line. label : String,
fn fake_text( scene : @scene.Scene,
chars : Int32, lines : Array[String],
char_width : Double, ) -> Unit {
line_height : Double, lines.push(label)
) -> @layout.MeasureFn { let batches = scene.batches().map(fn(b) { b.label() }).join(", ")
fn(known, available) { lines.push(" batches: \{batches}")
let natural = chars.to_double() * char_width for quad in scene.quads {
let wrap = match (known.width, available.width) { let b = quad.bounds
(Some(width), _) => width.to_double() let extra = if quad.border_widths.top.to_double() > 0.0 {
(None, Definite(width)) => width.to_double() " border \{quad.border_color.to_rgb()}"
(None, _) => natural } else {
""
} }
let width = if natural < wrap { natural } else { wrap } lines.push(
let per_line = (wrap / char_width).floor() " quad (\{b.origin.x.to_double()}, \{b.origin.y.to_double()}) \{b.size.width.to_double()} x \{b.size.height.to_double()}\{extra}",
let lines = (chars.to_double() / per_line).ceil() )
@geometry.size(@geometry.px(width), @geometry.px(lines * line_height))
} }
} }
///|
fn show_bounds(bounds : @geometry.Bounds[@geometry.Pixels]) -> String {
"(\{bounds.origin.x}, \{bounds.origin.y}) \{bounds.size.width} x \{bounds.size.height}"
}
///| ///|
/// Builds the report printed by `main`. /// Builds the report printed by `main`.
fn report() -> String { fn report() -> String {
let rem_size = @geometry.px(16.0) let cx = @test_platform.TestAppContext::new()
let scale_factor = 2.0 let (card, vcx) = cx.add_window_view(
let style = (Default::default() : @style.Style).refined(card_style()) size=@geometry.size(@geometry.px(400.0), @geometry.px(240.0)),
let text = (Default::default() : @style.TextStyle).refined(style.text) fn(_, _) { { expanded: false, clicks: 0, } },
let line_height = text.line_height_in_pixels(rem_size).to_double()
// Layout: window root > card > (title, body).
let engine = @layout.LayoutEngine::new()
let leaf_style : @style.Style = Default::default()
let title = engine.request_measured_layout(
leaf_style,
rem_size,
scale_factor,
fake_text(16, 9.0, line_height),
) )
let body = engine.request_measured_layout( let card : @app.Entity[Card] = card
leaf_style, let lines = []
rem_size, describe("first frame", vcx.scene(), lines)
scale_factor, // Hover the card, then click it: the view expands and the window redraws.
fake_text(90, 7.0, line_height), let inside = @geometry.point(@geometry.px(100.0), @geometry.px(60.0))
ignore(vcx.simulate_mouse_move(inside))
vcx.simulate_click(inside)
let state = cx.read_entity(card)
lines.push(
"clicked: expanded = \{state.expanded}, clicks = \{state.clicks}, frames = \{vcx.draw_count()}, dirty = \{vcx.window().is_dirty()}",
) )
let card = engine.request_layout(style, rem_size, scale_factor, [title, body]) describe("after click (hovered)", vcx.scene(), lines)
let root_style = (Default::default() : @style.Style).refined(
@style.StyleRefinement::new().flex().items_start().p(@geometry.px(40.0)),
)
let root = engine.request_layout(root_style, rem_size, scale_factor, [card])
let window_size = @geometry.size(@geometry.px(480.0), @geometry.px(320.0))
engine.stretch_auto_size_to_fill(root, window_size, scale_factor)
engine.compute_layout(
root,
@layout.AvailableSpace::from_size(window_size),
scale_factor,
)
let card_bounds = engine.layout_bounds(card, scale_factor)
let title_bounds = engine.layout_bounds(title, scale_factor)
let body_bounds = engine.layout_bounds(body, scale_factor)
// Paint.
let scene = @scene.Scene::new()
paint_card(scene, style, card_bounds, rem_size, scale_factor)
scene.insert_primitive(
Underline({
order: 0,
bounds: @geometry.bounds(
title_bounds.bottom_left(),
@geometry.size(title_bounds.size.width, @geometry.px(1.0)),
).scale(scale_factor),
content_mask: { bounds: card_bounds.scale(scale_factor), },
color: text.color,
thickness: @geometry.ScaledPixels(2.0),
wavy: false,
}),
)
scene.finish()
let lines = [
"card style",
" display: \{@debug.to_string(style.display)}, direction: \{@debug.to_string(style.flex_direction)}",
" width: \{style.size.width}, padding: \{style.padding.top}, gap: \{style.gap.width}",
" radius: \{style.corner_radii.top_left} = \{style.corner_radii.top_left.to_pixels(rem_size)}",
" shadows: \{style.box_shadow.length()}",
" text: \{text.font_size.to_pixels(rem_size)} \{text.font_family}, line height \{line_height}px, color \{text.color.to_rgb()}",
"layout (logical px)",
" window \{show_bounds(engine.layout_bounds(root, scale_factor))}",
" card \{show_bounds(card_bounds)}",
" title \{show_bounds(title_bounds)}",
" body \{show_bounds(body_bounds)}",
"scene at \{scale_factor}x",
]
for batch in scene.batches() {
lines.push(" \{batch.label()}")
}
for quad in scene.quads {
lines.push(
" quad order \{quad.order}: \{quad.bounds.size.width.0} x \{quad.bounds.size.height.0} device px",
)
}
lines.join("\n") lines.join("\n")
} }
+18 -16
View File
@@ -3,22 +3,24 @@ test "card report" {
inspect( inspect(
report(), report(),
content=( content=(
#|card style #|first frame
#| display: Flex, direction: Column #| batches: quads (1), shadows (2), quads (4)
#| width: 320px, padding: 1rem, gap: 0.5rem #| quad (0, 0) 400 x 240
#| radius: 0.5rem = 8px #| quad (40, 40) 320 x 62
#| shadows: 2 #| quad (57, 57) 160 x 10
#| text: 14px .SystemUIFont, line height 23px, color #1f2328ff #| quad (57, 75) 280 x 10
#|layout (logical px) #| quad (40, 40) 320 x 62 border #d0d7deff
#| window (0px, 0px) 480px x 320px #|clicked: expanded = true, clicks = 1, frames = 3, dirty = false
#| card (40px, 40px) 320px x 134px #|after click (hovered)
#| title (57px, 57px) 286px x 23px #| batches: quads (1), shadows (2), quads (7)
#| body (57px, 88px) 286px x 69px #| quad (0, 0) 400 x 240
#|scene at 2x #| quad (40, 40) 320 x 116
#| shadows (2) #| quad (57, 57) 160 x 10
#| quads (1) #| quad (57, 75) 280 x 10
#| underlines (1) #| quad (57, 93) 280 x 10
#| quad order 1: 640 x 268 device px #| quad (57, 111) 280 x 10
#| quad (57, 129) 280 x 10
#| quad (40, 40) 320 x 116 border #0969daff
), ),
) )
} }
+8 -3
View File
@@ -2,9 +2,14 @@ import {
"experiments/gpui/geometry", "experiments/gpui/geometry",
"experiments/gpui/color", "experiments/gpui/color",
"experiments/gpui/scene", "experiments/gpui/scene",
"experiments/gpui/style", "experiments/gpui/app",
"experiments/gpui/layout", "experiments/gpui/window",
"moonbitlang/core/debug", "experiments/gpui/elements",
"experiments/gpui/platform/test" @test_platform,
} }
pkgtype(kind: "executable") pkgtype(kind: "executable")
options(
"allow-experimental-packages": true,
)
+1
View File
@@ -6,6 +6,7 @@ package "experiments/gpui/examples/card"
// Errors // Errors
// Types and methods // Types and methods
type Card
// Type aliases // Type aliases
+92
View File
@@ -0,0 +1,92 @@
// The app model (M3) and executors (M4) without a window: two entities
// talking through notifications, typed events and a global, and a task
// ticking on the app's simulated clock.
//
// Run with: moon run src/examples/counter --target js
///|
struct Counter {
mut count : Int32
}
///|
struct History {
entries : Array[String]
}
///|
/// An event a counter emits when it passes a threshold.
let milestone : @app.EventKey[Int32] = @app.EventKey::new("Milestone")
///|
/// App-wide configuration.
struct Config {
mut step : Int32
}
///|
let config_key : @app.GlobalKey[Config] = @app.GlobalKey::new("Config")
///|
fn report() -> String {
let app = @app.App::new()
app.set_global(config_key, { step: 1, })
let counter : @app.Entity[Counter] = app.new_entity(fn(_) { { count: 0, } })
// The history observes the counter and subscribes to its milestones; both
// stop automatically when either entity is released.
let history : @app.Entity[History] = app.new_entity(fn(cx) {
cx
.observe(counter, fn(history, counter, cx) {
history.entries.push("count is \{counter.read(cx.app).count}")
})
.detach()
cx
.subscribe(counter, milestone, fn(history, _, value, _) {
history.entries.push("milestone \{value}!")
})
.detach()
cx
.observe_release(counter, fn(history, counter, _) {
history.entries.push("counter released at \{counter.count}")
})
.detach()
{ entries: [], }
})
let increment = fn() {
counter.update(app, fn(counter, cx) {
counter.count += cx.app.global(config_key).step
if counter.count % 5 == 0 {
cx.emit(milestone, counter.count)
}
// Notifying twice in one update still runs observers once.
cx.notify()
cx.notify()
})
}
increment()
increment()
app.update_global(config_key, fn(config, _) { config.step = 3 })
increment()
// A task that increments every 100ms until cancelled. `App::new()` uses a
// deterministic test dispatcher, so time only moves when we advance it.
let ticker = app.spawn(async fn(cx) {
while true {
cx.background_executor().sleep(100)
cx.update_entity(counter, fn(counter, cx) {
counter.count += 1
cx.notify()
})
}
})
app.advance_clock(250)
ticker.cancel()
app.advance_clock(1000)
app.release(counter)
// Updating a released entity would abort; the history keeps working.
history.read(app).entries.join("\n")
}
///|
fn main {
println(report())
}
+15
View File
@@ -0,0 +1,15 @@
///|
test "counter report" {
inspect(
report(),
content=(
#|count is 1
#|count is 2
#|milestone 5!
#|count is 5
#|count is 6
#|count is 7
#|counter released at 7
),
)
}
+5
View File
@@ -0,0 +1,5 @@
import {
"experiments/gpui/app",
}
pkgtype(kind: "executable")
+17
View File
@@ -0,0 +1,17 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/examples/counter"
// Values
// Errors
// Types and methods
type Config
type Counter
type History
// Type aliases
// Traits
+157
View File
@@ -0,0 +1,157 @@
// Coroutines on top of MoonBit's async intrinsics, scheduled by a
// `Dispatcher` instead of `moonbitlang/core/async`'s event loop.
//
// Why not `moonbitlang/core/async`: it owns the event loop (`async fn main`,
// `with_task_group`) and does not support the wasm-gc backend. GPUI's
// executors are driven by the platform (the browser's event loop, a native run
// loop, or a deterministic test scheduler), so we schedule coroutines
// ourselves with the same intrinsics `moonbitlang/core/async` is built on.
// They are experimental; see docs/PORTING.md.
///|
async fn[T] async_suspend(cb : ((T) -> Unit) -> Unit) -> T noraise + nocancel = "%async.suspend"
///|
fn run_async(f : async () -> Unit noraise + nocancel) = "%async.run"
///|
async fn[X] raise_cancellation_signal() -> X noraise = "%async.raise_cancellation_signal"
///|
async fn[X] capture_cancellation(
f : async () -> X,
handler~ : async () -> X nocancel,
) -> X nocancel = "%async.capture_cancellation"
///|
priv enum Wake {
Continue
Cancelled
}
///|
/// One running computation. While suspended, `continuation` resumes it.
priv struct Coroutine {
scheduler : Scheduler
mut continuation : ((Wake) -> Unit)?
mut cancelled : Bool
mut scheduled : Bool
mut finished : Bool
/// Woken while running: the next `suspend` returns immediately.
mut missed_wake : Bool
}
///|
/// Runs coroutines one step at a time through a dispatcher.
priv struct Scheduler {
dispatcher : &Dispatcher
}
///|
/// The coroutine running right now, across all schedulers (there is one
/// thread).
let current : Ref[Coroutine?] = { val: None, }
///|
/// Schedules `coroutine` to continue on the dispatcher, once.
fn Coroutine::wake(self : Coroutine) -> Unit {
if self.scheduled || self.finished {
return
}
self.scheduled = true
self.scheduler.dispatcher.dispatch(fn() { self.step() })
}
///|
fn Coroutine::step(self : Coroutine) -> Unit {
self.scheduled = false
guard self.continuation is Some(continuation) else {
// Woken while running (it has not suspended yet).
if !self.finished {
self.missed_wake = true
}
return
}
self.continuation = None
let previous = current.val
current.val = Some(self)
continuation(if self.cancelled { Cancelled } else { Continue })
current.val = previous
}
///|
/// The coroutine running right now; fails loudly outside of a task.
fn current_coroutine(operation : String) -> Coroutine {
match current.val {
Some(coroutine) => coroutine
None => abort("\{operation} must be called from inside a task")
}
}
///|
/// Suspends the current coroutine until it is woken. If the task is cancelled
/// (before or while suspended), raises the cancellation signal, which unwinds
/// the task and runs its `defer` blocks.
async fn suspend(coroutine : Coroutine) -> Unit noraise {
if coroutine.cancelled {
raise_cancellation_signal()
}
if coroutine.missed_wake {
coroutine.missed_wake = false
return
}
let wake : Wake = async_suspend(fn(k) { coroutine.continuation = Some(k) })
match wake {
Continue => ()
Cancelled => raise_cancellation_signal()
}
}
///|
/// Starts `body` as a new coroutine on the next dispatcher turn.
fn Scheduler::spawn(
self : Scheduler,
body : async () -> Unit,
on_cancelled : () -> Unit,
on_error : (Error) -> Unit,
on_finished : () -> Unit,
) -> Coroutine {
let coroutine : Coroutine = {
scheduler: self,
continuation: None,
cancelled: false,
scheduled: false,
finished: false,
missed_wake: false,
}
coroutine.continuation = Some(fn(wake) {
match wake {
Cancelled => {
// Cancelled before it ever ran: the body never starts.
coroutine.finished = true
on_cancelled()
on_finished()
}
Continue =>
run_async(() => {
capture_cancellation(body, handler=() => on_cancelled()) catch {
error => on_error(error)
}
coroutine.finished = true
on_finished()
})
}
})
coroutine.wake()
coroutine
}
///|
fn Coroutine::cancel(self : Coroutine) -> Unit {
if self.finished || self.cancelled {
return
}
self.cancelled = true
// Resume it so that it observes the cancellation (and runs its `defer`s).
self.wake()
}
+123
View File
@@ -0,0 +1,123 @@
// The platform hook that runs executor work (GPUI: `PlatformDispatcher`,
// reduced to a single thread: GPUI's background threads are not available
// on the web and MoonBit has no threads; background tasks share the main
// thread, as in GPUI's single-threaded web backend).
///|
/// Runs callbacks on the (only) thread, soon or after a delay.
pub(open) trait Dispatcher {
/// Run `runnable` soon, after the current callback returns.
fn dispatch(Self, runnable : () -> Unit) -> Unit
/// Run `runnable` after `delay_ms` milliseconds.
fn dispatch_after(Self, delay_ms : Int32, runnable : () -> Unit) -> Unit
/// Milliseconds since an arbitrary, fixed origin.
fn now(Self) -> Int64
}
///|
priv struct PendingTimer {
deadline : Int64
runnable : () -> Unit
}
///|
/// A deterministic dispatcher with a virtual clock, for tests (GPUI:
/// `TestScheduler`/`TestDispatcher`). Nothing runs until the test drives it
/// with `tick`, `run_until_parked` or `advance_clock`.
pub struct TestDispatcher {
priv queue : @deque.Deque[() -> Unit]
priv timers : Array[PendingTimer]
priv mut now_ms : Int64
}
///|
pub fn TestDispatcher::new() -> TestDispatcher {
{ queue: @deque.Deque([]), timers: [], now_ms: 0, }
}
///|
pub impl Dispatcher for TestDispatcher with fn dispatch(self, runnable) {
self.queue.push_back(runnable)
}
///|
pub impl Dispatcher for TestDispatcher with fn dispatch_after(
self,
delay_ms,
runnable,
) {
guard delay_ms >= 0 else {
abort("dispatch_after: negative delay \{delay_ms}ms")
}
let timer = { deadline: self.now_ms + delay_ms.to_int64(), runnable, }
// Keep timers sorted by deadline; equal deadlines keep insertion order.
let mut index = self.timers.length()
while index > 0 && self.timers[index - 1].deadline > timer.deadline {
index = index - 1
}
self.timers.insert(index, timer)
}
///|
pub impl Dispatcher for TestDispatcher with fn now(self) {
self.now_ms
}
///|
/// Moves timers whose deadline has passed into the run queue.
fn TestDispatcher::fire_due_timers(self : TestDispatcher) -> Unit {
while !self.timers.is_empty() && self.timers[0].deadline <= self.now_ms {
self.queue.push_back(self.timers.remove(0).runnable)
}
}
///|
/// Runs one ready callback; false if none is ready.
pub fn TestDispatcher::tick(self : TestDispatcher) -> Bool {
self.fire_due_timers()
match self.queue.pop_front() {
Some(runnable) => {
runnable()
true
}
None => false
}
}
///|
/// Runs callbacks until none is ready without advancing the clock (GPUI:
/// `run_until_parked`).
pub fn TestDispatcher::run_until_parked(self : TestDispatcher) -> Unit {
while self.tick() {
()
}
}
///|
/// Advances the virtual clock by `ms`, firing timers in deadline order and
/// running everything they wake (GPUI: `advance_clock`).
pub fn TestDispatcher::advance_clock(self : TestDispatcher, ms : Int32) -> Unit {
guard ms >= 0 else { abort("advance_clock: negative duration \{ms}ms") }
let target = self.now_ms + ms.to_int64()
while true {
self.run_until_parked()
if !self.timers.is_empty() && self.timers[0].deadline <= target {
self.now_ms = self.timers[0].deadline
} else {
break
}
}
self.now_ms = target
}
///|
/// Whether any callback is ready or any timer is pending.
pub fn TestDispatcher::has_pending_work(self : TestDispatcher) -> Bool {
!self.queue.is_empty() || !self.timers.is_empty()
}
///|
/// Number of pending timers.
pub fn TestDispatcher::pending_timer_count(self : TestDispatcher) -> Int32 {
self.timers.length()
}
+216
View File
@@ -0,0 +1,216 @@
///|
fn setup() -> (@executor.TestDispatcher, @executor.Executor) {
let dispatcher = @executor.TestDispatcher::new()
(dispatcher, @executor.Executor::new(dispatcher))
}
///|
fn[T] result_of(task : @executor.Task[T]) -> T? {
task.try_result() catch {
_ => None
}
}
///|
suberror Boom {
Boom(String)
}
///|
/// Port of the scheduler crate's `test_foreground_executor_spawn`.
test "spawn runs on the dispatcher" {
let (dispatcher, executor) = setup()
let task = executor.spawn(fn() { 42 })
// Nothing runs until the dispatcher is driven.
assert_false(task.is_ready())
dispatcher.run_until_parked()
assert_true(task.is_ready())
assert_eq(result_of(task), Some(42))
assert_eq(result_of(@executor.Task::ready("now")), Some("now"))
}
///|
/// Like the scheduler crate's `test_foreground_ordering`: tasks start in
/// spawn order.
test "tasks run in spawn order" {
let (dispatcher, executor) = setup()
let trace = []
for i in 0..<10 {
executor.spawn(fn() { trace.push(i) }).detach()
}
dispatcher.run_until_parked()
assert_eq(trace, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
}
///|
/// Port of the scheduler crate's `test_timer_ordering`.
test "timers fire in deadline order on the virtual clock" {
let (dispatcher, executor) = setup()
let order = []
for delay in [100, 50, 150] {
executor
.spawn(async fn() {
executor.sleep(delay)
order.push((delay, executor.now()))
})
.detach()
}
dispatcher.run_until_parked()
assert_eq(order, [])
dispatcher.advance_clock(60)
assert_eq(order, [(50, 50L)])
assert_eq(executor.now(), 60L)
dispatcher.advance_clock(1000)
assert_eq(order, [(50, 50L), (100, 100L), (150, 150L)])
assert_false(dispatcher.has_pending_work())
}
///|
test "tasks await tasks and errors propagate" {
let (dispatcher, executor) = setup()
let inner = executor.spawn(async fn() {
executor.sleep(10)
20
})
let outer = executor.spawn(async fn() { inner.wait() + 1 })
let failing : @executor.Task[Int32] = executor.spawn(fn() raise {
raise Boom("bad")
})
let observer = executor.spawn(async fn() {
try failing.wait() catch {
Boom(message) => "caught \{message}"
_ => "other"
} noraise {
_ => "no error"
}
})
dispatcher.advance_clock(10)
assert_eq(result_of(outer), Some(21))
assert_eq(result_of(observer), Some("caught bad"))
let raised = try failing.try_result() catch {
Boom(_) => true
_ => false
} noraise {
_ => false
}
assert_true(raised)
}
///|
test "cancel before start: the body never runs" {
let (dispatcher, executor) = setup()
let ran = Ref(false)
let task = executor.spawn(fn() { ran.val = true })
task.cancel()
dispatcher.run_until_parked()
assert_false(ran.val)
assert_true(task.is_cancelled())
let raised = try task.try_result() catch {
@executor.TaskCancelled => true
_ => false
} noraise {
_ => false
}
assert_true(raised)
}
///|
test "cancel while suspended unwinds the task and notifies waiters" {
let (dispatcher, executor) = setup()
let log = []
let sleeper = executor.spawn(async fn() {
defer log.push("cleanup")
log.push("sleeping")
executor.sleep(1000)
log.push("woke up")
})
let waiter = executor.spawn(async fn() {
try sleeper.wait() catch {
@executor.TaskCancelled => "sleeper cancelled"
_ => "other error"
} noraise {
_ => "finished"
}
})
dispatcher.run_until_parked()
assert_eq(log, ["sleeping"])
sleeper.cancel()
dispatcher.run_until_parked()
assert_eq(log, ["sleeping", "cleanup"])
assert_eq(result_of(waiter), Some("sleeper cancelled"))
// The timer still fires later, but nothing resumes.
dispatcher.advance_clock(2000)
assert_eq(log, ["sleeping", "cleanup"])
// Cancelling a finished task does nothing.
waiter.cancel()
assert_false(waiter.is_cancelled())
}
///|
test "cancelled timers report cancellation" {
let (dispatcher, executor) = setup()
let timer = executor.timer(50)
timer.cancel()
assert_true(timer.is_cancelled())
dispatcher.advance_clock(100)
assert_true(timer.is_cancelled())
}
///|
test "a task can cancel itself" {
let (dispatcher, executor) = setup()
let log = []
let task_ref : Ref[@executor.Task[Unit]?] = Ref(None)
let task = executor.spawn(async fn() {
defer log.push("unwound")
task_ref.val.unwrap().cancel()
log.push("still running until the next suspension")
executor.yield_now()
log.push("never")
})
task_ref.val = Some(task)
dispatcher.run_until_parked()
assert_eq(log, ["still running until the next suspension", "unwound"])
assert_true(task.is_cancelled())
}
///|
test "yield_now interleaves tasks" {
let (dispatcher, executor) = setup()
let trace = []
for name in ["a", "b"] {
executor
.spawn(async fn() {
for i in 0..<3 {
trace.push("\{name}\{i}")
executor.yield_now()
}
})
.detach()
}
dispatcher.run_until_parked()
assert_eq(trace, ["a0", "b0", "a1", "b1", "a2", "b2"])
}
///|
test "tick runs one step at a time" {
let (dispatcher, executor) = setup()
let trace = []
executor.spawn(fn() { trace.push(1) }).detach()
executor.spawn(fn() { trace.push(2) }).detach()
assert_true(dispatcher.tick())
assert_eq(trace, [1])
assert_true(dispatcher.tick())
assert_false(dispatcher.tick())
assert_eq(trace, [1, 2])
assert_eq(dispatcher.pending_timer_count(), 0)
}
///|
test "panic on a task waiting for itself" {
let (dispatcher, executor) = setup()
let task_ref : Ref[@executor.Task[Unit]?] = Ref(None)
let task = executor.spawn(async fn() { task_ref.val.unwrap().wait() })
task_ref.val = Some(task)
dispatcher.run_until_parked()
}
+11
View File
@@ -0,0 +1,11 @@
///|
test "panic on waiting outside a task" {
let dispatcher = TestDispatcher::new()
let task = Executor::new(dispatcher).timer(1)
// A coroutine that is not a task: `wait` cannot suspend it.
run_async(() => {
capture_cancellation(() => task.wait(), handler=() => ()) catch {
_ => ()
}
})
}
+10
View File
@@ -0,0 +1,10 @@
import {
"moonbitlang/core/deque",
}
// The coroutine intrinsics (%async.*) are experimental.
options(
"allow-experimental-packages": true,
experimental: true,
)
+54
View File
@@ -0,0 +1,54 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/executor"
import {
"moonbitlang/core/debug",
}
// Values
// Errors
#derive(@debug.Debug)
pub suberror TaskCancelled
// Types and methods
pub struct Executor {
// private fields
}
pub fn Executor::new(&Dispatcher) -> Self
pub fn Executor::now(Self) -> Int64
pub async fn Executor::sleep(Self, Int32) -> Unit
pub fn[T] Executor::spawn(Self, async () -> T) -> Task[T]
pub fn Executor::timer(Self, Int32) -> Task[Unit]
pub async fn Executor::yield_now(Self) -> Unit
pub struct Task[T] {
// private fields
}
pub fn[T] Task::cancel(Self[T]) -> Unit
pub fn[T] Task::detach(Self[T]) -> Unit
pub fn[T] Task::is_cancelled(Self[T]) -> Bool
pub fn[T] Task::is_ready(Self[T]) -> Bool
pub fn[T] Task::ready(T) -> Self[T]
pub fn[T] Task::try_result(Self[T]) -> T? raise
pub async fn[T] Task::wait(Self[T]) -> T
pub struct TestDispatcher {
// private fields
}
pub fn TestDispatcher::advance_clock(Self, Int32) -> Unit
pub fn TestDispatcher::has_pending_work(Self) -> Bool
pub fn TestDispatcher::new() -> Self
pub fn TestDispatcher::pending_timer_count(Self) -> Int32
pub fn TestDispatcher::run_until_parked(Self) -> Unit
pub fn TestDispatcher::tick(Self) -> Bool
pub impl Dispatcher for TestDispatcher
// Type aliases
// Traits
pub(open) trait Dispatcher {
fn dispatch(Self, () -> Unit) -> Unit
fn dispatch_after(Self, Int32, () -> Unit) -> Unit
fn now(Self) -> Int64
}
+184
View File
@@ -0,0 +1,184 @@
// Tasks and executors, ported from gpui/src/executor.rs and the `scheduler`
// crate (crates/scheduler/src/executor.rs).
//
// Deviations from GPUI:
// - Dropping a GPUI `Task` cancels it. There is no `Drop` in MoonBit: a task
// runs to completion unless `cancel()` is called. `detach()` is kept for
// parity.
// - There is one thread: background and foreground executors schedule on the
// same dispatcher (as GPUI's single-threaded web backend does).
// - Durations are milliseconds (`Int`); `now()` is milliseconds (`Int64`).
///|
/// Raised by `Task::wait` when the task was cancelled.
#derive(Debug)
pub suberror TaskCancelled
///|
priv enum Outcome[T] {
Pending
Done(T)
Failed(Error)
Cancelled
}
///|
priv struct TaskState[T] {
mut outcome : Outcome[T]
waiters : Array[Coroutine]
mut coroutine : Coroutine?
/// Cancels work that is not a coroutine (timers).
mut on_cancel : (() -> Unit)?
}
///|
/// The result of asynchronous work (GPUI: `Task<T>`). Await it with `wait`.
pub struct Task[T] {
priv state : TaskState[T]
}
///|
fn[T] TaskState::new() -> TaskState[T] {
{ outcome: Pending, waiters: [], coroutine: None, on_cancel: None, }
}
///|
fn[T] TaskState::complete(self : TaskState[T], outcome : Outcome[T]) -> Unit {
guard self.outcome is Pending else { return }
self.outcome = outcome
let waiters = self.waiters.copy()
self.waiters.clear()
for waiter in waiters {
waiter.wake()
}
}
///|
/// A task that is already complete (GPUI: `Task::ready`).
pub fn[T] Task::ready(value : T) -> Task[T] {
{ state: { ..TaskState::new(), outcome: Done(value), }, }
}
///|
/// Whether the task has finished: completed, failed or cancelled.
pub fn[T] Task::is_ready(self : Task[T]) -> Bool {
!(self.state.outcome is Pending)
}
///|
/// Whether the task was cancelled.
pub fn[T] Task::is_cancelled(self : Task[T]) -> Bool {
self.state.outcome is Cancelled
}
///|
/// Lets the task run to completion without anyone awaiting it. In MoonBit
/// this is the default; kept for GPUI parity.
pub fn[T] Task::detach(self : Task[T]) -> Unit {
ignore(self)
}
///|
/// Cancels the task. A running task is resumed with a cancellation signal at
/// its next suspension point, unwinding it (running `defer` blocks). Waiters
/// get `TaskCancelled`. No effect on finished tasks.
pub fn[T] Task::cancel(self : Task[T]) -> Unit {
guard self.state.outcome is Pending else { return }
match (self.state.coroutine, self.state.on_cancel) {
(Some(coroutine), _) => coroutine.cancel()
(None, Some(on_cancel)) => on_cancel()
(None, None) => self.state.complete(Cancelled)
}
}
///|
/// The result if the task has finished: `Some(value)`, or raises the task's
/// error (or `TaskCancelled`); `None` while it is pending.
pub fn[T] Task::try_result(self : Task[T]) -> T? raise {
match self.state.outcome {
Pending => None
Done(value) => Some(value)
Failed(error) => raise error
Cancelled => raise TaskCancelled
}
}
///|
/// Waits for the task from inside another task and returns its value. Raises
/// the task's error, or `TaskCancelled`.
pub async fn[T] Task::wait(self : Task[T]) -> T {
let state = self.state
while state.outcome is Pending {
let coroutine = current_coroutine("Task::wait")
if state.coroutine is Some(own) && physical_equal(own, coroutine) {
abort("a task cannot wait for itself")
}
state.waiters.push(coroutine)
suspend(coroutine)
}
match state.outcome {
Done(value) => value
Failed(error) => raise error
Cancelled => raise TaskCancelled
Pending => abort("unreachable: task still pending after wait")
}
}
///|
/// Spawns tasks and timers on a dispatcher (GPUI: `ForegroundExecutor` and
/// `BackgroundExecutor`, which coincide on one thread).
pub struct Executor {
priv scheduler : Scheduler
}
///|
pub fn Executor::new(dispatcher : &Dispatcher) -> Executor {
{ scheduler: { dispatcher, }, }
}
///|
/// Runs `f` as a task, starting on the next dispatcher turn.
pub fn[T] Executor::spawn(self : Executor, f : async () -> T) -> Task[T] {
let state : TaskState[T] = TaskState::new()
let coroutine = self.scheduler.spawn(
async fn() {
let value = f()
state.complete(Done(value))
},
fn() { state.complete(Cancelled) },
fn(error) { state.complete(Failed(error)) },
fn() { },
)
state.coroutine = Some(coroutine)
{ state, }
}
///|
/// A task that completes after `ms` milliseconds (GPUI: `timer`).
pub fn Executor::timer(self : Executor, ms : Int32) -> Task[Unit] {
let state : TaskState[Unit] = TaskState::new()
state.on_cancel = Some(fn() { state.complete(Cancelled) })
self.scheduler.dispatcher.dispatch_after(ms, fn() { state.complete(Done(())) })
{ state, }
}
///|
/// Suspends the current task for `ms` milliseconds.
pub async fn Executor::sleep(self : Executor, ms : Int32) -> Unit {
self.timer(ms).wait()
}
///|
/// Lets other ready tasks run before continuing.
pub async fn Executor::yield_now(self : Executor) -> Unit {
let coroutine = current_coroutine("Executor::yield_now")
ignore(self)
coroutine.wake()
suspend(coroutine)
}
///|
/// The dispatcher's clock, in milliseconds.
pub fn Executor::now(self : Executor) -> Int64 {
self.scheduler.dispatcher.now()
}
+212
View File
@@ -0,0 +1,212 @@
// Input event types, ported from gpui/src/interactive.rs and the Modifiers of
// gpui/src/platform/keystroke.rs. Keyboard events and keystrokes come with
// the keymap milestone (M5).
///|
/// Modifier keys held during an event.
#derive(Eq, Hash, Default, Debug)
pub(all) struct Modifiers {
control : Bool
alt : Bool
shift : Bool
/// Command on macOS, Windows/Super elsewhere.
platform : Bool
/// The function (fn) key.
function : Bool
}
///|
/// Whether any modifier is held.
pub fn Modifiers::modified(self : Modifiers) -> Bool {
self.control || self.alt || self.shift || self.platform || self.function
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum NavigationDirection {
Back
Forward
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum MouseButton {
Left
Right
Middle
Navigate(NavigationDirection)
}
///|
pub impl Default for MouseButton with fn default() {
Left
}
///|
#derive(Eq, Default, Debug)
pub(all) struct MouseDownEvent {
button : MouseButton
position : @geometry.Point[@geometry.Pixels]
modifiers : Modifiers
click_count : Int32
first_mouse : Bool
}
///|
#derive(Eq, Default, Debug)
pub(all) struct MouseUpEvent {
button : MouseButton
position : @geometry.Point[@geometry.Pixels]
modifiers : Modifiers
click_count : Int32
}
///|
#derive(Eq, Default, Debug)
pub(all) struct MouseMoveEvent {
position : @geometry.Point[@geometry.Pixels]
/// The button held during the move, if any.
pressed_button : MouseButton?
modifiers : Modifiers
}
///|
/// How a scroll delta is expressed.
#derive(Eq, Debug)
pub(all) enum ScrollDelta {
/// Precise pixels (trackpads).
Pixels(@geometry.Point[@geometry.Pixels])
/// Lines (mouse wheels).
Lines(@geometry.Point[Double])
}
///|
#derive(Eq, Debug)
pub(all) struct ScrollWheelEvent {
position : @geometry.Point[@geometry.Pixels]
delta : ScrollDelta
modifiers : Modifiers
}
///|
/// Fired when the pointer leaves the window (GPUI: `MouseExitEvent`).
#derive(Eq, Default, Debug)
pub(all) struct MouseExitEvent {
position : @geometry.Point[@geometry.Pixels]
pressed_button : MouseButton?
modifiers : Modifiers
}
///|
/// Fired when the held modifier keys change (GPUI: `ModifiersChangedEvent`).
#derive(Eq, Default, Debug)
pub(all) struct ModifiersChangedEvent {
modifiers : Modifiers
}
///|
/// A mouse click: the down and up events of one press (GPUI:
/// `MouseClickEvent`).
#derive(Eq, Default, Debug)
pub(all) struct ClickEvent {
down : MouseDownEvent
up : MouseUpEvent
}
///|
/// Pointer input delivered to a window (GPUI: the mouse variants of
/// `PlatformInput`).
#derive(Eq, Debug)
pub(all) enum MouseEvent {
MouseDown(MouseDownEvent)
MouseUp(MouseUpEvent)
MouseMove(MouseMoveEvent)
ScrollWheel(ScrollWheelEvent)
}
///|
pub fn MouseEvent::position(
self : MouseEvent,
) -> @geometry.Point[@geometry.Pixels] {
match self {
MouseDown(e) => e.position
MouseUp(e) => e.position
MouseMove(e) => e.position
ScrollWheel(e) => e.position
}
}
///|
pub fn MouseEvent::modifiers(self : MouseEvent) -> Modifiers {
match self {
MouseDown(e) => e.modifiers
MouseUp(e) => e.modifiers
MouseMove(e) => e.modifiers
ScrollWheel(e) => e.modifiers
}
}
///|
pub fn MouseEvent::to_platform_input(self : MouseEvent) -> PlatformInput {
match self {
MouseDown(e) => MouseDown(e)
MouseUp(e) => MouseUp(e)
MouseMove(e) => MouseMove(e)
ScrollWheel(e) => ScrollWheel(e)
}
}
///|
/// Input events delivered by a platform window (GPUI: `PlatformInput`).
#derive(Eq, Debug)
pub(all) enum PlatformInput {
MouseDown(MouseDownEvent)
MouseUp(MouseUpEvent)
MouseMove(MouseMoveEvent)
MouseExited(MouseExitEvent)
ScrollWheel(ScrollWheelEvent)
ModifiersChanged(ModifiersChangedEvent)
}
///|
pub fn PlatformInput::modifiers(self : PlatformInput) -> Modifiers {
match self {
MouseDown(e) => e.modifiers
MouseUp(e) => e.modifiers
MouseMove(e) => e.modifiers
MouseExited(e) => e.modifiers
ScrollWheel(e) => e.modifiers
ModifiersChanged(e) => e.modifiers
}
}
///|
/// Extracts the mouse event if this input is one of the window-dispatched
/// pointer events (`MouseExited` and `ModifiersChanged` return `None`).
pub fn PlatformInput::mouse_event(self : PlatformInput) -> MouseEvent? {
match self {
MouseDown(e) => Some(MouseDown(e))
MouseUp(e) => Some(MouseUp(e))
MouseMove(e) => Some(MouseMove(e))
ScrollWheel(e) => Some(ScrollWheel(e))
MouseExited(_) | ModifiersChanged(_) => None
}
}
///|
/// Result of dispatching a `PlatformInput` to a window (GPUI:
/// `DispatchEventResult`).
#derive(Eq, Default, Debug)
pub(all) struct DispatchEventResult {
propagate : Bool
default_prevented : Bool
}
///|
/// Listeners run twice per event: capture (root to leaf), then bubble (leaf
/// to root) (GPUI: `DispatchPhase`).
#derive(Eq, Hash, Debug)
pub(all) enum DispatchPhase {
Capture
Bubble
}
+3
View File
@@ -0,0 +1,3 @@
import {
"experiments/gpui/geometry",
}
+131
View File
@@ -0,0 +1,131 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/input"
import {
"experiments/gpui/geometry",
"moonbitlang/core/debug",
}
// Values
// Errors
// Types and methods
#derive(Default, Eq, @debug.Debug)
pub(all) struct ClickEvent {
down : MouseDownEvent
up : MouseUpEvent
}
#derive(Default, Eq, @debug.Debug)
pub(all) struct DispatchEventResult {
propagate : Bool
default_prevented : Bool
}
#derive(Eq, Hash, @debug.Debug)
pub(all) enum DispatchPhase {
Capture
Bubble
}
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct Modifiers {
control : Bool
alt : Bool
shift : Bool
platform : Bool
function : Bool
}
pub fn Modifiers::modified(Self) -> Bool
#derive(Default, Eq, @debug.Debug)
pub(all) struct ModifiersChangedEvent {
modifiers : Modifiers
}
#derive(Eq, Hash, @debug.Debug)
pub(all) enum MouseButton {
Left
Right
Middle
Navigate(NavigationDirection)
}
pub impl Default for MouseButton
#derive(Default, Eq, @debug.Debug)
pub(all) struct MouseDownEvent {
button : MouseButton
position : @geometry.Point[@geometry.Pixels]
modifiers : Modifiers
click_count : Int32
first_mouse : Bool
}
#derive(Eq, @debug.Debug)
pub(all) enum MouseEvent {
MouseDown(MouseDownEvent)
MouseUp(MouseUpEvent)
MouseMove(MouseMoveEvent)
ScrollWheel(ScrollWheelEvent)
}
pub fn MouseEvent::modifiers(Self) -> Modifiers
pub fn MouseEvent::position(Self) -> @geometry.Point[@geometry.Pixels]
pub fn MouseEvent::to_platform_input(Self) -> PlatformInput
#derive(Default, Eq, @debug.Debug)
pub(all) struct MouseExitEvent {
position : @geometry.Point[@geometry.Pixels]
pressed_button : MouseButton?
modifiers : Modifiers
}
#derive(Default, Eq, @debug.Debug)
pub(all) struct MouseMoveEvent {
position : @geometry.Point[@geometry.Pixels]
pressed_button : MouseButton?
modifiers : Modifiers
}
#derive(Default, Eq, @debug.Debug)
pub(all) struct MouseUpEvent {
button : MouseButton
position : @geometry.Point[@geometry.Pixels]
modifiers : Modifiers
click_count : Int32
}
#derive(Eq, Hash, @debug.Debug)
pub(all) enum NavigationDirection {
Back
Forward
}
#derive(Eq, @debug.Debug)
pub(all) enum PlatformInput {
MouseDown(MouseDownEvent)
MouseUp(MouseUpEvent)
MouseMove(MouseMoveEvent)
MouseExited(MouseExitEvent)
ScrollWheel(ScrollWheelEvent)
ModifiersChanged(ModifiersChangedEvent)
}
pub fn PlatformInput::modifiers(Self) -> Modifiers
pub fn PlatformInput::mouse_event(Self) -> MouseEvent?
#derive(Eq, @debug.Debug)
pub(all) enum ScrollDelta {
Pixels(@geometry.Point[@geometry.Pixels])
Lines(@geometry.Point[Double])
}
#derive(Eq, @debug.Debug)
pub(all) struct ScrollWheelEvent {
position : @geometry.Point[@geometry.Pixels]
delta : ScrollDelta
modifiers : Modifiers
}
// Type aliases
// Traits
+13
View File
@@ -0,0 +1,13 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/scene",
"experiments/gpui/style",
"experiments/gpui/input",
"experiments/gpui/executor",
}
// experiments/gpui/executor uses MoonBit's experimental async intrinsics.
options(
"allow-experimental-packages": true,
)
+111
View File
@@ -0,0 +1,111 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/platform"
import {
"experiments/gpui/executor",
"experiments/gpui/geometry",
"experiments/gpui/input",
"experiments/gpui/scene",
"experiments/gpui/style",
"moonbitlang/core/debug",
}
// Values
// Errors
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) enum ClipboardEntry {
String(ClipboardString)
}
#derive(Eq, @debug.Debug)
pub(all) struct ClipboardItem {
entries : Array[ClipboardEntry]
}
pub fn ClipboardItem::metadata(Self) -> String?
pub fn ClipboardItem::new_string(String) -> Self
pub fn ClipboardItem::new_string_with_metadata(String, String) -> Self
pub fn ClipboardItem::text(Self) -> String?
#derive(Eq, @debug.Debug)
pub(all) struct ClipboardString {
text : String
metadata : String?
}
pub fn ClipboardString::new(String) -> Self
pub fn ClipboardString::new_with_metadata(String, String) -> Self
#derive(Eq, @debug.Debug)
pub(all) enum WindowBounds {
Windowed(@geometry.Bounds[@geometry.Pixels])
Maximized(@geometry.Bounds[@geometry.Pixels])
Fullscreen(@geometry.Bounds[@geometry.Pixels])
}
pub fn WindowBounds::get_bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
pub impl Default for WindowBounds
#derive(Compare, Eq, Hash, @debug.Debug)
pub(all) struct WindowId(Int32)
pub impl Show for WindowId
#derive(Eq, @debug.Debug)
pub(all) struct WindowOptions {
window_bounds : WindowBounds?
title : String?
focus : Bool
show : Bool
scale_factor : Double?
rem_size : @geometry.Pixels
}
pub fn WindowOptions::with_size(@geometry.Size[@geometry.Pixels], scale_factor? : Double, title? : String, rem_size? : @geometry.Pixels) -> Self
pub impl Default for WindowOptions
#derive(Eq, @debug.Debug)
pub(all) struct WindowParams {
bounds : @geometry.Bounds[@geometry.Pixels]
title : String?
focus : Bool
show : Bool
scale_factor : Double?
}
// Type aliases
// Traits
pub(open) trait Platform {
fn dispatcher(Self) -> &@executor.Dispatcher
fn default_window_bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
fn open_window(Self, WindowId, WindowParams) -> &PlatformWindow
fn run(Self, () -> Unit) -> Unit
fn quit(Self) -> Unit
fn active_window(Self) -> WindowId?
fn set_cursor_style(Self, @style.CursorStyle) -> Unit
fn read_from_clipboard(Self) -> ClipboardItem?
fn write_to_clipboard(Self, ClipboardItem) -> Unit
fn open_url(Self, String) -> Unit
}
pub(open) trait PlatformWindow {
fn bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
fn content_size(Self) -> @geometry.Size[@geometry.Pixels]
fn scale_factor(Self) -> Double
fn mouse_position(Self) -> @geometry.Point[@geometry.Pixels]
fn modifiers(Self) -> @input.Modifiers
fn is_active(Self) -> Bool
fn is_hovered(Self) -> Bool
fn set_title(Self, String) -> Unit
fn activate(Self) -> Unit
fn resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit
fn draw(Self, @scene.Scene) -> Unit
fn schedule_frame(Self) -> Unit
fn close(Self) -> Unit
fn on_request_frame(Self, () -> Unit) -> Unit
fn on_input(Self, (@input.PlatformInput) -> @input.DispatchEventResult) -> Unit
fn on_resize(Self, (@geometry.Size[@geometry.Pixels], Double) -> Unit) -> Unit
fn on_active_status_change(Self, (Bool) -> Unit) -> Unit
fn on_hover_status_change(Self, (Bool) -> Unit) -> Unit
fn on_should_close(Self, () -> Bool) -> Unit
fn on_close(Self, () -> Unit) -> Unit
}
+83
View File
@@ -0,0 +1,83 @@
// Platform interfaces, ported from gpui/src/platform.rs (the core subset:
// windows, event loop, executor dispatcher, cursor and clipboard; text
// system, glyph atlas, IME, menus and displays arrive in M9/M10).
//
// Pure trait definitions only; concrete backends live in `platform/test`
// (M7) and `platform/web` (M8).
///|
/// A platform-backed window handle (GPUI: `PlatformWindow`).
pub(open) trait PlatformWindow {
/// Window bounds in logical pixels.
fn bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
/// Size of the drawable content area in logical pixels.
fn content_size(Self) -> @geometry.Size[@geometry.Pixels]
/// Device-pixel scale factor.
fn scale_factor(Self) -> Double
/// Last known pointer position in logical pixels.
fn mouse_position(Self) -> @geometry.Point[@geometry.Pixels]
/// Currently held modifier keys.
fn modifiers(Self) -> @input.Modifiers
/// Whether this window is currently active/focused.
fn is_active(Self) -> Bool
/// Whether the pointer is currently over this window.
fn is_hovered(Self) -> Bool
/// Sets the window's title.
fn set_title(Self, String) -> Unit
/// Focuses/brings this window to the front.
fn activate(Self) -> Unit
/// Programmatically resizes the window to `size`. Must not re-enter
/// `on_resize`.
fn resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit
/// Presents a finished `Scene`.
fn draw(Self, @scene.Scene) -> Unit
/// Requests that the platform invoke the `on_request_frame` callback on
/// the next frame.
fn schedule_frame(Self) -> Unit
/// App-driven teardown hook (MoonBit has no `Drop`). Must be idempotent
/// and must not re-invoke `on_close`.
fn close(Self) -> Unit
/// Registers the callback invoked when a scheduled frame should draw.
fn on_request_frame(Self, () -> Unit) -> Unit
/// Registers the callback invoked for platform input events.
fn on_input(Self, (@input.PlatformInput) -> @input.DispatchEventResult) -> Unit
/// Registers the callback invoked when the window size or scale factor
/// changes from the platform side.
fn on_resize(Self, (@geometry.Size[@geometry.Pixels], Double) -> Unit) -> Unit
/// Registers the callback invoked when active status changes.
fn on_active_status_change(Self, (Bool) -> Unit) -> Unit
/// Registers the callback invoked when pointer hover status changes.
fn on_hover_status_change(Self, (Bool) -> Unit) -> Unit
/// Registers the callback asked whether a user-initiated close should
/// proceed.
fn on_should_close(Self, () -> Bool) -> Unit
/// Registers the callback invoked when the platform closes the window.
fn on_close(Self, () -> Unit) -> Unit
}
///|
/// Platform services (GPUI: `Platform`).
pub(open) trait Platform {
/// The dispatcher used by the app's executors.
fn dispatcher(Self) -> &@executor.Dispatcher
/// Default logical bounds for a new window when `WindowOptions.window_bounds`
/// is `None`.
fn default_window_bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
/// Opens a new platform window with the given id and parameters.
fn open_window(Self, WindowId, WindowParams) -> &PlatformWindow
/// Starts the platform event loop, calling `on_finish_launching` once
/// ready.
fn run(Self, () -> Unit) -> Unit
/// Requests that the platform event loop exit.
fn quit(Self) -> Unit
/// The currently active window id, if any.
fn active_window(Self) -> WindowId?
/// Sets the pointer cursor style.
fn set_cursor_style(Self, @style.CursorStyle) -> Unit
/// Reads the current clipboard contents, if any.
fn read_from_clipboard(Self) -> ClipboardItem?
/// Replaces the clipboard contents.
fn write_to_clipboard(Self, ClipboardItem) -> Unit
/// Opens `url` in the system/browser handler.
fn open_url(Self, String) -> Unit
}
+70
View File
@@ -0,0 +1,70 @@
///|
test "WindowBounds get_bounds extracts bounds across variants" {
let b = @geometry.bounds(
@geometry.point(@geometry.px(10.0), @geometry.px(20.0)),
@geometry.size(@geometry.px(800.0), @geometry.px(600.0)),
)
assert_eq(@platform.WindowBounds::Windowed(b).get_bounds(), b)
assert_eq(@platform.WindowBounds::Maximized(b).get_bounds(), b)
assert_eq(@platform.WindowBounds::Fullscreen(b).get_bounds(), b)
assert_eq(
(Default::default() : @platform.WindowBounds),
@platform.WindowBounds::Windowed(Default::default()),
)
}
///|
test "WindowOptions default and with_size" {
let defaults : @platform.WindowOptions = Default::default()
assert_eq(defaults.window_bounds, None)
assert_eq(defaults.title, None)
assert_true(defaults.focus)
assert_true(defaults.show)
assert_eq(defaults.scale_factor, None)
assert_eq(defaults.rem_size, @geometry.px(16.0))
let opts = @platform.WindowOptions::with_size(
@geometry.size(@geometry.px(640.0), @geometry.px(480.0)),
scale_factor=2.0,
title="Demo",
rem_size=@geometry.px(14.0),
)
assert_eq(
opts.window_bounds,
Some(
@platform.WindowBounds::Windowed(
@geometry.bounds(
@geometry.point(@geometry.px(0.0), @geometry.px(0.0)),
@geometry.size(@geometry.px(640.0), @geometry.px(480.0)),
),
),
),
)
assert_eq(opts.scale_factor, Some(2.0))
assert_eq(opts.title, Some("Demo"))
assert_eq(opts.rem_size, @geometry.px(14.0))
}
///|
test "ClipboardItem text and metadata" {
let plain = @platform.ClipboardItem::new_string("hello")
assert_eq(plain.text(), Some("hello"))
assert_eq(plain.metadata(), None)
let with_meta = @platform.ClipboardItem::new_string_with_metadata(
"code", "rust",
)
assert_eq(with_meta.text(), Some("code"))
assert_eq(with_meta.metadata(), Some("rust"))
let multi : @platform.ClipboardItem = {
entries: [
@platform.ClipboardEntry::String(
@platform.ClipboardString::new_with_metadata("first", "m1"),
),
@platform.ClipboardEntry::String(@platform.ClipboardString::new("second")),
],
}
assert_eq(multi.text(), Some("first\nsecond"))
assert_eq(multi.metadata(), Some("m1"))
let empty : @platform.ClipboardItem = { entries: [], }
assert_eq(empty.text(), None)
assert_eq(empty.metadata(), None)
}
+20
View File
@@ -0,0 +1,20 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/scene",
"experiments/gpui/style",
"experiments/gpui/input",
"experiments/gpui/executor",
"experiments/gpui/app",
"experiments/gpui/platform",
"experiments/gpui/window",
}
// experiments/gpui/executor uses MoonBit's experimental async intrinsics.
options(
"allow-experimental-packages": true,
)
import {
"experiments/gpui/color",
} for "test"
+147
View File
@@ -0,0 +1,147 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/platform/test"
import {
"experiments/gpui/app",
"experiments/gpui/executor",
"experiments/gpui/geometry",
"experiments/gpui/input",
"experiments/gpui/platform",
"experiments/gpui/scene",
"experiments/gpui/style",
"experiments/gpui/window",
}
// Values
// Errors
// Types and methods
pub struct TestAppContext {
platform : TestPlatform
application : @window.Application
// private fields
}
pub fn TestAppContext::active_window(Self) -> @window.AnyWindowHandle?
pub fn TestAppContext::add_empty_window(Self, size? : @geometry.Size[@geometry.Pixels], scale_factor? : Double) -> VisualTestContext
pub fn[V : @window.Render] TestAppContext::add_window(Self, size? : @geometry.Size[@geometry.Pixels], scale_factor? : Double, title? : String, (@window.Window, @app.Context[V]) -> V) -> @window.WindowHandle[V]
pub fn[V : @window.Render] TestAppContext::add_window_view(Self, size? : @geometry.Size[@geometry.Pixels], scale_factor? : Double, title? : String, (@window.Window, @app.Context[V]) -> V) -> (@app.Entity[V], VisualTestContext)
pub fn TestAppContext::advance_clock(Self, Int32) -> Unit
pub fn TestAppContext::app(Self) -> @app.App
pub fn TestAppContext::application(Self) -> @window.Application
pub fn TestAppContext::background_executor(Self) -> @executor.Executor
pub fn TestAppContext::cursor_style(Self) -> @style.CursorStyle
pub fn TestAppContext::dispatcher(Self) -> @executor.TestDispatcher
pub fn TestAppContext::foreground_executor(Self) -> @executor.Executor
pub fn[G] TestAppContext::has_global(Self, @app.GlobalKey[G]) -> Bool
pub fn TestAppContext::new(default_bounds? : @geometry.Bounds[@geometry.Pixels], default_scale_factor? : Double) -> Self
pub fn[T] TestAppContext::new_entity(Self, (@app.Context[T]) -> T) -> @app.Entity[T]
pub fn[V : @window.Render] TestAppContext::open_window(Self, options? : @platform.WindowOptions, (@window.Window, @app.App) -> @app.Entity[V]) -> @window.WindowHandle[V]
pub fn TestAppContext::opened_url(Self) -> String?
pub fn TestAppContext::platform(Self) -> TestPlatform
pub fn TestAppContext::pump_frames(Self) -> Int32
pub fn TestAppContext::quit(Self) -> Unit
pub fn[R] TestAppContext::read(Self, (@app.App) -> R) -> R
pub fn[T] TestAppContext::read_entity(Self, @app.Entity[T]) -> T
pub fn TestAppContext::read_from_clipboard(Self) -> @platform.ClipboardItem?
pub fn[G] TestAppContext::read_global(Self, @app.GlobalKey[G]) -> G
pub fn TestAppContext::refresh(Self) -> Unit
pub fn TestAppContext::run_until_parked(Self) -> Unit
pub fn[G] TestAppContext::set_global(Self, @app.GlobalKey[G], G) -> Unit
pub fn TestAppContext::skip_drawing(Self, skip? : Bool) -> Unit
pub fn[R] TestAppContext::spawn(Self, async (@app.AsyncApp) -> R) -> @executor.Task[R]
pub fn TestAppContext::test_window(Self, @window.AnyWindowHandle) -> TestWindow
pub fn[R] TestAppContext::update(Self, (@app.App) -> R) -> R
pub fn[T, R] TestAppContext::update_entity(Self, @app.Entity[T], (T, @app.Context[T]) -> R) -> R
pub fn[G, R] TestAppContext::update_global(Self, @app.GlobalKey[G], (G, @app.App) -> R) -> R
pub fn TestAppContext::windows(Self) -> Array[@window.AnyWindowHandle]
pub fn TestAppContext::with_platform(TestPlatform) -> Self
pub fn TestAppContext::write_to_clipboard(Self, @platform.ClipboardItem) -> Unit
pub struct TestPlatform {
// private fields
}
pub fn TestPlatform::cursor_style(Self) -> @style.CursorStyle
pub fn TestPlatform::did_quit(Self) -> Bool
pub fn TestPlatform::did_run(Self) -> Bool
pub fn TestPlatform::new(dispatcher? : @executor.TestDispatcher, default_bounds? : @geometry.Bounds[@geometry.Pixels], default_scale_factor? : Double) -> Self
pub fn TestPlatform::opened_url(Self) -> String?
pub fn TestPlatform::opened_urls(Self) -> Array[String]
pub fn TestPlatform::pump_scheduled_frames(Self) -> Int32
pub fn TestPlatform::set_active_window(Self, TestWindow?) -> Unit
pub fn TestPlatform::test_dispatcher(Self) -> @executor.TestDispatcher
pub fn TestPlatform::window(Self, @platform.WindowId) -> TestWindow?
pub fn TestPlatform::windows(Self) -> Array[TestWindow]
pub impl @platform.Platform for TestPlatform
pub struct TestWindow {
// private fields
}
pub fn TestWindow::clear_drawn_scenes(Self) -> Unit
pub fn TestWindow::draw_count(Self) -> Int32
pub fn TestWindow::drawn_scenes(Self) -> Array[@scene.Scene]
pub fn TestWindow::frame_schedule_count(Self) -> Int32
pub fn TestWindow::frame_scheduled(Self) -> Bool
pub fn TestWindow::is_closed(Self) -> Bool
pub fn TestWindow::last_scene(Self) -> @scene.Scene?
pub fn TestWindow::simulate_active_status_change(Self, Bool) -> Unit
pub fn TestWindow::simulate_close(Self) -> Unit
pub fn TestWindow::simulate_close_requested(Self) -> Bool
pub fn TestWindow::simulate_frame_request(Self) -> Unit
pub fn TestWindow::simulate_hover_status_change(Self, Bool) -> Unit
pub fn TestWindow::simulate_input(Self, @input.PlatformInput) -> @input.DispatchEventResult
pub fn TestWindow::simulate_resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit
pub fn TestWindow::simulate_scale_factor_change(Self, Double) -> Unit
pub fn TestWindow::simulate_scheduled_frame(Self) -> Bool
pub fn TestWindow::simulate_should_close(Self) -> Bool
pub fn TestWindow::title(Self) -> String?
pub fn TestWindow::window_id(Self) -> @platform.WindowId
pub impl @platform.PlatformWindow for TestWindow
pub struct VisualTestContext {
cx : TestAppContext
window_handle : @window.AnyWindowHandle
}
pub fn VisualTestContext::advance_clock(Self, Int32) -> Unit
pub fn VisualTestContext::app(Self) -> @app.App
pub fn VisualTestContext::bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
pub fn VisualTestContext::cursor_style(Self) -> @style.CursorStyle
pub fn VisualTestContext::draw(Self) -> @scene.Scene
pub fn VisualTestContext::draw_count(Self) -> Int32
pub fn VisualTestContext::drawn_scenes(Self) -> Array[@scene.Scene]
pub fn VisualTestContext::from_window(@window.AnyWindowHandle, TestAppContext) -> Self
pub fn VisualTestContext::is_active(Self) -> Bool
pub fn VisualTestContext::is_closed(Self) -> Bool
pub fn VisualTestContext::is_hovered(Self) -> Bool
pub fn[T] VisualTestContext::new_entity(Self, (@app.Context[T]) -> T) -> @app.Entity[T]
pub fn[R] VisualTestContext::read(Self, (@app.App) -> R) -> R
pub fn VisualTestContext::read_from_clipboard(Self) -> @platform.ClipboardItem?
pub fn[V : @window.Render] VisualTestContext::replace_root_view(Self, (@window.Window, @app.Context[V]) -> V) -> @app.Entity[V]
pub fn VisualTestContext::run_until_parked(Self) -> Unit
pub fn VisualTestContext::scale_factor(Self) -> Double
pub fn VisualTestContext::scene(Self) -> @scene.Scene
pub fn VisualTestContext::simulate_active_status_change(Self, Bool) -> Unit
pub fn VisualTestContext::simulate_click(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers) -> Unit
pub fn VisualTestContext::simulate_close(Self) -> Bool
pub fn VisualTestContext::simulate_hover_status_change(Self, Bool) -> Unit
pub fn VisualTestContext::simulate_input(Self, @input.PlatformInput) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_modifiers_change(Self, @input.Modifiers) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_mouse_down(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers, click_count? : Int32) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_mouse_exit(Self, position? : @geometry.Point[@geometry.Pixels], modifiers? : @input.Modifiers) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_mouse_move(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_mouse_up(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers, click_count? : Int32) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit
pub fn VisualTestContext::simulate_scale_factor_change(Self, Double) -> Unit
pub fn VisualTestContext::simulate_scroll_wheel(Self, @geometry.Point[@geometry.Pixels], @input.ScrollDelta, modifiers? : @input.Modifiers) -> @input.DispatchEventResult
pub fn VisualTestContext::test_window(Self) -> TestWindow
pub fn[R] VisualTestContext::update(Self, (@window.Window, @app.App) -> R) -> R
pub fn[T, R] VisualTestContext::update_entity(Self, @app.Entity[T], (T, @app.Context[T]) -> R) -> R
pub fn VisualTestContext::window(Self) -> @window.Window
pub fn VisualTestContext::window_handle(Self) -> @window.AnyWindowHandle
pub fn VisualTestContext::window_id(Self) -> @platform.WindowId
pub fn VisualTestContext::window_title(Self) -> String?
pub fn VisualTestContext::write_to_clipboard(Self, @platform.ClipboardItem) -> Unit
// Type aliases
// Traits
+224
View File
@@ -0,0 +1,224 @@
// Headless test platform, ported from gpui/src/platform/test/platform.rs.
///|
let default_test_bounds : @geometry.Bounds[@geometry.Pixels] = @geometry.bounds(
@geometry.point(@geometry.px(0.0), @geometry.px(0.0)),
@geometry.size(@geometry.px(1024.0), @geometry.px(768.0)),
)
///|
/// A headless `Platform` backed by `TestDispatcher` and `TestWindow`s
/// (GPUI: `TestPlatform`).
pub struct TestPlatform {
priv dispatcher : @executor.TestDispatcher
priv default_bounds : @geometry.Bounds[@geometry.Pixels]
priv default_scale_factor : Double
priv windows : Map[@platform.WindowId, TestWindow]
priv mut active_window : TestWindow?
priv mut active_cursor : @style.CursorStyle
priv mut clipboard : @platform.ClipboardItem?
priv opened_urls : Array[String]
priv mut run_called : Bool
priv mut quit_called : Bool
}
///|
pub fn TestPlatform::new(
dispatcher? : @executor.TestDispatcher,
default_bounds? : @geometry.Bounds[@geometry.Pixels],
default_scale_factor~ : Double = 1.0,
) -> TestPlatform {
{
dispatcher: dispatcher.unwrap_or(@executor.TestDispatcher::new()),
default_bounds: default_bounds.unwrap_or(default_test_bounds),
default_scale_factor,
windows: {},
active_window: None,
active_cursor: Arrow,
clipboard: None,
opened_urls: [],
run_called: false,
quit_called: false,
}
}
///|
pub impl @platform.Platform for TestPlatform with fn dispatcher(self) {
let d : &@executor.Dispatcher = self.dispatcher
d
}
///|
pub impl @platform.Platform for TestPlatform with fn default_window_bounds(self) {
self.default_bounds
}
///|
pub impl @platform.Platform for TestPlatform with fn open_window(
self,
id,
params,
) {
let window = TestWindow::new(id, self, params, self.default_scale_factor)
self.windows[id] = window
if params.focus {
let previous = self.active_window
self.active_window = Some(window)
if previous is Some(prev) && prev.id != id {
@executor.Dispatcher::dispatch(self.dispatcher, fn() {
if !prev.closed {
prev.simulate_active_status_change(false)
}
})
}
}
let pw : &@platform.PlatformWindow = window
pw
}
///|
pub impl @platform.Platform for TestPlatform with fn run(
self,
on_finish_launching,
) {
self.run_called = true
on_finish_launching()
}
///|
pub impl @platform.Platform for TestPlatform with fn quit(self) {
self.quit_called = true
}
///|
pub impl @platform.Platform for TestPlatform with fn active_window(self) {
match self.active_window {
Some(win) if !win.closed => Some(win.id)
_ => None
}
}
///|
pub impl @platform.Platform for TestPlatform with fn set_cursor_style(
self,
style,
) {
self.active_cursor = style
}
///|
pub impl @platform.Platform for TestPlatform with fn read_from_clipboard(self) {
self.clipboard
}
///|
pub impl @platform.Platform for TestPlatform with fn write_to_clipboard(
self,
item,
) {
self.clipboard = Some(item)
}
///|
pub impl @platform.Platform for TestPlatform with fn open_url(self, url) {
self.opened_urls.push(url)
}
// ---------------------------------------------------------------------------
// Inspection and simulation helpers
// ---------------------------------------------------------------------------
///|
pub fn TestPlatform::test_dispatcher(
self : TestPlatform,
) -> @executor.TestDispatcher {
self.dispatcher
}
///|
pub fn TestPlatform::window(
self : TestPlatform,
id : @platform.WindowId,
) -> TestWindow? {
self.windows.get(id)
}
///|
pub fn TestPlatform::windows(self : TestPlatform) -> Array[TestWindow] {
let out = []
for _, win in self.windows {
out.push(win)
}
out
}
///|
pub fn TestPlatform::cursor_style(self : TestPlatform) -> @style.CursorStyle {
self.active_cursor
}
///|
pub fn TestPlatform::opened_url(self : TestPlatform) -> String? {
self.opened_urls.last()
}
///|
pub fn TestPlatform::opened_urls(self : TestPlatform) -> Array[String] {
self.opened_urls
}
///|
pub fn TestPlatform::did_run(self : TestPlatform) -> Bool {
self.run_called
}
///|
pub fn TestPlatform::did_quit(self : TestPlatform) -> Bool {
self.quit_called
}
///|
/// Transfers active window status, notifying the previous and new windows on
/// the dispatcher (GPUI: `TestPlatform::set_active_window`).
pub fn TestPlatform::set_active_window(
self : TestPlatform,
window : TestWindow?,
) -> Unit {
let previous = self.active_window
self.active_window = window
let same = match (previous, window) {
(Some(prev), Some(curr)) => prev.id == curr.id
(None, None) => true
_ => false
}
if same {
return
}
@executor.Dispatcher::dispatch(self.dispatcher, fn() {
if previous is Some(prev) && !prev.closed {
prev.simulate_active_status_change(false)
}
if window is Some(win) && !win.closed {
win.simulate_active_status_change(true)
}
})
}
///|
/// Delivers one scheduled frame for every open window that currently has a
/// frame scheduled, returning how many frames ran.
pub fn TestPlatform::pump_scheduled_frames(self : TestPlatform) -> Int32 {
let open = []
for _, win in self.windows {
if !win.closed && win.frame_scheduled {
open.push(win)
}
}
let mut pumped : Int32 = 0
for win in open {
if win.simulate_scheduled_frame() {
pumped = pumped + 1
}
}
pumped
}
+646
View File
@@ -0,0 +1,646 @@
// High-level test harnesses, ported from gpui/src/app/test_context.rs
// (`TestAppContext` and `VisualTestContext`).
///|
priv enum EmptyView {
EmptyView
}
///|
impl @window.Render for EmptyView with fn render(_self, _window, _cx) {
@window.empty()
}
///|
/// Owns a `TestPlatform` and `Application`, pumping tasks and scheduled
/// frames together for deterministic integration tests (GPUI:
/// `TestAppContext`).
pub struct TestAppContext {
platform : TestPlatform
application : @window.Application
priv mut skip_drawing : Bool
}
///|
pub fn TestAppContext::new(
default_bounds? : @geometry.Bounds[@geometry.Pixels],
default_scale_factor~ : Double = 1.0,
) -> TestAppContext {
let platform = TestPlatform::new(default_bounds?, default_scale_factor~)
TestAppContext::with_platform(platform)
}
///|
pub fn TestAppContext::with_platform(platform : TestPlatform) -> TestAppContext {
let p : &@platform.Platform = platform
let application = @window.Application::with_platform(p)
{ platform, application, skip_drawing: false, }
}
///|
pub fn TestAppContext::app(self : TestAppContext) -> @app.App {
self.application.app()
}
///|
pub fn TestAppContext::application(
self : TestAppContext,
) -> @window.Application {
self.application
}
///|
pub fn TestAppContext::platform(self : TestAppContext) -> TestPlatform {
self.platform
}
///|
pub fn TestAppContext::dispatcher(
self : TestAppContext,
) -> @executor.TestDispatcher {
self.platform.test_dispatcher()
}
///|
pub fn TestAppContext::foreground_executor(
self : TestAppContext,
) -> @executor.Executor {
self.application.app().foreground_executor()
}
///|
pub fn TestAppContext::background_executor(
self : TestAppContext,
) -> @executor.Executor {
self.application.app().background_executor()
}
///|
pub fn TestAppContext::windows(
self : TestAppContext,
) -> Array[@window.AnyWindowHandle] {
self.application.windows()
}
///|
pub fn TestAppContext::active_window(
self : TestAppContext,
) -> @window.AnyWindowHandle? {
self.application.active_window()
}
///|
pub fn TestAppContext::test_window(
self : TestAppContext,
handle : @window.AnyWindowHandle,
) -> TestWindow {
match self.platform.window(handle.window_id()) {
Some(win) => win
None => abort("no TestWindow for \{handle.window_id()}")
}
}
///|
/// Disables (or re-enables) automatic frame pumping in `run_until_parked`
/// (GPUI: `TestAppContext::skip_drawing`).
pub fn TestAppContext::skip_drawing(
self : TestAppContext,
skip~ : Bool = true,
) -> Unit {
self.skip_drawing = skip
}
///|
pub fn TestAppContext::pump_frames(self : TestAppContext) -> Int32 {
self.platform.pump_scheduled_frames()
}
///|
/// Drains all ready tasks and pumps scheduled frames until neither tasks nor
/// scheduled frames remain (GPUI: `TestAppContext::run_until_parked`). Aborts
/// after 100 frame pump passes to catch runaway redraw loops.
pub fn TestAppContext::run_until_parked(self : TestAppContext) -> Unit {
let max_passes = 100
let mut passes = 0
while true {
self.platform.test_dispatcher().run_until_parked()
if self.skip_drawing {
break
}
let pumped = self.platform.pump_scheduled_frames()
if pumped == 0 {
break
}
passes = passes + 1
if passes >= max_passes {
abort(
"TestAppContext::run_until_parked: runaway redraw loop (> \{max_passes} frame pumps)",
)
}
}
}
///|
/// Advances the virtual clock by `ms`, running timers, tasks and scheduled
/// frames (GPUI: `TestAppContext::advance_clock`).
pub fn TestAppContext::advance_clock(self : TestAppContext, ms : Int32) -> Unit {
self.run_until_parked()
self.platform.test_dispatcher().advance_clock(ms)
self.run_until_parked()
}
///|
pub fn[R] TestAppContext::update(
self : TestAppContext,
f : (@app.App) -> R,
) -> R {
let result = self.application.app().update(f)
self.run_until_parked()
result
}
///|
pub fn[R] TestAppContext::read(self : TestAppContext, f : (@app.App) -> R) -> R {
f(self.application.app())
}
///|
pub fn[T] TestAppContext::new_entity(
self : TestAppContext,
build : (@app.Context[T]) -> T,
) -> @app.Entity[T] {
self.update(fn(app) { app.new_entity(build) })
}
///|
pub fn[T, R] TestAppContext::update_entity(
self : TestAppContext,
entity : @app.Entity[T],
f : (T, @app.Context[T]) -> R,
) -> R {
self.update(fn(app) { app.update_entity(entity, f) })
}
///|
pub fn[T] TestAppContext::read_entity(
self : TestAppContext,
entity : @app.Entity[T],
) -> T {
self.application.app().read_entity(entity)
}
///|
pub fn[R] TestAppContext::spawn(
self : TestAppContext,
f : async (@app.AsyncApp) -> R,
) -> @executor.Task[R] {
self.application.app().spawn(f)
}
///|
pub fn[G] TestAppContext::set_global(
self : TestAppContext,
key : @app.GlobalKey[G],
value : G,
) -> Unit {
self.update(fn(app) { app.set_global(key, value) })
}
///|
pub fn[G] TestAppContext::read_global(
self : TestAppContext,
key : @app.GlobalKey[G],
) -> G {
self.application.app().global(key)
}
///|
pub fn[G] TestAppContext::has_global(
self : TestAppContext,
key : @app.GlobalKey[G],
) -> Bool {
self.application.app().has_global(key)
}
///|
pub fn[G, R] TestAppContext::update_global(
self : TestAppContext,
key : @app.GlobalKey[G],
f : (G, @app.App) -> R,
) -> R {
self.update(fn(app) { app.update_global(key, f) })
}
///|
pub fn TestAppContext::write_to_clipboard(
self : TestAppContext,
item : @platform.ClipboardItem,
) -> Unit {
self.application.write_to_clipboard(item)
}
///|
pub fn TestAppContext::read_from_clipboard(
self : TestAppContext,
) -> @platform.ClipboardItem? {
self.application.read_from_clipboard()
}
///|
pub fn TestAppContext::cursor_style(
self : TestAppContext,
) -> @style.CursorStyle {
self.platform.cursor_style()
}
///|
pub fn TestAppContext::opened_url(self : TestAppContext) -> String? {
self.platform.opened_url()
}
///|
pub fn TestAppContext::refresh(self : TestAppContext) -> Unit {
self.application.refresh_windows()
self.run_until_parked()
}
///|
pub fn TestAppContext::quit(self : TestAppContext) -> Unit {
self.application.quit()
}
///|
pub fn[V : @window.Render] TestAppContext::open_window(
self : TestAppContext,
options? : @platform.WindowOptions,
build_root : (@window.Window, @app.App) -> @app.Entity[V],
) -> @window.WindowHandle[V] {
let opts = options.unwrap_or(Default::default())
let handle = self.application.open_window(opts, build_root)
self.run_until_parked()
handle
}
///|
pub fn[V : @window.Render] TestAppContext::add_window(
self : TestAppContext,
size? : @geometry.Size[@geometry.Pixels],
scale_factor? : Double,
title? : String,
build_view : (@window.Window, @app.Context[V]) -> V,
) -> @window.WindowHandle[V] {
let options : @platform.WindowOptions = match size {
Some(s) => @platform.WindowOptions::with_size(s, scale_factor?, title?)
None => { ..Default::default(), scale_factor, title, }
}
self.open_window(options~, fn(window, app) {
app.new_entity(fn(cx) { build_view(window, cx) })
})
}
///|
pub fn[V : @window.Render] TestAppContext::add_window_view(
self : TestAppContext,
size? : @geometry.Size[@geometry.Pixels],
scale_factor? : Double,
title? : String,
build_view : (@window.Window, @app.Context[V]) -> V,
) -> (@app.Entity[V], VisualTestContext) {
let handle = self.add_window(size?, scale_factor?, title?, build_view)
let vcx = VisualTestContext::from_window(handle.to_any(), self)
(handle.entity(), vcx)
}
///|
pub fn TestAppContext::add_empty_window(
self : TestAppContext,
size? : @geometry.Size[@geometry.Pixels],
scale_factor? : Double,
) -> VisualTestContext {
let (_, vcx) = self.add_window_view(size?, scale_factor?, fn(_, _) {
EmptyView::EmptyView
})
vcx
}
// ---------------------------------------------------------------------------
// VisualTestContext
// ---------------------------------------------------------------------------
///|
/// Window-scoped test driver combining a `TestAppContext` with one
/// `AnyWindowHandle` (GPUI: `VisualTestContext`).
pub struct VisualTestContext {
cx : TestAppContext
window_handle : @window.AnyWindowHandle
}
///|
pub fn VisualTestContext::from_window(
window_handle : @window.AnyWindowHandle,
cx : TestAppContext,
) -> VisualTestContext {
{ cx, window_handle, }
}
///|
pub fn VisualTestContext::window_handle(
self : VisualTestContext,
) -> @window.AnyWindowHandle {
self.window_handle
}
///|
pub fn VisualTestContext::window_id(
self : VisualTestContext,
) -> @platform.WindowId {
self.window_handle.window_id()
}
///|
pub fn VisualTestContext::app(self : VisualTestContext) -> @app.App {
self.cx.app()
}
///|
pub fn VisualTestContext::test_window(self : VisualTestContext) -> TestWindow {
self.cx.test_window(self.window_handle)
}
///|
pub fn VisualTestContext::window(self : VisualTestContext) -> @window.Window {
match self.cx.application.window(self.window_id()) {
Some(win) => win
None => abort("window \{self.window_id()} is closed")
}
}
///|
pub fn VisualTestContext::is_closed(self : VisualTestContext) -> Bool {
self.test_window().is_closed()
}
///|
pub fn VisualTestContext::window_title(self : VisualTestContext) -> String? {
self.test_window().title()
}
///|
pub fn VisualTestContext::is_active(self : VisualTestContext) -> Bool {
@platform.PlatformWindow::is_active(self.test_window())
}
///|
pub fn VisualTestContext::is_hovered(self : VisualTestContext) -> Bool {
@platform.PlatformWindow::is_hovered(self.test_window())
}
///|
pub fn VisualTestContext::bounds(
self : VisualTestContext,
) -> @geometry.Bounds[@geometry.Pixels] {
@platform.PlatformWindow::bounds(self.test_window())
}
///|
pub fn VisualTestContext::scale_factor(self : VisualTestContext) -> Double {
@platform.PlatformWindow::scale_factor(self.test_window())
}
///|
pub fn VisualTestContext::cursor_style(
self : VisualTestContext,
) -> @style.CursorStyle {
self.cx.cursor_style()
}
///|
pub fn VisualTestContext::write_to_clipboard(
self : VisualTestContext,
item : @platform.ClipboardItem,
) -> Unit {
self.cx.write_to_clipboard(item)
}
///|
pub fn VisualTestContext::read_from_clipboard(
self : VisualTestContext,
) -> @platform.ClipboardItem? {
self.cx.read_from_clipboard()
}
///|
pub fn VisualTestContext::run_until_parked(self : VisualTestContext) -> Unit {
self.cx.run_until_parked()
}
///|
pub fn VisualTestContext::advance_clock(
self : VisualTestContext,
ms : Int32,
) -> Unit {
self.cx.advance_clock(ms)
}
///|
pub fn[R] VisualTestContext::update(
self : VisualTestContext,
f : (@window.Window, @app.App) -> R,
) -> R {
let window = self.window()
let result = self.app().update(fn(app) { f(window, app) })
self.cx.run_until_parked()
result
}
///|
pub fn[R] VisualTestContext::read(
self : VisualTestContext,
f : (@app.App) -> R,
) -> R {
self.cx.read(f)
}
///|
pub fn[T, R] VisualTestContext::update_entity(
self : VisualTestContext,
entity : @app.Entity[T],
f : (T, @app.Context[T]) -> R,
) -> R {
self.cx.update_entity(entity, f)
}
///|
pub fn[T] VisualTestContext::new_entity(
self : VisualTestContext,
build : (@app.Context[T]) -> T,
) -> @app.Entity[T] {
self.cx.new_entity(build)
}
///|
pub fn[V : @window.Render] VisualTestContext::replace_root_view(
self : VisualTestContext,
build : (@window.Window, @app.Context[V]) -> V,
) -> @app.Entity[V] {
self.update(fn(window, _) { window.replace_root_view(build) })
}
///|
pub fn VisualTestContext::draw(self : VisualTestContext) -> @scene.Scene {
let scene = self.window().draw()
self.cx.run_until_parked()
scene
}
///|
pub fn VisualTestContext::scene(self : VisualTestContext) -> @scene.Scene {
match self.test_window().last_scene() {
Some(scene) => scene
None => self.window().scene()
}
}
///|
pub fn VisualTestContext::drawn_scenes(
self : VisualTestContext,
) -> Array[@scene.Scene] {
self.test_window().drawn_scenes()
}
///|
pub fn VisualTestContext::draw_count(self : VisualTestContext) -> Int32 {
self.test_window().draw_count()
}
///|
pub fn VisualTestContext::simulate_input(
self : VisualTestContext,
event : @input.PlatformInput,
) -> @input.DispatchEventResult {
let result = self.test_window().simulate_input(event)
self.cx.run_until_parked()
result
}
///|
pub fn VisualTestContext::simulate_mouse_move(
self : VisualTestContext,
position : @geometry.Point[@geometry.Pixels],
button? : @input.MouseButton,
modifiers~ : @input.Modifiers = Default::default(),
) -> @input.DispatchEventResult {
self.simulate_input(
MouseMove({ position, pressed_button: button, modifiers, }),
)
}
///|
pub fn VisualTestContext::simulate_mouse_down(
self : VisualTestContext,
position : @geometry.Point[@geometry.Pixels],
button~ : @input.MouseButton = Left,
modifiers~ : @input.Modifiers = Default::default(),
click_count~ : Int32 = 1,
) -> @input.DispatchEventResult {
self.simulate_input(
MouseDown({ position, button, modifiers, click_count, first_mouse: false, }),
)
}
///|
pub fn VisualTestContext::simulate_mouse_up(
self : VisualTestContext,
position : @geometry.Point[@geometry.Pixels],
button~ : @input.MouseButton = Left,
modifiers~ : @input.Modifiers = Default::default(),
click_count~ : Int32 = 1,
) -> @input.DispatchEventResult {
self.simulate_input(MouseUp({ position, button, modifiers, click_count, }))
}
///|
pub fn VisualTestContext::simulate_click(
self : VisualTestContext,
position : @geometry.Point[@geometry.Pixels],
button~ : @input.MouseButton = Left,
modifiers~ : @input.Modifiers = Default::default(),
) -> Unit {
ignore(self.simulate_mouse_down(position, button~, modifiers~))
ignore(self.simulate_mouse_up(position, button~, modifiers~))
}
///|
pub fn VisualTestContext::simulate_scroll_wheel(
self : VisualTestContext,
position : @geometry.Point[@geometry.Pixels],
delta : @input.ScrollDelta,
modifiers~ : @input.Modifiers = Default::default(),
) -> @input.DispatchEventResult {
self.simulate_input(ScrollWheel({ position, delta, modifiers, }))
}
///|
pub fn VisualTestContext::simulate_mouse_exit(
self : VisualTestContext,
position~ : @geometry.Point[@geometry.Pixels] = @geometry.point(
@geometry.px(0.0),
@geometry.px(0.0),
),
modifiers~ : @input.Modifiers = Default::default(),
) -> @input.DispatchEventResult {
self.simulate_input(
MouseExited({ position, pressed_button: None, modifiers, }),
)
}
///|
pub fn VisualTestContext::simulate_modifiers_change(
self : VisualTestContext,
modifiers : @input.Modifiers,
) -> @input.DispatchEventResult {
self.simulate_input(ModifiersChanged({ modifiers, }))
}
///|
pub fn VisualTestContext::simulate_resize(
self : VisualTestContext,
size : @geometry.Size[@geometry.Pixels],
) -> Unit {
self.test_window().simulate_resize(size)
self.cx.run_until_parked()
}
///|
pub fn VisualTestContext::simulate_scale_factor_change(
self : VisualTestContext,
scale_factor : Double,
) -> Unit {
self.test_window().simulate_scale_factor_change(scale_factor)
self.cx.run_until_parked()
}
///|
pub fn VisualTestContext::simulate_active_status_change(
self : VisualTestContext,
active : Bool,
) -> Unit {
self.test_window().simulate_active_status_change(active)
self.cx.run_until_parked()
}
///|
pub fn VisualTestContext::simulate_hover_status_change(
self : VisualTestContext,
hovered : Bool,
) -> Unit {
self.test_window().simulate_hover_status_change(hovered)
self.cx.run_until_parked()
}
///|
pub fn VisualTestContext::simulate_close(self : VisualTestContext) -> Bool {
let closed = self.test_window().simulate_close_requested()
self.cx.run_until_parked()
closed
}
+498
View File
@@ -0,0 +1,498 @@
///|
fn px(v : Double) -> @geometry.Pixels {
@geometry.px(v)
}
///|
fn pt(x : Double, y : Double) -> @geometry.Point[@geometry.Pixels] {
@geometry.point(px(x), px(y))
}
///|
fn sz(w : Double, h : Double) -> @geometry.Size[@geometry.Pixels] {
@geometry.size(px(w), px(h))
}
///|
fn sp(v : Double) -> @geometry.ScaledPixels {
@geometry.ScaledPixels(v)
}
///|
/// A minimal element that paints a solid quad across its layout bounds and
/// optionally handles mouse events and hover.
priv struct BoxElement {
color : @color.Rgba
hover_color : @color.Rgba?
on_down : ((@input.MouseDownEvent, @window.Window, @app.App) -> Unit)?
on_scroll : ((@input.ScrollWheelEvent, @window.Window, @app.App) -> Unit)?
mut hitbox : @window.Hitbox?
}
///|
fn box_el(
color : @color.Rgba,
hover_color? : @color.Rgba,
on_down? : (@input.MouseDownEvent, @window.Window, @app.App) -> Unit,
on_scroll? : (@input.ScrollWheelEvent, @window.Window, @app.App) -> Unit,
) -> @window.AnyElement {
@window.AnyElement::new({
color,
hover_color,
on_down,
on_scroll,
hitbox: None,
})
}
///|
impl @window.Element for BoxElement with fn request_layout(_self, window, _app) {
window.request_layout(Default::default(), [])
}
///|
impl @window.Element for BoxElement with fn prepaint(self, bounds, window, _app) {
if self.hover_color is Some(_) ||
self.on_down is Some(_) ||
self.on_scroll is Some(_) {
self.hitbox = Some(window.insert_hitbox(bounds, Normal))
}
}
///|
impl @window.Element for BoxElement with fn paint(self, bounds, window, _app) {
let hovered = match self.hitbox {
Some(hitbox) => hitbox.is_hovered(window)
None => false
}
let bg = match (self.hover_color, hovered) {
(Some(hc), true) => hc
_ => self.color
}
if self.hitbox is Some(hitbox) {
if self.on_down is Some(cb) {
window.on_mouse_event(fn(event, phase, win, app) {
if phase == Bubble && event is MouseDown(down) && hitbox.is_hovered(win) {
cb(down, win, app)
}
})
}
if self.on_scroll is Some(cb) {
window.on_mouse_event(fn(event, phase, win, app) {
if phase == Bubble &&
event is ScrollWheel(scroll) &&
hitbox.is_hovered(win) {
cb(scroll, win, app)
}
})
}
}
window.paint_quad(@window.fill(bounds, bg.to_background()))
}
///|
struct TestView {
mut count : Int32
hover_bg : @color.Rgba?
prevent : Bool
stop : Bool
log : Array[String]
}
///|
impl @window.Render for TestView with fn render(self, _window, cx) {
box_el(
@color.rgb(0x112233),
hover_color?=self.hover_bg,
on_down=@window.listener(cx, fn(view, down, window, cx) {
view.count = view.count + 1
let btn = if down.button == Left { "Left" } else { "Other" }
view.log.push("down:\{btn}:\{down.modifiers.shift}")
if view.prevent {
window.prevent_default()
}
if view.stop {
window.stop_propagation()
}
cx.notify()
}),
on_scroll=@window.listener(cx, fn(view, scroll, _window, _cx) {
view.log.push("scroll:\{scroll.position.x.to_double()}")
}),
)
}
///|
enum PlainView {
PlainView
}
///|
impl @window.Render for PlainView with fn render(_self, _window, _cx) {
box_el(@color.rgb(0xabcdef))
}
///|
enum RunawayView {
RunawayView
}
///|
impl @window.Render for RunawayView with fn render(_self, window, _cx) {
window.refresh()
box_el(@color.rgb(0x000000))
}
///|
test "Application run, quit, and TestPlatform flags" {
let platform = @test.TestPlatform::new()
let app = @window.Application::with_platform(platform)
assert_false(platform.did_run())
assert_false(platform.did_quit())
let launched = Ref(false)
let found_app = Ref(false)
app.run(fn(a) {
launched.val = true
found_app.val = @window.application_for(a.app()) is Some(_)
a.quit()
})
assert_true(launched.val)
assert_true(found_app.val)
assert_true(platform.did_run())
assert_true(platform.did_quit())
}
///|
test "explicit frame scheduling on TestPlatform and TestWindow" {
let platform = @test.TestPlatform::new()
let app = @window.Application::with_platform(platform)
let view : Ref[@app.Entity[TestView]?] = Ref(None)
let unrelated : Ref[@app.Entity[PlainView]?] = Ref(None)
let handle = app.open_window(
@platform.WindowOptions::with_size(sz(300.0, 200.0), title="Manual"),
fn(_window, cx_app) {
unrelated.val = Some(cx_app.new_entity(fn(_) { PlainView }))
let v : @app.Entity[TestView] = cx_app.new_entity(fn(_) {
{ count: 0, hover_bg: None, prevent: false, stop: false, log: [], }
})
view.val = Some(v)
v
},
)
let tw = platform.window(handle.window_id()).unwrap()
assert_true(tw.frame_scheduled())
assert_eq(tw.draw_count(), 0)
assert_true(tw.simulate_scheduled_frame())
assert_false(tw.frame_scheduled())
assert_eq(tw.draw_count(), 1)
assert_false(tw.simulate_scheduled_frame())
// Unrelated entity notification must not schedule a frame.
unrelated.val.unwrap().update(app.app(), fn(_, cx) { cx.notify() })
assert_false(tw.frame_scheduled())
// Notifying rendered view re-schedules a frame.
view.val
.unwrap()
.update(app.app(), fn(v, cx) {
v.count = 1
cx.notify()
})
assert_true(tw.frame_scheduled())
assert_true(tw.simulate_scheduled_frame())
assert_eq(tw.draw_count(), 2)
}
///|
test "resize, scale factor, and programmatic Window::resize avoid recursion" {
let cx = @test.TestAppContext::new()
let vcx = cx.add_empty_window(size=sz(200.0, 100.0))
ignore(vcx.replace_root_view(fn(_, _) { PlainView }))
let before = vcx.draw_count()
vcx.simulate_resize(sz(320.0, 180.0))
assert_eq(vcx.draw_count(), before + 1)
assert_eq(vcx.bounds().size, sz(320.0, 180.0))
assert_eq(
vcx.scene().quads[0].bounds,
@geometry.bounds(
@geometry.point(sp(0.0), sp(0.0)),
@geometry.size(sp(320.0), sp(180.0)),
),
)
vcx.simulate_scale_factor_change(2.0)
assert_eq(vcx.scale_factor(), 2.0)
assert_eq(
vcx.scene().quads[0].bounds,
@geometry.bounds(
@geometry.point(sp(0.0), sp(0.0)),
@geometry.size(sp(640.0), sp(360.0)),
),
)
// Programmatic resize updates platform window bounds and schedules redraw without loop.
vcx.update(fn(win, _) { win.resize(sz(400.0, 200.0)) })
assert_eq(vcx.bounds().size, sz(400.0, 200.0))
assert_eq(vcx.scale_factor(), 2.0)
assert_eq(
vcx.scene().quads[0].bounds,
@geometry.bounds(
@geometry.point(sp(0.0), sp(0.0)),
@geometry.size(sp(800.0), sp(400.0)),
),
)
vcx.update(fn(win, _) { win.resize(sz(400.0, 200.0), scale_factor=1.5) })
assert_eq(vcx.window().scale_factor(), 1.5)
assert_eq(
vcx.scene().quads[0].bounds,
@geometry.bounds(
@geometry.point(sp(0.0), sp(0.0)),
@geometry.size(sp(600.0), sp(300.0)),
),
)
}
///|
test "title, cursor style, clipboard, and open_url" {
let cx = @test.TestAppContext::new()
let (_, vcx) = cx.add_window_view(size=sz(100.0, 100.0), title="Initial", fn(
_,
_,
) {
PlainView
})
assert_eq(vcx.window_title(), Some("Initial"))
vcx.update(fn(win, _) {
win.set_window_title("Updated")
win.set_cursor_style(PointingHand)
win.write_to_clipboard(
@platform.ClipboardItem::new_string_with_metadata("abc", "text"),
)
})
assert_eq(vcx.window_title(), Some("Updated"))
assert_eq(vcx.cursor_style(), @style.CursorStyle::PointingHand)
assert_eq(vcx.read_from_clipboard().unwrap().text(), Some("abc"))
assert_eq(cx.read_from_clipboard().unwrap().metadata(), Some("text"))
cx.application().open_url("https://example.com")
assert_eq(cx.opened_url(), Some("https://example.com"))
}
///|
test "multi-window activation and focus transfer" {
let cx = @test.TestAppContext::new()
let log : Array[String] = []
let (_, vcx1) = cx.add_window_view(size=sz(100.0, 100.0), fn(win, _) {
win.on_window_active_change(fn(w, _) {
log.push("w1:\{w.is_window_active()}")
})
PlainView
})
assert_true(vcx1.is_active())
assert_eq(cx.active_window(), Some(vcx1.window_handle()))
let (_, vcx2) = cx.add_window_view(size=sz(100.0, 100.0), fn(win, _) {
win.on_window_active_change(fn(w, _) {
log.push("w2:\{w.is_window_active()}")
})
PlainView
})
assert_false(vcx1.is_active())
assert_true(vcx2.is_active())
assert_eq(cx.active_window(), Some(vcx2.window_handle()))
assert_eq(log, ["w1:false"])
vcx1.update(fn(win, _) { win.activate_window() })
assert_true(vcx1.is_active())
assert_false(vcx2.is_active())
assert_eq(cx.active_window(), Some(vcx1.window_handle()))
assert_eq(log, ["w1:false", "w2:false", "w1:true"])
}
///|
test "MouseExited, hover status change, ModifiersChanged, and DispatchEventResult" {
let cx = @test.TestAppContext::new()
let (view, vcx) = cx.add_window_view(size=sz(100.0, 100.0), fn(_, _) {
{
count: 0,
hover_bg: Some(@color.rgb(0x00ff00)),
prevent: true,
stop: true,
log: [],
}
})
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x112233).to_background(),
)
ignore(vcx.simulate_mouse_move(pt(50.0, 50.0)))
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x00ff00).to_background(),
)
// MouseExited clears hovered hitboxes and marks window dirty -> redraws unhovered.
ignore(vcx.simulate_mouse_exit(position=pt(200.0, 200.0)))
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x112233).to_background(),
)
// Re-hover then lose window hover via platform hover status change.
ignore(vcx.simulate_mouse_move(pt(50.0, 50.0)))
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x00ff00).to_background(),
)
vcx.simulate_hover_status_change(false)
assert_false(vcx.is_hovered())
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x112233).to_background(),
)
// ModifiersChanged updates window modifiers and dirties/redraws on change.
let draws_before_mod = vcx.draw_count()
let shift_mods : @input.Modifiers = { ..Default::default(), shift: true, }
ignore(vcx.simulate_modifiers_change(shift_mods))
assert_eq(vcx.window().modifiers(), shift_mods)
assert_eq(vcx.draw_count(), draws_before_mod + 1)
// stop_propagation + prevent_default reflected in DispatchEventResult.
let result = vcx.simulate_mouse_down(pt(50.0, 50.0), modifiers=shift_mods)
assert_false(result.propagate)
assert_true(result.default_prevented)
assert_eq(cx.read_entity(view).log, ["down:Left:true"])
// ScrollWheel delivery.
ignore(
vcx.simulate_scroll_wheel(
pt(25.0, 25.0),
@input.ScrollDelta::Pixels(pt(0.0, -10.0)),
),
)
assert_eq(cx.read_entity(view).log, ["down:Left:true", "scroll:25"])
}
///|
test "window close veto, on_close, root release, and idempotence" {
let cx = @test.TestAppContext::new()
let can_close = Ref(false)
let events : Array[String] = []
let handle = cx.add_window(size=sz(100.0, 100.0), fn(win, ctx) {
ctx.on_release(fn(_, _) { events.push("released") }).detach()
win.on_should_close(fn(_, _) { can_close.val })
win.on_close(fn(_) { events.push("on_close") })
PlainView
})
let vcx = @test.VisualTestContext::from_window(handle.to_any(), cx)
assert_eq(cx.windows().length(), 1)
// Vetoed close leaves window open and view alive.
assert_false(vcx.simulate_close())
assert_false(vcx.is_closed())
assert_false(handle.entity().is_released())
assert_eq(events, [])
// Allowed close runs on_close, releases root view, removes window from Application.
can_close.val = true
assert_true(vcx.simulate_close())
assert_true(vcx.is_closed())
assert_eq(cx.windows().length(), 0)
assert_true(handle.entity().is_released())
assert_eq(events, ["on_close", "released"])
assert_eq(handle.update(cx.application(), fn(_, _, _) { 1 }), None)
// Idempotent repeat close calls do nothing extra.
vcx.test_window().simulate_close()
assert_eq(events, ["on_close", "released"])
}
///|
test "async task and virtual clock drive automatic redraws" {
let cx = @test.TestAppContext::new()
let (view, vcx) = cx.add_window_view(size=sz(120.0, 80.0), fn(_, ctx) {
let weak : @app.WeakEntity[TestView] = ctx.weak_entity()
ctx
.spawn(async fn(_, async_app) {
async_app.background_executor().sleep(50)
ignore(
weak.update(async_app.app, fn(v : TestView, cx) {
v.count = v.count + 10
cx.notify()
}),
)
})
.detach()
{ count: 1, hover_bg: None, prevent: false, stop: false, log: [], }
})
assert_eq(vcx.draw_count(), 1)
assert_eq(cx.read_entity(view).count, 1)
cx.advance_clock(50)
assert_eq(cx.read_entity(view).count, 11)
assert_eq(vcx.draw_count(), 2)
}
///|
test "replace_root_view and skip_drawing" {
let cx = @test.TestAppContext::new()
let released = Ref(false)
let (first, vcx) = cx.add_window_view(size=sz(100.0, 100.0), fn(_, ctx) {
ctx.on_release(fn(_, _) { released.val = true }).detach()
PlainView
})
assert_false(released.val)
let second = vcx.replace_root_view(fn(_, _) {
{ count: 42, hover_bg: None, prevent: false, stop: false, log: [], }
})
assert_true(first.is_released())
assert_true(released.val)
assert_eq(cx.read_entity(second).count, 42)
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x112233).to_background(),
)
// skip_drawing prevents automatic frame pumping until re-enabled.
cx.skip_drawing()
let count_before = vcx.draw_count()
cx.update_entity(second, fn(v, ctx) {
v.count = 43
ctx.notify()
})
assert_eq(vcx.draw_count(), count_before)
assert_true(vcx.test_window().frame_scheduled())
cx.skip_drawing(skip=false)
cx.run_until_parked()
assert_eq(vcx.draw_count(), count_before + 1)
}
///|
test "panic on drawing a closed window" {
let cx = @test.TestAppContext::new()
let vcx = cx.add_empty_window(size=sz(50.0, 50.0))
let win = vcx.window()
win.close()
ignore(win.draw())
}
///|
test "panic on dispatching input on a closed window" {
let cx = @test.TestAppContext::new()
let vcx = cx.add_empty_window(size=sz(50.0, 50.0))
let win = vcx.window()
win.close()
ignore(
win.dispatch_input(
MouseMove({ ..Default::default(), position: pt(5.0, 5.0), }),
),
)
}
///|
test "panic on runaway redraw loop" {
let cx = @test.TestAppContext::new()
ignore(cx.add_window(size=sz(50.0, 50.0), fn(_, _) { RunawayView }))
}
+429
View File
@@ -0,0 +1,429 @@
// Headless test window, ported from gpui/src/platform/test/window.rs.
///|
/// A headless `PlatformWindow` for tests: records presented `Scene`s and
/// provides simulation hooks for frames, input, resizing, focus and closing
/// (GPUI: `TestWindow`).
pub struct TestWindow {
priv id : @platform.WindowId
priv platform : TestPlatform
priv mut bounds : @geometry.Bounds[@geometry.Pixels]
priv mut scale_factor : Double
priv mut title : String?
priv mut active : Bool
priv mut hovered : Bool
priv mut mouse_position : @geometry.Point[@geometry.Pixels]
priv mut modifiers : @input.Modifiers
priv mut closed : Bool
priv mut frame_scheduled : Bool
priv mut frame_schedule_count : Int32
priv drawn_scenes : Array[@scene.Scene]
priv mut request_frame_callback : (() -> Unit)?
priv mut input_callback : ((@input.PlatformInput) -> @input.DispatchEventResult)?
priv mut resize_callback : ((@geometry.Size[@geometry.Pixels], Double) -> Unit)?
priv mut active_status_change_callback : ((Bool) -> Unit)?
priv mut hover_status_change_callback : ((Bool) -> Unit)?
priv mut should_close_callback : (() -> Bool)?
priv mut close_callback : (() -> Unit)?
}
///|
fn TestWindow::new(
id : @platform.WindowId,
platform : TestPlatform,
params : @platform.WindowParams,
default_scale_factor : Double,
) -> TestWindow {
{
id,
platform,
bounds: params.bounds,
scale_factor: params.scale_factor.unwrap_or(default_scale_factor),
title: params.title,
active: params.focus,
hovered: false,
mouse_position: @geometry.point(@geometry.px(0.0), @geometry.px(0.0)),
modifiers: Default::default(),
closed: false,
frame_scheduled: false,
frame_schedule_count: 0,
drawn_scenes: [],
request_frame_callback: None,
input_callback: None,
resize_callback: None,
active_status_change_callback: None,
hover_status_change_callback: None,
should_close_callback: None,
close_callback: None,
}
}
///|
fn TestWindow::clear_callbacks(self : TestWindow) -> Unit {
self.request_frame_callback = None
self.input_callback = None
self.resize_callback = None
self.active_status_change_callback = None
self.hover_status_change_callback = None
self.should_close_callback = None
self.close_callback = None
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn bounds(self) {
self.bounds
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn content_size(self) {
self.bounds.size
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn scale_factor(self) {
self.scale_factor
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn mouse_position(self) {
self.mouse_position
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn modifiers(self) {
self.modifiers
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn is_active(self) {
self.active
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn is_hovered(self) {
self.hovered
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn set_title(self, title) {
self.title = Some(title)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn activate(self) {
if !self.closed {
self.platform.set_active_window(Some(self))
}
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn resize(self, size) {
self.bounds = { ..self.bounds, size, }
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn draw(self, scene) {
self.drawn_scenes.push(scene)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn schedule_frame(self) {
if !self.closed {
self.frame_scheduled = true
self.frame_schedule_count = self.frame_schedule_count + 1
}
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn close(self) {
if self.closed {
return
}
self.closed = true
self.frame_scheduled = false
self.clear_callbacks()
if self.platform.active_window is Some(active) && active.id == self.id {
self.platform.active_window = None
}
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_request_frame(
self,
callback,
) {
self.request_frame_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_input(
self,
callback,
) {
self.input_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_resize(
self,
callback,
) {
self.resize_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_active_status_change(
self,
callback,
) {
self.active_status_change_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_hover_status_change(
self,
callback,
) {
self.hover_status_change_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_should_close(
self,
callback,
) {
self.should_close_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_close(
self,
callback,
) {
self.close_callback = Some(callback)
}
// ---------------------------------------------------------------------------
// Inspection helpers
// ---------------------------------------------------------------------------
///|
pub fn TestWindow::window_id(self : TestWindow) -> @platform.WindowId {
self.id
}
///|
pub fn TestWindow::title(self : TestWindow) -> String? {
self.title
}
///|
pub fn TestWindow::is_closed(self : TestWindow) -> Bool {
self.closed
}
///|
pub fn TestWindow::frame_scheduled(self : TestWindow) -> Bool {
self.frame_scheduled
}
///|
pub fn TestWindow::frame_schedule_count(self : TestWindow) -> Int32 {
self.frame_schedule_count
}
///|
pub fn TestWindow::drawn_scenes(self : TestWindow) -> Array[@scene.Scene] {
self.drawn_scenes
}
///|
pub fn TestWindow::draw_count(self : TestWindow) -> Int32 {
self.drawn_scenes.length()
}
///|
pub fn TestWindow::last_scene(self : TestWindow) -> @scene.Scene? {
self.drawn_scenes.last()
}
///|
pub fn TestWindow::clear_drawn_scenes(self : TestWindow) -> Unit {
self.drawn_scenes.clear()
}
// ---------------------------------------------------------------------------
// Simulation hooks
// ---------------------------------------------------------------------------
///|
/// Delivers one frame if one was scheduled; returns whether a frame ran
/// (GPUI: `TestWindow::simulate_scheduled_frame`).
pub fn TestWindow::simulate_scheduled_frame(self : TestWindow) -> Bool {
if self.closed || !self.frame_scheduled {
return false
}
self.frame_scheduled = false
match self.request_frame_callback {
Some(callback) => {
callback()
true
}
None => {
self.frame_scheduled = true
false
}
}
}
///|
/// Unconditionally invokes the registered frame callback, as a display-link
/// tick would (GPUI: `TestWindow::simulate_frame_request`).
pub fn TestWindow::simulate_frame_request(self : TestWindow) -> Unit {
if self.closed {
return
}
self.frame_scheduled = false
if self.request_frame_callback is Some(callback) {
callback()
}
}
///|
/// Simulates a `PlatformInput` event arriving from the OS/browser
/// (GPUI: `TestWindow::simulate_input`).
pub fn TestWindow::simulate_input(
self : TestWindow,
event : @input.PlatformInput,
) -> @input.DispatchEventResult {
if self.closed {
return { propagate: true, default_prevented: false, }
}
self.modifiers = event.modifiers()
match event {
MouseDown(e) => self.mouse_position = e.position
MouseUp(e) => self.mouse_position = e.position
MouseMove(e) => self.mouse_position = e.position
ScrollWheel(e) => self.mouse_position = e.position
MouseExited(e) => self.mouse_position = e.position
ModifiersChanged(_) => ()
}
match self.input_callback {
Some(callback) => callback(event)
None => { propagate: true, default_prevented: false, }
}
}
///|
/// Simulates a user/OS resize of the window (GPUI: `TestWindow::simulate_resize`).
pub fn TestWindow::simulate_resize(
self : TestWindow,
size : @geometry.Size[@geometry.Pixels],
) -> Unit {
if self.closed {
return
}
self.bounds = { ..self.bounds, size, }
if self.resize_callback is Some(callback) {
callback(size, self.scale_factor)
}
}
///|
/// Simulates a display scale-factor change
/// (GPUI: `TestWindow::simulate_scale_factor_change`).
pub fn TestWindow::simulate_scale_factor_change(
self : TestWindow,
scale_factor : Double,
) -> Unit {
if self.closed {
return
}
self.scale_factor = scale_factor
if self.resize_callback is Some(callback) {
callback(self.bounds.size, scale_factor)
}
}
///|
/// Simulates a window focus/activation change
/// (GPUI: `TestWindow::simulate_active_status_change`).
pub fn TestWindow::simulate_active_status_change(
self : TestWindow,
active : Bool,
) -> Unit {
if self.closed {
return
}
self.active = active
if active {
self.platform.active_window = Some(self)
} else if self.platform.active_window is Some(curr) && curr.id == self.id {
self.platform.active_window = None
}
if self.active_status_change_callback is Some(callback) {
callback(active)
}
}
///|
/// Simulates the pointer entering or leaving the window surface.
pub fn TestWindow::simulate_hover_status_change(
self : TestWindow,
hovered : Bool,
) -> Unit {
if self.closed {
return
}
self.hovered = hovered
if self.hover_status_change_callback is Some(callback) {
callback(hovered)
}
}
///|
/// Queries whether a close should proceed. Returns `true` if no handler is
/// registered.
pub fn TestWindow::simulate_should_close(self : TestWindow) -> Bool {
if self.closed {
return true
}
match self.should_close_callback {
Some(callback) => callback()
None => true
}
}
///|
/// Simulates the OS closing this window unconditionally and invoking the
/// registered `on_close` callback (GPUI: `TestWindow::simulate_close`).
pub fn TestWindow::simulate_close(self : TestWindow) -> Unit {
if self.closed {
return
}
let callback = self.close_callback
self.closed = true
self.frame_scheduled = false
self.clear_callbacks()
if self.platform.active_window is Some(curr) && curr.id == self.id {
self.platform.active_window = None
}
if callback is Some(callback) {
callback()
}
}
///|
/// Simulates a user-initiated close request: asks `on_should_close`, closes
/// if allowed, and returns whether the window closed.
pub fn TestWindow::simulate_close_requested(self : TestWindow) -> Bool {
if self.closed {
return false
}
if self.simulate_should_close() {
self.simulate_close()
true
} else {
false
}
}
+175
View File
@@ -0,0 +1,175 @@
// Core value types shared between GPUI windows and platform implementations,
// ported from gpui/src/platform.rs.
///|
/// Identifies an open window within an application (GPUI: `WindowId`).
#derive(Eq, Compare, Hash, Debug)
pub(all) struct WindowId(Int32)
///|
pub impl Show for WindowId with fn output(self, logger) {
logger.write_string("WindowId(\{self.0})")
}
///|
/// Requested window state and bounds (GPUI: `WindowBounds`).
#derive(Eq, Debug)
pub(all) enum WindowBounds {
Windowed(@geometry.Bounds[@geometry.Pixels])
Maximized(@geometry.Bounds[@geometry.Pixels])
Fullscreen(@geometry.Bounds[@geometry.Pixels])
}
///|
pub impl Default for WindowBounds with fn default() {
Windowed(Default::default())
}
///|
/// Returns the logical bounds stored in this `WindowBounds`.
pub fn WindowBounds::get_bounds(
self : WindowBounds,
) -> @geometry.Bounds[@geometry.Pixels] {
match self {
Windowed(bounds) | Maximized(bounds) | Fullscreen(bounds) => bounds
}
}
///|
/// Configuration passed when opening a window (GPUI: `WindowOptions`).
#derive(Eq, Debug)
pub(all) struct WindowOptions {
window_bounds : WindowBounds?
title : String?
focus : Bool
show : Bool
scale_factor : Double?
rem_size : @geometry.Pixels
}
///|
pub impl Default for WindowOptions with fn default() {
{
window_bounds: None,
title: None,
focus: true,
show: true,
scale_factor: None,
rem_size: @geometry.px(16.0),
}
}
///|
/// Convenience constructor for a windowed `WindowOptions` of `size` at the
/// origin.
pub fn WindowOptions::with_size(
size : @geometry.Size[@geometry.Pixels],
scale_factor? : Double,
title? : String,
rem_size~ : @geometry.Pixels = @geometry.px(16.0),
) -> WindowOptions {
{
..Default::default(),
window_bounds: Some(
Windowed(
@geometry.bounds(
@geometry.point(@geometry.px(0.0), @geometry.px(0.0)),
size,
),
),
),
title,
scale_factor,
rem_size,
}
}
///|
/// Resolved parameters handed to `Platform::open_window` (GPUI:
/// `WindowParams`).
#derive(Eq, Debug)
pub(all) struct WindowParams {
bounds : @geometry.Bounds[@geometry.Pixels]
title : String?
focus : Bool
show : Bool
scale_factor : Double?
}
///|
/// A plain-text clipboard entry with optional metadata (GPUI:
/// `ClipboardString`).
#derive(Eq, Debug)
pub(all) struct ClipboardString {
text : String
metadata : String?
}
///|
pub fn ClipboardString::new(text : String) -> ClipboardString {
{ text, metadata: None, }
}
///|
pub fn ClipboardString::new_with_metadata(
text : String,
metadata : String,
) -> ClipboardString {
{ text, metadata: Some(metadata), }
}
///|
/// One item inside a `ClipboardItem` (GPUI: `ClipboardEntry`, text subset).
#derive(Eq, Debug)
pub(all) enum ClipboardEntry {
String(ClipboardString)
}
///|
/// Data placed on or read from the system clipboard (GPUI: `ClipboardItem`).
#derive(Eq, Debug)
pub(all) struct ClipboardItem {
entries : Array[ClipboardEntry]
}
///|
/// Creates a `ClipboardItem` containing one plain-text entry.
pub fn ClipboardItem::new_string(text : String) -> ClipboardItem {
{ entries: [String(ClipboardString::new(text))], }
}
///|
/// Creates a `ClipboardItem` containing one plain-text entry with metadata.
pub fn ClipboardItem::new_string_with_metadata(
text : String,
metadata : String,
) -> ClipboardItem {
{ entries: [String(ClipboardString::new_with_metadata(text, metadata))], }
}
///|
/// Joins all text entries with `\n`, or returns `None` if there are none.
pub fn ClipboardItem::text(self : ClipboardItem) -> String? {
let texts = []
for entry in self.entries {
match entry {
String(s) => texts.push(s.text)
}
}
if texts.is_empty() {
None
} else {
Some(texts.join("\n"))
}
}
///|
/// Returns the metadata of the first text entry, if any.
pub fn ClipboardItem::metadata(self : ClipboardItem) -> String? {
for entry in self.entries {
match entry {
String(s) => return s.metadata
}
}
None
}
+294
View File
@@ -0,0 +1,294 @@
// Platform-backed Application lifecycle and window handles, ported from
// gpui/src/app.rs (`Application`, `open_window`, `windows`, `quit`) and
// gpui/src/window.rs (`AnyWindowHandle`, `WindowHandle<V>`).
///|
/// An untyped handle to an open window (GPUI: `AnyWindowHandle`).
#derive(Eq, Compare, Hash, Debug)
pub struct AnyWindowHandle {
id : @platform.WindowId
}
///|
pub fn AnyWindowHandle::window_id(self : AnyWindowHandle) -> @platform.WindowId {
self.id
}
///|
pub fn[R] AnyWindowHandle::update(
self : AnyWindowHandle,
application : Application,
f : (AnyView, Window, @app.App) -> R,
) -> R? {
application.update_window(self, f)
}
///|
/// A typed handle to an open window whose root view has type `V` (GPUI:
/// `WindowHandle<V>`).
pub struct WindowHandle[V] {
id : @platform.WindowId
priv root : @app.Entity[V]
}
///|
pub fn[V] WindowHandle::window_id(self : WindowHandle[V]) -> @platform.WindowId {
self.id
}
///|
pub fn[V] WindowHandle::to_any(self : WindowHandle[V]) -> AnyWindowHandle {
{ id: self.id, }
}
///|
pub fn[V] WindowHandle::entity(self : WindowHandle[V]) -> @app.Entity[V] {
self.root
}
///|
/// Updates the root view inside its window, returning `None` if the window
/// was closed or the view was released.
pub fn[V, R] WindowHandle::update(
self : WindowHandle[V],
application : Application,
f : (V, Window, @app.Context[V]) -> R,
) -> R? {
match application.window(self.id) {
Some(window) =>
if window.is_closed() || self.root.is_released() {
None
} else {
Some(
application.app.update_entity(self.root, fn(view, cx) {
f(view, window, cx)
}),
)
}
None => None
}
}
///|
/// Reads the root view if the window is still open and the view is alive.
pub fn[V, R] WindowHandle::read_with(
self : WindowHandle[V],
application : Application,
f : (V, @app.App) -> R,
) -> R? {
match application.window(self.id) {
Some(window) =>
if window.is_closed() || self.root.is_released() {
None
} else {
Some(f(self.root.read(application.app), application.app))
}
None => None
}
}
///|
/// An application wired to a `Platform`, owning its `App` and open windows
/// (GPUI: `Application`).
pub struct Application {
app : @app.App
platform : &@platform.Platform
priv mut next_window_id : Int32
priv windows : Map[@platform.WindowId, Window]
}
///|
let application_key : @app.GlobalKey[Application] = @app.GlobalKey::new(
"Application",
)
///|
/// Looks up the `Application` owning `app`, if it was created via
/// `Application::with_platform`.
pub fn application_for(app : @app.App) -> Application? {
app.try_global(application_key)
}
///|
/// Creates an `Application` backed by `platform` and registers it on the app.
pub fn Application::with_platform(
platform : &@platform.Platform,
) -> Application {
let app = @app.App::new(dispatcher=platform.dispatcher())
let application : Application = {
app,
platform,
next_window_id: 1,
windows: {},
}
app.set_global(application_key, application)
application
}
///|
pub fn Application::app(self : Application) -> @app.App {
self.app
}
///|
pub fn Application::platform(self : Application) -> &@platform.Platform {
self.platform
}
///|
/// Launches the platform event loop, calling `on_finish_launching` once
/// ready (GPUI: `Application::run`).
pub fn Application::run(
self : Application,
on_finish_launching : (Application) -> Unit,
) -> Unit {
self.platform.run(fn() { on_finish_launching(self) })
}
///|
/// Closes all open windows and asks the platform to exit (GPUI: `App::quit`).
pub fn Application::quit(self : Application) -> Unit {
let open = []
for _, win in self.windows {
open.push(win)
}
for win in open {
win.close()
}
self.platform.quit()
}
///|
/// Opens a platform-backed window with `options` and a root view created by
/// `build_root` (GPUI: `App::open_window`).
pub fn[V : Render] Application::open_window(
self : Application,
options : @platform.WindowOptions,
build_root : (Window, @app.App) -> @app.Entity[V],
) -> WindowHandle[V] {
let id = @platform.WindowId(self.next_window_id)
self.next_window_id = self.next_window_id + 1
let bounds = match options.window_bounds {
Some(wb) => wb.get_bounds()
None => self.platform.default_window_bounds()
}
let pw = self.platform.open_window(id, {
bounds,
title: options.title,
focus: options.focus,
show: options.show,
scale_factor: options.scale_factor,
})
let window = Window::from_platform(
id,
self.app,
self.platform,
pw,
rem_size=options.rem_size,
title?=options.title,
on_closed=fn() { self.windows.remove(id) },
)
self.windows[id] = window
let root = self.app.update(fn(app) { build_root(window, app) })
window.set_root_view(root)
{ id, root, }
}
///|
pub fn Application::windows(self : Application) -> Array[AnyWindowHandle] {
let handles : Array[AnyWindowHandle] = []
for id, _ in self.windows {
handles.push({ id, })
}
handles
}
///|
pub fn Application::window_count(self : Application) -> Int32 {
self.windows.length()
}
///|
pub fn Application::window(
self : Application,
id : @platform.WindowId,
) -> Window? {
self.windows.get(id)
}
///|
pub fn Application::active_window(self : Application) -> AnyWindowHandle? {
match self.platform.active_window() {
Some(id) =>
match self.windows.get(id) {
Some(win) if !win.is_closed() => Some({ id, })
_ => None
}
None => None
}
}
///|
pub fn[R] Application::update_window(
self : Application,
handle : AnyWindowHandle,
f : (AnyView, Window, @app.App) -> R,
) -> R? {
match self.windows.get(handle.id) {
Some(window) =>
if window.is_closed() {
None
} else {
match window.root_view() {
Some(root) => Some(self.app.update(fn(app) { f(root, window, app) }))
None => None
}
}
None => None
}
}
///|
pub fn Application::refresh_windows(self : Application) -> Unit {
for _, win in self.windows {
win.refresh()
}
}
///|
pub fn Application::close_window(
self : Application,
id : @platform.WindowId,
) -> Unit {
if self.windows.get(id) is Some(win) {
win.close()
}
}
///|
pub fn Application::read_from_clipboard(
self : Application,
) -> @platform.ClipboardItem? {
self.platform.read_from_clipboard()
}
///|
pub fn Application::write_to_clipboard(
self : Application,
item : @platform.ClipboardItem,
) -> Unit {
self.platform.write_to_clipboard(item)
}
///|
pub fn Application::set_cursor_style(
self : Application,
style : @style.CursorStyle,
) -> Unit {
self.platform.set_cursor_style(style)
}
///|
pub fn Application::open_url(self : Application, url : String) -> Unit {
self.platform.open_url(url)
}
+208
View File
@@ -0,0 +1,208 @@
// Elements and views, ported from gpui/src/element.rs and gpui/src/view.rs.
//
// Deviations from GPUI (see docs/PORTING.md):
// - `Element` has no associated `RequestLayoutState`/`PrepaintState` types:
// an element keeps per-frame state in its own mutable fields, set in
// `request_layout` and read in `prepaint` and `paint`. Elements are built
// fresh every frame, as in GPUI.
// - `render` returns `AnyElement` (no `impl IntoElement` return types).
// - Global element ids are paths of strings.
///|
/// A node of the element tree, laid out and painted each frame (GPUI:
/// `Element`).
pub(open) trait Element {
/// Requests a layout node (and those of the children).
fn request_layout(Self, Window, @app.App) -> @layout.LayoutId
/// Runs after layout with the element's bounds: hitboxes, child offsets.
fn prepaint(Self, @geometry.Bounds[@geometry.Pixels], Window, @app.App) -> Unit
/// Emits primitives into the scene and registers event listeners.
fn paint(Self, @geometry.Bounds[@geometry.Pixels], Window, @app.App) -> Unit
}
///|
/// Anything that can become an element (GPUI: `IntoElement`).
pub(open) trait IntoElement {
fn into_any_element(Self) -> AnyElement
}
///|
/// A type-erased element plus its per-frame layout state (GPUI:
/// `AnyElement`, with `Drawable`'s phase tracking).
pub struct AnyElement {
priv element : &Element
priv mut layout_id : @layout.LayoutId?
priv mut bounds : @geometry.Bounds[@geometry.Pixels]?
}
///|
pub fn AnyElement::new(element : &Element) -> AnyElement {
{ element, layout_id: None, bounds: None, }
}
///|
pub impl IntoElement for AnyElement with fn into_any_element(self) {
self
}
///|
/// Requests layout; must be called once per frame, before `prepaint`.
pub fn AnyElement::request_layout(
self : AnyElement,
window : Window,
app : @app.App,
) -> @layout.LayoutId {
guard self.layout_id is None else {
abort("element layout requested twice in one frame")
}
let id = self.element.request_layout(window, app)
self.layout_id = Some(id)
id
}
///|
/// Resolves the element's bounds from layout (plus the window's element
/// offset) and prepaints it.
pub fn AnyElement::prepaint(
self : AnyElement,
window : Window,
app : @app.App,
) -> Unit {
guard self.layout_id is Some(layout_id) else {
abort("element prepainted before its layout was requested")
}
let bounds = window.layout_bounds(layout_id)
self.bounds = Some(bounds)
self.element.prepaint(bounds, window, app)
}
///|
/// Paints the element at the bounds computed in `prepaint`.
pub fn AnyElement::paint(
self : AnyElement,
window : Window,
app : @app.App,
) -> Unit {
guard self.bounds is Some(bounds) else {
abort("element painted before it was prepainted")
}
self.element.paint(bounds, window, app)
}
///|
/// The bounds from the last `prepaint`, if any.
pub fn AnyElement::bounds(
self : AnyElement,
) -> @geometry.Bounds[@geometry.Pixels]? {
self.bounds
}
///|
/// A view's state renders itself into an element tree each frame (GPUI:
/// `Render`).
pub(open) trait Render {
fn render(Self, Window, @app.Context[Self]) -> AnyElement
}
///|
/// A type-erased view: an entity whose state implements `Render` (GPUI:
/// `AnyView`).
pub struct AnyView {
entity_id : @app.EntityId
priv render_fn : (Window, @app.App) -> AnyElement
priv release_fn : (@app.App) -> Unit
}
///|
pub fn[V : Render] AnyView::from_entity(entity : @app.Entity[V]) -> AnyView {
{
entity_id: entity.entity_id(),
render_fn: fn(window, app) {
app.update_entity(entity, fn(state, cx) {
Render::render(state, window, cx)
})
},
release_fn: fn(app) { app.release(entity) },
}
}
///|
/// The element a view renders into for one frame.
priv struct ViewElement {
view : AnyView
mut rendered : AnyElement?
}
///|
impl Element for ViewElement with fn request_layout(self, window, app) {
window.record_rendered_view(self.view.entity_id)
let element = (self.view.render_fn)(window, app)
self.rendered = Some(element)
element.request_layout(window, app)
}
///|
impl Element for ViewElement with fn prepaint(self, _bounds, window, app) {
self.rendered.unwrap().prepaint(window, app)
}
///|
impl Element for ViewElement with fn paint(self, _bounds, window, app) {
self.rendered.unwrap().paint(window, app)
}
///|
pub impl IntoElement for AnyView with fn into_any_element(self) {
AnyElement::new(({ view: self, rendered: None, } : ViewElement))
}
///|
pub extend AnyView with IntoElement::{into_any_element}
///|
/// Views are elements: `div().child(entity)` renders the entity.
pub impl[V : Render] IntoElement for @app.Entity[V] with fn into_any_element(
self,
) {
AnyView::from_entity(self).into_any_element()
}
///|
/// Wraps a view method as an event listener that updates the view (GPUI:
/// `cx.listener`). The listener does nothing once the view is released.
pub fn[T, E] listener(
cx : @app.Context[T],
f : (T, E, Window, @app.Context[T]) -> Unit,
) -> (E, Window, @app.App) -> Unit {
let weak = cx.weak_entity()
fn(event, window, app) {
ignore(weak.update(app, fn(state, cx) { f(state, event, window, cx) }))
}
}
///|
/// An element that takes no space and paints nothing (GPUI: `Empty`).
priv enum Empty {
Empty
}
///|
impl Element for Empty with fn request_layout(_self, window, _app) {
window.request_layout(Default::default(), [])
}
///|
impl Element for Empty with fn prepaint(_self, _bounds, _window, _app) {
()
}
///|
impl Element for Empty with fn paint(_self, _bounds, _window, _app) {
()
}
///|
/// An empty element.
pub fn empty() -> AnyElement {
AnyElement::new(Empty::Empty)
}
+17
View File
@@ -0,0 +1,17 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/color",
"experiments/gpui/scene",
"experiments/gpui/style",
"experiments/gpui/layout",
"experiments/gpui/input",
"experiments/gpui/app",
"experiments/gpui/platform",
"moonbitlang/core/hashset",
"moonbitlang/core/cmp",
"moonbitlang/core/debug",
}
options(
"allow-experimental-packages": true,
)
+301
View File
@@ -0,0 +1,301 @@
// Painting, ported from gpui/src/window.rs (`paint_quad`, `paint_drop_shadows`,
// `paint_inset_shadows`, the snapping helpers) and `Style::paint` from
// gpui/src/style.rs.
//
// Deviation: GPUI splits bordered quads into a background quad and border
// strips (`insert_quad`) as a renderer optimization; here a quad is inserted
// as is.
///|
/// A quad to paint, in logical pixels (GPUI: `PaintQuad`).
#derive(Eq, Debug)
pub(all) struct PaintQuad {
bounds : @geometry.Bounds[@geometry.Pixels]
corner_radii : @geometry.Corners[@geometry.Pixels]
background : @color.Background
border_widths : @geometry.Edges[@geometry.Pixels]
border_color : @color.Hsla
border_style : @scene.BorderStyle
}
///|
/// A filled quad without border (GPUI: `fill`).
pub fn fill(
bounds : @geometry.Bounds[@geometry.Pixels],
background : @color.Background,
) -> PaintQuad {
{
bounds,
corner_radii: Default::default(),
background,
border_widths: Default::default(),
border_color: @color.transparent_black(),
border_style: Solid,
}
}
///|
/// A 1px outline (GPUI: `outline`).
pub fn outline(
bounds : @geometry.Bounds[@geometry.Pixels],
border_color : @color.Hsla,
border_style~ : @scene.BorderStyle = Solid,
) -> PaintQuad {
{
bounds,
corner_radii: Default::default(),
background: @color.transparent_black().to_background(),
border_widths: @geometry.Edges::all(@geometry.px(1.0)),
border_color,
border_style,
}
}
///|
fn round_half_toward_zero(value : Double) -> Double {
@layout.round_half_toward_zero(value)
}
///|
/// Logical bounds to device pixels, edges rounded (GPUI: `snap_bounds`).
fn Window::snap_bounds(
self : Window,
bounds : @geometry.Bounds[@geometry.Pixels],
) -> @geometry.Bounds[@geometry.ScaledPixels] {
let s = self.scale_factor
let left = round_half_toward_zero(bounds.left().to_double() * s)
let top = round_half_toward_zero(bounds.top().to_double() * s)
let right = @cmp.maximum(
round_half_toward_zero(bounds.right().to_double() * s),
left,
)
let bottom = @cmp.maximum(
round_half_toward_zero(bounds.bottom().to_double() * s),
top,
)
@geometry.Bounds::from_corners(
@geometry.point(@geometry.ScaledPixels(left), @geometry.ScaledPixels(top)),
@geometry.point(
@geometry.ScaledPixels(right),
@geometry.ScaledPixels(bottom),
),
)
}
///|
/// Logical bounds to the device pixels they touch (GPUI: `cover_bounds`).
fn Window::cover_bounds(
self : Window,
bounds : @geometry.Bounds[@geometry.Pixels],
) -> @geometry.Bounds[@geometry.ScaledPixels] {
let s = self.scale_factor
let left = (bounds.left().to_double() * s).floor()
let top = (bounds.top().to_double() * s).floor()
if bounds.is_empty() {
return {
origin: @geometry.point(
@geometry.ScaledPixels(left),
@geometry.ScaledPixels(top),
),
size: Default::default(),
}
}
let right = @cmp.maximum((bounds.right().to_double() * s).ceil(), left)
let bottom = @cmp.maximum((bounds.bottom().to_double() * s).ceil(), top)
@geometry.Bounds::from_corners(
@geometry.point(@geometry.ScaledPixels(left), @geometry.ScaledPixels(top)),
@geometry.point(
@geometry.ScaledPixels(right),
@geometry.ScaledPixels(bottom),
),
)
}
///|
fn Window::snapped_content_mask(
self : Window,
) -> @geometry.ContentMask[@geometry.ScaledPixels] {
{ bounds: self.cover_bounds(self.content_mask().bounds), }
}
///|
/// Paints a quad, snapped to device pixels and faded by the element opacity
/// (GPUI: `paint_quad`). Only during paint.
pub fn Window::paint_quad(self : Window, quad : PaintQuad) -> Unit {
self.assert_phase("paint_quad", [Paint])
let opacity = self.element_opacity
let scene_quad : @scene.Quad = {
order: 0,
bounds: self.snap_bounds(quad.bounds),
content_mask: self.snapped_content_mask(),
background: quad.background.opacity(opacity),
border_color: quad.border_color.opacity(opacity),
corner_radii: quad.corner_radii.scale(self.scale_factor),
border_widths: quad.border_widths.map(fn(width) {
@geometry.ScaledPixels(
@layout.round_stroke_to_device_pixel(
width.to_double(),
self.scale_factor,
),
)
}),
border_style: quad.border_style,
}
let has_background = !scene_quad.background.is_transparent()
let has_border = scene_quad.border_widths != Default::default() &&
!scene_quad.border_color.is_transparent()
if has_background || has_border {
self.next_scene.insert_primitive(Quad(scene_quad))
}
}
///|
/// Paints the outer (non-inset) box shadows of a rounded rectangle (GPUI:
/// `paint_drop_shadows`).
pub fn Window::paint_drop_shadows(
self : Window,
bounds : @geometry.Bounds[@geometry.Pixels],
corner_radii : @geometry.Corners[@geometry.Pixels],
shadows : Array[@style.BoxShadow],
) -> Unit {
self.assert_phase("paint_drop_shadows", [Paint])
let content_mask = self.snapped_content_mask()
for shadow in shadows {
if shadow.inset {
continue
}
let shape_bounds = self.cover_bounds(
bounds.translate(shadow.offset).dilate(shadow.spread_radius),
)
if shape_bounds.is_empty() {
continue
}
let blur_radius = shadow.blur_radius.scale(self.scale_factor)
self.next_scene.insert_primitive(
Shadow({
order: 0,
blur_radius,
bounds: shape_bounds.dilate(blur_radius.mul_scalar(3.0)),
content_mask,
corner_radii: Default::default(),
color: shadow.color.opacity(self.element_opacity),
shape_bounds,
shape_corner_radii: corner_radii.scale(self.scale_factor),
inset: false,
}),
)
}
}
///|
/// Paints the inset box shadows of a rounded rectangle (GPUI:
/// `paint_inset_shadows`).
pub fn Window::paint_inset_shadows(
self : Window,
bounds : @geometry.Bounds[@geometry.Pixels],
corner_radii : @geometry.Corners[@geometry.Pixels],
shadows : Array[@style.BoxShadow],
) -> Unit {
self.assert_phase("paint_inset_shadows", [Paint])
let content_mask = self.snapped_content_mask()
let element_bounds = self.cover_bounds(bounds)
for shadow in shadows {
if !shadow.inset {
continue
}
let hole = bounds.translate(shadow.offset).dilate(-shadow.spread_radius)
let shrink = fn(radius : @geometry.Pixels) {
@cmp.maximum(radius - shadow.spread_radius, @geometry.px(0.0))
}
self.next_scene.insert_primitive(
Shadow({
order: 0,
blur_radius: shadow.blur_radius.scale(self.scale_factor),
bounds: element_bounds,
content_mask,
corner_radii: corner_radii.scale(self.scale_factor),
color: shadow.color.opacity(self.element_opacity),
shape_bounds: self.cover_bounds(hole),
shape_corner_radii: corner_radii.map(shrink).scale(self.scale_factor),
inset: true,
}),
)
}
}
///|
/// Paints an element's box (drop shadows, background, inset shadows), runs
/// `paint_children`, then paints the border on top (GPUI: `Style::paint`).
pub fn Window::paint_style(
self : Window,
style : @style.Style,
bounds : @geometry.Bounds[@geometry.Pixels],
paint_children : () -> Unit,
) -> Unit {
self.assert_phase("paint_style", [Paint])
if style.debug {
self.paint_quad(outline(bounds, @color.red()))
}
let corner_radii = style.corner_radii
.absolute_to_pixels(self.rem_size)
.clamp_radii_for_quad_size(bounds.size)
self.paint_drop_shadows(bounds, corner_radii, style.box_shadow)
if style.background is Some(fill) &&
fill.color() is Some(background) &&
!background.is_transparent() {
let border_color = match background.tag {
LinearGradient => background.colors.0.color
_ => background.solid
}
self.paint_quad({
bounds,
corner_radii,
background,
border_widths: Default::default(),
border_color: border_color.alpha(0.0),
border_style: style.border_style,
})
}
self.paint_inset_shadows(bounds, corner_radii, style.box_shadow)
paint_children()
if style.is_border_visible() {
let border_color = style.border_color.unwrap()
self.paint_quad({
bounds,
corner_radii,
background: border_color.alpha(0.0).to_background(),
border_widths: style.border_widths.absolute_to_pixels(self.rem_size),
border_color,
border_style: style.border_style,
})
}
}
///|
/// Paints an arbitrary primitive (escape hatch for custom elements such as
/// `canvas`). Only during paint.
pub fn Window::paint_primitive(
self : Window,
primitive : @scene.Primitive,
) -> Unit {
self.assert_phase("paint_primitive", [Paint])
self.next_scene.insert_primitive(primitive)
}
///|
/// Paints a filled path given by polygon contours in logical pixels (GPUI:
/// `paint_path`, simplified to polygons).
pub fn Window::paint_path(
self : Window,
contours : Array[Array[@geometry.Point[@geometry.Pixels]]],
color : @color.Background,
) -> Unit {
self.assert_phase("paint_path", [Paint])
let path = @scene.PaintedPath::new(
contours,
self.scale_factor,
self.content_mask(),
color.opacity(self.element_opacity),
)
self.next_scene.insert_primitive(Path(path))
}
+198
View File
@@ -0,0 +1,198 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/window"
import {
"experiments/gpui/app",
"experiments/gpui/color",
"experiments/gpui/geometry",
"experiments/gpui/input",
"experiments/gpui/layout",
"experiments/gpui/platform",
"experiments/gpui/scene",
"experiments/gpui/style",
"moonbitlang/core/debug",
}
// Values
pub fn application_for(@app.App) -> Application?
pub fn empty() -> AnyElement
pub fn fill(@geometry.Bounds[@geometry.Pixels], @color.Background) -> PaintQuad
pub fn[T, E] listener(@app.Context[T], (T, E, Window, @app.Context[T]) -> Unit) -> (E, Window, @app.App) -> Unit
pub fn outline(@geometry.Bounds[@geometry.Pixels], @color.Hsla, border_style? : @scene.BorderStyle) -> PaintQuad
// Errors
// Types and methods
pub struct AnyElement {
// private fields
}
pub fn AnyElement::bounds(Self) -> @geometry.Bounds[@geometry.Pixels]?
pub fn AnyElement::new(&Element) -> Self
pub fn AnyElement::paint(Self, Window, @app.App) -> Unit
pub fn AnyElement::prepaint(Self, Window, @app.App) -> Unit
pub fn AnyElement::request_layout(Self, Window, @app.App) -> @layout.LayoutId
pub impl IntoElement for AnyElement
pub struct AnyView {
entity_id : @app.EntityId
// private fields
}
pub fn[V : Render] AnyView::from_entity(@app.Entity[V]) -> Self
pub fn AnyView::into_any_element(Self) -> AnyElement
pub impl IntoElement for AnyView
#derive(Compare, Eq, Hash, @debug.Debug)
pub struct AnyWindowHandle {
id : @platform.WindowId
}
pub fn[R] AnyWindowHandle::update(Self, Application, (AnyView, Window, @app.App) -> R) -> R?
pub fn AnyWindowHandle::window_id(Self) -> @platform.WindowId
pub struct Application {
app : @app.App
platform : &@platform.Platform
// private fields
}
pub fn Application::active_window(Self) -> AnyWindowHandle?
pub fn Application::app(Self) -> @app.App
pub fn Application::close_window(Self, @platform.WindowId) -> Unit
pub fn Application::open_url(Self, String) -> Unit
pub fn[V : Render] Application::open_window(Self, @platform.WindowOptions, (Window, @app.App) -> @app.Entity[V]) -> WindowHandle[V]
pub fn Application::platform(Self) -> &@platform.Platform
pub fn Application::quit(Self) -> Unit
pub fn Application::read_from_clipboard(Self) -> @platform.ClipboardItem?
pub fn Application::refresh_windows(Self) -> Unit
pub fn Application::run(Self, (Self) -> Unit) -> Unit
pub fn Application::set_cursor_style(Self, @style.CursorStyle) -> Unit
pub fn[R] Application::update_window(Self, AnyWindowHandle, (AnyView, Window, @app.App) -> R) -> R?
pub fn Application::window(Self, @platform.WindowId) -> Window?
pub fn Application::window_count(Self) -> Int32
pub fn Application::windows(Self) -> Array[AnyWindowHandle]
pub fn Application::with_platform(&@platform.Platform) -> Self
pub fn Application::write_to_clipboard(Self, @platform.ClipboardItem) -> Unit
pub struct ElementStateKey[S] {
id : Int32
name : String
// private fields
}
pub fn[S] ElementStateKey::new(String) -> Self[S]
#derive(Eq, @debug.Debug)
pub(all) struct Hitbox {
id : Int32
bounds : @geometry.Bounds[@geometry.Pixels]
content_mask : @geometry.ContentMask[@geometry.Pixels]
behavior : HitboxBehavior
}
pub fn Hitbox::is_hovered(Self, Window) -> Bool
#derive(Eq, Hash, @debug.Debug)
pub(all) enum HitboxBehavior {
Normal
BlockMouse
}
#derive(Eq, @debug.Debug)
pub(all) struct PaintQuad {
bounds : @geometry.Bounds[@geometry.Pixels]
corner_radii : @geometry.Corners[@geometry.Pixels]
background : @color.Background
border_widths : @geometry.Edges[@geometry.Pixels]
border_color : @color.Hsla
border_style : @scene.BorderStyle
}
pub struct Window {
// private fields
}
pub fn Window::activate_window(Self) -> Unit
pub fn Window::bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
pub fn Window::close(Self) -> Unit
pub fn Window::content_mask(Self) -> @geometry.ContentMask[@geometry.Pixels]
pub fn Window::default_prevented(Self) -> Bool
pub fn Window::dispatch_input(Self, @input.PlatformInput) -> @input.DispatchEventResult
pub fn Window::dispatch_mouse_event(Self, @input.MouseEvent) -> Bool
pub fn Window::draw(Self) -> @scene.Scene
pub fn Window::draw_if_dirty(Self) -> Bool
pub fn Window::element_offset(Self) -> @geometry.Point[@geometry.Pixels]
pub fn Window::element_opacity(Self) -> Double
pub fn Window::frame_count(Self) -> Int32
pub fn Window::global_element_id(Self) -> String?
pub fn Window::insert_hitbox(Self, @geometry.Bounds[@geometry.Pixels], HitboxBehavior) -> Hitbox
pub fn Window::is_closed(Self) -> Bool
pub fn Window::is_dirty(Self) -> Bool
pub fn Window::is_window_active(Self) -> Bool
pub fn Window::is_window_hovered(Self) -> Bool
pub fn Window::layout_bounds(Self, @layout.LayoutId) -> @geometry.Bounds[@geometry.Pixels]
pub fn Window::modifiers(Self) -> @input.Modifiers
pub fn Window::mouse_position(Self) -> @geometry.Point[@geometry.Pixels]
pub fn Window::new(@app.App, @geometry.Size[@geometry.Pixels], scale_factor? : Double, rem_size? : @geometry.Pixels) -> Self
pub fn Window::on_close(Self, (@app.App) -> Unit) -> Unit
pub fn Window::on_mouse_event(Self, (@input.MouseEvent, @input.DispatchPhase, Self, @app.App) -> Unit) -> Unit
pub fn Window::on_should_close(Self, (Self, @app.App) -> Bool) -> Unit
pub fn Window::on_window_active_change(Self, (Self, @app.App) -> Unit) -> Unit
pub fn Window::paint_drop_shadows(Self, @geometry.Bounds[@geometry.Pixels], @geometry.Corners[@geometry.Pixels], Array[@style.BoxShadow]) -> Unit
pub fn Window::paint_inset_shadows(Self, @geometry.Bounds[@geometry.Pixels], @geometry.Corners[@geometry.Pixels], Array[@style.BoxShadow]) -> Unit
pub fn Window::paint_path(Self, Array[Array[@geometry.Point[@geometry.Pixels]]], @color.Background) -> Unit
pub fn Window::paint_primitive(Self, @scene.Primitive) -> Unit
pub fn Window::paint_quad(Self, PaintQuad) -> Unit
pub fn Window::paint_style(Self, @style.Style, @geometry.Bounds[@geometry.Pixels], () -> Unit) -> Unit
pub fn Window::prevent_default(Self) -> Unit
pub fn Window::read_from_clipboard(Self) -> @platform.ClipboardItem?
pub fn Window::refresh(Self) -> Unit
pub fn Window::rem_size(Self) -> @geometry.Pixels
pub fn Window::remove_window(Self) -> Unit
pub fn[V : Render] Window::replace_root_view(Self, (Self, @app.Context[V]) -> V) -> @app.Entity[V]
pub fn Window::request_layout(Self, @style.Style, Array[@layout.LayoutId]) -> @layout.LayoutId
pub fn Window::request_measured_layout(Self, @style.Style, (@geometry.Size[@geometry.Pixels?], @geometry.Size[@layout.AvailableSpace]) -> @geometry.Size[@geometry.Pixels]) -> @layout.LayoutId
pub fn Window::resize(Self, @geometry.Size[@geometry.Pixels], scale_factor? : Double) -> Unit
pub fn Window::root_view(Self) -> AnyView?
pub fn Window::scale_factor(Self) -> Double
pub fn Window::scene(Self) -> @scene.Scene
pub fn Window::set_cursor_style(Self, @style.CursorStyle) -> Unit
pub fn Window::set_rem_size(Self, @geometry.Pixels) -> Unit
pub fn[V : Render] Window::set_root_view(Self, @app.Entity[V]) -> Unit
pub fn Window::set_window_title(Self, String) -> Unit
pub fn Window::stop_propagation(Self) -> Unit
pub fn Window::viewport_size(Self) -> @geometry.Size[@geometry.Pixels]
pub fn Window::window_id(Self) -> @platform.WindowId
pub fn Window::window_title(Self) -> String?
pub fn[R] Window::with_content_mask(Self, @geometry.ContentMask[@geometry.Pixels]?, () -> R) -> R
pub fn[R] Window::with_element_id(Self, String?, () -> R) -> R
pub fn[R] Window::with_element_offset(Self, @geometry.Point[@geometry.Pixels], () -> R) -> R
pub fn[R] Window::with_element_opacity(Self, Double?, () -> R) -> R
pub fn[S, R] Window::with_element_state(Self, ElementStateKey[S], (S?) -> (R, S)) -> R
pub fn Window::write_to_clipboard(Self, @platform.ClipboardItem) -> Unit
pub struct WindowHandle[V] {
id : @platform.WindowId
// private fields
}
pub fn[V] WindowHandle::entity(Self[V]) -> @app.Entity[V]
pub fn[V, R] WindowHandle::read_with(Self[V], Application, (V, @app.App) -> R) -> R?
pub fn[V] WindowHandle::to_any(Self[V]) -> AnyWindowHandle
pub fn[V, R] WindowHandle::update(Self[V], Application, (V, Window, @app.Context[V]) -> R) -> R?
pub fn[V] WindowHandle::window_id(Self[V]) -> @platform.WindowId
// Type aliases
// Traits
pub(open) trait Element {
fn request_layout(Self, Window, @app.App) -> @layout.LayoutId
fn prepaint(Self, @geometry.Bounds[@geometry.Pixels], Window, @app.App) -> Unit
fn paint(Self, @geometry.Bounds[@geometry.Pixels], Window, @app.App) -> Unit
}
pub(open) trait IntoElement {
fn into_any_element(Self) -> AnyElement
}
pub impl[V : Render] IntoElement for @app.Entity[V]
pub(open) trait Render {
fn render(Self, Window, @app.Context[Self]) -> AnyElement
}
File diff suppressed because it is too large. Load diff
+18 -6
View File
@@ -16,8 +16,9 @@ Outputs (all in src/style/):
styled_extend_generated.mbt promotes all `Styled` methods on styled_extend_generated.mbt promotes all `Styled` methods on
StyleRefinement StyleRefinement
Other packages that implement `Styled` (e.g. `Div`) need the same `extend` Other packages that implement `Styled` need the same `extend` list. The
list; pass `--extend Type=path/to/file.mbt` to emit it there. default run also emits it for the elements package (`Div`, `Canvas`); add
more with `--extend Type=path/to/file.mbt`.
""" """
import argparse import argparse
@@ -636,11 +637,11 @@ def gen_styled():
return "".join(out), names return "".join(out), names
def gen_extend(type_name, names): def gen_extend(type_name, names, trait_ref="Styled"):
body = ",\n ".join(names) body = ",\n ".join(names)
return ( return (
HEADER HEADER
+ f"///|\npub extend {type_name} with Styled::{{\n {body},\n}}\n" + f"///|\npub extend {type_name} with {trait_ref}::{{\n {body},\n}}\n"
) )
@@ -650,6 +651,13 @@ def write(path, content):
print(f"wrote {os.path.relpath(path, ROOT)}") print(f"wrote {os.path.relpath(path, ROOT)}")
# Styled types outside the style package, emitted on every run.
DEFAULT_EXTENDS = [
"Div=src/elements/div_styled_generated.mbt",
"Canvas=src/elements/canvas_styled_generated.mbt",
]
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument( parser.add_argument(
@@ -668,11 +676,15 @@ def main():
os.path.join(STYLE_DIR, "styled_extend_generated.mbt"), os.path.join(STYLE_DIR, "styled_extend_generated.mbt"),
gen_extend("StyleRefinement", names), gen_extend("StyleRefinement", names),
) )
for spec in args.extend: for spec in DEFAULT_EXTENDS + args.extend:
if "=" not in spec: if "=" not in spec:
sys.exit(f"gen_style: --extend expects TYPE=FILE, got {spec!r}") sys.exit(f"gen_style: --extend expects TYPE=FILE, got {spec!r}")
type_name, path = spec.split("=", 1) type_name, path = spec.split("=", 1)
write(os.path.join(ROOT, path), gen_extend(type_name, names)) full = os.path.join(ROOT, path)
# Outside the style package the trait must be package-qualified.
inside = os.path.dirname(os.path.abspath(full)) == STYLE_DIR
trait_ref = "Styled" if inside else "@style.Styled"
write(full, gen_extend(type_name, names, trait_ref))
print(f"{len(names)} Styled methods") print(f"{len(names)} Styled methods")