37 changed files with 205 additions and 19042 deletions

No files matched your search

+8 -19
View File
@@ -17,36 +17,26 @@ roadmap.
| `experiments/gpui/style` | `style.rs`, `styled.rs`, Refineable, gpui_macros style helpers | Ported (`Style`/`StyleRefinement`, the full `Styled` fluent API) | | `experiments/gpui/style` | `style.rs`, `styled.rs`, Refineable, gpui_macros style helpers | Ported (`Style`/`StyleRefinement`, the full `Styled` fluent API) |
| `experiments/gpui/app` | `app.rs`, `entity_map.rs`, `context.rs`, `subscription.rs` | Ported (entities, contexts, notify/observe, typed events and globals, effect flushing) | | `experiments/gpui/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/executor` | `executor.rs`, `scheduler` crate | Ported (tasks, timers, cancellation, deterministic test dispatcher; single thread) |
| `experiments/gpui/input` | mouse/window input of `interactive.rs` | Ported (mouse events, modifiers, `PlatformInput`, `DispatchEventResult`) |
| `experiments/gpui/window` | `window.rs`, `element.rs`, `view.rs`, `app.rs` | Ported, headless (`Application`, `PlatformWindow` integration, frame lifecycle, views, hitboxes, mouse dispatch, painting) |
| `experiments/gpui/elements` | `elements/div.rs`, `elements/canvas.rs` | Ported (`div` with styles, hover, clicks and mouse listeners; `canvas`) |
| `experiments/gpui/layout` | `taffy.rs` | Ported on [`Milky2018/chicle`](https://mooncakes.io/docs/Milky2018/chicle) (flexbox, grid, block) | | `experiments/gpui/layout` | `taffy.rs` | Ported on [`Milky2018/chicle`](https://mooncakes.io/docs/Milky2018/chicle) (flexbox, grid, block) |
| `experiments/gpui/platform` | `platform.rs` | Ported (core `Platform`/`PlatformWindow` traits, window options/params, clipboard) |
| `experiments/gpui/platform/test` | `platform/test/*`, `app/test_context.rs` | Ported (`TestPlatform`, `TestWindow`, `TestAppContext`, `VisualTestContext`) |
## Example ## Example
Nothing is shown on screen yet (the renderer comes with M8). `src/examples/card` Nothing renders yet. `src/examples/card` resolves a style written with
is a view rendering a `div()` card with GPUI's fluent API inside a GPUI's fluent API, lays the card and its (fake-measured) text out with the
`TestPlatform` window; `VisualTestContext` simulates a hover and click while layout engine, paints it into a `Scene`, and prints the layout and the draw
pumping frames automatically, and prints the scene's draw batches and quads: batches:
```sh ```sh
moon run src/examples/card --target js moon run src/examples/card --target js
``` ```
```moonbit ```moonbit
@elements.div() @style.StyleRefinement::new()
.id("card")
.flex().flex_col().gap_2().p_4() .flex().flex_col().gap_2().p_4()
.w(@geometry.px(320.0)) .w(@geometry.px(320.0))
.rounded_lg().border_1().border_color(@color.rgb(0xd0d7de)) .rounded_lg().border_1().border_color(@color.rgb(0xd0d7de))
.bg(@color.rgb(0xffffff)).shadow_md() .bg(@color.rgb(0xffffff)).shadow_md()
.hover(fn(style) { style.border_color(@color.rgb(0x0969da)) }) .text_color(@color.rgb(0x1f2328)).text_sm()
.on_click(@window.listener(cx, fn(card, _, _, cx) {
card.expanded = !card.expanded
cx.notify()
}))
``` ```
`src/examples/counter` shows the app model and executors: two entities `src/examples/counter` shows the app model and executors: two entities
@@ -58,9 +48,8 @@ the roadmap.
## Generated code ## Generated code
`src/style/style_generated.mbt`, `styled_generated.mbt`, `src/style/style_generated.mbt`, `styled_generated.mbt` and
`styled_extend_generated.mbt`, and the `*_styled_generated.mbt` files in `styled_extend_generated.mbt` are generated by `tools/gen_style.py`, which
`src/elements` are generated by `tools/gen_style.py`, which
stands in for GPUI's Rust macros. Do not edit them by hand; change the stands in for GPUI's Rust macros. Do not edit them by hand; change the
script or `src/style/styled.mbt`, then run: script or `src/style/styled.mbt`, then run:
+18 -102
View File
@@ -137,19 +137,18 @@ stays isolated.
| `action` | `action.rs` | pure | planned | | `action` | `action.rs` | pure | planned |
| `app` | `app.rs`, `app/entity_map.rs`, `app/context.rs`, `subscription.rs`, `global.rs` | pure | **done** (no windows, executors or actions yet) | | `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) | | `executor` | `executor.rs`, `scheduler` crate (`executor.rs`, `test_scheduler.rs`) | pure core + `Dispatcher` platform hook | **done** (single thread) |
| `input` | mouse/window input of `interactive.rs`, `Modifiers`, `PlatformInput`, `DispatchEventResult` | pure | **done** (mouse/modifiers; keys in M5) | | `element` | `element.rs`, `view.rs`, `elements/div.rs`, `interactive.rs` | pure | planned |
| `window` | `window.rs`, `element.rs`, `view.rs`, `Style::paint`, `Application`, window handles | pure | **done** (`PlatformWindow`-backed + standalone headless; no focus/keys/caching yet) | | `window` | `window.rs`, `key_dispatch.rs`, `tab_stop.rs` | pure (talks to platform traits) | planned |
| `elements` | `elements/div.rs` (+ `Interactivity`), `elements/canvas.rs` | pure | **done** (`div`, `canvas`) |
| `text` | `text_system.rs`, `text_system/*` | mixed: wrapping/caching pure, shaping platform | planned | | `text` | `text_system.rs`, `text_system/*` | mixed: wrapping/caching pure, shaping platform | planned |
| `platform` | `platform.rs` (core traits, `WindowId`, `WindowOptions`, `WindowParams`, `ClipboardItem`) | pure (interfaces) | **done** (core subset; text/atlas/IME/displays later) | | `platform` | `platform.rs` (traits only), `interactive.rs` input types | pure (interfaces) | planned |
| `platform/test` | `platform/test/*`, `app/test_context.rs` (`TestAppContext`, `VisualTestContext`) | pure | **done** | | `platform/test` | `platform/test/*` | pure | planned: headless platform for tests |
| `platform/web` | `gpui_web` | **js only** | planned | | `platform/web` | `gpui_web` | **js only** | planned |
| `renderer/canvas2d` | (new) | **js only** | planned | | `renderer/canvas2d` | (new) | **js only** | planned |
| `renderer/software` | (new; optional) | pure | candidate | | `renderer/software` | (new; optional) | pure | candidate |
| `renderer/wgpu` | `gpui_wgpu` | native (+ js WebGPU) | later | | `renderer/wgpu` | `gpui_wgpu` | native (+ js WebGPU) | later |
| `platform/native/*` | `gpui_macos`, `gpui_linux`, `gpui_windows` | native only | later | | `platform/native/*` | `gpui_macos`, `gpui_linux`, `gpui_windows` | native only | later |
| `examples/*` | `examples/*` | executables | `counter` (M3–M4), `card` (headless on `TestPlatform`, prints a scene report) | | `examples/*` | `examples/*` | executables | `card` (headless, prints a scene report) |
| `elements/*` | `elements/{text,img,svg,list,uniform_list,anchored,deferred,animation}.rs` | pure | later | | `elements/*` | `elements/{text,img,svg,list,uniform_list,anchored,deferred,canvas,animation}.rs` | pure | later |
A facade package (`experiments/gpui` re-exporting the common API, similar to A facade package (`experiments/gpui` re-exporting the common API, similar to
GPUI's `prelude.rs`) should come once there are enough packages to make GPUI's `prelude.rs`) should come once there are enough packages to make
@@ -379,49 +378,18 @@ gantt
multi-stroke matching. multi-stroke matching.
- `ActionRegistry`. - `ActionRegistry`.
- Tests ported from `keymap.rs` and `keymap/context.rs`. - Tests ported from `keymap.rs` and `keymap/context.rs`.
- **M6: elements and window (done).** - **M6: elements and window.**
- `Element`/`AnyElement`/`IntoElement`, `Render`, `AnyView`, views as - `Element`/`AnyElement`/`IntoElement`/`ParentElement`, `Render`, and
elements, `listener`, and `empty`. views.
- `Window`: - `div` with styles, hover and active styles, mouse listeners, and
- `draw` (render, then layout to fill the viewport, prepaint, paint, scrolling.
`Scene::finish`) with phase checks, and `draw_if_dirty`. - `Window::draw` (request_layout → prepaint → paint), element ids and
- The content-mask, element-offset, opacity, and element-id stacks. state, hitboxes, the content-mask stack, and the dispatch tree.
- Element state across frames (`ElementStateKey`), hitboxes and hit - Tests: build a tree, draw against the test platform, assert on the
testing, occlusion, and mouse dispatch (capture and bubble, Scene.
`stop_propagation`). - **M7: test platform.** A headless `Platform`/`PlatformWindow` that records
- Hover-driven and notify-driven invalidation, with only rendered views scenes and injects input events, mirroring GPUI's `TestPlatform` and
invalidating the window, plus `resize`. `VisualTestContext`. This is the base for most later tests.
- Painting: `paint_quad` with device-pixel snapping, drop and inset
shadows, `paint_path`, and `paint_style` (a port of `Style::paint`).
- `div()`:
- Styles through the generated `Styled` list, plus children and hover
styles.
- Mouse down, up, move and scroll listeners, and clicks (with element
state).
- `occlude`, overflow clipping, and opacity.
- `canvas()`.
- Tests: end-to-end views to scene, clicks, hover, invalidation, nested
views, bubbling, occlusion, shadows and borders, clipping, canvas,
resize, and the aborts expected on misuse.
- **M7: test platform (done).**
- `input`: `MouseExitEvent`, `ModifiersChangedEvent`, `PlatformInput`, and
`DispatchEventResult`.
- `platform`: core `Platform` and `PlatformWindow` traits plus `WindowId`,
`WindowBounds`, `WindowOptions`, `WindowParams`, and `ClipboardItem`
(text subset).
- `window`: `Application`, `AnyWindowHandle`, `WindowHandle[V]`,
`Window::dispatch_input`, `prevent_default`, close/activation hooks,
`replace_root_view`, and `PlatformWindow` callback/frame wiring (keeping
standalone `Window::new`). Closing a window releases its root view.
- `platform/test`: `TestPlatform` and `TestWindow` (recording presented
`Scene`s and simulating frames, input, resize, scale factor, active/hover
status, and close requests), plus `TestAppContext` and `VisualTestContext`
which pump tasks and scheduled frames together with a runaway-redraw
guard.
- Tests: platform types, `TestPlatform`/`TestWindow`/`TestAppContext` unit
tests, `elements` visual integration tests (`VisualTestContext`), panic
tests on closed-window misuse and runaway redraws, and `src/examples/card`
updated to run on `TestPlatform`/`VisualTestContext`.
- **M8: web platform + Canvas2D renderer (first pixels).** - **M8: web platform + Canvas2D renderer (first pixels).**
- A `<canvas>` window, rAF-driven frames, resize, and DPR. - A `<canvas>` window, rAF-driven frames, resize, and DPR.
- DOM pointer, wheel, and key events → `PlatformInput`. - DOM pointer, wheel, and key events → `PlatformInput`.
@@ -564,53 +532,6 @@ gantt
- **`AsyncApp` methods return values, not `Result`s.** An app is never - **`AsyncApp` methods return values, not `Result`s.** An app is never
dropped while a task references it. dropped while a task references it.
### Deviations taken in M6 (elements and window)
- **Element state lives in the element.** `Element` has no associated state
types. Elements keep per-frame state in their own fields and are rebuilt
every frame. `render` returns `AnyElement`.
- **Element ids are strings, and state is keyed by `ElementStateKey[S]`**
(the same key pattern as globals). `Div::id` makes a div stateful, and
`on_click` aborts without an id. There is no separate `Stateful<Div>` type.
- **Hover styles apply at paint time only.** Hovering cannot change layout.
Any change in the hovered hitboxes marks the window dirty, not only for
elements with hover styles.
- **The window is headless.** It is created directly with a viewport size,
scale factor, and rem size, and `draw` returns the `Scene`. There is no
platform window or frame scheduling yet (M7/M8).
- **Invalidation without accessed-entity tracking.** A window re-renders when
a view it rendered in the last frame is notified, through
`App::observe_notifications`. There is no view caching or `Scene::replay`
reuse yet; every frame renders everything.
- **Quads are not split.** GPUI splits bordered quads into a fill and border
strips; that renderer optimization is not ported.
- **Not yet ported:**
- Focus and the key dispatch tree (M5/M10).
- Active and group styles.
- Drag and drop, tooltips, scroll state, and deferred draws.
- Text (M9).
### Deviations taken in M7 (test platform)
- **Core platform subset.** `Platform` and `PlatformWindow` include window
lifecycle, frame scheduling/drawing, input/resize/focus/hover callbacks,
executor dispatcher, cursor style, clipboard, and `open_url`. Text
system, glyph atlas, IME, displays, menus, and screen capture come in
later milestones.
- **Explicit `PlatformWindow::close`.** MoonBit has no `Drop`, so
app-driven window teardown calls `PlatformWindow::close` explicitly (without
re-invoking `on_close`). Closing a `Window` releases its root view
(Design Decision 1).
- **`TestWindow` defaults to `scale_factor = 1.0`.** Matches M6's
`Window::new` (GPUI historically defaults to `2.0`), configurable via
`TestPlatform::new(default_scale_factor=...)` or `WindowOptions`.
- **`Application` lives in `window`.** `Application` owns the `App`,
`Platform`, and open windows so `app` stays independent of `platform`,
`scene`, and `style`; `application_for(app)` looks it up via a private
`GlobalKey`.
- **Automatic frame pumping in tests.** `TestAppContext::run_until_parked()`
alternates draining ready tasks on `TestDispatcher` with pumping scheduled
frames, aborting after 100 consecutive redraws to catch runaway redraw
loops.
## 7. Design decisions ## 7. Design decisions
Decided on 2026-11-24, following the recommendations below. Decided on 2026-11-24, following the recommendations below.
@@ -661,8 +582,3 @@ Decided on 2026-11-24, following the recommendations below.
expected. Closures that raise must say so (`fn() raise { ... }`). expected. Closures that raise must say so (`fn() raise { ... }`).
- `Ref(x)` builds a `Ref`; `{ val: x }` needs a type annotation. - `Ref(x)` builds a `Ref`; `{ val: x }` needs a type annotation.
- Test-only imports go in `import { ... } for "test"` in `moon.pkg`. - Test-only imports go in `import { ... } for "test"` in `moon.pkg`.
- Package import aliases in `moon.pkg` write `"path/to/pkg" @alias,` (without
`as`).
- Tuple destructuring cannot annotate element types inside the pattern
(`let (a : T, b)`); annotate the whole tuple or bind afterwards
(`let a : T = a`).
-19
View File
@@ -51,8 +51,6 @@ pub struct App {
priv release_listeners : SubscriberSet[EntityId, (App) -> Unit] priv release_listeners : SubscriberSet[EntityId, (App) -> Unit]
priv global_observers : SubscriberSet[Int32, (App) -> Bool] priv global_observers : SubscriberSet[Int32, (App) -> Bool]
priv globals : Map[Int32, () -> Unit] priv globals : Map[Int32, () -> Unit]
/// Called synchronously by `notify` (windows invalidate views with it).
priv notify_hooks : SubscriberSet[Unit, (EntityId) -> Unit]
priv executor : @executor.Executor priv executor : @executor.Executor
/// Set when the app drives its own deterministic dispatcher (tests). /// Set when the app drives its own deterministic dispatcher (tests).
priv test_dispatcher : @executor.TestDispatcher? priv test_dispatcher : @executor.TestDispatcher?
@@ -94,7 +92,6 @@ pub fn App::new(dispatcher? : &@executor.Dispatcher) -> App {
release_listeners: SubscriberSet::new(), release_listeners: SubscriberSet::new(),
global_observers: SubscriberSet::new(), global_observers: SubscriberSet::new(),
globals: {}, globals: {},
notify_hooks: SubscriberSet::new(),
} }
} }
@@ -277,26 +274,10 @@ pub fn App::entity_count(self : App) -> Int32 {
///| ///|
/// Marks an entity as changed: its observers run during the next flush /// Marks an entity as changed: its observers run during the next flush
/// (GPUI: `App::notify`). Repeated notifications before the flush coalesce. /// (GPUI: `App::notify`). Repeated notifications before the flush coalesce.
/// Notification hooks (windows rendering the entity) run immediately.
pub fn App::notify(self : App, entity_id : EntityId) -> Unit { pub fn App::notify(self : App, entity_id : EntityId) -> Unit {
self.notify_hooks.retain((), fn(hook) {
hook(entity_id)
true
})
self.update(fn(app) { app.push_effect(Notify(entity_id)) }) self.update(fn(app) { app.push_effect(Notify(entity_id)) })
} }
///|
/// Calls `hook` synchronously whenever any entity is notified. Used by
/// windows to invalidate the views they rendered (GPUI keeps per-window
/// invalidators for this).
pub fn App::observe_notifications(
self : App,
hook : (EntityId) -> Unit,
) -> Subscription {
self.notify_hooks.insert((), hook)
}
///| ///|
fn[T] App::emit_event( fn[T] App::emit_event(
self : App, self : App,
-1
View File
@@ -29,7 +29,6 @@ pub fn[T] App::new_entity(Self, (Context[T]) -> T) -> Entity[T]
pub fn App::notify(Self, EntityId) -> Unit pub fn App::notify(Self, EntityId) -> Unit
pub fn[T] App::observe(Self, Entity[T], (Entity[T], Self) -> Unit) -> Subscription 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[G] App::observe_global(Self, GlobalKey[G], (Self) -> Unit) -> Subscription
pub fn App::observe_notifications(Self, (EntityId) -> Unit) -> Subscription
pub fn[T] App::observe_release(Self, Entity[T], (T, Self) -> Unit) -> Subscription pub fn[T] App::observe_release(Self, Entity[T], (T, Self) -> Unit) -> Subscription
pub fn[T] App::read_entity(Self, Entity[T]) -> T pub fn[T] App::read_entity(Self, Entity[T]) -> T
pub fn[T] App::release(Self, Entity[T]) -> Unit pub fn[T] App::release(Self, Entity[T]) -> Unit
-72
View File
@@ -1,72 +0,0 @@
// `canvas()`, ported from gpui/src/elements/canvas.rs: an element laid out by
// its style that paints with a closure.
///|
/// An element that paints itself with a closure (GPUI: `Canvas`).
pub struct Canvas {
priv base_style : @style.StyleRefinement
priv prepaint_fn : (
@geometry.Bounds[@geometry.Pixels],
@window.Window,
@app.App,
) -> Unit
priv paint_fn : (@geometry.Bounds[@geometry.Pixels], @window.Window, @app.App) -> Unit
priv mut layout_style : @style.Style?
}
///|
/// A canvas that runs `paint` with its bounds during the paint phase, and
/// `prepaint` (if given) during prepaint. Size it with style methods, e.g.
/// `canvas(paint).size_full()`.
pub fn canvas(
paint : (@geometry.Bounds[@geometry.Pixels], @window.Window, @app.App) -> Unit,
prepaint~ : (@geometry.Bounds[@geometry.Pixels], @window.Window, @app.App) -> Unit = fn(
_,
_,
_,
) {
},
) -> Canvas {
{
base_style: @style.StyleRefinement::new(),
prepaint_fn: prepaint,
paint_fn: paint,
layout_style: None,
}
}
///|
pub impl @style.Styled for Canvas with fn style(self) {
self.base_style
}
///|
pub impl @window.IntoElement for Canvas with fn into_any_element(self) {
@window.AnyElement::new(self)
}
///|
pub extend Canvas with @window.IntoElement::{into_any_element}
///|
impl @window.Element for Canvas with fn request_layout(self, window, _app) {
let style = (Default::default() : @style.Style).refined(self.base_style)
self.layout_style = Some(style)
window.request_layout(style, [])
}
///|
impl @window.Element for Canvas with fn prepaint(self, bounds, window, app) {
(self.prepaint_fn)(bounds, window, app)
}
///|
impl @window.Element for Canvas with fn paint(self, bounds, window, app) {
guard self.layout_style is Some(style) else {
abort("canvas painted before layout")
}
window.paint_style(style, bounds, fn() {
(self.paint_fn)(bounds, window, app)
})
}
File diff suppressed because it is too large. Load diff
-355
View File
@@ -1,355 +0,0 @@
// `div()`, ported from gpui/src/elements/div.rs (`Div` and the parts of
// `Interactivity` that need neither focus nor actions).
//
// Ported: styles (via `Styled`), children, hover styles, mouse down/up/move
// and scroll listeners, clicks (which need an element id), hitbox
// occlusion, overflow clipping and opacity.
//
// Not ported yet: focus and key listeners and actions (M5/M10), active and
// group styles, drag and drop, tooltips, scrolling state, and the
// `Stateful<Div>` split (an id is set with `.id(...)` on `Div` itself, and
// `on_click` fails loudly without one).
//
// Deviation: hover styles apply at paint time only. GPUI also lays out with
// them (using the previous frame's hover state); here hovering cannot change
// an element's layout.
///|
/// A flexible container: GPUI's workhorse element (`div()`).
pub struct Div {
priv base_style : @style.StyleRefinement
priv mut hover_style : @style.StyleRefinement?
priv mut element_id : String?
priv mut occlude_mouse : Bool
priv children : Array[@window.AnyElement]
priv mouse_down_listeners : Array[
(
@input.MouseButton,
(@input.MouseDownEvent, @window.Window, @app.App) -> Unit,
),
]
priv mouse_up_listeners : Array[
(
@input.MouseButton,
(@input.MouseUpEvent, @window.Window, @app.App) -> Unit,
),
]
priv mouse_move_listeners : Array[
(@input.MouseMoveEvent, @window.Window, @app.App) -> Unit,
]
priv scroll_listeners : Array[
(@input.ScrollWheelEvent, @window.Window, @app.App) -> Unit,
]
priv click_listeners : Array[
(@input.ClickEvent, @window.Window, @app.App) -> Unit,
]
// Per-frame state.
priv mut layout_style : @style.Style?
priv mut hitbox : @window.Hitbox?
}
///|
/// A new, empty `div`.
pub fn div() -> Div {
{
base_style: @style.StyleRefinement::new(),
hover_style: None,
element_id: None,
occlude_mouse: false,
children: [],
mouse_down_listeners: [],
mouse_up_listeners: [],
mouse_move_listeners: [],
scroll_listeners: [],
click_listeners: [],
layout_style: None,
hitbox: None,
}
}
///|
pub impl @style.Styled for Div with fn style(self) {
self.base_style
}
///|
pub impl @window.IntoElement for Div with fn into_any_element(self) {
@window.AnyElement::new(self)
}
///|
pub extend Div with @window.IntoElement::{into_any_element}
///|
/// Gives the element an id, which makes it stateful (needed for clicks).
/// Ids are scoped to the parent's id (GPUI: `.id(...)`).
pub fn Div::id(self : Div, id : String) -> Div {
self.element_id = Some(id)
self
}
///|
/// Adds a child (GPUI: `ParentElement::child`).
pub fn[E : @window.IntoElement] Div::child(self : Div, child : E) -> Div {
self.children.push(child.into_any_element())
self
}
///|
/// Adds children (GPUI: `ParentElement::children`).
pub fn[E : @window.IntoElement] Div::children(
self : Div,
children : Array[E],
) -> Div {
for child in children {
self.children.push(child.into_any_element())
}
self
}
///|
/// Styles applied while the mouse is over the element (GPUI: `.hover(...)`).
pub fn Div::hover(
self : Div,
f : (@style.StyleRefinement) -> @style.StyleRefinement,
) -> Div {
let current = match self.hover_style {
Some(style) => style
None => @style.StyleRefinement::new()
}
self.hover_style = Some(f(current))
self
}
///|
/// Hitboxes painted below this element are not hovered (GPUI:
/// `.occlude()`).
pub fn Div::occlude(self : Div) -> Div {
self.occlude_mouse = true
self
}
///|
/// Called when `button` is pressed over the element (bubble phase).
pub fn Div::on_mouse_down(
self : Div,
button : @input.MouseButton,
listener : (@input.MouseDownEvent, @window.Window, @app.App) -> Unit,
) -> Div {
self.mouse_down_listeners.push((button, listener))
self
}
///|
/// Called when `button` is released over the element (bubble phase).
pub fn Div::on_mouse_up(
self : Div,
button : @input.MouseButton,
listener : (@input.MouseUpEvent, @window.Window, @app.App) -> Unit,
) -> Div {
self.mouse_up_listeners.push((button, listener))
self
}
///|
/// Called when the mouse moves over the element (bubble phase).
pub fn Div::on_mouse_move(
self : Div,
listener : (@input.MouseMoveEvent, @window.Window, @app.App) -> Unit,
) -> Div {
self.mouse_move_listeners.push(listener)
self
}
///|
/// Called on scroll-wheel events over the element (bubble phase).
pub fn Div::on_scroll_wheel(
self : Div,
listener : (@input.ScrollWheelEvent, @window.Window, @app.App) -> Unit,
) -> Div {
self.scroll_listeners.push(listener)
self
}
///|
/// Called when the left button is pressed and released over the element.
/// The element needs an id (GPUI: `StatefulInteractiveElement::on_click`).
pub fn Div::on_click(
self : Div,
listener : (@input.ClickEvent, @window.Window, @app.App) -> Unit,
) -> Div {
self.click_listeners.push(listener)
self
}
///|
fn Div::is_interactive(self : Div) -> Bool {
self.hover_style is Some(_) ||
self.occlude_mouse ||
!self.mouse_down_listeners.is_empty() ||
!self.mouse_up_listeners.is_empty() ||
!self.mouse_move_listeners.is_empty() ||
!self.scroll_listeners.is_empty() ||
!self.click_listeners.is_empty()
}
///|
/// The pending press of a click, kept across frames.
priv struct ClickState {
mut pending : @input.MouseDownEvent?
}
///|
let click_state_key : @window.ElementStateKey[ClickState] = @window.ElementStateKey::new(
"ClickState",
)
///|
impl @window.Element for Div with fn request_layout(self, window, app) {
let style = (Default::default() : @style.Style).refined(self.base_style)
self.layout_style = Some(style)
window.with_element_id(self.element_id, fn() {
let child_ids = self.children.map(fn(child) {
child.request_layout(window, app)
})
window.request_layout(style, child_ids)
})
}
///|
impl @window.Element for Div with fn prepaint(self, bounds, window, app) {
guard self.layout_style is Some(style) else {
abort("div prepainted before layout")
}
window.with_element_id(self.element_id, fn() {
if self.is_interactive() {
let behavior : @window.HitboxBehavior = if self.occlude_mouse {
BlockMouse
} else {
Normal
}
self.hitbox = Some(window.insert_hitbox(bounds, behavior))
}
window.with_content_mask(style.overflow_mask(bounds, window.rem_size()), fn() {
for child in self.children {
child.prepaint(window, app)
}
})
})
}
///|
impl @window.Element for Div with fn paint(self, bounds, window, app) {
guard self.layout_style is Some(layout_style) else {
abort("div painted before layout")
}
let hovered = match self.hitbox {
Some(hitbox) => hitbox.is_hovered(window)
None => false
}
let style = match (self.hover_style, hovered) {
(Some(hover), true) => layout_style.refined(hover)
_ => layout_style
}
window.with_element_id(self.element_id, fn() {
if self.hitbox is Some(hitbox) {
self.register_listeners(hitbox, window)
}
window.with_element_opacity(style.opacity, fn() {
window.paint_style(style, bounds, fn() {
window.with_content_mask(
style.overflow_mask(bounds, window.rem_size()),
fn() {
for child in self.children {
child.paint(window, app)
}
},
)
})
})
})
}
///|
fn Div::register_listeners(
self : Div,
hitbox : @window.Hitbox,
window : @window.Window,
) -> Unit {
for entry in self.mouse_down_listeners {
let (button, listener) = entry
window.on_mouse_event(fn(event, phase, window, app) {
if phase == Bubble &&
event is MouseDown(down) &&
down.button == button &&
hitbox.is_hovered(window) {
listener(down, window, app)
}
})
}
for entry in self.mouse_up_listeners {
let (button, listener) = entry
window.on_mouse_event(fn(event, phase, window, app) {
if phase == Bubble &&
event is MouseUp(up) &&
up.button == button &&
hitbox.is_hovered(window) {
listener(up, window, app)
}
})
}
for listener in self.mouse_move_listeners {
window.on_mouse_event(fn(event, phase, window, app) {
if phase == Bubble &&
event is MouseMove(moved) &&
hitbox.is_hovered(window) {
listener(moved, window, app)
}
})
}
for listener in self.scroll_listeners {
window.on_mouse_event(fn(event, phase, window, app) {
if phase == Bubble &&
event is ScrollWheel(scroll) &&
hitbox.is_hovered(window) {
listener(scroll, window, app)
}
})
}
if !self.click_listeners.is_empty() {
guard window.global_element_id() is Some(_) else {
abort("on_click requires an element id: call .id(...) on the div")
}
// The pending press lives in element state so it survives redraws
// between mouse down and mouse up.
let state = window.with_element_state(click_state_key, fn(previous) {
let state = match previous {
Some(state) => state
None => { pending: None, }
}
(state, state)
})
let listeners = self.click_listeners
window.on_mouse_event(fn(event, phase, window, app) {
match (event, phase) {
(MouseDown(down), Bubble) =>
if down.button == Left && hitbox.is_hovered(window) {
state.pending = Some(down)
}
(MouseUp(up), Capture) =>
if up.button == Left {
match state.pending {
Some(down) if hitbox.is_hovered(window) => {
state.pending = None
for listener in listeners {
listener({ down, up, }, window, app)
}
}
_ => state.pending = None
}
}
_ => ()
}
})
}
}
File diff suppressed because it is too large. Load diff
-427
View File
@@ -1,427 +0,0 @@
///|
fn px(v : Double) -> @geometry.Pixels {
@geometry.px(v)
}
///|
fn pt(x : Double, y : Double) -> @geometry.Point[@geometry.Pixels] {
@geometry.point(px(x), px(y))
}
///|
fn mouse_down(x : Double, y : Double) -> @input.MouseEvent {
MouseDown({ ..Default::default(), position: pt(x, y), click_count: 1, })
}
///|
fn mouse_up(x : Double, y : Double) -> @input.MouseEvent {
MouseUp({ ..Default::default(), position: pt(x, y), click_count: 1, })
}
///|
fn mouse_move(x : Double, y : Double) -> @input.MouseEvent {
MouseMove({ ..Default::default(), position: pt(x, y), })
}
///|
fn sp(v : Double) -> @geometry.ScaledPixels {
@geometry.ScaledPixels(v)
}
///|
fn sbounds(
x : Double,
y : Double,
w : Double,
h : Double,
) -> @geometry.Bounds[@geometry.ScaledPixels] {
@geometry.bounds(@geometry.point(sp(x), sp(y)), @geometry.size(sp(w), sp(h)))
}
// A counter view: a row with a decrement button, a value bar and an
// increment button.
///|
struct Counter {
mut count : Int32
mut renders : Int32
}
///|
impl @window.Render for Counter with fn render(self, _window, cx) {
self.renders += 1
@elements.div()
.flex()
.flex_row()
.gap(px(10.0))
.p(px(10.0))
.size_full()
.bg(@color.rgb(0xffffff))
.child(
@elements.div()
.id("minus")
.size(px(20.0))
.bg(@color.rgb(0xcc0000))
.on_click(
@window.listener(cx, fn(counter, _, _, cx) {
counter.count -= 1
cx.notify()
}),
),
)
.child(
@elements.div()
.w(px((self.count * 10).to_double()))
.h(px(20.0))
.bg(@color.rgb(0x0000cc)),
)
.child(
@elements.div()
.id("plus")
.size(px(20.0))
.bg(@color.rgb(0x00cc00))
.hover(fn(style) { style.bg(@color.rgb(0x00ff00)) })
.on_click(
@window.listener(cx, fn(counter, _, _, cx) {
counter.count += 1
cx.notify()
}),
),
)
.into_any_element()
}
///|
fn setup_counter(
count~ : Int32 = 3,
scale_factor~ : Double = 1.0,
) -> (@app.App, @window.Window, @app.Entity[Counter]) {
let app = @app.App::new()
let window = @window.Window::new(
app,
@geometry.size(px(200.0), px(40.0)),
scale_factor~,
)
let counter : @app.Entity[Counter] = app.new_entity(fn(_) {
{ count, renders: 0, }
})
window.set_root_view(counter)
(app, window, counter)
}
///|
test "a view renders a laid-out div tree into the scene" {
let (_, window, _) = setup_counter()
let scene = window.draw()
// Root background, minus, value bar (3 * 10px) and plus.
assert_eq(scene.quads.length(), 4)
let bounds = scene.quads.map(fn(q) { q.bounds })
assert_eq(bounds, [
sbounds(0.0, 0.0, 200.0, 40.0),
sbounds(10.0, 10.0, 20.0, 20.0),
sbounds(40.0, 10.0, 30.0, 20.0),
sbounds(80.0, 10.0, 20.0, 20.0),
])
assert_eq(scene.quads[1].background, @color.rgb(0xcc0000).to_background())
assert_eq(scene.batches().map(fn(b) { b.label() }), ["quads (4)"])
assert_eq(window.frame_count(), 1)
assert_false(window.is_dirty())
}
///|
test "device pixels at 2x" {
let (_, window, _) = setup_counter(scale_factor=2.0)
let scene = window.draw()
assert_eq(scene.quads[3].bounds, sbounds(160.0, 20.0, 40.0, 40.0))
}
///|
test "clicks update the view and invalidate the window" {
let (app, window, counter) = setup_counter()
ignore(window.draw())
// Click "plus" (80..100, 10..30).
ignore(window.dispatch_mouse_event(mouse_down(90.0, 20.0)))
ignore(window.dispatch_mouse_event(mouse_up(90.0, 20.0)))
assert_eq(counter.read(app).count, 4)
assert_true(window.is_dirty())
let scene = window.draw()
// The value bar grew to 40px and pushed "plus" to the right.
assert_eq(scene.quads[2].bounds.size.width, sp(40.0))
assert_eq(scene.quads[3].bounds.origin.x, sp(90.0))
// Click "minus" twice.
for _ in 0..<2 {
ignore(window.dispatch_mouse_event(mouse_down(15.0, 15.0)))
ignore(window.dispatch_mouse_event(mouse_up(15.0, 15.0)))
ignore(window.draw())
}
assert_eq(counter.read(app).count, 2)
}
///|
test "a click needs press and release over the same element" {
let (app, window, counter) = setup_counter()
ignore(window.draw())
// Press on "plus", release elsewhere: no click.
ignore(window.dispatch_mouse_event(mouse_down(90.0, 20.0)))
ignore(window.dispatch_mouse_event(mouse_up(150.0, 20.0)))
assert_eq(counter.read(app).count, 3)
// Press elsewhere, release on "plus": no click either.
ignore(window.dispatch_mouse_event(mouse_down(150.0, 20.0)))
ignore(window.dispatch_mouse_event(mouse_up(90.0, 20.0)))
assert_eq(counter.read(app).count, 3)
}
///|
test "hover styles apply under the mouse" {
let (_, window, _) = setup_counter()
ignore(window.draw())
ignore(window.dispatch_mouse_event(mouse_move(90.0, 20.0)))
// Entering a hitbox marks the window dirty.
assert_true(window.is_dirty())
let scene = window.draw()
assert_eq(scene.quads[3].background, @color.rgb(0x00ff00).to_background())
ignore(window.dispatch_mouse_event(mouse_move(150.0, 20.0)))
let scene = window.draw()
assert_eq(scene.quads[3].background, @color.rgb(0x00cc00).to_background())
// Moving within nothing interactive does not dirty the window.
ignore(window.dispatch_mouse_event(mouse_move(151.0, 20.0)))
assert_false(window.is_dirty())
}
///|
test "only rendered views invalidate the window" {
let (app, window, counter) = setup_counter()
ignore(window.draw())
let unrelated : @app.Entity[Counter] = app.new_entity(fn(_) {
{ count: 0, renders: 0, }
})
unrelated.update(app, fn(_, cx) { cx.notify() })
assert_false(window.is_dirty())
assert_false(window.draw_if_dirty())
counter.update(app, fn(_, cx) { cx.notify() })
assert_true(window.draw_if_dirty())
assert_eq(counter.read(app).renders, 2)
}
///|
struct Panel {
child : @app.Entity[Counter]
log : Array[String]
}
///|
impl @window.Render for Panel with fn render(self, _window, _cx) {
let log = self.log
@elements.div()
.size_full()
.p(px(4.0))
.on_mouse_down(Left, fn(_, _, _) { log.push("panel down") })
.child(self.child)
.into_any_element()
}
///|
test "nested views and event bubbling" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(208.0), px(48.0)))
let child : @app.Entity[Counter] = app.new_entity(fn(_) {
{ count: 0, renders: 0, }
})
let panel : @app.Entity[Panel] = app.new_entity(fn(_) { { child, log: [], } })
window.set_root_view(panel)
let scene = window.draw()
// The child view is laid out inside the panel's padding.
assert_eq(scene.quads[0].bounds.origin, @geometry.point(sp(4.0), sp(4.0)))
// With a count of 0 the value bar is empty: "plus" spans x 54..74.
// A press on it reaches the button first, then bubbles to the panel.
ignore(window.dispatch_mouse_event(mouse_down(64.0, 24.0)))
ignore(window.dispatch_mouse_event(mouse_up(64.0, 24.0)))
assert_eq(child.read(app).count, 1)
assert_eq(panel.read(app).log, ["panel down"])
// Notifying the nested view invalidates the window too.
ignore(window.draw())
child.update(app, fn(_, cx) { cx.notify() })
assert_true(window.is_dirty())
}
///|
struct Layers {
log : Array[String]
}
///|
impl @window.Render for Layers with fn render(self, _window, _cx) {
let log = self.log
@elements.div()
.size_full()
.relative()
.on_mouse_down(Left, fn(_, _, _) { log.push("background") })
.child(
@elements.div()
.absolute()
.size(px(50.0))
.occlude()
.on_mouse_down(Left, fn(_, window, _) {
log.push("overlay")
window.stop_propagation()
}),
)
.into_any_element()
}
///|
test "occlusion and stop_propagation" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(100.0), px(100.0)))
let view : @app.Entity[Layers] = app.new_entity(fn(_) { { log: [], } })
window.set_root_view(view)
ignore(window.draw())
let propagated = window.dispatch_mouse_event(mouse_down(10.0, 10.0))
assert_false(propagated)
ignore(window.dispatch_mouse_event(mouse_down(80.0, 80.0)))
assert_eq(view.read(app).log, ["overlay", "background"])
}
///|
struct Styled {
opacity : Double
}
///|
impl @window.Render for Styled with fn render(self, _window, _cx) {
@elements.div()
.size_full()
.overflow_hidden()
.opacity(self.opacity)
.shadow_sm()
.rounded_md()
.border_2()
.border_color(@color.black())
.bg(@color.rgb(0x336699))
.child(@elements.div().w(px(500.0)).h(px(10.0)).bg(@color.red()))
.into_any_element()
}
///|
test "shadows, borders, opacity and overflow clipping" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(100.0), px(100.0)))
let view : @app.Entity[Styled] = app.new_entity(fn(_) { { opacity: 0.5, } })
window.set_root_view(view)
let scene = window.draw()
assert_eq(scene.shadows.length(), 2)
// Background, child, border.
assert_eq(scene.quads.length(), 3)
let background = scene.quads[0]
assert_eq(background.background.solid.a, 0.5)
assert_eq(background.corner_radii.top_left, sp(6.0))
let border = scene.quads.filter(fn(q) { q.border_widths.top == sp(2.0) })
assert_eq(border.length(), 1)
assert_eq(border[0].border_color.a, 0.5)
// The wide child is clipped to the inside of the border.
let child = scene.quads.filter(fn(q) { q.bounds.size.width == sp(500.0) })
assert_eq(child[0].content_mask.bounds, sbounds(2.0, 2.0, 96.0, 96.0))
// Quads overlapping quads share a draw order and form one batch, drawn in
// insertion order: background, child, then the border on top.
assert_eq(scene.batches().map(fn(b) { b.label() }), [
"shadows (2)", "quads (3)",
])
assert_eq(scene.quads[2].border_widths.top, sp(2.0))
}
///|
enum Drawing {
Drawing
}
///|
impl @window.Render for Drawing with fn render(_self, _window, _cx) {
@elements.div()
.size_full()
.p(px(10.0))
.child(
@elements.canvas(fn(bounds, window, _) {
window.paint_path(
[[bounds.origin, bounds.top_right(), bounds.bottom_left()]],
@color.blue().to_background(),
)
}).size(px(30.0)),
)
.into_any_element()
}
///|
test "canvas paints with its bounds" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(100.0), px(100.0)))
let view : @app.Entity[Drawing] = app.new_entity(fn(_) { Drawing })
window.set_root_view(view)
let scene = window.draw()
assert_eq(scene.paths.length(), 1)
assert_eq(scene.paths[0].bounds, sbounds(10.0, 10.0, 30.0, 30.0))
}
///|
test "resizing relayouts" {
let (_, window, _) = setup_counter()
ignore(window.draw())
window.resize(@geometry.size(px(300.0), px(60.0)), scale_factor=2.0)
assert_true(window.is_dirty())
let scene = window.draw()
assert_eq(scene.quads[0].bounds, sbounds(0.0, 0.0, 600.0, 120.0))
}
///|
enum Broken {
Broken
}
///|
impl @window.Render for Broken with fn render(_self, _window, _cx) {
@elements.div().on_click(fn(_, _, _) { }).into_any_element()
}
///|
test "panic on on_click without an id" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(10.0), px(10.0)))
let view : @app.Entity[Broken] = app.new_entity(fn(_) { Broken })
window.set_root_view(view)
ignore(window.draw())
}
///|
test "panic on drawing without a root view" {
let window = @window.Window::new(
@app.App::new(),
@geometry.size(px(10.0), px(10.0)),
)
ignore(window.draw())
}
///|
enum PaintsDuringLayout {
PaintsDuringLayout
}
///|
impl @window.Render for PaintsDuringLayout with fn render(_self, window, _cx) {
window.paint_quad(
@window.fill(
@geometry.bounds(pt(0.0, 0.0), @geometry.size(px(1.0), px(1.0))),
@color.red().to_background(),
),
)
@window.empty()
}
///|
test "panic on painting outside the paint phase" {
let app = @app.App::new()
let window = @window.Window::new(app, @geometry.size(px(10.0), px(10.0)))
let view : @app.Entity[PaintsDuringLayout] = app.new_entity(fn(_) {
PaintsDuringLayout
})
window.set_root_view(view)
ignore(window.draw())
}
-16
View File
@@ -1,16 +0,0 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/style",
"experiments/gpui/input",
"experiments/gpui/app",
"experiments/gpui/window",
}
options(
"allow-experimental-packages": true,
)
import {
"experiments/gpui/color",
"experiments/gpui/platform/test" @test_platform,
} for "test"
File diff suppressed because it is too large. Load diff
-187
View File
@@ -1,187 +0,0 @@
///|
struct VisualCounter {
mut count : Int32
}
///|
impl @window.Render for VisualCounter with fn render(self, _window, cx) {
@elements.div()
.flex()
.flex_row()
.gap(px(10.0))
.p(px(10.0))
.size_full()
.bg(@color.rgb(0xffffff))
.child(
@elements.div()
.id("minus")
.size(px(20.0))
.bg(@color.rgb(0xcc0000))
.on_click(
@window.listener(cx, fn(counter, _, _, cx) {
counter.count -= 1
cx.notify()
}),
),
)
.child(
@elements.div()
.w(px((self.count * 10).to_double()))
.h(px(20.0))
.bg(@color.rgb(0x0000cc)),
)
.child(
@elements.div()
.id("plus")
.size(px(20.0))
.bg(@color.rgb(0x00cc00))
.hover(fn(style) { style.bg(@color.rgb(0x00ff00)) })
.on_click(
@window.listener(cx, fn(counter, _, _, cx) {
counter.count += 1
cx.notify()
}),
),
)
.into_any_element()
}
///|
test "VisualTestContext renders div counter and tracks scene history" {
let cx = @test_platform.TestAppContext::new()
let (counter, vcx) = cx.add_window_view(
size=@geometry.size(px(200.0), px(40.0)),
fn(_, _) { { count: 3, } },
)
assert_eq(vcx.draw_count(), 1)
assert_eq(vcx.scene().quads.length(), 4)
assert_eq(vcx.scene().quads[2].bounds.size.width, sp(30.0))
assert_eq(
vcx.scene().quads[3].background,
@color.rgb(0x00cc00).to_background(),
)
// Moving onto "plus" triggers hover redraw automatically.
ignore(vcx.simulate_mouse_move(pt(90.0, 20.0)))
assert_eq(vcx.draw_count(), 2)
assert_eq(
vcx.scene().quads[3].background,
@color.rgb(0x00ff00).to_background(),
)
// Clicking "plus" updates the view and draws the expanded value bar.
vcx.simulate_click(pt(90.0, 20.0))
assert_eq(cx.read_entity(counter).count, 4)
assert_eq(vcx.draw_count(), 3)
assert_eq(vcx.drawn_scenes().length(), 3)
assert_eq(vcx.scene().quads[2].bounds.size.width, sp(40.0))
assert_eq(vcx.scene().quads[3].bounds.origin.x, sp(90.0))
}
///|
enum VisualCanvasView {
VisualCanvasView
}
///|
impl @window.Render for VisualCanvasView with fn render(_self, _window, _cx) {
@elements.div()
.flex()
.size_full()
.p(px(10.0))
.child(
@elements.canvas(fn(bounds, window, _) {
window.paint_path(
[[bounds.origin, bounds.top_right(), bounds.bottom_left()]],
@color.blue().to_background(),
)
}).size_full(),
)
.into_any_element()
}
///|
test "VisualTestContext resize, scale factor, and canvas view" {
let cx = @test_platform.TestAppContext::new()
let (_, vcx) = cx.add_window_view(size=@geometry.size(px(100.0), px(80.0)), fn(
_,
_,
) {
VisualCanvasView
})
assert_eq(vcx.scene().paths.length(), 1)
assert_eq(vcx.scene().paths[0].bounds, sbounds(10.0, 10.0, 80.0, 60.0))
vcx.simulate_resize(@geometry.size(px(150.0), px(100.0)))
vcx.simulate_scale_factor_change(2.0)
assert_eq(vcx.scene().paths[0].bounds, sbounds(20.0, 20.0, 260.0, 160.0))
}
///|
struct VisualTicker {
mut ticks : Int32
}
///|
impl @window.Render for VisualTicker with fn render(self, _window, _cx) {
@elements.div()
.size_full()
.child(
@elements.div()
.w(px((self.ticks * 20).to_double()))
.h(px(10.0))
.bg(@color.red()),
)
.into_any_element()
}
///|
test "VisualTestContext async ticker updates div layout on virtual clock" {
let cx = @test_platform.TestAppContext::new()
let (ticker, vcx) = cx.add_window_view(
size=@geometry.size(px(200.0), px(40.0)),
fn(_, ctx) {
let weak : @app.WeakEntity[VisualTicker] = ctx.weak_entity()
ctx
.spawn(async fn(_, async_app) {
while true {
async_app.background_executor().sleep(100)
let alive = weak.update(async_app.app, fn(t : VisualTicker, cx) {
t.ticks = t.ticks + 1
cx.notify()
})
if alive is None {
break
}
}
})
.detach()
{ ticks: 0, }
},
)
assert_eq(vcx.draw_count(), 1)
assert_eq(vcx.scene().quads.length(), 0)
cx.advance_clock(250)
assert_eq(cx.read_entity(ticker).ticks, 2)
assert_true(vcx.draw_count() >= 2)
assert_eq(vcx.scene().quads.length(), 1)
assert_eq(vcx.scene().quads[0].bounds.size.width, sp(40.0))
}
///|
test "closing VisualTestContext window releases rendered div view" {
let cx = @test_platform.TestAppContext::new()
let released = Ref(false)
let (counter, vcx) = cx.add_window_view(
size=@geometry.size(px(100.0), px(40.0)),
fn(_, ctx) {
ctx.on_release(fn(_, _) { released.val = true }).detach()
{ count: 1, }
},
)
assert_false(released.val)
assert_true(vcx.simulate_close())
assert_true(counter.is_released())
assert_true(released.val)
}
+154 -74
View File
@@ -1,33 +1,15 @@
// A headless example of what exists so far (M0-M7): a view renders a card // A headless example of what exists so far (M0-M2): describe a "card" with
// with GPUI's `div()` and fluent styles inside a `TestPlatform` window, // GPUI's fluent style API, lay it out with the layout engine (text is a fake
// and `VisualTestContext` simulates a hover and click while pumping frames // fixed-width measure until the text system lands), and paint it into a
// automatically. There is no renderer or text yet (text lines are // Scene. There is no renderer yet, so the output is a text report.
// placeholder bars), so the output is a report of the scene's draw batches
// and quads.
// //
// Run with: moon run src/examples/card --target js // Run with: moon run src/examples/card --target js
///| ///|
struct Card { /// The card's style, written exactly as in GPUI:
mut expanded : Bool /// `div().flex().p_4().rounded_lg().border_1().shadow_md().bg(...)`.
mut clicks : Int32 fn card_style() -> @style.StyleRefinement {
} @style.StyleRefinement::new()
///|
/// A placeholder for a line of text (the text system arrives in M9).
fn text_bar(width : Double, color : UInt32) -> @elements.Div {
@elements.div()
.w(@geometry.px(width))
.h(@geometry.px(10.0))
.rounded_sm()
.bg(@color.rgb(color))
}
///|
impl @window.Render for Card with fn render(self, _window, cx) {
let body_lines = if self.expanded { 4 } else { 1 }
let card = @elements.div()
.id("card")
.flex() .flex()
.flex_col() .flex_col()
.gap_2() .gap_2()
@@ -38,70 +20,168 @@ impl @window.Render for Card with fn render(self, _window, cx) {
.border_color(@color.rgb(0xd0d7de)) .border_color(@color.rgb(0xd0d7de))
.bg(@color.rgb(0xffffff)) .bg(@color.rgb(0xffffff))
.shadow_md() .shadow_md()
.hover(fn(style) { style.border_color(@color.rgb(0x0969da)) }) .text_color(@color.rgb(0x1f2328))
.on_click( .text_sm()
@window.listener(cx, fn(card, _, _, cx) {
card.expanded = !card.expanded
card.clicks += 1
cx.notify()
}),
)
.child(text_bar(160.0, 0x1f2328))
for _ in 0..<body_lines {
ignore(card.child(text_bar(280.0, 0x656d76)))
}
@elements.div()
.size_full()
.flex()
.items_start()
.p(@geometry.px(40.0))
.bg(@color.rgb(0xf6f8fa))
.child(card)
.into_any_element()
} }
///| ///|
fn describe( /// Paints the resolved style's background, border and shadows, the way
label : String, /// GPUI's `Style::paint` will once the Window exists (M6).
fn paint_card(
scene : @scene.Scene, scene : @scene.Scene,
lines : Array[String], style : @style.Style,
bounds : @geometry.Bounds[@geometry.Pixels],
rem_size : @geometry.Pixels,
scale_factor : Double,
) -> Unit { ) -> Unit {
lines.push(label) let corner_radii = style.corner_radii
let batches = scene.batches().map(fn(b) { b.label() }).join(", ") .absolute_to_pixels(rem_size)
lines.push(" batches: \{batches}") .clamp_radii_for_quad_size(bounds.size)
for quad in scene.quads { let mask : @geometry.ContentMask[@geometry.Pixels] = {
let b = quad.bounds bounds: bounds.dilate(@geometry.px(64.0)),
let extra = if quad.border_widths.top.to_double() > 0.0 {
" border \{quad.border_color.to_rgb()}"
} else {
""
} }
lines.push( for shadow in style.box_shadow {
" quad (\{b.origin.x.to_double()}, \{b.origin.y.to_double()}) \{b.size.width.to_double()} x \{b.size.height.to_double()}\{extra}", let shadow_bounds = bounds
.translate(shadow.offset)
.dilate(shadow.spread_radius)
scene.insert_primitive(
Shadow({
order: 0,
blur_radius: shadow.blur_radius.scale(scale_factor),
bounds: shadow_bounds.scale(scale_factor),
corner_radii: corner_radii.scale(scale_factor),
content_mask: mask.scale(scale_factor),
color: shadow.color,
shape_bounds: bounds.scale(scale_factor),
shape_corner_radii: corner_radii.scale(scale_factor),
inset: false,
}),
) )
} }
let background = match style.background {
Some(fill) => fill.color().unwrap()
None => Default::default()
}
scene.insert_primitive(
Quad({
order: 0,
border_style: style.border_style,
bounds: bounds.scale(scale_factor),
content_mask: mask.scale(scale_factor),
background,
border_color: style.border_color.unwrap_or(@color.transparent_black()),
corner_radii: corner_radii.scale(scale_factor),
border_widths: style.border_widths
.absolute_to_pixels(rem_size)
.scale(scale_factor),
}),
)
}
///|
/// A stand-in for text measurement (M9): `char_width` per character, wrapping
/// at the available width, one `line_height` per line.
fn fake_text(
chars : Int32,
char_width : Double,
line_height : Double,
) -> @layout.MeasureFn {
fn(known, available) {
let natural = chars.to_double() * char_width
let wrap = match (known.width, available.width) {
(Some(width), _) => width.to_double()
(None, Definite(width)) => width.to_double()
(None, _) => natural
}
let width = if natural < wrap { natural } else { wrap }
let per_line = (wrap / char_width).floor()
let lines = (chars.to_double() / per_line).ceil()
@geometry.size(@geometry.px(width), @geometry.px(lines * line_height))
}
}
///|
fn show_bounds(bounds : @geometry.Bounds[@geometry.Pixels]) -> String {
"(\{bounds.origin.x}, \{bounds.origin.y}) \{bounds.size.width} x \{bounds.size.height}"
} }
///| ///|
/// Builds the report printed by `main`. /// Builds the report printed by `main`.
fn report() -> String { fn report() -> String {
let cx = @test_platform.TestAppContext::new() let rem_size = @geometry.px(16.0)
let (card, vcx) = cx.add_window_view( let scale_factor = 2.0
size=@geometry.size(@geometry.px(400.0), @geometry.px(240.0)), let style = (Default::default() : @style.Style).refined(card_style())
fn(_, _) { { expanded: false, clicks: 0, } }, let text = (Default::default() : @style.TextStyle).refined(style.text)
let line_height = text.line_height_in_pixels(rem_size).to_double()
// Layout: window root > card > (title, body).
let engine = @layout.LayoutEngine::new()
let leaf_style : @style.Style = Default::default()
let title = engine.request_measured_layout(
leaf_style,
rem_size,
scale_factor,
fake_text(16, 9.0, line_height),
) )
let card : @app.Entity[Card] = card let body = engine.request_measured_layout(
let lines = [] leaf_style,
describe("first frame", vcx.scene(), lines) rem_size,
// Hover the card, then click it: the view expands and the window redraws. scale_factor,
let inside = @geometry.point(@geometry.px(100.0), @geometry.px(60.0)) fake_text(90, 7.0, line_height),
ignore(vcx.simulate_mouse_move(inside)) )
vcx.simulate_click(inside) let card = engine.request_layout(style, rem_size, scale_factor, [title, body])
let state = cx.read_entity(card) let root_style = (Default::default() : @style.Style).refined(
@style.StyleRefinement::new().flex().items_start().p(@geometry.px(40.0)),
)
let root = engine.request_layout(root_style, rem_size, scale_factor, [card])
let window_size = @geometry.size(@geometry.px(480.0), @geometry.px(320.0))
engine.stretch_auto_size_to_fill(root, window_size, scale_factor)
engine.compute_layout(
root,
@layout.AvailableSpace::from_size(window_size),
scale_factor,
)
let card_bounds = engine.layout_bounds(card, scale_factor)
let title_bounds = engine.layout_bounds(title, scale_factor)
let body_bounds = engine.layout_bounds(body, scale_factor)
// Paint.
let scene = @scene.Scene::new()
paint_card(scene, style, card_bounds, rem_size, scale_factor)
scene.insert_primitive(
Underline({
order: 0,
bounds: @geometry.bounds(
title_bounds.bottom_left(),
@geometry.size(title_bounds.size.width, @geometry.px(1.0)),
).scale(scale_factor),
content_mask: { bounds: card_bounds.scale(scale_factor), },
color: text.color,
thickness: @geometry.ScaledPixels(2.0),
wavy: false,
}),
)
scene.finish()
let lines = [
"card style",
" display: \{@debug.to_string(style.display)}, direction: \{@debug.to_string(style.flex_direction)}",
" width: \{style.size.width}, padding: \{style.padding.top}, gap: \{style.gap.width}",
" radius: \{style.corner_radii.top_left} = \{style.corner_radii.top_left.to_pixels(rem_size)}",
" shadows: \{style.box_shadow.length()}",
" text: \{text.font_size.to_pixels(rem_size)} \{text.font_family}, line height \{line_height}px, color \{text.color.to_rgb()}",
"layout (logical px)",
" window \{show_bounds(engine.layout_bounds(root, scale_factor))}",
" card \{show_bounds(card_bounds)}",
" title \{show_bounds(title_bounds)}",
" body \{show_bounds(body_bounds)}",
"scene at \{scale_factor}x",
]
for batch in scene.batches() {
lines.push(" \{batch.label()}")
}
for quad in scene.quads {
lines.push( lines.push(
"clicked: expanded = \{state.expanded}, clicks = \{state.clicks}, frames = \{vcx.draw_count()}, dirty = \{vcx.window().is_dirty()}", " quad order \{quad.order}: \{quad.bounds.size.width.0} x \{quad.bounds.size.height.0} device px",
) )
describe("after click (hovered)", vcx.scene(), lines) }
lines.join("\n") lines.join("\n")
} }
+16 -18
View File
@@ -3,24 +3,22 @@ test "card report" {
inspect( inspect(
report(), report(),
content=( content=(
#|first frame #|card style
#| batches: quads (1), shadows (2), quads (4) #| display: Flex, direction: Column
#| quad (0, 0) 400 x 240 #| width: 320px, padding: 1rem, gap: 0.5rem
#| quad (40, 40) 320 x 62 #| radius: 0.5rem = 8px
#| quad (57, 57) 160 x 10 #| shadows: 2
#| quad (57, 75) 280 x 10 #| text: 14px .SystemUIFont, line height 23px, color #1f2328ff
#| quad (40, 40) 320 x 62 border #d0d7deff #|layout (logical px)
#|clicked: expanded = true, clicks = 1, frames = 3, dirty = false #| window (0px, 0px) 480px x 320px
#|after click (hovered) #| card (40px, 40px) 320px x 134px
#| batches: quads (1), shadows (2), quads (7) #| title (57px, 57px) 286px x 23px
#| quad (0, 0) 400 x 240 #| body (57px, 88px) 286px x 69px
#| quad (40, 40) 320 x 116 #|scene at 2x
#| quad (57, 57) 160 x 10 #| shadows (2)
#| quad (57, 75) 280 x 10 #| quads (1)
#| quad (57, 93) 280 x 10 #| underlines (1)
#| quad (57, 111) 280 x 10 #| quad order 1: 640 x 268 device px
#| quad (57, 129) 280 x 10
#| quad (40, 40) 320 x 116 border #0969daff
), ),
) )
} }
+3 -8
View File
@@ -2,14 +2,9 @@ import {
"experiments/gpui/geometry", "experiments/gpui/geometry",
"experiments/gpui/color", "experiments/gpui/color",
"experiments/gpui/scene", "experiments/gpui/scene",
"experiments/gpui/app", "experiments/gpui/style",
"experiments/gpui/window", "experiments/gpui/layout",
"experiments/gpui/elements", "moonbitlang/core/debug",
"experiments/gpui/platform/test" @test_platform,
} }
pkgtype(kind: "executable") pkgtype(kind: "executable")
options(
"allow-experimental-packages": true,
)
-1
View File
@@ -6,7 +6,6 @@ package "experiments/gpui/examples/card"
// Errors // Errors
// Types and methods // Types and methods
type Card
// Type aliases // Type aliases
-212
View File
@@ -1,212 +0,0 @@
// Input event types, ported from gpui/src/interactive.rs and the Modifiers of
// gpui/src/platform/keystroke.rs. Keyboard events and keystrokes come with
// the keymap milestone (M5).
///|
/// Modifier keys held during an event.
#derive(Eq, Hash, Default, Debug)
pub(all) struct Modifiers {
control : Bool
alt : Bool
shift : Bool
/// Command on macOS, Windows/Super elsewhere.
platform : Bool
/// The function (fn) key.
function : Bool
}
///|
/// Whether any modifier is held.
pub fn Modifiers::modified(self : Modifiers) -> Bool {
self.control || self.alt || self.shift || self.platform || self.function
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum NavigationDirection {
Back
Forward
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum MouseButton {
Left
Right
Middle
Navigate(NavigationDirection)
}
///|
pub impl Default for MouseButton with fn default() {
Left
}
///|
#derive(Eq, Default, Debug)
pub(all) struct MouseDownEvent {
button : MouseButton
position : @geometry.Point[@geometry.Pixels]
modifiers : Modifiers
click_count : Int32
first_mouse : Bool
}
///|
#derive(Eq, Default, Debug)
pub(all) struct MouseUpEvent {
button : MouseButton
position : @geometry.Point[@geometry.Pixels]
modifiers : Modifiers
click_count : Int32
}
///|
#derive(Eq, Default, Debug)
pub(all) struct MouseMoveEvent {
position : @geometry.Point[@geometry.Pixels]
/// The button held during the move, if any.
pressed_button : MouseButton?
modifiers : Modifiers
}
///|
/// How a scroll delta is expressed.
#derive(Eq, Debug)
pub(all) enum ScrollDelta {
/// Precise pixels (trackpads).
Pixels(@geometry.Point[@geometry.Pixels])
/// Lines (mouse wheels).
Lines(@geometry.Point[Double])
}
///|
#derive(Eq, Debug)
pub(all) struct ScrollWheelEvent {
position : @geometry.Point[@geometry.Pixels]
delta : ScrollDelta
modifiers : Modifiers
}
///|
/// Fired when the pointer leaves the window (GPUI: `MouseExitEvent`).
#derive(Eq, Default, Debug)
pub(all) struct MouseExitEvent {
position : @geometry.Point[@geometry.Pixels]
pressed_button : MouseButton?
modifiers : Modifiers
}
///|
/// Fired when the held modifier keys change (GPUI: `ModifiersChangedEvent`).
#derive(Eq, Default, Debug)
pub(all) struct ModifiersChangedEvent {
modifiers : Modifiers
}
///|
/// A mouse click: the down and up events of one press (GPUI:
/// `MouseClickEvent`).
#derive(Eq, Default, Debug)
pub(all) struct ClickEvent {
down : MouseDownEvent
up : MouseUpEvent
}
///|
/// Pointer input delivered to a window (GPUI: the mouse variants of
/// `PlatformInput`).
#derive(Eq, Debug)
pub(all) enum MouseEvent {
MouseDown(MouseDownEvent)
MouseUp(MouseUpEvent)
MouseMove(MouseMoveEvent)
ScrollWheel(ScrollWheelEvent)
}
///|
pub fn MouseEvent::position(
self : MouseEvent,
) -> @geometry.Point[@geometry.Pixels] {
match self {
MouseDown(e) => e.position
MouseUp(e) => e.position
MouseMove(e) => e.position
ScrollWheel(e) => e.position
}
}
///|
pub fn MouseEvent::modifiers(self : MouseEvent) -> Modifiers {
match self {
MouseDown(e) => e.modifiers
MouseUp(e) => e.modifiers
MouseMove(e) => e.modifiers
ScrollWheel(e) => e.modifiers
}
}
///|
pub fn MouseEvent::to_platform_input(self : MouseEvent) -> PlatformInput {
match self {
MouseDown(e) => MouseDown(e)
MouseUp(e) => MouseUp(e)
MouseMove(e) => MouseMove(e)
ScrollWheel(e) => ScrollWheel(e)
}
}
///|
/// Input events delivered by a platform window (GPUI: `PlatformInput`).
#derive(Eq, Debug)
pub(all) enum PlatformInput {
MouseDown(MouseDownEvent)
MouseUp(MouseUpEvent)
MouseMove(MouseMoveEvent)
MouseExited(MouseExitEvent)
ScrollWheel(ScrollWheelEvent)
ModifiersChanged(ModifiersChangedEvent)
}
///|
pub fn PlatformInput::modifiers(self : PlatformInput) -> Modifiers {
match self {
MouseDown(e) => e.modifiers
MouseUp(e) => e.modifiers
MouseMove(e) => e.modifiers
MouseExited(e) => e.modifiers
ScrollWheel(e) => e.modifiers
ModifiersChanged(e) => e.modifiers
}
}
///|
/// Extracts the mouse event if this input is one of the window-dispatched
/// pointer events (`MouseExited` and `ModifiersChanged` return `None`).
pub fn PlatformInput::mouse_event(self : PlatformInput) -> MouseEvent? {
match self {
MouseDown(e) => Some(MouseDown(e))
MouseUp(e) => Some(MouseUp(e))
MouseMove(e) => Some(MouseMove(e))
ScrollWheel(e) => Some(ScrollWheel(e))
MouseExited(_) | ModifiersChanged(_) => None
}
}
///|
/// Result of dispatching a `PlatformInput` to a window (GPUI:
/// `DispatchEventResult`).
#derive(Eq, Default, Debug)
pub(all) struct DispatchEventResult {
propagate : Bool
default_prevented : Bool
}
///|
/// Listeners run twice per event: capture (root to leaf), then bubble (leaf
/// to root) (GPUI: `DispatchPhase`).
#derive(Eq, Hash, Debug)
pub(all) enum DispatchPhase {
Capture
Bubble
}
-3
View File
@@ -1,3 +0,0 @@
import {
"experiments/gpui/geometry",
}
-131
View File
@@ -1,131 +0,0 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/input"
import {
"experiments/gpui/geometry",
"moonbitlang/core/debug",
}
// Values
// Errors
// Types and methods
#derive(Default, Eq, @debug.Debug)
pub(all) struct ClickEvent {
down : MouseDownEvent
up : MouseUpEvent
}
#derive(Default, Eq, @debug.Debug)
pub(all) struct DispatchEventResult {
propagate : Bool
default_prevented : Bool
}
#derive(Eq, Hash, @debug.Debug)
pub(all) enum DispatchPhase {
Capture
Bubble
}
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct Modifiers {
control : Bool
alt : Bool
shift : Bool
platform : Bool
function : Bool
}
pub fn Modifiers::modified(Self) -> Bool
#derive(Default, Eq, @debug.Debug)
pub(all) struct ModifiersChangedEvent {
modifiers : Modifiers
}
#derive(Eq, Hash, @debug.Debug)
pub(all) enum MouseButton {
Left
Right
Middle
Navigate(NavigationDirection)
}
pub impl Default for MouseButton
#derive(Default, Eq, @debug.Debug)
pub(all) struct MouseDownEvent {
button : MouseButton
position : @geometry.Point[@geometry.Pixels]
modifiers : Modifiers
click_count : Int32
first_mouse : Bool
}
#derive(Eq, @debug.Debug)
pub(all) enum MouseEvent {
MouseDown(MouseDownEvent)
MouseUp(MouseUpEvent)
MouseMove(MouseMoveEvent)
ScrollWheel(ScrollWheelEvent)
}
pub fn MouseEvent::modifiers(Self) -> Modifiers
pub fn MouseEvent::position(Self) -> @geometry.Point[@geometry.Pixels]
pub fn MouseEvent::to_platform_input(Self) -> PlatformInput
#derive(Default, Eq, @debug.Debug)
pub(all) struct MouseExitEvent {
position : @geometry.Point[@geometry.Pixels]
pressed_button : MouseButton?
modifiers : Modifiers
}
#derive(Default, Eq, @debug.Debug)
pub(all) struct MouseMoveEvent {
position : @geometry.Point[@geometry.Pixels]
pressed_button : MouseButton?
modifiers : Modifiers
}
#derive(Default, Eq, @debug.Debug)
pub(all) struct MouseUpEvent {
button : MouseButton
position : @geometry.Point[@geometry.Pixels]
modifiers : Modifiers
click_count : Int32
}
#derive(Eq, Hash, @debug.Debug)
pub(all) enum NavigationDirection {
Back
Forward
}
#derive(Eq, @debug.Debug)
pub(all) enum PlatformInput {
MouseDown(MouseDownEvent)
MouseUp(MouseUpEvent)
MouseMove(MouseMoveEvent)
MouseExited(MouseExitEvent)
ScrollWheel(ScrollWheelEvent)
ModifiersChanged(ModifiersChangedEvent)
}
pub fn PlatformInput::modifiers(Self) -> Modifiers
pub fn PlatformInput::mouse_event(Self) -> MouseEvent?
#derive(Eq, @debug.Debug)
pub(all) enum ScrollDelta {
Pixels(@geometry.Point[@geometry.Pixels])
Lines(@geometry.Point[Double])
}
#derive(Eq, @debug.Debug)
pub(all) struct ScrollWheelEvent {
position : @geometry.Point[@geometry.Pixels]
delta : ScrollDelta
modifiers : Modifiers
}
// Type aliases
// Traits
-13
View File
@@ -1,13 +0,0 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/scene",
"experiments/gpui/style",
"experiments/gpui/input",
"experiments/gpui/executor",
}
// experiments/gpui/executor uses MoonBit's experimental async intrinsics.
options(
"allow-experimental-packages": true,
)
-111
View File
@@ -1,111 +0,0 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/platform"
import {
"experiments/gpui/executor",
"experiments/gpui/geometry",
"experiments/gpui/input",
"experiments/gpui/scene",
"experiments/gpui/style",
"moonbitlang/core/debug",
}
// Values
// Errors
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) enum ClipboardEntry {
String(ClipboardString)
}
#derive(Eq, @debug.Debug)
pub(all) struct ClipboardItem {
entries : Array[ClipboardEntry]
}
pub fn ClipboardItem::metadata(Self) -> String?
pub fn ClipboardItem::new_string(String) -> Self
pub fn ClipboardItem::new_string_with_metadata(String, String) -> Self
pub fn ClipboardItem::text(Self) -> String?
#derive(Eq, @debug.Debug)
pub(all) struct ClipboardString {
text : String
metadata : String?
}
pub fn ClipboardString::new(String) -> Self
pub fn ClipboardString::new_with_metadata(String, String) -> Self
#derive(Eq, @debug.Debug)
pub(all) enum WindowBounds {
Windowed(@geometry.Bounds[@geometry.Pixels])
Maximized(@geometry.Bounds[@geometry.Pixels])
Fullscreen(@geometry.Bounds[@geometry.Pixels])
}
pub fn WindowBounds::get_bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
pub impl Default for WindowBounds
#derive(Compare, Eq, Hash, @debug.Debug)
pub(all) struct WindowId(Int32)
pub impl Show for WindowId
#derive(Eq, @debug.Debug)
pub(all) struct WindowOptions {
window_bounds : WindowBounds?
title : String?
focus : Bool
show : Bool
scale_factor : Double?
rem_size : @geometry.Pixels
}
pub fn WindowOptions::with_size(@geometry.Size[@geometry.Pixels], scale_factor? : Double, title? : String, rem_size? : @geometry.Pixels) -> Self
pub impl Default for WindowOptions
#derive(Eq, @debug.Debug)
pub(all) struct WindowParams {
bounds : @geometry.Bounds[@geometry.Pixels]
title : String?
focus : Bool
show : Bool
scale_factor : Double?
}
// Type aliases
// Traits
pub(open) trait Platform {
fn dispatcher(Self) -> &@executor.Dispatcher
fn default_window_bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
fn open_window(Self, WindowId, WindowParams) -> &PlatformWindow
fn run(Self, () -> Unit) -> Unit
fn quit(Self) -> Unit
fn active_window(Self) -> WindowId?
fn set_cursor_style(Self, @style.CursorStyle) -> Unit
fn read_from_clipboard(Self) -> ClipboardItem?
fn write_to_clipboard(Self, ClipboardItem) -> Unit
fn open_url(Self, String) -> Unit
}
pub(open) trait PlatformWindow {
fn bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
fn content_size(Self) -> @geometry.Size[@geometry.Pixels]
fn scale_factor(Self) -> Double
fn mouse_position(Self) -> @geometry.Point[@geometry.Pixels]
fn modifiers(Self) -> @input.Modifiers
fn is_active(Self) -> Bool
fn is_hovered(Self) -> Bool
fn set_title(Self, String) -> Unit
fn activate(Self) -> Unit
fn resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit
fn draw(Self, @scene.Scene) -> Unit
fn schedule_frame(Self) -> Unit
fn close(Self) -> Unit
fn on_request_frame(Self, () -> Unit) -> Unit
fn on_input(Self, (@input.PlatformInput) -> @input.DispatchEventResult) -> Unit
fn on_resize(Self, (@geometry.Size[@geometry.Pixels], Double) -> Unit) -> Unit
fn on_active_status_change(Self, (Bool) -> Unit) -> Unit
fn on_hover_status_change(Self, (Bool) -> Unit) -> Unit
fn on_should_close(Self, () -> Bool) -> Unit
fn on_close(Self, () -> Unit) -> Unit
}
-83
View File
@@ -1,83 +0,0 @@
// Platform interfaces, ported from gpui/src/platform.rs (the core subset:
// windows, event loop, executor dispatcher, cursor and clipboard; text
// system, glyph atlas, IME, menus and displays arrive in M9/M10).
//
// Pure trait definitions only; concrete backends live in `platform/test`
// (M7) and `platform/web` (M8).
///|
/// A platform-backed window handle (GPUI: `PlatformWindow`).
pub(open) trait PlatformWindow {
/// Window bounds in logical pixels.
fn bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
/// Size of the drawable content area in logical pixels.
fn content_size(Self) -> @geometry.Size[@geometry.Pixels]
/// Device-pixel scale factor.
fn scale_factor(Self) -> Double
/// Last known pointer position in logical pixels.
fn mouse_position(Self) -> @geometry.Point[@geometry.Pixels]
/// Currently held modifier keys.
fn modifiers(Self) -> @input.Modifiers
/// Whether this window is currently active/focused.
fn is_active(Self) -> Bool
/// Whether the pointer is currently over this window.
fn is_hovered(Self) -> Bool
/// Sets the window's title.
fn set_title(Self, String) -> Unit
/// Focuses/brings this window to the front.
fn activate(Self) -> Unit
/// Programmatically resizes the window to `size`. Must not re-enter
/// `on_resize`.
fn resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit
/// Presents a finished `Scene`.
fn draw(Self, @scene.Scene) -> Unit
/// Requests that the platform invoke the `on_request_frame` callback on
/// the next frame.
fn schedule_frame(Self) -> Unit
/// App-driven teardown hook (MoonBit has no `Drop`). Must be idempotent
/// and must not re-invoke `on_close`.
fn close(Self) -> Unit
/// Registers the callback invoked when a scheduled frame should draw.
fn on_request_frame(Self, () -> Unit) -> Unit
/// Registers the callback invoked for platform input events.
fn on_input(Self, (@input.PlatformInput) -> @input.DispatchEventResult) -> Unit
/// Registers the callback invoked when the window size or scale factor
/// changes from the platform side.
fn on_resize(Self, (@geometry.Size[@geometry.Pixels], Double) -> Unit) -> Unit
/// Registers the callback invoked when active status changes.
fn on_active_status_change(Self, (Bool) -> Unit) -> Unit
/// Registers the callback invoked when pointer hover status changes.
fn on_hover_status_change(Self, (Bool) -> Unit) -> Unit
/// Registers the callback asked whether a user-initiated close should
/// proceed.
fn on_should_close(Self, () -> Bool) -> Unit
/// Registers the callback invoked when the platform closes the window.
fn on_close(Self, () -> Unit) -> Unit
}
///|
/// Platform services (GPUI: `Platform`).
pub(open) trait Platform {
/// The dispatcher used by the app's executors.
fn dispatcher(Self) -> &@executor.Dispatcher
/// Default logical bounds for a new window when `WindowOptions.window_bounds`
/// is `None`.
fn default_window_bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
/// Opens a new platform window with the given id and parameters.
fn open_window(Self, WindowId, WindowParams) -> &PlatformWindow
/// Starts the platform event loop, calling `on_finish_launching` once
/// ready.
fn run(Self, () -> Unit) -> Unit
/// Requests that the platform event loop exit.
fn quit(Self) -> Unit
/// The currently active window id, if any.
fn active_window(Self) -> WindowId?
/// Sets the pointer cursor style.
fn set_cursor_style(Self, @style.CursorStyle) -> Unit
/// Reads the current clipboard contents, if any.
fn read_from_clipboard(Self) -> ClipboardItem?
/// Replaces the clipboard contents.
fn write_to_clipboard(Self, ClipboardItem) -> Unit
/// Opens `url` in the system/browser handler.
fn open_url(Self, String) -> Unit
}
-70
View File
@@ -1,70 +0,0 @@
///|
test "WindowBounds get_bounds extracts bounds across variants" {
let b = @geometry.bounds(
@geometry.point(@geometry.px(10.0), @geometry.px(20.0)),
@geometry.size(@geometry.px(800.0), @geometry.px(600.0)),
)
assert_eq(@platform.WindowBounds::Windowed(b).get_bounds(), b)
assert_eq(@platform.WindowBounds::Maximized(b).get_bounds(), b)
assert_eq(@platform.WindowBounds::Fullscreen(b).get_bounds(), b)
assert_eq(
(Default::default() : @platform.WindowBounds),
@platform.WindowBounds::Windowed(Default::default()),
)
}
///|
test "WindowOptions default and with_size" {
let defaults : @platform.WindowOptions = Default::default()
assert_eq(defaults.window_bounds, None)
assert_eq(defaults.title, None)
assert_true(defaults.focus)
assert_true(defaults.show)
assert_eq(defaults.scale_factor, None)
assert_eq(defaults.rem_size, @geometry.px(16.0))
let opts = @platform.WindowOptions::with_size(
@geometry.size(@geometry.px(640.0), @geometry.px(480.0)),
scale_factor=2.0,
title="Demo",
rem_size=@geometry.px(14.0),
)
assert_eq(
opts.window_bounds,
Some(
@platform.WindowBounds::Windowed(
@geometry.bounds(
@geometry.point(@geometry.px(0.0), @geometry.px(0.0)),
@geometry.size(@geometry.px(640.0), @geometry.px(480.0)),
),
),
),
)
assert_eq(opts.scale_factor, Some(2.0))
assert_eq(opts.title, Some("Demo"))
assert_eq(opts.rem_size, @geometry.px(14.0))
}
///|
test "ClipboardItem text and metadata" {
let plain = @platform.ClipboardItem::new_string("hello")
assert_eq(plain.text(), Some("hello"))
assert_eq(plain.metadata(), None)
let with_meta = @platform.ClipboardItem::new_string_with_metadata(
"code", "rust",
)
assert_eq(with_meta.text(), Some("code"))
assert_eq(with_meta.metadata(), Some("rust"))
let multi : @platform.ClipboardItem = {
entries: [
@platform.ClipboardEntry::String(
@platform.ClipboardString::new_with_metadata("first", "m1"),
),
@platform.ClipboardEntry::String(@platform.ClipboardString::new("second")),
],
}
assert_eq(multi.text(), Some("first\nsecond"))
assert_eq(multi.metadata(), Some("m1"))
let empty : @platform.ClipboardItem = { entries: [], }
assert_eq(empty.text(), None)
assert_eq(empty.metadata(), None)
}
-20
View File
@@ -1,20 +0,0 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/scene",
"experiments/gpui/style",
"experiments/gpui/input",
"experiments/gpui/executor",
"experiments/gpui/app",
"experiments/gpui/platform",
"experiments/gpui/window",
}
// experiments/gpui/executor uses MoonBit's experimental async intrinsics.
options(
"allow-experimental-packages": true,
)
import {
"experiments/gpui/color",
} for "test"
-147
View File
@@ -1,147 +0,0 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/platform/test"
import {
"experiments/gpui/app",
"experiments/gpui/executor",
"experiments/gpui/geometry",
"experiments/gpui/input",
"experiments/gpui/platform",
"experiments/gpui/scene",
"experiments/gpui/style",
"experiments/gpui/window",
}
// Values
// Errors
// Types and methods
pub struct TestAppContext {
platform : TestPlatform
application : @window.Application
// private fields
}
pub fn TestAppContext::active_window(Self) -> @window.AnyWindowHandle?
pub fn TestAppContext::add_empty_window(Self, size? : @geometry.Size[@geometry.Pixels], scale_factor? : Double) -> VisualTestContext
pub fn[V : @window.Render] TestAppContext::add_window(Self, size? : @geometry.Size[@geometry.Pixels], scale_factor? : Double, title? : String, (@window.Window, @app.Context[V]) -> V) -> @window.WindowHandle[V]
pub fn[V : @window.Render] TestAppContext::add_window_view(Self, size? : @geometry.Size[@geometry.Pixels], scale_factor? : Double, title? : String, (@window.Window, @app.Context[V]) -> V) -> (@app.Entity[V], VisualTestContext)
pub fn TestAppContext::advance_clock(Self, Int32) -> Unit
pub fn TestAppContext::app(Self) -> @app.App
pub fn TestAppContext::application(Self) -> @window.Application
pub fn TestAppContext::background_executor(Self) -> @executor.Executor
pub fn TestAppContext::cursor_style(Self) -> @style.CursorStyle
pub fn TestAppContext::dispatcher(Self) -> @executor.TestDispatcher
pub fn TestAppContext::foreground_executor(Self) -> @executor.Executor
pub fn[G] TestAppContext::has_global(Self, @app.GlobalKey[G]) -> Bool
pub fn TestAppContext::new(default_bounds? : @geometry.Bounds[@geometry.Pixels], default_scale_factor? : Double) -> Self
pub fn[T] TestAppContext::new_entity(Self, (@app.Context[T]) -> T) -> @app.Entity[T]
pub fn[V : @window.Render] TestAppContext::open_window(Self, options? : @platform.WindowOptions, (@window.Window, @app.App) -> @app.Entity[V]) -> @window.WindowHandle[V]
pub fn TestAppContext::opened_url(Self) -> String?
pub fn TestAppContext::platform(Self) -> TestPlatform
pub fn TestAppContext::pump_frames(Self) -> Int32
pub fn TestAppContext::quit(Self) -> Unit
pub fn[R] TestAppContext::read(Self, (@app.App) -> R) -> R
pub fn[T] TestAppContext::read_entity(Self, @app.Entity[T]) -> T
pub fn TestAppContext::read_from_clipboard(Self) -> @platform.ClipboardItem?
pub fn[G] TestAppContext::read_global(Self, @app.GlobalKey[G]) -> G
pub fn TestAppContext::refresh(Self) -> Unit
pub fn TestAppContext::run_until_parked(Self) -> Unit
pub fn[G] TestAppContext::set_global(Self, @app.GlobalKey[G], G) -> Unit
pub fn TestAppContext::skip_drawing(Self, skip? : Bool) -> Unit
pub fn[R] TestAppContext::spawn(Self, async (@app.AsyncApp) -> R) -> @executor.Task[R]
pub fn TestAppContext::test_window(Self, @window.AnyWindowHandle) -> TestWindow
pub fn[R] TestAppContext::update(Self, (@app.App) -> R) -> R
pub fn[T, R] TestAppContext::update_entity(Self, @app.Entity[T], (T, @app.Context[T]) -> R) -> R
pub fn[G, R] TestAppContext::update_global(Self, @app.GlobalKey[G], (G, @app.App) -> R) -> R
pub fn TestAppContext::windows(Self) -> Array[@window.AnyWindowHandle]
pub fn TestAppContext::with_platform(TestPlatform) -> Self
pub fn TestAppContext::write_to_clipboard(Self, @platform.ClipboardItem) -> Unit
pub struct TestPlatform {
// private fields
}
pub fn TestPlatform::cursor_style(Self) -> @style.CursorStyle
pub fn TestPlatform::did_quit(Self) -> Bool
pub fn TestPlatform::did_run(Self) -> Bool
pub fn TestPlatform::new(dispatcher? : @executor.TestDispatcher, default_bounds? : @geometry.Bounds[@geometry.Pixels], default_scale_factor? : Double) -> Self
pub fn TestPlatform::opened_url(Self) -> String?
pub fn TestPlatform::opened_urls(Self) -> Array[String]
pub fn TestPlatform::pump_scheduled_frames(Self) -> Int32
pub fn TestPlatform::set_active_window(Self, TestWindow?) -> Unit
pub fn TestPlatform::test_dispatcher(Self) -> @executor.TestDispatcher
pub fn TestPlatform::window(Self, @platform.WindowId) -> TestWindow?
pub fn TestPlatform::windows(Self) -> Array[TestWindow]
pub impl @platform.Platform for TestPlatform
pub struct TestWindow {
// private fields
}
pub fn TestWindow::clear_drawn_scenes(Self) -> Unit
pub fn TestWindow::draw_count(Self) -> Int32
pub fn TestWindow::drawn_scenes(Self) -> Array[@scene.Scene]
pub fn TestWindow::frame_schedule_count(Self) -> Int32
pub fn TestWindow::frame_scheduled(Self) -> Bool
pub fn TestWindow::is_closed(Self) -> Bool
pub fn TestWindow::last_scene(Self) -> @scene.Scene?
pub fn TestWindow::simulate_active_status_change(Self, Bool) -> Unit
pub fn TestWindow::simulate_close(Self) -> Unit
pub fn TestWindow::simulate_close_requested(Self) -> Bool
pub fn TestWindow::simulate_frame_request(Self) -> Unit
pub fn TestWindow::simulate_hover_status_change(Self, Bool) -> Unit
pub fn TestWindow::simulate_input(Self, @input.PlatformInput) -> @input.DispatchEventResult
pub fn TestWindow::simulate_resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit
pub fn TestWindow::simulate_scale_factor_change(Self, Double) -> Unit
pub fn TestWindow::simulate_scheduled_frame(Self) -> Bool
pub fn TestWindow::simulate_should_close(Self) -> Bool
pub fn TestWindow::title(Self) -> String?
pub fn TestWindow::window_id(Self) -> @platform.WindowId
pub impl @platform.PlatformWindow for TestWindow
pub struct VisualTestContext {
cx : TestAppContext
window_handle : @window.AnyWindowHandle
}
pub fn VisualTestContext::advance_clock(Self, Int32) -> Unit
pub fn VisualTestContext::app(Self) -> @app.App
pub fn VisualTestContext::bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
pub fn VisualTestContext::cursor_style(Self) -> @style.CursorStyle
pub fn VisualTestContext::draw(Self) -> @scene.Scene
pub fn VisualTestContext::draw_count(Self) -> Int32
pub fn VisualTestContext::drawn_scenes(Self) -> Array[@scene.Scene]
pub fn VisualTestContext::from_window(@window.AnyWindowHandle, TestAppContext) -> Self
pub fn VisualTestContext::is_active(Self) -> Bool
pub fn VisualTestContext::is_closed(Self) -> Bool
pub fn VisualTestContext::is_hovered(Self) -> Bool
pub fn[T] VisualTestContext::new_entity(Self, (@app.Context[T]) -> T) -> @app.Entity[T]
pub fn[R] VisualTestContext::read(Self, (@app.App) -> R) -> R
pub fn VisualTestContext::read_from_clipboard(Self) -> @platform.ClipboardItem?
pub fn[V : @window.Render] VisualTestContext::replace_root_view(Self, (@window.Window, @app.Context[V]) -> V) -> @app.Entity[V]
pub fn VisualTestContext::run_until_parked(Self) -> Unit
pub fn VisualTestContext::scale_factor(Self) -> Double
pub fn VisualTestContext::scene(Self) -> @scene.Scene
pub fn VisualTestContext::simulate_active_status_change(Self, Bool) -> Unit
pub fn VisualTestContext::simulate_click(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers) -> Unit
pub fn VisualTestContext::simulate_close(Self) -> Bool
pub fn VisualTestContext::simulate_hover_status_change(Self, Bool) -> Unit
pub fn VisualTestContext::simulate_input(Self, @input.PlatformInput) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_modifiers_change(Self, @input.Modifiers) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_mouse_down(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers, click_count? : Int32) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_mouse_exit(Self, position? : @geometry.Point[@geometry.Pixels], modifiers? : @input.Modifiers) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_mouse_move(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_mouse_up(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers, click_count? : Int32) -> @input.DispatchEventResult
pub fn VisualTestContext::simulate_resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit
pub fn VisualTestContext::simulate_scale_factor_change(Self, Double) -> Unit
pub fn VisualTestContext::simulate_scroll_wheel(Self, @geometry.Point[@geometry.Pixels], @input.ScrollDelta, modifiers? : @input.Modifiers) -> @input.DispatchEventResult
pub fn VisualTestContext::test_window(Self) -> TestWindow
pub fn[R] VisualTestContext::update(Self, (@window.Window, @app.App) -> R) -> R
pub fn[T, R] VisualTestContext::update_entity(Self, @app.Entity[T], (T, @app.Context[T]) -> R) -> R
pub fn VisualTestContext::window(Self) -> @window.Window
pub fn VisualTestContext::window_handle(Self) -> @window.AnyWindowHandle
pub fn VisualTestContext::window_id(Self) -> @platform.WindowId
pub fn VisualTestContext::window_title(Self) -> String?
pub fn VisualTestContext::write_to_clipboard(Self, @platform.ClipboardItem) -> Unit
// Type aliases
// Traits
-224
View File
@@ -1,224 +0,0 @@
// Headless test platform, ported from gpui/src/platform/test/platform.rs.
///|
let default_test_bounds : @geometry.Bounds[@geometry.Pixels] = @geometry.bounds(
@geometry.point(@geometry.px(0.0), @geometry.px(0.0)),
@geometry.size(@geometry.px(1024.0), @geometry.px(768.0)),
)
///|
/// A headless `Platform` backed by `TestDispatcher` and `TestWindow`s
/// (GPUI: `TestPlatform`).
pub struct TestPlatform {
priv dispatcher : @executor.TestDispatcher
priv default_bounds : @geometry.Bounds[@geometry.Pixels]
priv default_scale_factor : Double
priv windows : Map[@platform.WindowId, TestWindow]
priv mut active_window : TestWindow?
priv mut active_cursor : @style.CursorStyle
priv mut clipboard : @platform.ClipboardItem?
priv opened_urls : Array[String]
priv mut run_called : Bool
priv mut quit_called : Bool
}
///|
pub fn TestPlatform::new(
dispatcher? : @executor.TestDispatcher,
default_bounds? : @geometry.Bounds[@geometry.Pixels],
default_scale_factor~ : Double = 1.0,
) -> TestPlatform {
{
dispatcher: dispatcher.unwrap_or(@executor.TestDispatcher::new()),
default_bounds: default_bounds.unwrap_or(default_test_bounds),
default_scale_factor,
windows: {},
active_window: None,
active_cursor: Arrow,
clipboard: None,
opened_urls: [],
run_called: false,
quit_called: false,
}
}
///|
pub impl @platform.Platform for TestPlatform with fn dispatcher(self) {
let d : &@executor.Dispatcher = self.dispatcher
d
}
///|
pub impl @platform.Platform for TestPlatform with fn default_window_bounds(self) {
self.default_bounds
}
///|
pub impl @platform.Platform for TestPlatform with fn open_window(
self,
id,
params,
) {
let window = TestWindow::new(id, self, params, self.default_scale_factor)
self.windows[id] = window
if params.focus {
let previous = self.active_window
self.active_window = Some(window)
if previous is Some(prev) && prev.id != id {
@executor.Dispatcher::dispatch(self.dispatcher, fn() {
if !prev.closed {
prev.simulate_active_status_change(false)
}
})
}
}
let pw : &@platform.PlatformWindow = window
pw
}
///|
pub impl @platform.Platform for TestPlatform with fn run(
self,
on_finish_launching,
) {
self.run_called = true
on_finish_launching()
}
///|
pub impl @platform.Platform for TestPlatform with fn quit(self) {
self.quit_called = true
}
///|
pub impl @platform.Platform for TestPlatform with fn active_window(self) {
match self.active_window {
Some(win) if !win.closed => Some(win.id)
_ => None
}
}
///|
pub impl @platform.Platform for TestPlatform with fn set_cursor_style(
self,
style,
) {
self.active_cursor = style
}
///|
pub impl @platform.Platform for TestPlatform with fn read_from_clipboard(self) {
self.clipboard
}
///|
pub impl @platform.Platform for TestPlatform with fn write_to_clipboard(
self,
item,
) {
self.clipboard = Some(item)
}
///|
pub impl @platform.Platform for TestPlatform with fn open_url(self, url) {
self.opened_urls.push(url)
}
// ---------------------------------------------------------------------------
// Inspection and simulation helpers
// ---------------------------------------------------------------------------
///|
pub fn TestPlatform::test_dispatcher(
self : TestPlatform,
) -> @executor.TestDispatcher {
self.dispatcher
}
///|
pub fn TestPlatform::window(
self : TestPlatform,
id : @platform.WindowId,
) -> TestWindow? {
self.windows.get(id)
}
///|
pub fn TestPlatform::windows(self : TestPlatform) -> Array[TestWindow] {
let out = []
for _, win in self.windows {
out.push(win)
}
out
}
///|
pub fn TestPlatform::cursor_style(self : TestPlatform) -> @style.CursorStyle {
self.active_cursor
}
///|
pub fn TestPlatform::opened_url(self : TestPlatform) -> String? {
self.opened_urls.last()
}
///|
pub fn TestPlatform::opened_urls(self : TestPlatform) -> Array[String] {
self.opened_urls
}
///|
pub fn TestPlatform::did_run(self : TestPlatform) -> Bool {
self.run_called
}
///|
pub fn TestPlatform::did_quit(self : TestPlatform) -> Bool {
self.quit_called
}
///|
/// Transfers active window status, notifying the previous and new windows on
/// the dispatcher (GPUI: `TestPlatform::set_active_window`).
pub fn TestPlatform::set_active_window(
self : TestPlatform,
window : TestWindow?,
) -> Unit {
let previous = self.active_window
self.active_window = window
let same = match (previous, window) {
(Some(prev), Some(curr)) => prev.id == curr.id
(None, None) => true
_ => false
}
if same {
return
}
@executor.Dispatcher::dispatch(self.dispatcher, fn() {
if previous is Some(prev) && !prev.closed {
prev.simulate_active_status_change(false)
}
if window is Some(win) && !win.closed {
win.simulate_active_status_change(true)
}
})
}
///|
/// Delivers one scheduled frame for every open window that currently has a
/// frame scheduled, returning how many frames ran.
pub fn TestPlatform::pump_scheduled_frames(self : TestPlatform) -> Int32 {
let open = []
for _, win in self.windows {
if !win.closed && win.frame_scheduled {
open.push(win)
}
}
let mut pumped : Int32 = 0
for win in open {
if win.simulate_scheduled_frame() {
pumped = pumped + 1
}
}
pumped
}
-646
View File
@@ -1,646 +0,0 @@
// High-level test harnesses, ported from gpui/src/app/test_context.rs
// (`TestAppContext` and `VisualTestContext`).
///|
priv enum EmptyView {
EmptyView
}
///|
impl @window.Render for EmptyView with fn render(_self, _window, _cx) {
@window.empty()
}
///|
/// Owns a `TestPlatform` and `Application`, pumping tasks and scheduled
/// frames together for deterministic integration tests (GPUI:
/// `TestAppContext`).
pub struct TestAppContext {
platform : TestPlatform
application : @window.Application
priv mut skip_drawing : Bool
}
///|
pub fn TestAppContext::new(
default_bounds? : @geometry.Bounds[@geometry.Pixels],
default_scale_factor~ : Double = 1.0,
) -> TestAppContext {
let platform = TestPlatform::new(default_bounds?, default_scale_factor~)
TestAppContext::with_platform(platform)
}
///|
pub fn TestAppContext::with_platform(platform : TestPlatform) -> TestAppContext {
let p : &@platform.Platform = platform
let application = @window.Application::with_platform(p)
{ platform, application, skip_drawing: false, }
}
///|
pub fn TestAppContext::app(self : TestAppContext) -> @app.App {
self.application.app()
}
///|
pub fn TestAppContext::application(
self : TestAppContext,
) -> @window.Application {
self.application
}
///|
pub fn TestAppContext::platform(self : TestAppContext) -> TestPlatform {
self.platform
}
///|
pub fn TestAppContext::dispatcher(
self : TestAppContext,
) -> @executor.TestDispatcher {
self.platform.test_dispatcher()
}
///|
pub fn TestAppContext::foreground_executor(
self : TestAppContext,
) -> @executor.Executor {
self.application.app().foreground_executor()
}
///|
pub fn TestAppContext::background_executor(
self : TestAppContext,
) -> @executor.Executor {
self.application.app().background_executor()
}
///|
pub fn TestAppContext::windows(
self : TestAppContext,
) -> Array[@window.AnyWindowHandle] {
self.application.windows()
}
///|
pub fn TestAppContext::active_window(
self : TestAppContext,
) -> @window.AnyWindowHandle? {
self.application.active_window()
}
///|
pub fn TestAppContext::test_window(
self : TestAppContext,
handle : @window.AnyWindowHandle,
) -> TestWindow {
match self.platform.window(handle.window_id()) {
Some(win) => win
None => abort("no TestWindow for \{handle.window_id()}")
}
}
///|
/// Disables (or re-enables) automatic frame pumping in `run_until_parked`
/// (GPUI: `TestAppContext::skip_drawing`).
pub fn TestAppContext::skip_drawing(
self : TestAppContext,
skip~ : Bool = true,
) -> Unit {
self.skip_drawing = skip
}
///|
pub fn TestAppContext::pump_frames(self : TestAppContext) -> Int32 {
self.platform.pump_scheduled_frames()
}
///|
/// Drains all ready tasks and pumps scheduled frames until neither tasks nor
/// scheduled frames remain (GPUI: `TestAppContext::run_until_parked`). Aborts
/// after 100 frame pump passes to catch runaway redraw loops.
pub fn TestAppContext::run_until_parked(self : TestAppContext) -> Unit {
let max_passes = 100
let mut passes = 0
while true {
self.platform.test_dispatcher().run_until_parked()
if self.skip_drawing {
break
}
let pumped = self.platform.pump_scheduled_frames()
if pumped == 0 {
break
}
passes = passes + 1
if passes >= max_passes {
abort(
"TestAppContext::run_until_parked: runaway redraw loop (> \{max_passes} frame pumps)",
)
}
}
}
///|
/// Advances the virtual clock by `ms`, running timers, tasks and scheduled
/// frames (GPUI: `TestAppContext::advance_clock`).
pub fn TestAppContext::advance_clock(self : TestAppContext, ms : Int32) -> Unit {
self.run_until_parked()
self.platform.test_dispatcher().advance_clock(ms)
self.run_until_parked()
}
///|
pub fn[R] TestAppContext::update(
self : TestAppContext,
f : (@app.App) -> R,
) -> R {
let result = self.application.app().update(f)
self.run_until_parked()
result
}
///|
pub fn[R] TestAppContext::read(self : TestAppContext, f : (@app.App) -> R) -> R {
f(self.application.app())
}
///|
pub fn[T] TestAppContext::new_entity(
self : TestAppContext,
build : (@app.Context[T]) -> T,
) -> @app.Entity[T] {
self.update(fn(app) { app.new_entity(build) })
}
///|
pub fn[T, R] TestAppContext::update_entity(
self : TestAppContext,
entity : @app.Entity[T],
f : (T, @app.Context[T]) -> R,
) -> R {
self.update(fn(app) { app.update_entity(entity, f) })
}
///|
pub fn[T] TestAppContext::read_entity(
self : TestAppContext,
entity : @app.Entity[T],
) -> T {
self.application.app().read_entity(entity)
}
///|
pub fn[R] TestAppContext::spawn(
self : TestAppContext,
f : async (@app.AsyncApp) -> R,
) -> @executor.Task[R] {
self.application.app().spawn(f)
}
///|
pub fn[G] TestAppContext::set_global(
self : TestAppContext,
key : @app.GlobalKey[G],
value : G,
) -> Unit {
self.update(fn(app) { app.set_global(key, value) })
}
///|
pub fn[G] TestAppContext::read_global(
self : TestAppContext,
key : @app.GlobalKey[G],
) -> G {
self.application.app().global(key)
}
///|
pub fn[G] TestAppContext::has_global(
self : TestAppContext,
key : @app.GlobalKey[G],
) -> Bool {
self.application.app().has_global(key)
}
///|
pub fn[G, R] TestAppContext::update_global(
self : TestAppContext,
key : @app.GlobalKey[G],
f : (G, @app.App) -> R,
) -> R {
self.update(fn(app) { app.update_global(key, f) })
}
///|
pub fn TestAppContext::write_to_clipboard(
self : TestAppContext,
item : @platform.ClipboardItem,
) -> Unit {
self.application.write_to_clipboard(item)
}
///|
pub fn TestAppContext::read_from_clipboard(
self : TestAppContext,
) -> @platform.ClipboardItem? {
self.application.read_from_clipboard()
}
///|
pub fn TestAppContext::cursor_style(
self : TestAppContext,
) -> @style.CursorStyle {
self.platform.cursor_style()
}
///|
pub fn TestAppContext::opened_url(self : TestAppContext) -> String? {
self.platform.opened_url()
}
///|
pub fn TestAppContext::refresh(self : TestAppContext) -> Unit {
self.application.refresh_windows()
self.run_until_parked()
}
///|
pub fn TestAppContext::quit(self : TestAppContext) -> Unit {
self.application.quit()
}
///|
pub fn[V : @window.Render] TestAppContext::open_window(
self : TestAppContext,
options? : @platform.WindowOptions,
build_root : (@window.Window, @app.App) -> @app.Entity[V],
) -> @window.WindowHandle[V] {
let opts = options.unwrap_or(Default::default())
let handle = self.application.open_window(opts, build_root)
self.run_until_parked()
handle
}
///|
pub fn[V : @window.Render] TestAppContext::add_window(
self : TestAppContext,
size? : @geometry.Size[@geometry.Pixels],
scale_factor? : Double,
title? : String,
build_view : (@window.Window, @app.Context[V]) -> V,
) -> @window.WindowHandle[V] {
let options : @platform.WindowOptions = match size {
Some(s) => @platform.WindowOptions::with_size(s, scale_factor?, title?)
None => { ..Default::default(), scale_factor, title, }
}
self.open_window(options~, fn(window, app) {
app.new_entity(fn(cx) { build_view(window, cx) })
})
}
///|
pub fn[V : @window.Render] TestAppContext::add_window_view(
self : TestAppContext,
size? : @geometry.Size[@geometry.Pixels],
scale_factor? : Double,
title? : String,
build_view : (@window.Window, @app.Context[V]) -> V,
) -> (@app.Entity[V], VisualTestContext) {
let handle = self.add_window(size?, scale_factor?, title?, build_view)
let vcx = VisualTestContext::from_window(handle.to_any(), self)
(handle.entity(), vcx)
}
///|
pub fn TestAppContext::add_empty_window(
self : TestAppContext,
size? : @geometry.Size[@geometry.Pixels],
scale_factor? : Double,
) -> VisualTestContext {
let (_, vcx) = self.add_window_view(size?, scale_factor?, fn(_, _) {
EmptyView::EmptyView
})
vcx
}
// ---------------------------------------------------------------------------
// VisualTestContext
// ---------------------------------------------------------------------------
///|
/// Window-scoped test driver combining a `TestAppContext` with one
/// `AnyWindowHandle` (GPUI: `VisualTestContext`).
pub struct VisualTestContext {
cx : TestAppContext
window_handle : @window.AnyWindowHandle
}
///|
pub fn VisualTestContext::from_window(
window_handle : @window.AnyWindowHandle,
cx : TestAppContext,
) -> VisualTestContext {
{ cx, window_handle, }
}
///|
pub fn VisualTestContext::window_handle(
self : VisualTestContext,
) -> @window.AnyWindowHandle {
self.window_handle
}
///|
pub fn VisualTestContext::window_id(
self : VisualTestContext,
) -> @platform.WindowId {
self.window_handle.window_id()
}
///|
pub fn VisualTestContext::app(self : VisualTestContext) -> @app.App {
self.cx.app()
}
///|
pub fn VisualTestContext::test_window(self : VisualTestContext) -> TestWindow {
self.cx.test_window(self.window_handle)
}
///|
pub fn VisualTestContext::window(self : VisualTestContext) -> @window.Window {
match self.cx.application.window(self.window_id()) {
Some(win) => win
None => abort("window \{self.window_id()} is closed")
}
}
///|
pub fn VisualTestContext::is_closed(self : VisualTestContext) -> Bool {
self.test_window().is_closed()
}
///|
pub fn VisualTestContext::window_title(self : VisualTestContext) -> String? {
self.test_window().title()
}
///|
pub fn VisualTestContext::is_active(self : VisualTestContext) -> Bool {
@platform.PlatformWindow::is_active(self.test_window())
}
///|
pub fn VisualTestContext::is_hovered(self : VisualTestContext) -> Bool {
@platform.PlatformWindow::is_hovered(self.test_window())
}
///|
pub fn VisualTestContext::bounds(
self : VisualTestContext,
) -> @geometry.Bounds[@geometry.Pixels] {
@platform.PlatformWindow::bounds(self.test_window())
}
///|
pub fn VisualTestContext::scale_factor(self : VisualTestContext) -> Double {
@platform.PlatformWindow::scale_factor(self.test_window())
}
///|
pub fn VisualTestContext::cursor_style(
self : VisualTestContext,
) -> @style.CursorStyle {
self.cx.cursor_style()
}
///|
pub fn VisualTestContext::write_to_clipboard(
self : VisualTestContext,
item : @platform.ClipboardItem,
) -> Unit {
self.cx.write_to_clipboard(item)
}
///|
pub fn VisualTestContext::read_from_clipboard(
self : VisualTestContext,
) -> @platform.ClipboardItem? {
self.cx.read_from_clipboard()
}
///|
pub fn VisualTestContext::run_until_parked(self : VisualTestContext) -> Unit {
self.cx.run_until_parked()
}
///|
pub fn VisualTestContext::advance_clock(
self : VisualTestContext,
ms : Int32,
) -> Unit {
self.cx.advance_clock(ms)
}
///|
pub fn[R] VisualTestContext::update(
self : VisualTestContext,
f : (@window.Window, @app.App) -> R,
) -> R {
let window = self.window()
let result = self.app().update(fn(app) { f(window, app) })
self.cx.run_until_parked()
result
}
///|
pub fn[R] VisualTestContext::read(
self : VisualTestContext,
f : (@app.App) -> R,
) -> R {
self.cx.read(f)
}
///|
pub fn[T, R] VisualTestContext::update_entity(
self : VisualTestContext,
entity : @app.Entity[T],
f : (T, @app.Context[T]) -> R,
) -> R {
self.cx.update_entity(entity, f)
}
///|
pub fn[T] VisualTestContext::new_entity(
self : VisualTestContext,
build : (@app.Context[T]) -> T,
) -> @app.Entity[T] {
self.cx.new_entity(build)
}
///|
pub fn[V : @window.Render] VisualTestContext::replace_root_view(
self : VisualTestContext,
build : (@window.Window, @app.Context[V]) -> V,
) -> @app.Entity[V] {
self.update(fn(window, _) { window.replace_root_view(build) })
}
///|
pub fn VisualTestContext::draw(self : VisualTestContext) -> @scene.Scene {
let scene = self.window().draw()
self.cx.run_until_parked()
scene
}
///|
pub fn VisualTestContext::scene(self : VisualTestContext) -> @scene.Scene {
match self.test_window().last_scene() {
Some(scene) => scene
None => self.window().scene()
}
}
///|
pub fn VisualTestContext::drawn_scenes(
self : VisualTestContext,
) -> Array[@scene.Scene] {
self.test_window().drawn_scenes()
}
///|
pub fn VisualTestContext::draw_count(self : VisualTestContext) -> Int32 {
self.test_window().draw_count()
}
///|
pub fn VisualTestContext::simulate_input(
self : VisualTestContext,
event : @input.PlatformInput,
) -> @input.DispatchEventResult {
let result = self.test_window().simulate_input(event)
self.cx.run_until_parked()
result
}
///|
pub fn VisualTestContext::simulate_mouse_move(
self : VisualTestContext,
position : @geometry.Point[@geometry.Pixels],
button? : @input.MouseButton,
modifiers~ : @input.Modifiers = Default::default(),
) -> @input.DispatchEventResult {
self.simulate_input(
MouseMove({ position, pressed_button: button, modifiers, }),
)
}
///|
pub fn VisualTestContext::simulate_mouse_down(
self : VisualTestContext,
position : @geometry.Point[@geometry.Pixels],
button~ : @input.MouseButton = Left,
modifiers~ : @input.Modifiers = Default::default(),
click_count~ : Int32 = 1,
) -> @input.DispatchEventResult {
self.simulate_input(
MouseDown({ position, button, modifiers, click_count, first_mouse: false, }),
)
}
///|
pub fn VisualTestContext::simulate_mouse_up(
self : VisualTestContext,
position : @geometry.Point[@geometry.Pixels],
button~ : @input.MouseButton = Left,
modifiers~ : @input.Modifiers = Default::default(),
click_count~ : Int32 = 1,
) -> @input.DispatchEventResult {
self.simulate_input(MouseUp({ position, button, modifiers, click_count, }))
}
///|
pub fn VisualTestContext::simulate_click(
self : VisualTestContext,
position : @geometry.Point[@geometry.Pixels],
button~ : @input.MouseButton = Left,
modifiers~ : @input.Modifiers = Default::default(),
) -> Unit {
ignore(self.simulate_mouse_down(position, button~, modifiers~))
ignore(self.simulate_mouse_up(position, button~, modifiers~))
}
///|
pub fn VisualTestContext::simulate_scroll_wheel(
self : VisualTestContext,
position : @geometry.Point[@geometry.Pixels],
delta : @input.ScrollDelta,
modifiers~ : @input.Modifiers = Default::default(),
) -> @input.DispatchEventResult {
self.simulate_input(ScrollWheel({ position, delta, modifiers, }))
}
///|
pub fn VisualTestContext::simulate_mouse_exit(
self : VisualTestContext,
position~ : @geometry.Point[@geometry.Pixels] = @geometry.point(
@geometry.px(0.0),
@geometry.px(0.0),
),
modifiers~ : @input.Modifiers = Default::default(),
) -> @input.DispatchEventResult {
self.simulate_input(
MouseExited({ position, pressed_button: None, modifiers, }),
)
}
///|
pub fn VisualTestContext::simulate_modifiers_change(
self : VisualTestContext,
modifiers : @input.Modifiers,
) -> @input.DispatchEventResult {
self.simulate_input(ModifiersChanged({ modifiers, }))
}
///|
pub fn VisualTestContext::simulate_resize(
self : VisualTestContext,
size : @geometry.Size[@geometry.Pixels],
) -> Unit {
self.test_window().simulate_resize(size)
self.cx.run_until_parked()
}
///|
pub fn VisualTestContext::simulate_scale_factor_change(
self : VisualTestContext,
scale_factor : Double,
) -> Unit {
self.test_window().simulate_scale_factor_change(scale_factor)
self.cx.run_until_parked()
}
///|
pub fn VisualTestContext::simulate_active_status_change(
self : VisualTestContext,
active : Bool,
) -> Unit {
self.test_window().simulate_active_status_change(active)
self.cx.run_until_parked()
}
///|
pub fn VisualTestContext::simulate_hover_status_change(
self : VisualTestContext,
hovered : Bool,
) -> Unit {
self.test_window().simulate_hover_status_change(hovered)
self.cx.run_until_parked()
}
///|
pub fn VisualTestContext::simulate_close(self : VisualTestContext) -> Bool {
let closed = self.test_window().simulate_close_requested()
self.cx.run_until_parked()
closed
}
-498
View File
@@ -1,498 +0,0 @@
///|
fn px(v : Double) -> @geometry.Pixels {
@geometry.px(v)
}
///|
fn pt(x : Double, y : Double) -> @geometry.Point[@geometry.Pixels] {
@geometry.point(px(x), px(y))
}
///|
fn sz(w : Double, h : Double) -> @geometry.Size[@geometry.Pixels] {
@geometry.size(px(w), px(h))
}
///|
fn sp(v : Double) -> @geometry.ScaledPixels {
@geometry.ScaledPixels(v)
}
///|
/// A minimal element that paints a solid quad across its layout bounds and
/// optionally handles mouse events and hover.
priv struct BoxElement {
color : @color.Rgba
hover_color : @color.Rgba?
on_down : ((@input.MouseDownEvent, @window.Window, @app.App) -> Unit)?
on_scroll : ((@input.ScrollWheelEvent, @window.Window, @app.App) -> Unit)?
mut hitbox : @window.Hitbox?
}
///|
fn box_el(
color : @color.Rgba,
hover_color? : @color.Rgba,
on_down? : (@input.MouseDownEvent, @window.Window, @app.App) -> Unit,
on_scroll? : (@input.ScrollWheelEvent, @window.Window, @app.App) -> Unit,
) -> @window.AnyElement {
@window.AnyElement::new({
color,
hover_color,
on_down,
on_scroll,
hitbox: None,
})
}
///|
impl @window.Element for BoxElement with fn request_layout(_self, window, _app) {
window.request_layout(Default::default(), [])
}
///|
impl @window.Element for BoxElement with fn prepaint(self, bounds, window, _app) {
if self.hover_color is Some(_) ||
self.on_down is Some(_) ||
self.on_scroll is Some(_) {
self.hitbox = Some(window.insert_hitbox(bounds, Normal))
}
}
///|
impl @window.Element for BoxElement with fn paint(self, bounds, window, _app) {
let hovered = match self.hitbox {
Some(hitbox) => hitbox.is_hovered(window)
None => false
}
let bg = match (self.hover_color, hovered) {
(Some(hc), true) => hc
_ => self.color
}
if self.hitbox is Some(hitbox) {
if self.on_down is Some(cb) {
window.on_mouse_event(fn(event, phase, win, app) {
if phase == Bubble && event is MouseDown(down) && hitbox.is_hovered(win) {
cb(down, win, app)
}
})
}
if self.on_scroll is Some(cb) {
window.on_mouse_event(fn(event, phase, win, app) {
if phase == Bubble &&
event is ScrollWheel(scroll) &&
hitbox.is_hovered(win) {
cb(scroll, win, app)
}
})
}
}
window.paint_quad(@window.fill(bounds, bg.to_background()))
}
///|
struct TestView {
mut count : Int32
hover_bg : @color.Rgba?
prevent : Bool
stop : Bool
log : Array[String]
}
///|
impl @window.Render for TestView with fn render(self, _window, cx) {
box_el(
@color.rgb(0x112233),
hover_color?=self.hover_bg,
on_down=@window.listener(cx, fn(view, down, window, cx) {
view.count = view.count + 1
let btn = if down.button == Left { "Left" } else { "Other" }
view.log.push("down:\{btn}:\{down.modifiers.shift}")
if view.prevent {
window.prevent_default()
}
if view.stop {
window.stop_propagation()
}
cx.notify()
}),
on_scroll=@window.listener(cx, fn(view, scroll, _window, _cx) {
view.log.push("scroll:\{scroll.position.x.to_double()}")
}),
)
}
///|
enum PlainView {
PlainView
}
///|
impl @window.Render for PlainView with fn render(_self, _window, _cx) {
box_el(@color.rgb(0xabcdef))
}
///|
enum RunawayView {
RunawayView
}
///|
impl @window.Render for RunawayView with fn render(_self, window, _cx) {
window.refresh()
box_el(@color.rgb(0x000000))
}
///|
test "Application run, quit, and TestPlatform flags" {
let platform = @test.TestPlatform::new()
let app = @window.Application::with_platform(platform)
assert_false(platform.did_run())
assert_false(platform.did_quit())
let launched = Ref(false)
let found_app = Ref(false)
app.run(fn(a) {
launched.val = true
found_app.val = @window.application_for(a.app()) is Some(_)
a.quit()
})
assert_true(launched.val)
assert_true(found_app.val)
assert_true(platform.did_run())
assert_true(platform.did_quit())
}
///|
test "explicit frame scheduling on TestPlatform and TestWindow" {
let platform = @test.TestPlatform::new()
let app = @window.Application::with_platform(platform)
let view : Ref[@app.Entity[TestView]?] = Ref(None)
let unrelated : Ref[@app.Entity[PlainView]?] = Ref(None)
let handle = app.open_window(
@platform.WindowOptions::with_size(sz(300.0, 200.0), title="Manual"),
fn(_window, cx_app) {
unrelated.val = Some(cx_app.new_entity(fn(_) { PlainView }))
let v : @app.Entity[TestView] = cx_app.new_entity(fn(_) {
{ count: 0, hover_bg: None, prevent: false, stop: false, log: [], }
})
view.val = Some(v)
v
},
)
let tw = platform.window(handle.window_id()).unwrap()
assert_true(tw.frame_scheduled())
assert_eq(tw.draw_count(), 0)
assert_true(tw.simulate_scheduled_frame())
assert_false(tw.frame_scheduled())
assert_eq(tw.draw_count(), 1)
assert_false(tw.simulate_scheduled_frame())
// Unrelated entity notification must not schedule a frame.
unrelated.val.unwrap().update(app.app(), fn(_, cx) { cx.notify() })
assert_false(tw.frame_scheduled())
// Notifying rendered view re-schedules a frame.
view.val
.unwrap()
.update(app.app(), fn(v, cx) {
v.count = 1
cx.notify()
})
assert_true(tw.frame_scheduled())
assert_true(tw.simulate_scheduled_frame())
assert_eq(tw.draw_count(), 2)
}
///|
test "resize, scale factor, and programmatic Window::resize avoid recursion" {
let cx = @test.TestAppContext::new()
let vcx = cx.add_empty_window(size=sz(200.0, 100.0))
ignore(vcx.replace_root_view(fn(_, _) { PlainView }))
let before = vcx.draw_count()
vcx.simulate_resize(sz(320.0, 180.0))
assert_eq(vcx.draw_count(), before + 1)
assert_eq(vcx.bounds().size, sz(320.0, 180.0))
assert_eq(
vcx.scene().quads[0].bounds,
@geometry.bounds(
@geometry.point(sp(0.0), sp(0.0)),
@geometry.size(sp(320.0), sp(180.0)),
),
)
vcx.simulate_scale_factor_change(2.0)
assert_eq(vcx.scale_factor(), 2.0)
assert_eq(
vcx.scene().quads[0].bounds,
@geometry.bounds(
@geometry.point(sp(0.0), sp(0.0)),
@geometry.size(sp(640.0), sp(360.0)),
),
)
// Programmatic resize updates platform window bounds and schedules redraw without loop.
vcx.update(fn(win, _) { win.resize(sz(400.0, 200.0)) })
assert_eq(vcx.bounds().size, sz(400.0, 200.0))
assert_eq(vcx.scale_factor(), 2.0)
assert_eq(
vcx.scene().quads[0].bounds,
@geometry.bounds(
@geometry.point(sp(0.0), sp(0.0)),
@geometry.size(sp(800.0), sp(400.0)),
),
)
vcx.update(fn(win, _) { win.resize(sz(400.0, 200.0), scale_factor=1.5) })
assert_eq(vcx.window().scale_factor(), 1.5)
assert_eq(
vcx.scene().quads[0].bounds,
@geometry.bounds(
@geometry.point(sp(0.0), sp(0.0)),
@geometry.size(sp(600.0), sp(300.0)),
),
)
}
///|
test "title, cursor style, clipboard, and open_url" {
let cx = @test.TestAppContext::new()
let (_, vcx) = cx.add_window_view(size=sz(100.0, 100.0), title="Initial", fn(
_,
_,
) {
PlainView
})
assert_eq(vcx.window_title(), Some("Initial"))
vcx.update(fn(win, _) {
win.set_window_title("Updated")
win.set_cursor_style(PointingHand)
win.write_to_clipboard(
@platform.ClipboardItem::new_string_with_metadata("abc", "text"),
)
})
assert_eq(vcx.window_title(), Some("Updated"))
assert_eq(vcx.cursor_style(), @style.CursorStyle::PointingHand)
assert_eq(vcx.read_from_clipboard().unwrap().text(), Some("abc"))
assert_eq(cx.read_from_clipboard().unwrap().metadata(), Some("text"))
cx.application().open_url("https://example.com")
assert_eq(cx.opened_url(), Some("https://example.com"))
}
///|
test "multi-window activation and focus transfer" {
let cx = @test.TestAppContext::new()
let log : Array[String] = []
let (_, vcx1) = cx.add_window_view(size=sz(100.0, 100.0), fn(win, _) {
win.on_window_active_change(fn(w, _) {
log.push("w1:\{w.is_window_active()}")
})
PlainView
})
assert_true(vcx1.is_active())
assert_eq(cx.active_window(), Some(vcx1.window_handle()))
let (_, vcx2) = cx.add_window_view(size=sz(100.0, 100.0), fn(win, _) {
win.on_window_active_change(fn(w, _) {
log.push("w2:\{w.is_window_active()}")
})
PlainView
})
assert_false(vcx1.is_active())
assert_true(vcx2.is_active())
assert_eq(cx.active_window(), Some(vcx2.window_handle()))
assert_eq(log, ["w1:false"])
vcx1.update(fn(win, _) { win.activate_window() })
assert_true(vcx1.is_active())
assert_false(vcx2.is_active())
assert_eq(cx.active_window(), Some(vcx1.window_handle()))
assert_eq(log, ["w1:false", "w2:false", "w1:true"])
}
///|
test "MouseExited, hover status change, ModifiersChanged, and DispatchEventResult" {
let cx = @test.TestAppContext::new()
let (view, vcx) = cx.add_window_view(size=sz(100.0, 100.0), fn(_, _) {
{
count: 0,
hover_bg: Some(@color.rgb(0x00ff00)),
prevent: true,
stop: true,
log: [],
}
})
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x112233).to_background(),
)
ignore(vcx.simulate_mouse_move(pt(50.0, 50.0)))
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x00ff00).to_background(),
)
// MouseExited clears hovered hitboxes and marks window dirty -> redraws unhovered.
ignore(vcx.simulate_mouse_exit(position=pt(200.0, 200.0)))
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x112233).to_background(),
)
// Re-hover then lose window hover via platform hover status change.
ignore(vcx.simulate_mouse_move(pt(50.0, 50.0)))
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x00ff00).to_background(),
)
vcx.simulate_hover_status_change(false)
assert_false(vcx.is_hovered())
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x112233).to_background(),
)
// ModifiersChanged updates window modifiers and dirties/redraws on change.
let draws_before_mod = vcx.draw_count()
let shift_mods : @input.Modifiers = { ..Default::default(), shift: true, }
ignore(vcx.simulate_modifiers_change(shift_mods))
assert_eq(vcx.window().modifiers(), shift_mods)
assert_eq(vcx.draw_count(), draws_before_mod + 1)
// stop_propagation + prevent_default reflected in DispatchEventResult.
let result = vcx.simulate_mouse_down(pt(50.0, 50.0), modifiers=shift_mods)
assert_false(result.propagate)
assert_true(result.default_prevented)
assert_eq(cx.read_entity(view).log, ["down:Left:true"])
// ScrollWheel delivery.
ignore(
vcx.simulate_scroll_wheel(
pt(25.0, 25.0),
@input.ScrollDelta::Pixels(pt(0.0, -10.0)),
),
)
assert_eq(cx.read_entity(view).log, ["down:Left:true", "scroll:25"])
}
///|
test "window close veto, on_close, root release, and idempotence" {
let cx = @test.TestAppContext::new()
let can_close = Ref(false)
let events : Array[String] = []
let handle = cx.add_window(size=sz(100.0, 100.0), fn(win, ctx) {
ctx.on_release(fn(_, _) { events.push("released") }).detach()
win.on_should_close(fn(_, _) { can_close.val })
win.on_close(fn(_) { events.push("on_close") })
PlainView
})
let vcx = @test.VisualTestContext::from_window(handle.to_any(), cx)
assert_eq(cx.windows().length(), 1)
// Vetoed close leaves window open and view alive.
assert_false(vcx.simulate_close())
assert_false(vcx.is_closed())
assert_false(handle.entity().is_released())
assert_eq(events, [])
// Allowed close runs on_close, releases root view, removes window from Application.
can_close.val = true
assert_true(vcx.simulate_close())
assert_true(vcx.is_closed())
assert_eq(cx.windows().length(), 0)
assert_true(handle.entity().is_released())
assert_eq(events, ["on_close", "released"])
assert_eq(handle.update(cx.application(), fn(_, _, _) { 1 }), None)
// Idempotent repeat close calls do nothing extra.
vcx.test_window().simulate_close()
assert_eq(events, ["on_close", "released"])
}
///|
test "async task and virtual clock drive automatic redraws" {
let cx = @test.TestAppContext::new()
let (view, vcx) = cx.add_window_view(size=sz(120.0, 80.0), fn(_, ctx) {
let weak : @app.WeakEntity[TestView] = ctx.weak_entity()
ctx
.spawn(async fn(_, async_app) {
async_app.background_executor().sleep(50)
ignore(
weak.update(async_app.app, fn(v : TestView, cx) {
v.count = v.count + 10
cx.notify()
}),
)
})
.detach()
{ count: 1, hover_bg: None, prevent: false, stop: false, log: [], }
})
assert_eq(vcx.draw_count(), 1)
assert_eq(cx.read_entity(view).count, 1)
cx.advance_clock(50)
assert_eq(cx.read_entity(view).count, 11)
assert_eq(vcx.draw_count(), 2)
}
///|
test "replace_root_view and skip_drawing" {
let cx = @test.TestAppContext::new()
let released = Ref(false)
let (first, vcx) = cx.add_window_view(size=sz(100.0, 100.0), fn(_, ctx) {
ctx.on_release(fn(_, _) { released.val = true }).detach()
PlainView
})
assert_false(released.val)
let second = vcx.replace_root_view(fn(_, _) {
{ count: 42, hover_bg: None, prevent: false, stop: false, log: [], }
})
assert_true(first.is_released())
assert_true(released.val)
assert_eq(cx.read_entity(second).count, 42)
assert_eq(
vcx.scene().quads[0].background,
@color.rgb(0x112233).to_background(),
)
// skip_drawing prevents automatic frame pumping until re-enabled.
cx.skip_drawing()
let count_before = vcx.draw_count()
cx.update_entity(second, fn(v, ctx) {
v.count = 43
ctx.notify()
})
assert_eq(vcx.draw_count(), count_before)
assert_true(vcx.test_window().frame_scheduled())
cx.skip_drawing(skip=false)
cx.run_until_parked()
assert_eq(vcx.draw_count(), count_before + 1)
}
///|
test "panic on drawing a closed window" {
let cx = @test.TestAppContext::new()
let vcx = cx.add_empty_window(size=sz(50.0, 50.0))
let win = vcx.window()
win.close()
ignore(win.draw())
}
///|
test "panic on dispatching input on a closed window" {
let cx = @test.TestAppContext::new()
let vcx = cx.add_empty_window(size=sz(50.0, 50.0))
let win = vcx.window()
win.close()
ignore(
win.dispatch_input(
MouseMove({ ..Default::default(), position: pt(5.0, 5.0), }),
),
)
}
///|
test "panic on runaway redraw loop" {
let cx = @test.TestAppContext::new()
ignore(cx.add_window(size=sz(50.0, 50.0), fn(_, _) { RunawayView }))
}
-429
View File
@@ -1,429 +0,0 @@
// Headless test window, ported from gpui/src/platform/test/window.rs.
///|
/// A headless `PlatformWindow` for tests: records presented `Scene`s and
/// provides simulation hooks for frames, input, resizing, focus and closing
/// (GPUI: `TestWindow`).
pub struct TestWindow {
priv id : @platform.WindowId
priv platform : TestPlatform
priv mut bounds : @geometry.Bounds[@geometry.Pixels]
priv mut scale_factor : Double
priv mut title : String?
priv mut active : Bool
priv mut hovered : Bool
priv mut mouse_position : @geometry.Point[@geometry.Pixels]
priv mut modifiers : @input.Modifiers
priv mut closed : Bool
priv mut frame_scheduled : Bool
priv mut frame_schedule_count : Int32
priv drawn_scenes : Array[@scene.Scene]
priv mut request_frame_callback : (() -> Unit)?
priv mut input_callback : ((@input.PlatformInput) -> @input.DispatchEventResult)?
priv mut resize_callback : ((@geometry.Size[@geometry.Pixels], Double) -> Unit)?
priv mut active_status_change_callback : ((Bool) -> Unit)?
priv mut hover_status_change_callback : ((Bool) -> Unit)?
priv mut should_close_callback : (() -> Bool)?
priv mut close_callback : (() -> Unit)?
}
///|
fn TestWindow::new(
id : @platform.WindowId,
platform : TestPlatform,
params : @platform.WindowParams,
default_scale_factor : Double,
) -> TestWindow {
{
id,
platform,
bounds: params.bounds,
scale_factor: params.scale_factor.unwrap_or(default_scale_factor),
title: params.title,
active: params.focus,
hovered: false,
mouse_position: @geometry.point(@geometry.px(0.0), @geometry.px(0.0)),
modifiers: Default::default(),
closed: false,
frame_scheduled: false,
frame_schedule_count: 0,
drawn_scenes: [],
request_frame_callback: None,
input_callback: None,
resize_callback: None,
active_status_change_callback: None,
hover_status_change_callback: None,
should_close_callback: None,
close_callback: None,
}
}
///|
fn TestWindow::clear_callbacks(self : TestWindow) -> Unit {
self.request_frame_callback = None
self.input_callback = None
self.resize_callback = None
self.active_status_change_callback = None
self.hover_status_change_callback = None
self.should_close_callback = None
self.close_callback = None
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn bounds(self) {
self.bounds
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn content_size(self) {
self.bounds.size
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn scale_factor(self) {
self.scale_factor
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn mouse_position(self) {
self.mouse_position
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn modifiers(self) {
self.modifiers
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn is_active(self) {
self.active
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn is_hovered(self) {
self.hovered
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn set_title(self, title) {
self.title = Some(title)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn activate(self) {
if !self.closed {
self.platform.set_active_window(Some(self))
}
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn resize(self, size) {
self.bounds = { ..self.bounds, size, }
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn draw(self, scene) {
self.drawn_scenes.push(scene)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn schedule_frame(self) {
if !self.closed {
self.frame_scheduled = true
self.frame_schedule_count = self.frame_schedule_count + 1
}
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn close(self) {
if self.closed {
return
}
self.closed = true
self.frame_scheduled = false
self.clear_callbacks()
if self.platform.active_window is Some(active) && active.id == self.id {
self.platform.active_window = None
}
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_request_frame(
self,
callback,
) {
self.request_frame_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_input(
self,
callback,
) {
self.input_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_resize(
self,
callback,
) {
self.resize_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_active_status_change(
self,
callback,
) {
self.active_status_change_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_hover_status_change(
self,
callback,
) {
self.hover_status_change_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_should_close(
self,
callback,
) {
self.should_close_callback = Some(callback)
}
///|
pub impl @platform.PlatformWindow for TestWindow with fn on_close(
self,
callback,
) {
self.close_callback = Some(callback)
}
// ---------------------------------------------------------------------------
// Inspection helpers
// ---------------------------------------------------------------------------
///|
pub fn TestWindow::window_id(self : TestWindow) -> @platform.WindowId {
self.id
}
///|
pub fn TestWindow::title(self : TestWindow) -> String? {
self.title
}
///|
pub fn TestWindow::is_closed(self : TestWindow) -> Bool {
self.closed
}
///|
pub fn TestWindow::frame_scheduled(self : TestWindow) -> Bool {
self.frame_scheduled
}
///|
pub fn TestWindow::frame_schedule_count(self : TestWindow) -> Int32 {
self.frame_schedule_count
}
///|
pub fn TestWindow::drawn_scenes(self : TestWindow) -> Array[@scene.Scene] {
self.drawn_scenes
}
///|
pub fn TestWindow::draw_count(self : TestWindow) -> Int32 {
self.drawn_scenes.length()
}
///|
pub fn TestWindow::last_scene(self : TestWindow) -> @scene.Scene? {
self.drawn_scenes.last()
}
///|
pub fn TestWindow::clear_drawn_scenes(self : TestWindow) -> Unit {
self.drawn_scenes.clear()
}
// ---------------------------------------------------------------------------
// Simulation hooks
// ---------------------------------------------------------------------------
///|
/// Delivers one frame if one was scheduled; returns whether a frame ran
/// (GPUI: `TestWindow::simulate_scheduled_frame`).
pub fn TestWindow::simulate_scheduled_frame(self : TestWindow) -> Bool {
if self.closed || !self.frame_scheduled {
return false
}
self.frame_scheduled = false
match self.request_frame_callback {
Some(callback) => {
callback()
true
}
None => {
self.frame_scheduled = true
false
}
}
}
///|
/// Unconditionally invokes the registered frame callback, as a display-link
/// tick would (GPUI: `TestWindow::simulate_frame_request`).
pub fn TestWindow::simulate_frame_request(self : TestWindow) -> Unit {
if self.closed {
return
}
self.frame_scheduled = false
if self.request_frame_callback is Some(callback) {
callback()
}
}
///|
/// Simulates a `PlatformInput` event arriving from the OS/browser
/// (GPUI: `TestWindow::simulate_input`).
pub fn TestWindow::simulate_input(
self : TestWindow,
event : @input.PlatformInput,
) -> @input.DispatchEventResult {
if self.closed {
return { propagate: true, default_prevented: false, }
}
self.modifiers = event.modifiers()
match event {
MouseDown(e) => self.mouse_position = e.position
MouseUp(e) => self.mouse_position = e.position
MouseMove(e) => self.mouse_position = e.position
ScrollWheel(e) => self.mouse_position = e.position
MouseExited(e) => self.mouse_position = e.position
ModifiersChanged(_) => ()
}
match self.input_callback {
Some(callback) => callback(event)
None => { propagate: true, default_prevented: false, }
}
}
///|
/// Simulates a user/OS resize of the window (GPUI: `TestWindow::simulate_resize`).
pub fn TestWindow::simulate_resize(
self : TestWindow,
size : @geometry.Size[@geometry.Pixels],
) -> Unit {
if self.closed {
return
}
self.bounds = { ..self.bounds, size, }
if self.resize_callback is Some(callback) {
callback(size, self.scale_factor)
}
}
///|
/// Simulates a display scale-factor change
/// (GPUI: `TestWindow::simulate_scale_factor_change`).
pub fn TestWindow::simulate_scale_factor_change(
self : TestWindow,
scale_factor : Double,
) -> Unit {
if self.closed {
return
}
self.scale_factor = scale_factor
if self.resize_callback is Some(callback) {
callback(self.bounds.size, scale_factor)
}
}
///|
/// Simulates a window focus/activation change
/// (GPUI: `TestWindow::simulate_active_status_change`).
pub fn TestWindow::simulate_active_status_change(
self : TestWindow,
active : Bool,
) -> Unit {
if self.closed {
return
}
self.active = active
if active {
self.platform.active_window = Some(self)
} else if self.platform.active_window is Some(curr) && curr.id == self.id {
self.platform.active_window = None
}
if self.active_status_change_callback is Some(callback) {
callback(active)
}
}
///|
/// Simulates the pointer entering or leaving the window surface.
pub fn TestWindow::simulate_hover_status_change(
self : TestWindow,
hovered : Bool,
) -> Unit {
if self.closed {
return
}
self.hovered = hovered
if self.hover_status_change_callback is Some(callback) {
callback(hovered)
}
}
///|
/// Queries whether a close should proceed. Returns `true` if no handler is
/// registered.
pub fn TestWindow::simulate_should_close(self : TestWindow) -> Bool {
if self.closed {
return true
}
match self.should_close_callback {
Some(callback) => callback()
None => true
}
}
///|
/// Simulates the OS closing this window unconditionally and invoking the
/// registered `on_close` callback (GPUI: `TestWindow::simulate_close`).
pub fn TestWindow::simulate_close(self : TestWindow) -> Unit {
if self.closed {
return
}
let callback = self.close_callback
self.closed = true
self.frame_scheduled = false
self.clear_callbacks()
if self.platform.active_window is Some(curr) && curr.id == self.id {
self.platform.active_window = None
}
if callback is Some(callback) {
callback()
}
}
///|
/// Simulates a user-initiated close request: asks `on_should_close`, closes
/// if allowed, and returns whether the window closed.
pub fn TestWindow::simulate_close_requested(self : TestWindow) -> Bool {
if self.closed {
return false
}
if self.simulate_should_close() {
self.simulate_close()
true
} else {
false
}
}
-175
View File
@@ -1,175 +0,0 @@
// Core value types shared between GPUI windows and platform implementations,
// ported from gpui/src/platform.rs.
///|
/// Identifies an open window within an application (GPUI: `WindowId`).
#derive(Eq, Compare, Hash, Debug)
pub(all) struct WindowId(Int32)
///|
pub impl Show for WindowId with fn output(self, logger) {
logger.write_string("WindowId(\{self.0})")
}
///|
/// Requested window state and bounds (GPUI: `WindowBounds`).
#derive(Eq, Debug)
pub(all) enum WindowBounds {
Windowed(@geometry.Bounds[@geometry.Pixels])
Maximized(@geometry.Bounds[@geometry.Pixels])
Fullscreen(@geometry.Bounds[@geometry.Pixels])
}
///|
pub impl Default for WindowBounds with fn default() {
Windowed(Default::default())
}
///|
/// Returns the logical bounds stored in this `WindowBounds`.
pub fn WindowBounds::get_bounds(
self : WindowBounds,
) -> @geometry.Bounds[@geometry.Pixels] {
match self {
Windowed(bounds) | Maximized(bounds) | Fullscreen(bounds) => bounds
}
}
///|
/// Configuration passed when opening a window (GPUI: `WindowOptions`).
#derive(Eq, Debug)
pub(all) struct WindowOptions {
window_bounds : WindowBounds?
title : String?
focus : Bool
show : Bool
scale_factor : Double?
rem_size : @geometry.Pixels
}
///|
pub impl Default for WindowOptions with fn default() {
{
window_bounds: None,
title: None,
focus: true,
show: true,
scale_factor: None,
rem_size: @geometry.px(16.0),
}
}
///|
/// Convenience constructor for a windowed `WindowOptions` of `size` at the
/// origin.
pub fn WindowOptions::with_size(
size : @geometry.Size[@geometry.Pixels],
scale_factor? : Double,
title? : String,
rem_size~ : @geometry.Pixels = @geometry.px(16.0),
) -> WindowOptions {
{
..Default::default(),
window_bounds: Some(
Windowed(
@geometry.bounds(
@geometry.point(@geometry.px(0.0), @geometry.px(0.0)),
size,
),
),
),
title,
scale_factor,
rem_size,
}
}
///|
/// Resolved parameters handed to `Platform::open_window` (GPUI:
/// `WindowParams`).
#derive(Eq, Debug)
pub(all) struct WindowParams {
bounds : @geometry.Bounds[@geometry.Pixels]
title : String?
focus : Bool
show : Bool
scale_factor : Double?
}
///|
/// A plain-text clipboard entry with optional metadata (GPUI:
/// `ClipboardString`).
#derive(Eq, Debug)
pub(all) struct ClipboardString {
text : String
metadata : String?
}
///|
pub fn ClipboardString::new(text : String) -> ClipboardString {
{ text, metadata: None, }
}
///|
pub fn ClipboardString::new_with_metadata(
text : String,
metadata : String,
) -> ClipboardString {
{ text, metadata: Some(metadata), }
}
///|
/// One item inside a `ClipboardItem` (GPUI: `ClipboardEntry`, text subset).
#derive(Eq, Debug)
pub(all) enum ClipboardEntry {
String(ClipboardString)
}
///|
/// Data placed on or read from the system clipboard (GPUI: `ClipboardItem`).
#derive(Eq, Debug)
pub(all) struct ClipboardItem {
entries : Array[ClipboardEntry]
}
///|
/// Creates a `ClipboardItem` containing one plain-text entry.
pub fn ClipboardItem::new_string(text : String) -> ClipboardItem {
{ entries: [String(ClipboardString::new(text))], }
}
///|
/// Creates a `ClipboardItem` containing one plain-text entry with metadata.
pub fn ClipboardItem::new_string_with_metadata(
text : String,
metadata : String,
) -> ClipboardItem {
{ entries: [String(ClipboardString::new_with_metadata(text, metadata))], }
}
///|
/// Joins all text entries with `\n`, or returns `None` if there are none.
pub fn ClipboardItem::text(self : ClipboardItem) -> String? {
let texts = []
for entry in self.entries {
match entry {
String(s) => texts.push(s.text)
}
}
if texts.is_empty() {
None
} else {
Some(texts.join("\n"))
}
}
///|
/// Returns the metadata of the first text entry, if any.
pub fn ClipboardItem::metadata(self : ClipboardItem) -> String? {
for entry in self.entries {
match entry {
String(s) => return s.metadata
}
}
None
}
-294
View File
@@ -1,294 +0,0 @@
// Platform-backed Application lifecycle and window handles, ported from
// gpui/src/app.rs (`Application`, `open_window`, `windows`, `quit`) and
// gpui/src/window.rs (`AnyWindowHandle`, `WindowHandle<V>`).
///|
/// An untyped handle to an open window (GPUI: `AnyWindowHandle`).
#derive(Eq, Compare, Hash, Debug)
pub struct AnyWindowHandle {
id : @platform.WindowId
}
///|
pub fn AnyWindowHandle::window_id(self : AnyWindowHandle) -> @platform.WindowId {
self.id
}
///|
pub fn[R] AnyWindowHandle::update(
self : AnyWindowHandle,
application : Application,
f : (AnyView, Window, @app.App) -> R,
) -> R? {
application.update_window(self, f)
}
///|
/// A typed handle to an open window whose root view has type `V` (GPUI:
/// `WindowHandle<V>`).
pub struct WindowHandle[V] {
id : @platform.WindowId
priv root : @app.Entity[V]
}
///|
pub fn[V] WindowHandle::window_id(self : WindowHandle[V]) -> @platform.WindowId {
self.id
}
///|
pub fn[V] WindowHandle::to_any(self : WindowHandle[V]) -> AnyWindowHandle {
{ id: self.id, }
}
///|
pub fn[V] WindowHandle::entity(self : WindowHandle[V]) -> @app.Entity[V] {
self.root
}
///|
/// Updates the root view inside its window, returning `None` if the window
/// was closed or the view was released.
pub fn[V, R] WindowHandle::update(
self : WindowHandle[V],
application : Application,
f : (V, Window, @app.Context[V]) -> R,
) -> R? {
match application.window(self.id) {
Some(window) =>
if window.is_closed() || self.root.is_released() {
None
} else {
Some(
application.app.update_entity(self.root, fn(view, cx) {
f(view, window, cx)
}),
)
}
None => None
}
}
///|
/// Reads the root view if the window is still open and the view is alive.
pub fn[V, R] WindowHandle::read_with(
self : WindowHandle[V],
application : Application,
f : (V, @app.App) -> R,
) -> R? {
match application.window(self.id) {
Some(window) =>
if window.is_closed() || self.root.is_released() {
None
} else {
Some(f(self.root.read(application.app), application.app))
}
None => None
}
}
///|
/// An application wired to a `Platform`, owning its `App` and open windows
/// (GPUI: `Application`).
pub struct Application {
app : @app.App
platform : &@platform.Platform
priv mut next_window_id : Int32
priv windows : Map[@platform.WindowId, Window]
}
///|
let application_key : @app.GlobalKey[Application] = @app.GlobalKey::new(
"Application",
)
///|
/// Looks up the `Application` owning `app`, if it was created via
/// `Application::with_platform`.
pub fn application_for(app : @app.App) -> Application? {
app.try_global(application_key)
}
///|
/// Creates an `Application` backed by `platform` and registers it on the app.
pub fn Application::with_platform(
platform : &@platform.Platform,
) -> Application {
let app = @app.App::new(dispatcher=platform.dispatcher())
let application : Application = {
app,
platform,
next_window_id: 1,
windows: {},
}
app.set_global(application_key, application)
application
}
///|
pub fn Application::app(self : Application) -> @app.App {
self.app
}
///|
pub fn Application::platform(self : Application) -> &@platform.Platform {
self.platform
}
///|
/// Launches the platform event loop, calling `on_finish_launching` once
/// ready (GPUI: `Application::run`).
pub fn Application::run(
self : Application,
on_finish_launching : (Application) -> Unit,
) -> Unit {
self.platform.run(fn() { on_finish_launching(self) })
}
///|
/// Closes all open windows and asks the platform to exit (GPUI: `App::quit`).
pub fn Application::quit(self : Application) -> Unit {
let open = []
for _, win in self.windows {
open.push(win)
}
for win in open {
win.close()
}
self.platform.quit()
}
///|
/// Opens a platform-backed window with `options` and a root view created by
/// `build_root` (GPUI: `App::open_window`).
pub fn[V : Render] Application::open_window(
self : Application,
options : @platform.WindowOptions,
build_root : (Window, @app.App) -> @app.Entity[V],
) -> WindowHandle[V] {
let id = @platform.WindowId(self.next_window_id)
self.next_window_id = self.next_window_id + 1
let bounds = match options.window_bounds {
Some(wb) => wb.get_bounds()
None => self.platform.default_window_bounds()
}
let pw = self.platform.open_window(id, {
bounds,
title: options.title,
focus: options.focus,
show: options.show,
scale_factor: options.scale_factor,
})
let window = Window::from_platform(
id,
self.app,
self.platform,
pw,
rem_size=options.rem_size,
title?=options.title,
on_closed=fn() { self.windows.remove(id) },
)
self.windows[id] = window
let root = self.app.update(fn(app) { build_root(window, app) })
window.set_root_view(root)
{ id, root, }
}
///|
pub fn Application::windows(self : Application) -> Array[AnyWindowHandle] {
let handles : Array[AnyWindowHandle] = []
for id, _ in self.windows {
handles.push({ id, })
}
handles
}
///|
pub fn Application::window_count(self : Application) -> Int32 {
self.windows.length()
}
///|
pub fn Application::window(
self : Application,
id : @platform.WindowId,
) -> Window? {
self.windows.get(id)
}
///|
pub fn Application::active_window(self : Application) -> AnyWindowHandle? {
match self.platform.active_window() {
Some(id) =>
match self.windows.get(id) {
Some(win) if !win.is_closed() => Some({ id, })
_ => None
}
None => None
}
}
///|
pub fn[R] Application::update_window(
self : Application,
handle : AnyWindowHandle,
f : (AnyView, Window, @app.App) -> R,
) -> R? {
match self.windows.get(handle.id) {
Some(window) =>
if window.is_closed() {
None
} else {
match window.root_view() {
Some(root) => Some(self.app.update(fn(app) { f(root, window, app) }))
None => None
}
}
None => None
}
}
///|
pub fn Application::refresh_windows(self : Application) -> Unit {
for _, win in self.windows {
win.refresh()
}
}
///|
pub fn Application::close_window(
self : Application,
id : @platform.WindowId,
) -> Unit {
if self.windows.get(id) is Some(win) {
win.close()
}
}
///|
pub fn Application::read_from_clipboard(
self : Application,
) -> @platform.ClipboardItem? {
self.platform.read_from_clipboard()
}
///|
pub fn Application::write_to_clipboard(
self : Application,
item : @platform.ClipboardItem,
) -> Unit {
self.platform.write_to_clipboard(item)
}
///|
pub fn Application::set_cursor_style(
self : Application,
style : @style.CursorStyle,
) -> Unit {
self.platform.set_cursor_style(style)
}
///|
pub fn Application::open_url(self : Application, url : String) -> Unit {
self.platform.open_url(url)
}
-208
View File
@@ -1,208 +0,0 @@
// Elements and views, ported from gpui/src/element.rs and gpui/src/view.rs.
//
// Deviations from GPUI (see docs/PORTING.md):
// - `Element` has no associated `RequestLayoutState`/`PrepaintState` types:
// an element keeps per-frame state in its own mutable fields, set in
// `request_layout` and read in `prepaint` and `paint`. Elements are built
// fresh every frame, as in GPUI.
// - `render` returns `AnyElement` (no `impl IntoElement` return types).
// - Global element ids are paths of strings.
///|
/// A node of the element tree, laid out and painted each frame (GPUI:
/// `Element`).
pub(open) trait Element {
/// Requests a layout node (and those of the children).
fn request_layout(Self, Window, @app.App) -> @layout.LayoutId
/// Runs after layout with the element's bounds: hitboxes, child offsets.
fn prepaint(Self, @geometry.Bounds[@geometry.Pixels], Window, @app.App) -> Unit
/// Emits primitives into the scene and registers event listeners.
fn paint(Self, @geometry.Bounds[@geometry.Pixels], Window, @app.App) -> Unit
}
///|
/// Anything that can become an element (GPUI: `IntoElement`).
pub(open) trait IntoElement {
fn into_any_element(Self) -> AnyElement
}
///|
/// A type-erased element plus its per-frame layout state (GPUI:
/// `AnyElement`, with `Drawable`'s phase tracking).
pub struct AnyElement {
priv element : &Element
priv mut layout_id : @layout.LayoutId?
priv mut bounds : @geometry.Bounds[@geometry.Pixels]?
}
///|
pub fn AnyElement::new(element : &Element) -> AnyElement {
{ element, layout_id: None, bounds: None, }
}
///|
pub impl IntoElement for AnyElement with fn into_any_element(self) {
self
}
///|
/// Requests layout; must be called once per frame, before `prepaint`.
pub fn AnyElement::request_layout(
self : AnyElement,
window : Window,
app : @app.App,
) -> @layout.LayoutId {
guard self.layout_id is None else {
abort("element layout requested twice in one frame")
}
let id = self.element.request_layout(window, app)
self.layout_id = Some(id)
id
}
///|
/// Resolves the element's bounds from layout (plus the window's element
/// offset) and prepaints it.
pub fn AnyElement::prepaint(
self : AnyElement,
window : Window,
app : @app.App,
) -> Unit {
guard self.layout_id is Some(layout_id) else {
abort("element prepainted before its layout was requested")
}
let bounds = window.layout_bounds(layout_id)
self.bounds = Some(bounds)
self.element.prepaint(bounds, window, app)
}
///|
/// Paints the element at the bounds computed in `prepaint`.
pub fn AnyElement::paint(
self : AnyElement,
window : Window,
app : @app.App,
) -> Unit {
guard self.bounds is Some(bounds) else {
abort("element painted before it was prepainted")
}
self.element.paint(bounds, window, app)
}
///|
/// The bounds from the last `prepaint`, if any.
pub fn AnyElement::bounds(
self : AnyElement,
) -> @geometry.Bounds[@geometry.Pixels]? {
self.bounds
}
///|
/// A view's state renders itself into an element tree each frame (GPUI:
/// `Render`).
pub(open) trait Render {
fn render(Self, Window, @app.Context[Self]) -> AnyElement
}
///|
/// A type-erased view: an entity whose state implements `Render` (GPUI:
/// `AnyView`).
pub struct AnyView {
entity_id : @app.EntityId
priv render_fn : (Window, @app.App) -> AnyElement
priv release_fn : (@app.App) -> Unit
}
///|
pub fn[V : Render] AnyView::from_entity(entity : @app.Entity[V]) -> AnyView {
{
entity_id: entity.entity_id(),
render_fn: fn(window, app) {
app.update_entity(entity, fn(state, cx) {
Render::render(state, window, cx)
})
},
release_fn: fn(app) { app.release(entity) },
}
}
///|
/// The element a view renders into for one frame.
priv struct ViewElement {
view : AnyView
mut rendered : AnyElement?
}
///|
impl Element for ViewElement with fn request_layout(self, window, app) {
window.record_rendered_view(self.view.entity_id)
let element = (self.view.render_fn)(window, app)
self.rendered = Some(element)
element.request_layout(window, app)
}
///|
impl Element for ViewElement with fn prepaint(self, _bounds, window, app) {
self.rendered.unwrap().prepaint(window, app)
}
///|
impl Element for ViewElement with fn paint(self, _bounds, window, app) {
self.rendered.unwrap().paint(window, app)
}
///|
pub impl IntoElement for AnyView with fn into_any_element(self) {
AnyElement::new(({ view: self, rendered: None, } : ViewElement))
}
///|
pub extend AnyView with IntoElement::{into_any_element}
///|
/// Views are elements: `div().child(entity)` renders the entity.
pub impl[V : Render] IntoElement for @app.Entity[V] with fn into_any_element(
self,
) {
AnyView::from_entity(self).into_any_element()
}
///|
/// Wraps a view method as an event listener that updates the view (GPUI:
/// `cx.listener`). The listener does nothing once the view is released.
pub fn[T, E] listener(
cx : @app.Context[T],
f : (T, E, Window, @app.Context[T]) -> Unit,
) -> (E, Window, @app.App) -> Unit {
let weak = cx.weak_entity()
fn(event, window, app) {
ignore(weak.update(app, fn(state, cx) { f(state, event, window, cx) }))
}
}
///|
/// An element that takes no space and paints nothing (GPUI: `Empty`).
priv enum Empty {
Empty
}
///|
impl Element for Empty with fn request_layout(_self, window, _app) {
window.request_layout(Default::default(), [])
}
///|
impl Element for Empty with fn prepaint(_self, _bounds, _window, _app) {
()
}
///|
impl Element for Empty with fn paint(_self, _bounds, _window, _app) {
()
}
///|
/// An empty element.
pub fn empty() -> AnyElement {
AnyElement::new(Empty::Empty)
}
-17
View File
@@ -1,17 +0,0 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/color",
"experiments/gpui/scene",
"experiments/gpui/style",
"experiments/gpui/layout",
"experiments/gpui/input",
"experiments/gpui/app",
"experiments/gpui/platform",
"moonbitlang/core/hashset",
"moonbitlang/core/cmp",
"moonbitlang/core/debug",
}
options(
"allow-experimental-packages": true,
)
-301
View File
@@ -1,301 +0,0 @@
// Painting, ported from gpui/src/window.rs (`paint_quad`, `paint_drop_shadows`,
// `paint_inset_shadows`, the snapping helpers) and `Style::paint` from
// gpui/src/style.rs.
//
// Deviation: GPUI splits bordered quads into a background quad and border
// strips (`insert_quad`) as a renderer optimization; here a quad is inserted
// as is.
///|
/// A quad to paint, in logical pixels (GPUI: `PaintQuad`).
#derive(Eq, Debug)
pub(all) struct PaintQuad {
bounds : @geometry.Bounds[@geometry.Pixels]
corner_radii : @geometry.Corners[@geometry.Pixels]
background : @color.Background
border_widths : @geometry.Edges[@geometry.Pixels]
border_color : @color.Hsla
border_style : @scene.BorderStyle
}
///|
/// A filled quad without border (GPUI: `fill`).
pub fn fill(
bounds : @geometry.Bounds[@geometry.Pixels],
background : @color.Background,
) -> PaintQuad {
{
bounds,
corner_radii: Default::default(),
background,
border_widths: Default::default(),
border_color: @color.transparent_black(),
border_style: Solid,
}
}
///|
/// A 1px outline (GPUI: `outline`).
pub fn outline(
bounds : @geometry.Bounds[@geometry.Pixels],
border_color : @color.Hsla,
border_style~ : @scene.BorderStyle = Solid,
) -> PaintQuad {
{
bounds,
corner_radii: Default::default(),
background: @color.transparent_black().to_background(),
border_widths: @geometry.Edges::all(@geometry.px(1.0)),
border_color,
border_style,
}
}
///|
fn round_half_toward_zero(value : Double) -> Double {
@layout.round_half_toward_zero(value)
}
///|
/// Logical bounds to device pixels, edges rounded (GPUI: `snap_bounds`).
fn Window::snap_bounds(
self : Window,
bounds : @geometry.Bounds[@geometry.Pixels],
) -> @geometry.Bounds[@geometry.ScaledPixels] {
let s = self.scale_factor
let left = round_half_toward_zero(bounds.left().to_double() * s)
let top = round_half_toward_zero(bounds.top().to_double() * s)
let right = @cmp.maximum(
round_half_toward_zero(bounds.right().to_double() * s),
left,
)
let bottom = @cmp.maximum(
round_half_toward_zero(bounds.bottom().to_double() * s),
top,
)
@geometry.Bounds::from_corners(
@geometry.point(@geometry.ScaledPixels(left), @geometry.ScaledPixels(top)),
@geometry.point(
@geometry.ScaledPixels(right),
@geometry.ScaledPixels(bottom),
),
)
}
///|
/// Logical bounds to the device pixels they touch (GPUI: `cover_bounds`).
fn Window::cover_bounds(
self : Window,
bounds : @geometry.Bounds[@geometry.Pixels],
) -> @geometry.Bounds[@geometry.ScaledPixels] {
let s = self.scale_factor
let left = (bounds.left().to_double() * s).floor()
let top = (bounds.top().to_double() * s).floor()
if bounds.is_empty() {
return {
origin: @geometry.point(
@geometry.ScaledPixels(left),
@geometry.ScaledPixels(top),
),
size: Default::default(),
}
}
let right = @cmp.maximum((bounds.right().to_double() * s).ceil(), left)
let bottom = @cmp.maximum((bounds.bottom().to_double() * s).ceil(), top)
@geometry.Bounds::from_corners(
@geometry.point(@geometry.ScaledPixels(left), @geometry.ScaledPixels(top)),
@geometry.point(
@geometry.ScaledPixels(right),
@geometry.ScaledPixels(bottom),
),
)
}
///|
fn Window::snapped_content_mask(
self : Window,
) -> @geometry.ContentMask[@geometry.ScaledPixels] {
{ bounds: self.cover_bounds(self.content_mask().bounds), }
}
///|
/// Paints a quad, snapped to device pixels and faded by the element opacity
/// (GPUI: `paint_quad`). Only during paint.
pub fn Window::paint_quad(self : Window, quad : PaintQuad) -> Unit {
self.assert_phase("paint_quad", [Paint])
let opacity = self.element_opacity
let scene_quad : @scene.Quad = {
order: 0,
bounds: self.snap_bounds(quad.bounds),
content_mask: self.snapped_content_mask(),
background: quad.background.opacity(opacity),
border_color: quad.border_color.opacity(opacity),
corner_radii: quad.corner_radii.scale(self.scale_factor),
border_widths: quad.border_widths.map(fn(width) {
@geometry.ScaledPixels(
@layout.round_stroke_to_device_pixel(
width.to_double(),
self.scale_factor,
),
)
}),
border_style: quad.border_style,
}
let has_background = !scene_quad.background.is_transparent()
let has_border = scene_quad.border_widths != Default::default() &&
!scene_quad.border_color.is_transparent()
if has_background || has_border {
self.next_scene.insert_primitive(Quad(scene_quad))
}
}
///|
/// Paints the outer (non-inset) box shadows of a rounded rectangle (GPUI:
/// `paint_drop_shadows`).
pub fn Window::paint_drop_shadows(
self : Window,
bounds : @geometry.Bounds[@geometry.Pixels],
corner_radii : @geometry.Corners[@geometry.Pixels],
shadows : Array[@style.BoxShadow],
) -> Unit {
self.assert_phase("paint_drop_shadows", [Paint])
let content_mask = self.snapped_content_mask()
for shadow in shadows {
if shadow.inset {
continue
}
let shape_bounds = self.cover_bounds(
bounds.translate(shadow.offset).dilate(shadow.spread_radius),
)
if shape_bounds.is_empty() {
continue
}
let blur_radius = shadow.blur_radius.scale(self.scale_factor)
self.next_scene.insert_primitive(
Shadow({
order: 0,
blur_radius,
bounds: shape_bounds.dilate(blur_radius.mul_scalar(3.0)),
content_mask,
corner_radii: Default::default(),
color: shadow.color.opacity(self.element_opacity),
shape_bounds,
shape_corner_radii: corner_radii.scale(self.scale_factor),
inset: false,
}),
)
}
}
///|
/// Paints the inset box shadows of a rounded rectangle (GPUI:
/// `paint_inset_shadows`).
pub fn Window::paint_inset_shadows(
self : Window,
bounds : @geometry.Bounds[@geometry.Pixels],
corner_radii : @geometry.Corners[@geometry.Pixels],
shadows : Array[@style.BoxShadow],
) -> Unit {
self.assert_phase("paint_inset_shadows", [Paint])
let content_mask = self.snapped_content_mask()
let element_bounds = self.cover_bounds(bounds)
for shadow in shadows {
if !shadow.inset {
continue
}
let hole = bounds.translate(shadow.offset).dilate(-shadow.spread_radius)
let shrink = fn(radius : @geometry.Pixels) {
@cmp.maximum(radius - shadow.spread_radius, @geometry.px(0.0))
}
self.next_scene.insert_primitive(
Shadow({
order: 0,
blur_radius: shadow.blur_radius.scale(self.scale_factor),
bounds: element_bounds,
content_mask,
corner_radii: corner_radii.scale(self.scale_factor),
color: shadow.color.opacity(self.element_opacity),
shape_bounds: self.cover_bounds(hole),
shape_corner_radii: corner_radii.map(shrink).scale(self.scale_factor),
inset: true,
}),
)
}
}
///|
/// Paints an element's box (drop shadows, background, inset shadows), runs
/// `paint_children`, then paints the border on top (GPUI: `Style::paint`).
pub fn Window::paint_style(
self : Window,
style : @style.Style,
bounds : @geometry.Bounds[@geometry.Pixels],
paint_children : () -> Unit,
) -> Unit {
self.assert_phase("paint_style", [Paint])
if style.debug {
self.paint_quad(outline(bounds, @color.red()))
}
let corner_radii = style.corner_radii
.absolute_to_pixels(self.rem_size)
.clamp_radii_for_quad_size(bounds.size)
self.paint_drop_shadows(bounds, corner_radii, style.box_shadow)
if style.background is Some(fill) &&
fill.color() is Some(background) &&
!background.is_transparent() {
let border_color = match background.tag {
LinearGradient => background.colors.0.color
_ => background.solid
}
self.paint_quad({
bounds,
corner_radii,
background,
border_widths: Default::default(),
border_color: border_color.alpha(0.0),
border_style: style.border_style,
})
}
self.paint_inset_shadows(bounds, corner_radii, style.box_shadow)
paint_children()
if style.is_border_visible() {
let border_color = style.border_color.unwrap()
self.paint_quad({
bounds,
corner_radii,
background: border_color.alpha(0.0).to_background(),
border_widths: style.border_widths.absolute_to_pixels(self.rem_size),
border_color,
border_style: style.border_style,
})
}
}
///|
/// Paints an arbitrary primitive (escape hatch for custom elements such as
/// `canvas`). Only during paint.
pub fn Window::paint_primitive(
self : Window,
primitive : @scene.Primitive,
) -> Unit {
self.assert_phase("paint_primitive", [Paint])
self.next_scene.insert_primitive(primitive)
}
///|
/// Paints a filled path given by polygon contours in logical pixels (GPUI:
/// `paint_path`, simplified to polygons).
pub fn Window::paint_path(
self : Window,
contours : Array[Array[@geometry.Point[@geometry.Pixels]]],
color : @color.Background,
) -> Unit {
self.assert_phase("paint_path", [Paint])
let path = @scene.PaintedPath::new(
contours,
self.scale_factor,
self.content_mask(),
color.opacity(self.element_opacity),
)
self.next_scene.insert_primitive(Path(path))
}
-198
View File
@@ -1,198 +0,0 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/window"
import {
"experiments/gpui/app",
"experiments/gpui/color",
"experiments/gpui/geometry",
"experiments/gpui/input",
"experiments/gpui/layout",
"experiments/gpui/platform",
"experiments/gpui/scene",
"experiments/gpui/style",
"moonbitlang/core/debug",
}
// Values
pub fn application_for(@app.App) -> Application?
pub fn empty() -> AnyElement
pub fn fill(@geometry.Bounds[@geometry.Pixels], @color.Background) -> PaintQuad
pub fn[T, E] listener(@app.Context[T], (T, E, Window, @app.Context[T]) -> Unit) -> (E, Window, @app.App) -> Unit
pub fn outline(@geometry.Bounds[@geometry.Pixels], @color.Hsla, border_style? : @scene.BorderStyle) -> PaintQuad
// Errors
// Types and methods
pub struct AnyElement {
// private fields
}
pub fn AnyElement::bounds(Self) -> @geometry.Bounds[@geometry.Pixels]?
pub fn AnyElement::new(&Element) -> Self
pub fn AnyElement::paint(Self, Window, @app.App) -> Unit
pub fn AnyElement::prepaint(Self, Window, @app.App) -> Unit
pub fn AnyElement::request_layout(Self, Window, @app.App) -> @layout.LayoutId
pub impl IntoElement for AnyElement
pub struct AnyView {
entity_id : @app.EntityId
// private fields
}
pub fn[V : Render] AnyView::from_entity(@app.Entity[V]) -> Self
pub fn AnyView::into_any_element(Self) -> AnyElement
pub impl IntoElement for AnyView
#derive(Compare, Eq, Hash, @debug.Debug)
pub struct AnyWindowHandle {
id : @platform.WindowId
}
pub fn[R] AnyWindowHandle::update(Self, Application, (AnyView, Window, @app.App) -> R) -> R?
pub fn AnyWindowHandle::window_id(Self) -> @platform.WindowId
pub struct Application {
app : @app.App
platform : &@platform.Platform
// private fields
}
pub fn Application::active_window(Self) -> AnyWindowHandle?
pub fn Application::app(Self) -> @app.App
pub fn Application::close_window(Self, @platform.WindowId) -> Unit
pub fn Application::open_url(Self, String) -> Unit
pub fn[V : Render] Application::open_window(Self, @platform.WindowOptions, (Window, @app.App) -> @app.Entity[V]) -> WindowHandle[V]
pub fn Application::platform(Self) -> &@platform.Platform
pub fn Application::quit(Self) -> Unit
pub fn Application::read_from_clipboard(Self) -> @platform.ClipboardItem?
pub fn Application::refresh_windows(Self) -> Unit
pub fn Application::run(Self, (Self) -> Unit) -> Unit
pub fn Application::set_cursor_style(Self, @style.CursorStyle) -> Unit
pub fn[R] Application::update_window(Self, AnyWindowHandle, (AnyView, Window, @app.App) -> R) -> R?
pub fn Application::window(Self, @platform.WindowId) -> Window?
pub fn Application::window_count(Self) -> Int32
pub fn Application::windows(Self) -> Array[AnyWindowHandle]
pub fn Application::with_platform(&@platform.Platform) -> Self
pub fn Application::write_to_clipboard(Self, @platform.ClipboardItem) -> Unit
pub struct ElementStateKey[S] {
id : Int32
name : String
// private fields
}
pub fn[S] ElementStateKey::new(String) -> Self[S]
#derive(Eq, @debug.Debug)
pub(all) struct Hitbox {
id : Int32
bounds : @geometry.Bounds[@geometry.Pixels]
content_mask : @geometry.ContentMask[@geometry.Pixels]
behavior : HitboxBehavior
}
pub fn Hitbox::is_hovered(Self, Window) -> Bool
#derive(Eq, Hash, @debug.Debug)
pub(all) enum HitboxBehavior {
Normal
BlockMouse
}
#derive(Eq, @debug.Debug)
pub(all) struct PaintQuad {
bounds : @geometry.Bounds[@geometry.Pixels]
corner_radii : @geometry.Corners[@geometry.Pixels]
background : @color.Background
border_widths : @geometry.Edges[@geometry.Pixels]
border_color : @color.Hsla
border_style : @scene.BorderStyle
}
pub struct Window {
// private fields
}
pub fn Window::activate_window(Self) -> Unit
pub fn Window::bounds(Self) -> @geometry.Bounds[@geometry.Pixels]
pub fn Window::close(Self) -> Unit
pub fn Window::content_mask(Self) -> @geometry.ContentMask[@geometry.Pixels]
pub fn Window::default_prevented(Self) -> Bool
pub fn Window::dispatch_input(Self, @input.PlatformInput) -> @input.DispatchEventResult
pub fn Window::dispatch_mouse_event(Self, @input.MouseEvent) -> Bool
pub fn Window::draw(Self) -> @scene.Scene
pub fn Window::draw_if_dirty(Self) -> Bool
pub fn Window::element_offset(Self) -> @geometry.Point[@geometry.Pixels]
pub fn Window::element_opacity(Self) -> Double
pub fn Window::frame_count(Self) -> Int32
pub fn Window::global_element_id(Self) -> String?
pub fn Window::insert_hitbox(Self, @geometry.Bounds[@geometry.Pixels], HitboxBehavior) -> Hitbox
pub fn Window::is_closed(Self) -> Bool
pub fn Window::is_dirty(Self) -> Bool
pub fn Window::is_window_active(Self) -> Bool
pub fn Window::is_window_hovered(Self) -> Bool
pub fn Window::layout_bounds(Self, @layout.LayoutId) -> @geometry.Bounds[@geometry.Pixels]
pub fn Window::modifiers(Self) -> @input.Modifiers
pub fn Window::mouse_position(Self) -> @geometry.Point[@geometry.Pixels]
pub fn Window::new(@app.App, @geometry.Size[@geometry.Pixels], scale_factor? : Double, rem_size? : @geometry.Pixels) -> Self
pub fn Window::on_close(Self, (@app.App) -> Unit) -> Unit
pub fn Window::on_mouse_event(Self, (@input.MouseEvent, @input.DispatchPhase, Self, @app.App) -> Unit) -> Unit
pub fn Window::on_should_close(Self, (Self, @app.App) -> Bool) -> Unit
pub fn Window::on_window_active_change(Self, (Self, @app.App) -> Unit) -> Unit
pub fn Window::paint_drop_shadows(Self, @geometry.Bounds[@geometry.Pixels], @geometry.Corners[@geometry.Pixels], Array[@style.BoxShadow]) -> Unit
pub fn Window::paint_inset_shadows(Self, @geometry.Bounds[@geometry.Pixels], @geometry.Corners[@geometry.Pixels], Array[@style.BoxShadow]) -> Unit
pub fn Window::paint_path(Self, Array[Array[@geometry.Point[@geometry.Pixels]]], @color.Background) -> Unit
pub fn Window::paint_primitive(Self, @scene.Primitive) -> Unit
pub fn Window::paint_quad(Self, PaintQuad) -> Unit
pub fn Window::paint_style(Self, @style.Style, @geometry.Bounds[@geometry.Pixels], () -> Unit) -> Unit
pub fn Window::prevent_default(Self) -> Unit
pub fn Window::read_from_clipboard(Self) -> @platform.ClipboardItem?
pub fn Window::refresh(Self) -> Unit
pub fn Window::rem_size(Self) -> @geometry.Pixels
pub fn Window::remove_window(Self) -> Unit
pub fn[V : Render] Window::replace_root_view(Self, (Self, @app.Context[V]) -> V) -> @app.Entity[V]
pub fn Window::request_layout(Self, @style.Style, Array[@layout.LayoutId]) -> @layout.LayoutId
pub fn Window::request_measured_layout(Self, @style.Style, (@geometry.Size[@geometry.Pixels?], @geometry.Size[@layout.AvailableSpace]) -> @geometry.Size[@geometry.Pixels]) -> @layout.LayoutId
pub fn Window::resize(Self, @geometry.Size[@geometry.Pixels], scale_factor? : Double) -> Unit
pub fn Window::root_view(Self) -> AnyView?
pub fn Window::scale_factor(Self) -> Double
pub fn Window::scene(Self) -> @scene.Scene
pub fn Window::set_cursor_style(Self, @style.CursorStyle) -> Unit
pub fn Window::set_rem_size(Self, @geometry.Pixels) -> Unit
pub fn[V : Render] Window::set_root_view(Self, @app.Entity[V]) -> Unit
pub fn Window::set_window_title(Self, String) -> Unit
pub fn Window::stop_propagation(Self) -> Unit
pub fn Window::viewport_size(Self) -> @geometry.Size[@geometry.Pixels]
pub fn Window::window_id(Self) -> @platform.WindowId
pub fn Window::window_title(Self) -> String?
pub fn[R] Window::with_content_mask(Self, @geometry.ContentMask[@geometry.Pixels]?, () -> R) -> R
pub fn[R] Window::with_element_id(Self, String?, () -> R) -> R
pub fn[R] Window::with_element_offset(Self, @geometry.Point[@geometry.Pixels], () -> R) -> R
pub fn[R] Window::with_element_opacity(Self, Double?, () -> R) -> R
pub fn[S, R] Window::with_element_state(Self, ElementStateKey[S], (S?) -> (R, S)) -> R
pub fn Window::write_to_clipboard(Self, @platform.ClipboardItem) -> Unit
pub struct WindowHandle[V] {
id : @platform.WindowId
// private fields
}
pub fn[V] WindowHandle::entity(Self[V]) -> @app.Entity[V]
pub fn[V, R] WindowHandle::read_with(Self[V], Application, (V, @app.App) -> R) -> R?
pub fn[V] WindowHandle::to_any(Self[V]) -> AnyWindowHandle
pub fn[V, R] WindowHandle::update(Self[V], Application, (V, Window, @app.Context[V]) -> R) -> R?
pub fn[V] WindowHandle::window_id(Self[V]) -> @platform.WindowId
// Type aliases
// Traits
pub(open) trait Element {
fn request_layout(Self, Window, @app.App) -> @layout.LayoutId
fn prepaint(Self, @geometry.Bounds[@geometry.Pixels], Window, @app.App) -> Unit
fn paint(Self, @geometry.Bounds[@geometry.Pixels], Window, @app.App) -> Unit
}
pub(open) trait IntoElement {
fn into_any_element(Self) -> AnyElement
}
pub impl[V : Render] IntoElement for @app.Entity[V]
pub(open) trait Render {
fn render(Self, Window, @app.Context[Self]) -> AnyElement
}
File diff suppressed because it is too large. Load diff
+6 -18
View File
@@ -16,9 +16,8 @@ Outputs (all in src/style/):
styled_extend_generated.mbt promotes all `Styled` methods on styled_extend_generated.mbt promotes all `Styled` methods on
StyleRefinement StyleRefinement
Other packages that implement `Styled` need the same `extend` list. The Other packages that implement `Styled` (e.g. `Div`) need the same `extend`
default run also emits it for the elements package (`Div`, `Canvas`); add list; pass `--extend Type=path/to/file.mbt` to emit it there.
more with `--extend Type=path/to/file.mbt`.
""" """
import argparse import argparse
@@ -637,11 +636,11 @@ def gen_styled():
return "".join(out), names return "".join(out), names
def gen_extend(type_name, names, trait_ref="Styled"): def gen_extend(type_name, names):
body = ",\n ".join(names) body = ",\n ".join(names)
return ( return (
HEADER HEADER
+ f"///|\npub extend {type_name} with {trait_ref}::{{\n {body},\n}}\n" + f"///|\npub extend {type_name} with Styled::{{\n {body},\n}}\n"
) )
@@ -651,13 +650,6 @@ def write(path, content):
print(f"wrote {os.path.relpath(path, ROOT)}") print(f"wrote {os.path.relpath(path, ROOT)}")
# Styled types outside the style package, emitted on every run.
DEFAULT_EXTENDS = [
"Div=src/elements/div_styled_generated.mbt",
"Canvas=src/elements/canvas_styled_generated.mbt",
]
def main(): def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument( parser.add_argument(
@@ -676,15 +668,11 @@ def main():
os.path.join(STYLE_DIR, "styled_extend_generated.mbt"), os.path.join(STYLE_DIR, "styled_extend_generated.mbt"),
gen_extend("StyleRefinement", names), gen_extend("StyleRefinement", names),
) )
for spec in DEFAULT_EXTENDS + args.extend: for spec in args.extend:
if "=" not in spec: if "=" not in spec:
sys.exit(f"gen_style: --extend expects TYPE=FILE, got {spec!r}") sys.exit(f"gen_style: --extend expects TYPE=FILE, got {spec!r}")
type_name, path = spec.split("=", 1) type_name, path = spec.split("=", 1)
full = os.path.join(ROOT, path) write(os.path.join(ROOT, path), gen_extend(type_name, names))
# Outside the style package the trait must be package-qualified.
inside = os.path.dirname(os.path.abspath(full)) == STYLE_DIR
trait_ref = "Styled" if inside else "@style.Styled"
write(full, gen_extend(type_name, names, trait_ref))
print(f"{len(names)} Styled methods") print(f"{len(names)} Styled methods")