Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eeab51348e | ||
|
|
64bf747047 |
No files matched your search
@@ -15,6 +15,8 @@ roadmap.
|
||||
| `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/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/layout` | `taffy.rs` | Ported on [`Milky2018/chicle`](https://mooncakes.io/docs/Milky2018/chicle) (flexbox, grid, block) |
|
||||
|
||||
## Example
|
||||
@@ -37,6 +39,10 @@ moon run src/examples/card --target js
|
||||
.text_color(@color.rgb(0x1f2328)).text_sm()
|
||||
```
|
||||
|
||||
`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 roadmap.
|
||||
|
||||
|
||||
+98
-14
@@ -135,8 +135,8 @@ stays isolated.
|
||||
| `layout` | `taffy.rs` (engine on `Milky2018/chicle`, a taffy port) | pure | **done** (no cross-frame node cache yet) |
|
||||
| `keymap` | `keymap.rs`, `keymap/*`, `platform/keystroke.rs` | pure | planned |
|
||||
| `action` | `action.rs` | pure | planned |
|
||||
| `app` | `app.rs`, `app/*`, `subscription.rs`, `global.rs`, `gpui.rs` traits | pure | planned |
|
||||
| `executor` | `executor.rs`, `platform_scheduler.rs`, `scheduler` crate | pure core + platform hooks | planned |
|
||||
| `app` | `app.rs`, `app/entity_map.rs`, `app/context.rs`, `subscription.rs`, `global.rs` | pure | **done** (no windows, executors or actions yet) |
|
||||
| `executor` | `executor.rs`, `scheduler` crate (`executor.rs`, `test_scheduler.rs`) | pure core + `Dispatcher` platform hook | **done** (single thread) |
|
||||
| `element` | `element.rs`, `view.rs`, `elements/div.rs`, `interactive.rs` | pure | planned |
|
||||
| `window` | `window.rs`, `key_dispatch.rs`, `tab_stop.rs` | pure (talks to platform traits) | planned |
|
||||
| `text` | `text_system.rs`, `text_system/*` | mixed: wrapping/caching pure, shaping platform | planned |
|
||||
@@ -218,7 +218,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. |
|
||||
| WebGPU | `Milky2018/wgpu_mbt@0.16.2` | **native only** | wgpu-native C API bindings; macOS is supported, Linux and Windows are experimental. `tonyfettes/webgpu` and `emadurandal/rhodonite_webgpu` cover browser WebGPU. |
|
||||
| Windowing | `Milky2018/window@0.6.2` (winit port, **native, macOS only**), `mizchi/glfw`, `klaseca/sdl`, `laplaceliu/tycho_window` (Xlib) | native only | |
|
||||
| Async | `moonbitlang/async@0.22.10` | **native** (some wasm) | Not usable on js. Core has a `moonbitlang/core/async` package; its js story needs checking before the executor milestone. |
|
||||
| Async | `moonbitlang/async@0.22.10`, `moonbitlang/core/async` | native, wasm; js partly; **not wasm-gc** | Not used. Both own the event loop (`async fn main`, task groups), which conflicts with a platform-driven executor, and neither supports wasm-gc. `executor` uses the same compiler intrinsics (`%async.suspend`/`%async.run`) directly; see M4. |
|
||||
| Taffy-free layout ref | `Frank-III/onebit-tui` | native | Uses Yoga through FFI. Not useful here. |
|
||||
|
||||
Recommendation: depend on `moon_cosmic` for text when that milestone
|
||||
@@ -352,17 +352,25 @@ gantt
|
||||
- Tests: GPUI's rounding and stroke-snapping tests, plus layout
|
||||
scenarios. The engine is checked separately by the 1,038-fixture
|
||||
conformance suite in `conformance/chicle`.
|
||||
- **M3: app model.**
|
||||
- `App`, `Entity[T]`/`WeakEntity[T]`, and `Context[T]`.
|
||||
- `notify`, `observe`, `subscribe`/`emit` with typed event keys, globals,
|
||||
and observers.
|
||||
- The effect queue and `flush_effects` semantics: deferral, and dedup of
|
||||
notifications.
|
||||
- Tests ported from GPUI's `app` tests.
|
||||
- **M4: executor.**
|
||||
- Foreground executor, timers, and `Task[T]` (cancel and detach).
|
||||
- `TestScheduler` with a virtual clock and `run_until_parked`.
|
||||
- `spawn` from `Context`.
|
||||
- **M3: app model (done).**
|
||||
- `App`, `Entity[T]`/`WeakEntity[T]`/`Reservation[T]`, and `Context[T]`.
|
||||
- `notify`, `observe`, `subscribe`/`emit` with typed `EventKey`s,
|
||||
globals with `GlobalKey`s, release listeners, and `defer_call`.
|
||||
- The effect queue and `flush_effects` semantics: deferred activation of
|
||||
new subscriptions, dedup of notifications, and cascading effects.
|
||||
- Tests: GPUI's subscription tests are ported, plus app-model tests,
|
||||
including the aborts expected on misuse.
|
||||
- `src/examples/counter` shows the model end to end.
|
||||
- **M4: executor (done).**
|
||||
- `Executor` (spawn, timer, sleep, yield_now, now), and `Task[T]` (wait,
|
||||
cancel with unwinding, try_result, ready, detach).
|
||||
- A `Dispatcher` trait as the platform hook, plus `TestDispatcher`, a
|
||||
deterministic dispatcher with a virtual clock (`tick`,
|
||||
`run_until_parked`, `advance_clock`, with GPUI's timer semantics).
|
||||
- `AsyncApp`, `App::spawn`, `Context::spawn` (weak entity), and the
|
||||
app's `foreground_executor`/`background_executor`.
|
||||
- `App::new()` uses its own `TestDispatcher` (like GPUI's
|
||||
`TestAppContext`); a platform passes its own dispatcher.
|
||||
- **M5: input model.**
|
||||
- `Keystroke::parse`, `Modifiers`.
|
||||
- `KeyContext` and the predicate parser and evaluator.
|
||||
@@ -460,6 +468,70 @@ gantt
|
||||
`parent`/`children` queries. Misuse fails loudly: an unknown or stale
|
||||
`LayoutId`, or a child given two parents, aborts.
|
||||
|
||||
### Deviations taken in M3 (app model)
|
||||
- **Type keys replace `TypeId`.** Events and globals are identified by
|
||||
`EventKey[E]` and `GlobalKey[G]` values, created once per type (usually a
|
||||
top-level `let`). The app stores values under the key's id as closures
|
||||
that write into the key's typed slot. Reading one back through the same
|
||||
key is type-safe and needs no downcast.
|
||||
- `EventEmitter<E>` (a compile-time check that `T` may emit `E`) has no
|
||||
equivalent: any entity may emit any `EventKey`.
|
||||
- **Entities are not reference counted.** A handle points at a typed cell.
|
||||
`App::release(entity)` plays the role of the last handle being dropped:
|
||||
- Weak handles stop upgrading at once.
|
||||
- At the next flush, observers and subscriptions are removed and release
|
||||
listeners run.
|
||||
- Double release is a no-op.
|
||||
- Use after release, re-entrant updates, reads during an update, and using
|
||||
an entity with another `App` all abort, as GPUI panics.
|
||||
- **Subscriptions do not end when dropped.** A `Subscription` stays active
|
||||
until `unsubscribe()` is called, or until the entity it belongs to is
|
||||
released. GPUI unsubscribes on drop; `detach()` is kept for parity.
|
||||
- **Entity state is passed by reference.** Update callbacks receive the
|
||||
state; entity types should be structs with `mut` fields (GPUI's `&mut T`).
|
||||
- **Renames.**
|
||||
- Entity creation is `App::new_entity`, because `App::new` creates the app.
|
||||
- `cx.defer` is `defer_call`, because `defer` is a MoonBit keyword.
|
||||
- `Context<T>` does not deref to `App`; use `cx.app`.
|
||||
- **Top-level `App` methods open an update.** Methods such as `notify`,
|
||||
`set_global`, `release` and `defer_call` flush their effects when called
|
||||
outside an update.
|
||||
- `global_mut` and `default_global` return the global to be mutated, so
|
||||
they must be called inside `App::update`; outside one they abort.
|
||||
- **Not yet ported:**
|
||||
- `observe_new` (needs a per-type key for entities).
|
||||
- Accessed-entity tracking and window invalidation (M6).
|
||||
- `spawn` and `AsyncApp` (M4).
|
||||
- Actions (M5).
|
||||
- Leak detection.
|
||||
|
||||
### Deviations taken in M4 (executor)
|
||||
- **Coroutines come from MoonBit's experimental async intrinsics.**
|
||||
`%async.suspend`, `%async.run`, `%async.capture_cancellation`, and
|
||||
`%async.raise_cancellation_signal` are scheduled by our own `Dispatcher`.
|
||||
This is what `moonbitlang/core/async` is built on, minus its event loop.
|
||||
It works on all four backends, including wasm-gc.
|
||||
- The package must set `experimental: true`, and packages importing it
|
||||
need `"allow-experimental-packages": true`.
|
||||
- Risk: the intrinsics may change with the toolchain. They are wrapped in
|
||||
`src/executor/coroutine.mbt`.
|
||||
- **One thread.** Background and foreground executors are the same executor
|
||||
on the main thread, as in GPUI's single-threaded web backend. There are no
|
||||
priorities, dedicated threads, `block_on`, or `scoped`.
|
||||
- **Tasks are not cancelled on drop.** A GPUI `Task` cancels its future when
|
||||
dropped. Here a task runs to completion unless `cancel()` is called.
|
||||
- Cancellation resumes the task with a cancellation signal at its next
|
||||
suspension point, running its `defer` blocks.
|
||||
- Waiters get `TaskCancelled`; errors raised by a task are re-raised by
|
||||
`wait`.
|
||||
- **Durations are integer milliseconds.** `now()` returns `Int64`
|
||||
milliseconds.
|
||||
- **The test dispatcher is FIFO and deterministic.** GPUI's `TestScheduler`
|
||||
can randomize the interleaving of sessions with a seed. That is not ported.
|
||||
There is also no parking detection.
|
||||
- **`AsyncApp` methods return values, not `Result`s.** An app is never
|
||||
dropped while a task references it.
|
||||
|
||||
## 7. Design decisions
|
||||
|
||||
Decided on 2026-11-24, following the recommendations below.
|
||||
@@ -497,4 +569,16 @@ Decided on 2026-11-24, following the recommendations below.
|
||||
Always run `python3 tools/gen_style.py && moon fmt` together.
|
||||
- A value converts implicitly to a trait object (`&IntoLength`) at a call
|
||||
site. That is how GPUI's `impl Into<Length>` parameters are expressed.
|
||||
- `defer` is a keyword (GPUI's `cx.defer` became `defer_call`).
|
||||
- Closures are not allowed to raise implicitly: `assert_*` cannot be called
|
||||
inside a callback in a test. Record values and assert afterwards. A test
|
||||
whose name starts with `panic` passes only if it aborts; use this to test
|
||||
the fail-loudly paths.
|
||||
- `test` is a keyword, so a binding cannot be named `test`. Trait-object
|
||||
coercion does not reach inside tuples: build `(&Trait, ...)` values
|
||||
separately.
|
||||
- Async code: `async fn` bodies that never suspend get an "unused async"
|
||||
warning; a plain `fn` closure is accepted where an `async` one is
|
||||
expected. Closures that raise must say so (`fn() raise { ... }`).
|
||||
- `Ref(x)` builds a `Ref`; `{ val: x }` needs a type annotation.
|
||||
- Test-only imports go in `import { ... } for "test"` in `moon.pkg`.
|
||||
+502
@@ -0,0 +1,502 @@
|
||||
// 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]
|
||||
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: {},
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// 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.
|
||||
pub fn App::notify(self : App, entity_id : EntityId) -> Unit {
|
||||
self.update(fn(app) { app.push_effect(Notify(entity_id)) })
|
||||
}
|
||||
|
||||
///|
|
||||
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
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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) })
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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,
|
||||
)
|
||||
@@ -0,0 +1,131 @@
|
||||
// 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[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
|
||||
@@ -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()
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import {
|
||||
"experiments/gpui/app",
|
||||
}
|
||||
|
||||
pkgtype(kind: "executable")
|
||||
@@ -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
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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 {
|
||||
_ => ()
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import {
|
||||
"moonbitlang/core/deque",
|
||||
}
|
||||
|
||||
// The coroutine intrinsics (%async.*) are experimental.
|
||||
|
||||
options(
|
||||
"allow-experimental-packages": true,
|
||||
experimental: true,
|
||||
)
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
Reference in new issue
Block a user