diff --git a/README.md b/README.md index 9ad8358..a7dc707 100644 --- a/README.md +++ b/README.md @@ -17,18 +17,19 @@ roadmap. | `experiments/gpui/style` | `style.rs`, `styled.rs`, Refineable, gpui_macros style helpers | Ported (`Style`/`StyleRefinement`, the full `Styled` fluent API) | | `experiments/gpui/app` | `app.rs`, `entity_map.rs`, `context.rs`, `subscription.rs` | Ported (entities, contexts, notify/observe, typed events and globals, effect flushing) | | `experiments/gpui/executor` | `executor.rs`, `scheduler` crate | Ported (tasks, timers, cancellation, deterministic test dispatcher; single thread) | -| `experiments/gpui/input` | mouse events of `interactive.rs` | Ported (mouse events, modifiers) | -| `experiments/gpui/window` | `window.rs`, `element.rs`, `view.rs` | Ported, headless (frame lifecycle, views, hitboxes, mouse dispatch, painting) | +| `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/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 Nothing is shown on screen yet (the renderer comes with M8). `src/examples/card` -is a view rendering a `div()` card with GPUI's fluent API; a headless window -lays it out, paints it into a `Scene`, and dispatches a simulated hover and -click (which expands the card). It prints the scene's draw batches and -quads: +is a view rendering a `div()` card with GPUI's fluent API inside a +`TestPlatform` window; `VisualTestContext` simulates a hover and click while +pumping frames automatically, and prints the scene's draw batches and quads: ```sh moon run src/examples/card --target js diff --git a/docs/PORTING.md b/docs/PORTING.md index 9184dde..f7e0c91 100644 --- a/docs/PORTING.md +++ b/docs/PORTING.md @@ -137,18 +137,18 @@ stays isolated. | `action` | `action.rs` | pure | planned | | `app` | `app.rs`, `app/entity_map.rs`, `app/context.rs`, `subscription.rs`, `global.rs` | pure | **done** (no windows, executors or actions yet) | | `executor` | `executor.rs`, `scheduler` crate (`executor.rs`, `test_scheduler.rs`) | pure core + `Dispatcher` platform hook | **done** (single thread) | -| `input` | mouse events of `interactive.rs`, `Modifiers` | pure | **done** (mouse only; keys in M5) | -| `window` | `window.rs`, `element.rs`, `view.rs`, `Style::paint` | pure | **done** (headless; no focus/keys/caching yet) | +| `input` | mouse/window input of `interactive.rs`, `Modifiers`, `PlatformInput`, `DispatchEventResult` | pure | **done** (mouse/modifiers; keys in M5) | +| `window` | `window.rs`, `element.rs`, `view.rs`, `Style::paint`, `Application`, window handles | pure | **done** (`PlatformWindow`-backed + standalone headless; no focus/keys/caching yet) | | `elements` | `elements/div.rs` (+ `Interactivity`), `elements/canvas.rs` | pure | **done** (`div`, `canvas`) | | `text` | `text_system.rs`, `text_system/*` | mixed: wrapping/caching pure, shaping platform | planned | -| `platform` | `platform.rs` (traits only), `interactive.rs` input types | pure (interfaces) | planned | -| `platform/test` | `platform/test/*` | pure | planned: headless platform for tests | +| `platform` | `platform.rs` (core traits, `WindowId`, `WindowOptions`, `WindowParams`, `ClipboardItem`) | pure (interfaces) | **done** (core subset; text/atlas/IME/displays later) | +| `platform/test` | `platform/test/*`, `app/test_context.rs` (`TestAppContext`, `VisualTestContext`) | pure | **done** | | `platform/web` | `gpui_web` | **js only** | planned | | `renderer/canvas2d` | (new) | **js only** | planned | | `renderer/software` | (new; optional) | pure | candidate | | `renderer/wgpu` | `gpui_wgpu` | native (+ js WebGPU) | later | | `platform/native/*` | `gpui_macos`, `gpui_linux`, `gpui_windows` | native only | later | -| `examples/*` | `examples/*` | executables | `card` (headless, prints a scene report) | +| `examples/*` | `examples/*` | executables | `counter` (M3–M4), `card` (headless on `TestPlatform`, prints a scene report) | | `elements/*` | `elements/{text,img,svg,list,uniform_list,anchored,deferred,animation}.rs` | pure | later | A facade package (`experiments/gpui` re-exporting the common API, similar to @@ -403,9 +403,25 @@ gantt - 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.** A headless `Platform`/`PlatformWindow` that records - scenes and injects input events, mirroring GPUI's `TestPlatform` and - `VisualTestContext`. This is the base for most later tests. +- **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).** - A `` window, rAF-driven frames, resize, and DPR. - DOM pointer, wheel, and key events → `PlatformInput`. @@ -573,6 +589,28 @@ gantt - 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 Decided on 2026-11-24, following the recommendations below. @@ -623,3 +661,8 @@ Decided on 2026-11-24, following the recommendations below. expected. Closures that raise must say so (`fn() raise { ... }`). - `Ref(x)` builds a `Ref`; `{ val: x }` needs a type annotation. - Test-only imports go in `import { ... } for "test"` in `moon.pkg`. +- 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`). diff --git a/src/elements/moon.pkg b/src/elements/moon.pkg index 322a9b7..8949a5f 100644 --- a/src/elements/moon.pkg +++ b/src/elements/moon.pkg @@ -12,4 +12,5 @@ options( import { "experiments/gpui/color", + "experiments/gpui/platform/test" @test_platform, } for "test" diff --git a/src/elements/visual_test.mbt b/src/elements/visual_test.mbt new file mode 100644 index 0000000..a8ba43b --- /dev/null +++ b/src/elements/visual_test.mbt @@ -0,0 +1,187 @@ +///| +struct VisualCounter { + mut count : Int32 +} + +///| +impl @window.Render for VisualCounter with fn render(self, _window, cx) { + @elements.div() + .flex() + .flex_row() + .gap(px(10.0)) + .p(px(10.0)) + .size_full() + .bg(@color.rgb(0xffffff)) + .child( + @elements.div() + .id("minus") + .size(px(20.0)) + .bg(@color.rgb(0xcc0000)) + .on_click( + @window.listener(cx, fn(counter, _, _, cx) { + counter.count -= 1 + cx.notify() + }), + ), + ) + .child( + @elements.div() + .w(px((self.count * 10).to_double())) + .h(px(20.0)) + .bg(@color.rgb(0x0000cc)), + ) + .child( + @elements.div() + .id("plus") + .size(px(20.0)) + .bg(@color.rgb(0x00cc00)) + .hover(fn(style) { style.bg(@color.rgb(0x00ff00)) }) + .on_click( + @window.listener(cx, fn(counter, _, _, cx) { + counter.count += 1 + cx.notify() + }), + ), + ) + .into_any_element() +} + +///| +test "VisualTestContext renders div counter and tracks scene history" { + let cx = @test_platform.TestAppContext::new() + let (counter, vcx) = cx.add_window_view( + size=@geometry.size(px(200.0), px(40.0)), + fn(_, _) { { count: 3, } }, + ) + assert_eq(vcx.draw_count(), 1) + assert_eq(vcx.scene().quads.length(), 4) + assert_eq(vcx.scene().quads[2].bounds.size.width, sp(30.0)) + assert_eq( + vcx.scene().quads[3].background, + @color.rgb(0x00cc00).to_background(), + ) + + // Moving onto "plus" triggers hover redraw automatically. + ignore(vcx.simulate_mouse_move(pt(90.0, 20.0))) + assert_eq(vcx.draw_count(), 2) + assert_eq( + vcx.scene().quads[3].background, + @color.rgb(0x00ff00).to_background(), + ) + + // Clicking "plus" updates the view and draws the expanded value bar. + vcx.simulate_click(pt(90.0, 20.0)) + assert_eq(cx.read_entity(counter).count, 4) + assert_eq(vcx.draw_count(), 3) + assert_eq(vcx.drawn_scenes().length(), 3) + assert_eq(vcx.scene().quads[2].bounds.size.width, sp(40.0)) + assert_eq(vcx.scene().quads[3].bounds.origin.x, sp(90.0)) +} + +///| +enum VisualCanvasView { + VisualCanvasView +} + +///| +impl @window.Render for VisualCanvasView with fn render(_self, _window, _cx) { + @elements.div() + .flex() + .size_full() + .p(px(10.0)) + .child( + @elements.canvas(fn(bounds, window, _) { + window.paint_path( + [[bounds.origin, bounds.top_right(), bounds.bottom_left()]], + @color.blue().to_background(), + ) + }).size_full(), + ) + .into_any_element() +} + +///| +test "VisualTestContext resize, scale factor, and canvas view" { + let cx = @test_platform.TestAppContext::new() + let (_, vcx) = cx.add_window_view(size=@geometry.size(px(100.0), px(80.0)), fn( + _, + _, + ) { + VisualCanvasView + }) + assert_eq(vcx.scene().paths.length(), 1) + assert_eq(vcx.scene().paths[0].bounds, sbounds(10.0, 10.0, 80.0, 60.0)) + + vcx.simulate_resize(@geometry.size(px(150.0), px(100.0))) + vcx.simulate_scale_factor_change(2.0) + assert_eq(vcx.scene().paths[0].bounds, sbounds(20.0, 20.0, 260.0, 160.0)) +} + +///| +struct VisualTicker { + mut ticks : Int32 +} + +///| +impl @window.Render for VisualTicker with fn render(self, _window, _cx) { + @elements.div() + .size_full() + .child( + @elements.div() + .w(px((self.ticks * 20).to_double())) + .h(px(10.0)) + .bg(@color.red()), + ) + .into_any_element() +} + +///| +test "VisualTestContext async ticker updates div layout on virtual clock" { + let cx = @test_platform.TestAppContext::new() + let (ticker, vcx) = cx.add_window_view( + size=@geometry.size(px(200.0), px(40.0)), + fn(_, ctx) { + let weak : @app.WeakEntity[VisualTicker] = ctx.weak_entity() + ctx + .spawn(async fn(_, async_app) { + while true { + async_app.background_executor().sleep(100) + let alive = weak.update(async_app.app, fn(t : VisualTicker, cx) { + t.ticks = t.ticks + 1 + cx.notify() + }) + if alive is None { + break + } + } + }) + .detach() + { ticks: 0, } + }, + ) + assert_eq(vcx.draw_count(), 1) + assert_eq(vcx.scene().quads.length(), 0) + + cx.advance_clock(250) + assert_eq(cx.read_entity(ticker).ticks, 2) + assert_true(vcx.draw_count() >= 2) + assert_eq(vcx.scene().quads.length(), 1) + assert_eq(vcx.scene().quads[0].bounds.size.width, sp(40.0)) +} + +///| +test "closing VisualTestContext window releases rendered div view" { + let cx = @test_platform.TestAppContext::new() + let released = Ref(false) + let (counter, vcx) = cx.add_window_view( + size=@geometry.size(px(100.0), px(40.0)), + fn(_, ctx) { + ctx.on_release(fn(_, _) { released.val = true }).detach() + { count: 1, } + }, + ) + assert_false(released.val) + assert_true(vcx.simulate_close()) + assert_true(counter.is_released()) + assert_true(released.val) +} diff --git a/src/examples/card/main.mbt b/src/examples/card/main.mbt index a4e3858..1d1f9e2 100644 --- a/src/examples/card/main.mbt +++ b/src/examples/card/main.mbt @@ -1,8 +1,9 @@ -// A headless example of what exists so far (M0-M6): a view renders a card -// with GPUI's `div()` and fluent styles; the window lays it out, paints it -// into a Scene and dispatches a simulated click. There is no renderer or -// text yet (text lines are placeholder bars), so the output is a report of -// the scene's draw batches and quads. +// A headless example of what exists so far (M0-M7): a view renders a card +// with GPUI's `div()` and fluent styles inside a `TestPlatform` window, +// and `VisualTestContext` simulates a hover and click while pumping frames +// automatically. There is no renderer or text yet (text lines are +// placeholder bars), so the output is a report of the scene's draw batches +// and quads. // // Run with: moon run src/examples/card --target js @@ -84,40 +85,23 @@ fn describe( ///| /// Builds the report printed by `main`. fn report() -> String { - let app = @app.App::new() - let window = @window.Window::new( - app, - @geometry.size(@geometry.px(400.0), @geometry.px(240.0)), + let cx = @test_platform.TestAppContext::new() + let (card, vcx) = cx.add_window_view( + size=@geometry.size(@geometry.px(400.0), @geometry.px(240.0)), + fn(_, _) { { expanded: false, clicks: 0, } }, ) - let card : @app.Entity[Card] = app.new_entity(fn(_) { - { expanded: false, clicks: 0, } - }) - window.set_root_view(card) + let card : @app.Entity[Card] = card let lines = [] - describe("first frame", window.draw(), lines) + describe("first frame", vcx.scene(), lines) // Hover the card, then click it: the view expands and the window redraws. let inside = @geometry.point(@geometry.px(100.0), @geometry.px(60.0)) - ignore( - window.dispatch_mouse_event( - MouseMove({ ..Default::default(), position: inside, }), - ), - ) - ignore(window.draw_if_dirty()) - ignore( - window.dispatch_mouse_event( - MouseDown({ ..Default::default(), position: inside, click_count: 1, }), - ), - ) - ignore( - window.dispatch_mouse_event( - MouseUp({ ..Default::default(), position: inside, click_count: 1, }), - ), - ) - let state = card.read(app) + ignore(vcx.simulate_mouse_move(inside)) + vcx.simulate_click(inside) + let state = cx.read_entity(card) lines.push( - "clicked: expanded = \{state.expanded}, clicks = \{state.clicks}, dirty = \{window.is_dirty()}", + "clicked: expanded = \{state.expanded}, clicks = \{state.clicks}, frames = \{vcx.draw_count()}, dirty = \{vcx.window().is_dirty()}", ) - describe("after click (hovered)", window.draw(), lines) + describe("after click (hovered)", vcx.scene(), lines) lines.join("\n") } diff --git a/src/examples/card/main_wbtest.mbt b/src/examples/card/main_wbtest.mbt index 9757b3a..cfe4e97 100644 --- a/src/examples/card/main_wbtest.mbt +++ b/src/examples/card/main_wbtest.mbt @@ -10,7 +10,7 @@ test "card report" { #| quad (57, 57) 160 x 10 #| quad (57, 75) 280 x 10 #| quad (40, 40) 320 x 62 border #d0d7deff - #|clicked: expanded = true, clicks = 1, dirty = true + #|clicked: expanded = true, clicks = 1, frames = 3, dirty = false #|after click (hovered) #| batches: quads (1), shadows (2), quads (7) #| quad (0, 0) 400 x 240 diff --git a/src/examples/card/moon.pkg b/src/examples/card/moon.pkg index 51f47b5..dd5dc3b 100644 --- a/src/examples/card/moon.pkg +++ b/src/examples/card/moon.pkg @@ -5,6 +5,7 @@ import { "experiments/gpui/app", "experiments/gpui/window", "experiments/gpui/elements", + "experiments/gpui/platform/test" @test_platform, } pkgtype(kind: "executable") diff --git a/src/input/input.mbt b/src/input/input.mbt index 22177c7..67b2b67 100644 --- a/src/input/input.mbt +++ b/src/input/input.mbt @@ -88,6 +88,22 @@ pub(all) struct ScrollWheelEvent { 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`). @@ -120,6 +136,72 @@ pub fn MouseEvent::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`). diff --git a/src/input/pkg.generated.mbti b/src/input/pkg.generated.mbti index 0c9ad37..a2f63c2 100644 --- a/src/input/pkg.generated.mbti +++ b/src/input/pkg.generated.mbti @@ -17,6 +17,12 @@ pub(all) struct ClickEvent { 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 @@ -33,6 +39,11 @@ pub(all) struct Modifiers { } 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 @@ -58,7 +69,16 @@ pub(all) enum MouseEvent { 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 { @@ -81,6 +101,18 @@ pub(all) enum NavigationDirection { 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]) diff --git a/src/platform/moon.pkg b/src/platform/moon.pkg new file mode 100644 index 0000000..27b2906 --- /dev/null +++ b/src/platform/moon.pkg @@ -0,0 +1,13 @@ +import { + "experiments/gpui/geometry", + "experiments/gpui/scene", + "experiments/gpui/style", + "experiments/gpui/input", + "experiments/gpui/executor", +} + +// experiments/gpui/executor uses MoonBit's experimental async intrinsics. + +options( + "allow-experimental-packages": true, +) diff --git a/src/platform/pkg.generated.mbti b/src/platform/pkg.generated.mbti new file mode 100644 index 0000000..38c6647 --- /dev/null +++ b/src/platform/pkg.generated.mbti @@ -0,0 +1,111 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/gpui/platform" + +import { + "experiments/gpui/executor", + "experiments/gpui/geometry", + "experiments/gpui/input", + "experiments/gpui/scene", + "experiments/gpui/style", + "moonbitlang/core/debug", +} + +// Values + +// Errors + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) enum ClipboardEntry { + String(ClipboardString) +} + +#derive(Eq, @debug.Debug) +pub(all) struct ClipboardItem { + entries : Array[ClipboardEntry] +} +pub fn ClipboardItem::metadata(Self) -> String? +pub fn ClipboardItem::new_string(String) -> Self +pub fn ClipboardItem::new_string_with_metadata(String, String) -> Self +pub fn ClipboardItem::text(Self) -> String? + +#derive(Eq, @debug.Debug) +pub(all) struct ClipboardString { + text : String + metadata : String? +} +pub fn ClipboardString::new(String) -> Self +pub fn ClipboardString::new_with_metadata(String, String) -> Self + +#derive(Eq, @debug.Debug) +pub(all) enum WindowBounds { + Windowed(@geometry.Bounds[@geometry.Pixels]) + Maximized(@geometry.Bounds[@geometry.Pixels]) + Fullscreen(@geometry.Bounds[@geometry.Pixels]) +} +pub fn WindowBounds::get_bounds(Self) -> @geometry.Bounds[@geometry.Pixels] +pub impl Default for WindowBounds + +#derive(Compare, Eq, Hash, @debug.Debug) +pub(all) struct WindowId(Int32) +pub impl Show for WindowId + +#derive(Eq, @debug.Debug) +pub(all) struct WindowOptions { + window_bounds : WindowBounds? + title : String? + focus : Bool + show : Bool + scale_factor : Double? + rem_size : @geometry.Pixels +} +pub fn WindowOptions::with_size(@geometry.Size[@geometry.Pixels], scale_factor? : Double, title? : String, rem_size? : @geometry.Pixels) -> Self +pub impl Default for WindowOptions + +#derive(Eq, @debug.Debug) +pub(all) struct WindowParams { + bounds : @geometry.Bounds[@geometry.Pixels] + title : String? + focus : Bool + show : Bool + scale_factor : Double? +} + +// Type aliases + +// Traits +pub(open) trait Platform { + fn dispatcher(Self) -> &@executor.Dispatcher + fn default_window_bounds(Self) -> @geometry.Bounds[@geometry.Pixels] + fn open_window(Self, WindowId, WindowParams) -> &PlatformWindow + fn run(Self, () -> Unit) -> Unit + fn quit(Self) -> Unit + fn active_window(Self) -> WindowId? + fn set_cursor_style(Self, @style.CursorStyle) -> Unit + fn read_from_clipboard(Self) -> ClipboardItem? + fn write_to_clipboard(Self, ClipboardItem) -> Unit + fn open_url(Self, String) -> Unit +} + +pub(open) trait PlatformWindow { + fn bounds(Self) -> @geometry.Bounds[@geometry.Pixels] + fn content_size(Self) -> @geometry.Size[@geometry.Pixels] + fn scale_factor(Self) -> Double + fn mouse_position(Self) -> @geometry.Point[@geometry.Pixels] + fn modifiers(Self) -> @input.Modifiers + fn is_active(Self) -> Bool + fn is_hovered(Self) -> Bool + fn set_title(Self, String) -> Unit + fn activate(Self) -> Unit + fn resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit + fn draw(Self, @scene.Scene) -> Unit + fn schedule_frame(Self) -> Unit + fn close(Self) -> Unit + fn on_request_frame(Self, () -> Unit) -> Unit + fn on_input(Self, (@input.PlatformInput) -> @input.DispatchEventResult) -> Unit + fn on_resize(Self, (@geometry.Size[@geometry.Pixels], Double) -> Unit) -> Unit + fn on_active_status_change(Self, (Bool) -> Unit) -> Unit + fn on_hover_status_change(Self, (Bool) -> Unit) -> Unit + fn on_should_close(Self, () -> Bool) -> Unit + fn on_close(Self, () -> Unit) -> Unit +} diff --git a/src/platform/platform.mbt b/src/platform/platform.mbt new file mode 100644 index 0000000..f6c9d77 --- /dev/null +++ b/src/platform/platform.mbt @@ -0,0 +1,83 @@ +// Platform interfaces, ported from gpui/src/platform.rs (the core subset: +// windows, event loop, executor dispatcher, cursor and clipboard; text +// system, glyph atlas, IME, menus and displays arrive in M9/M10). +// +// Pure trait definitions only; concrete backends live in `platform/test` +// (M7) and `platform/web` (M8). + +///| +/// A platform-backed window handle (GPUI: `PlatformWindow`). +pub(open) trait PlatformWindow { + /// Window bounds in logical pixels. + fn bounds(Self) -> @geometry.Bounds[@geometry.Pixels] + /// Size of the drawable content area in logical pixels. + fn content_size(Self) -> @geometry.Size[@geometry.Pixels] + /// Device-pixel scale factor. + fn scale_factor(Self) -> Double + /// Last known pointer position in logical pixels. + fn mouse_position(Self) -> @geometry.Point[@geometry.Pixels] + /// Currently held modifier keys. + fn modifiers(Self) -> @input.Modifiers + /// Whether this window is currently active/focused. + fn is_active(Self) -> Bool + /// Whether the pointer is currently over this window. + fn is_hovered(Self) -> Bool + /// Sets the window's title. + fn set_title(Self, String) -> Unit + /// Focuses/brings this window to the front. + fn activate(Self) -> Unit + /// Programmatically resizes the window to `size`. Must not re-enter + /// `on_resize`. + fn resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit + /// Presents a finished `Scene`. + fn draw(Self, @scene.Scene) -> Unit + /// Requests that the platform invoke the `on_request_frame` callback on + /// the next frame. + fn schedule_frame(Self) -> Unit + /// App-driven teardown hook (MoonBit has no `Drop`). Must be idempotent + /// and must not re-invoke `on_close`. + fn close(Self) -> Unit + /// Registers the callback invoked when a scheduled frame should draw. + fn on_request_frame(Self, () -> Unit) -> Unit + /// Registers the callback invoked for platform input events. + fn on_input(Self, (@input.PlatformInput) -> @input.DispatchEventResult) -> Unit + /// Registers the callback invoked when the window size or scale factor + /// changes from the platform side. + fn on_resize(Self, (@geometry.Size[@geometry.Pixels], Double) -> Unit) -> Unit + /// Registers the callback invoked when active status changes. + fn on_active_status_change(Self, (Bool) -> Unit) -> Unit + /// Registers the callback invoked when pointer hover status changes. + fn on_hover_status_change(Self, (Bool) -> Unit) -> Unit + /// Registers the callback asked whether a user-initiated close should + /// proceed. + fn on_should_close(Self, () -> Bool) -> Unit + /// Registers the callback invoked when the platform closes the window. + fn on_close(Self, () -> Unit) -> Unit +} + +///| +/// Platform services (GPUI: `Platform`). +pub(open) trait Platform { + /// The dispatcher used by the app's executors. + fn dispatcher(Self) -> &@executor.Dispatcher + /// Default logical bounds for a new window when `WindowOptions.window_bounds` + /// is `None`. + fn default_window_bounds(Self) -> @geometry.Bounds[@geometry.Pixels] + /// Opens a new platform window with the given id and parameters. + fn open_window(Self, WindowId, WindowParams) -> &PlatformWindow + /// Starts the platform event loop, calling `on_finish_launching` once + /// ready. + fn run(Self, () -> Unit) -> Unit + /// Requests that the platform event loop exit. + fn quit(Self) -> Unit + /// The currently active window id, if any. + fn active_window(Self) -> WindowId? + /// Sets the pointer cursor style. + fn set_cursor_style(Self, @style.CursorStyle) -> Unit + /// Reads the current clipboard contents, if any. + fn read_from_clipboard(Self) -> ClipboardItem? + /// Replaces the clipboard contents. + fn write_to_clipboard(Self, ClipboardItem) -> Unit + /// Opens `url` in the system/browser handler. + fn open_url(Self, String) -> Unit +} diff --git a/src/platform/platform_test.mbt b/src/platform/platform_test.mbt new file mode 100644 index 0000000..e2b0759 --- /dev/null +++ b/src/platform/platform_test.mbt @@ -0,0 +1,70 @@ +///| +test "WindowBounds get_bounds extracts bounds across variants" { + let b = @geometry.bounds( + @geometry.point(@geometry.px(10.0), @geometry.px(20.0)), + @geometry.size(@geometry.px(800.0), @geometry.px(600.0)), + ) + assert_eq(@platform.WindowBounds::Windowed(b).get_bounds(), b) + assert_eq(@platform.WindowBounds::Maximized(b).get_bounds(), b) + assert_eq(@platform.WindowBounds::Fullscreen(b).get_bounds(), b) + assert_eq( + (Default::default() : @platform.WindowBounds), + @platform.WindowBounds::Windowed(Default::default()), + ) +} + +///| +test "WindowOptions default and with_size" { + let defaults : @platform.WindowOptions = Default::default() + assert_eq(defaults.window_bounds, None) + assert_eq(defaults.title, None) + assert_true(defaults.focus) + assert_true(defaults.show) + assert_eq(defaults.scale_factor, None) + assert_eq(defaults.rem_size, @geometry.px(16.0)) + let opts = @platform.WindowOptions::with_size( + @geometry.size(@geometry.px(640.0), @geometry.px(480.0)), + scale_factor=2.0, + title="Demo", + rem_size=@geometry.px(14.0), + ) + assert_eq( + opts.window_bounds, + Some( + @platform.WindowBounds::Windowed( + @geometry.bounds( + @geometry.point(@geometry.px(0.0), @geometry.px(0.0)), + @geometry.size(@geometry.px(640.0), @geometry.px(480.0)), + ), + ), + ), + ) + assert_eq(opts.scale_factor, Some(2.0)) + assert_eq(opts.title, Some("Demo")) + assert_eq(opts.rem_size, @geometry.px(14.0)) +} + +///| +test "ClipboardItem text and metadata" { + let plain = @platform.ClipboardItem::new_string("hello") + assert_eq(plain.text(), Some("hello")) + assert_eq(plain.metadata(), None) + let with_meta = @platform.ClipboardItem::new_string_with_metadata( + "code", "rust", + ) + assert_eq(with_meta.text(), Some("code")) + assert_eq(with_meta.metadata(), Some("rust")) + let multi : @platform.ClipboardItem = { + entries: [ + @platform.ClipboardEntry::String( + @platform.ClipboardString::new_with_metadata("first", "m1"), + ), + @platform.ClipboardEntry::String(@platform.ClipboardString::new("second")), + ], + } + assert_eq(multi.text(), Some("first\nsecond")) + assert_eq(multi.metadata(), Some("m1")) + let empty : @platform.ClipboardItem = { entries: [], } + assert_eq(empty.text(), None) + assert_eq(empty.metadata(), None) +} diff --git a/src/platform/test/moon.pkg b/src/platform/test/moon.pkg new file mode 100644 index 0000000..5c024f2 --- /dev/null +++ b/src/platform/test/moon.pkg @@ -0,0 +1,20 @@ +import { + "experiments/gpui/geometry", + "experiments/gpui/scene", + "experiments/gpui/style", + "experiments/gpui/input", + "experiments/gpui/executor", + "experiments/gpui/app", + "experiments/gpui/platform", + "experiments/gpui/window", +} + +// experiments/gpui/executor uses MoonBit's experimental async intrinsics. + +options( + "allow-experimental-packages": true, +) + +import { + "experiments/gpui/color", +} for "test" diff --git a/src/platform/test/pkg.generated.mbti b/src/platform/test/pkg.generated.mbti new file mode 100644 index 0000000..4feeb3f --- /dev/null +++ b/src/platform/test/pkg.generated.mbti @@ -0,0 +1,147 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/gpui/platform/test" + +import { + "experiments/gpui/app", + "experiments/gpui/executor", + "experiments/gpui/geometry", + "experiments/gpui/input", + "experiments/gpui/platform", + "experiments/gpui/scene", + "experiments/gpui/style", + "experiments/gpui/window", +} + +// Values + +// Errors + +// Types and methods +pub struct TestAppContext { + platform : TestPlatform + application : @window.Application + // private fields +} +pub fn TestAppContext::active_window(Self) -> @window.AnyWindowHandle? +pub fn TestAppContext::add_empty_window(Self, size? : @geometry.Size[@geometry.Pixels], scale_factor? : Double) -> VisualTestContext +pub fn[V : @window.Render] TestAppContext::add_window(Self, size? : @geometry.Size[@geometry.Pixels], scale_factor? : Double, title? : String, (@window.Window, @app.Context[V]) -> V) -> @window.WindowHandle[V] +pub fn[V : @window.Render] TestAppContext::add_window_view(Self, size? : @geometry.Size[@geometry.Pixels], scale_factor? : Double, title? : String, (@window.Window, @app.Context[V]) -> V) -> (@app.Entity[V], VisualTestContext) +pub fn TestAppContext::advance_clock(Self, Int32) -> Unit +pub fn TestAppContext::app(Self) -> @app.App +pub fn TestAppContext::application(Self) -> @window.Application +pub fn TestAppContext::background_executor(Self) -> @executor.Executor +pub fn TestAppContext::cursor_style(Self) -> @style.CursorStyle +pub fn TestAppContext::dispatcher(Self) -> @executor.TestDispatcher +pub fn TestAppContext::foreground_executor(Self) -> @executor.Executor +pub fn[G] TestAppContext::has_global(Self, @app.GlobalKey[G]) -> Bool +pub fn TestAppContext::new(default_bounds? : @geometry.Bounds[@geometry.Pixels], default_scale_factor? : Double) -> Self +pub fn[T] TestAppContext::new_entity(Self, (@app.Context[T]) -> T) -> @app.Entity[T] +pub fn[V : @window.Render] TestAppContext::open_window(Self, options? : @platform.WindowOptions, (@window.Window, @app.App) -> @app.Entity[V]) -> @window.WindowHandle[V] +pub fn TestAppContext::opened_url(Self) -> String? +pub fn TestAppContext::platform(Self) -> TestPlatform +pub fn TestAppContext::pump_frames(Self) -> Int32 +pub fn TestAppContext::quit(Self) -> Unit +pub fn[R] TestAppContext::read(Self, (@app.App) -> R) -> R +pub fn[T] TestAppContext::read_entity(Self, @app.Entity[T]) -> T +pub fn TestAppContext::read_from_clipboard(Self) -> @platform.ClipboardItem? +pub fn[G] TestAppContext::read_global(Self, @app.GlobalKey[G]) -> G +pub fn TestAppContext::refresh(Self) -> Unit +pub fn TestAppContext::run_until_parked(Self) -> Unit +pub fn[G] TestAppContext::set_global(Self, @app.GlobalKey[G], G) -> Unit +pub fn TestAppContext::skip_drawing(Self, skip? : Bool) -> Unit +pub fn[R] TestAppContext::spawn(Self, async (@app.AsyncApp) -> R) -> @executor.Task[R] +pub fn TestAppContext::test_window(Self, @window.AnyWindowHandle) -> TestWindow +pub fn[R] TestAppContext::update(Self, (@app.App) -> R) -> R +pub fn[T, R] TestAppContext::update_entity(Self, @app.Entity[T], (T, @app.Context[T]) -> R) -> R +pub fn[G, R] TestAppContext::update_global(Self, @app.GlobalKey[G], (G, @app.App) -> R) -> R +pub fn TestAppContext::windows(Self) -> Array[@window.AnyWindowHandle] +pub fn TestAppContext::with_platform(TestPlatform) -> Self +pub fn TestAppContext::write_to_clipboard(Self, @platform.ClipboardItem) -> Unit + +pub struct TestPlatform { + // private fields +} +pub fn TestPlatform::cursor_style(Self) -> @style.CursorStyle +pub fn TestPlatform::did_quit(Self) -> Bool +pub fn TestPlatform::did_run(Self) -> Bool +pub fn TestPlatform::new(dispatcher? : @executor.TestDispatcher, default_bounds? : @geometry.Bounds[@geometry.Pixels], default_scale_factor? : Double) -> Self +pub fn TestPlatform::opened_url(Self) -> String? +pub fn TestPlatform::opened_urls(Self) -> Array[String] +pub fn TestPlatform::pump_scheduled_frames(Self) -> Int32 +pub fn TestPlatform::set_active_window(Self, TestWindow?) -> Unit +pub fn TestPlatform::test_dispatcher(Self) -> @executor.TestDispatcher +pub fn TestPlatform::window(Self, @platform.WindowId) -> TestWindow? +pub fn TestPlatform::windows(Self) -> Array[TestWindow] +pub impl @platform.Platform for TestPlatform + +pub struct TestWindow { + // private fields +} +pub fn TestWindow::clear_drawn_scenes(Self) -> Unit +pub fn TestWindow::draw_count(Self) -> Int32 +pub fn TestWindow::drawn_scenes(Self) -> Array[@scene.Scene] +pub fn TestWindow::frame_schedule_count(Self) -> Int32 +pub fn TestWindow::frame_scheduled(Self) -> Bool +pub fn TestWindow::is_closed(Self) -> Bool +pub fn TestWindow::last_scene(Self) -> @scene.Scene? +pub fn TestWindow::simulate_active_status_change(Self, Bool) -> Unit +pub fn TestWindow::simulate_close(Self) -> Unit +pub fn TestWindow::simulate_close_requested(Self) -> Bool +pub fn TestWindow::simulate_frame_request(Self) -> Unit +pub fn TestWindow::simulate_hover_status_change(Self, Bool) -> Unit +pub fn TestWindow::simulate_input(Self, @input.PlatformInput) -> @input.DispatchEventResult +pub fn TestWindow::simulate_resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit +pub fn TestWindow::simulate_scale_factor_change(Self, Double) -> Unit +pub fn TestWindow::simulate_scheduled_frame(Self) -> Bool +pub fn TestWindow::simulate_should_close(Self) -> Bool +pub fn TestWindow::title(Self) -> String? +pub fn TestWindow::window_id(Self) -> @platform.WindowId +pub impl @platform.PlatformWindow for TestWindow + +pub struct VisualTestContext { + cx : TestAppContext + window_handle : @window.AnyWindowHandle +} +pub fn VisualTestContext::advance_clock(Self, Int32) -> Unit +pub fn VisualTestContext::app(Self) -> @app.App +pub fn VisualTestContext::bounds(Self) -> @geometry.Bounds[@geometry.Pixels] +pub fn VisualTestContext::cursor_style(Self) -> @style.CursorStyle +pub fn VisualTestContext::draw(Self) -> @scene.Scene +pub fn VisualTestContext::draw_count(Self) -> Int32 +pub fn VisualTestContext::drawn_scenes(Self) -> Array[@scene.Scene] +pub fn VisualTestContext::from_window(@window.AnyWindowHandle, TestAppContext) -> Self +pub fn VisualTestContext::is_active(Self) -> Bool +pub fn VisualTestContext::is_closed(Self) -> Bool +pub fn VisualTestContext::is_hovered(Self) -> Bool +pub fn[T] VisualTestContext::new_entity(Self, (@app.Context[T]) -> T) -> @app.Entity[T] +pub fn[R] VisualTestContext::read(Self, (@app.App) -> R) -> R +pub fn VisualTestContext::read_from_clipboard(Self) -> @platform.ClipboardItem? +pub fn[V : @window.Render] VisualTestContext::replace_root_view(Self, (@window.Window, @app.Context[V]) -> V) -> @app.Entity[V] +pub fn VisualTestContext::run_until_parked(Self) -> Unit +pub fn VisualTestContext::scale_factor(Self) -> Double +pub fn VisualTestContext::scene(Self) -> @scene.Scene +pub fn VisualTestContext::simulate_active_status_change(Self, Bool) -> Unit +pub fn VisualTestContext::simulate_click(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers) -> Unit +pub fn VisualTestContext::simulate_close(Self) -> Bool +pub fn VisualTestContext::simulate_hover_status_change(Self, Bool) -> Unit +pub fn VisualTestContext::simulate_input(Self, @input.PlatformInput) -> @input.DispatchEventResult +pub fn VisualTestContext::simulate_modifiers_change(Self, @input.Modifiers) -> @input.DispatchEventResult +pub fn VisualTestContext::simulate_mouse_down(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers, click_count? : Int32) -> @input.DispatchEventResult +pub fn VisualTestContext::simulate_mouse_exit(Self, position? : @geometry.Point[@geometry.Pixels], modifiers? : @input.Modifiers) -> @input.DispatchEventResult +pub fn VisualTestContext::simulate_mouse_move(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers) -> @input.DispatchEventResult +pub fn VisualTestContext::simulate_mouse_up(Self, @geometry.Point[@geometry.Pixels], button? : @input.MouseButton, modifiers? : @input.Modifiers, click_count? : Int32) -> @input.DispatchEventResult +pub fn VisualTestContext::simulate_resize(Self, @geometry.Size[@geometry.Pixels]) -> Unit +pub fn VisualTestContext::simulate_scale_factor_change(Self, Double) -> Unit +pub fn VisualTestContext::simulate_scroll_wheel(Self, @geometry.Point[@geometry.Pixels], @input.ScrollDelta, modifiers? : @input.Modifiers) -> @input.DispatchEventResult +pub fn VisualTestContext::test_window(Self) -> TestWindow +pub fn[R] VisualTestContext::update(Self, (@window.Window, @app.App) -> R) -> R +pub fn[T, R] VisualTestContext::update_entity(Self, @app.Entity[T], (T, @app.Context[T]) -> R) -> R +pub fn VisualTestContext::window(Self) -> @window.Window +pub fn VisualTestContext::window_handle(Self) -> @window.AnyWindowHandle +pub fn VisualTestContext::window_id(Self) -> @platform.WindowId +pub fn VisualTestContext::window_title(Self) -> String? +pub fn VisualTestContext::write_to_clipboard(Self, @platform.ClipboardItem) -> Unit + +// Type aliases + +// Traits diff --git a/src/platform/test/platform.mbt b/src/platform/test/platform.mbt new file mode 100644 index 0000000..fd3afca --- /dev/null +++ b/src/platform/test/platform.mbt @@ -0,0 +1,224 @@ +// Headless test platform, ported from gpui/src/platform/test/platform.rs. + +///| +let default_test_bounds : @geometry.Bounds[@geometry.Pixels] = @geometry.bounds( + @geometry.point(@geometry.px(0.0), @geometry.px(0.0)), + @geometry.size(@geometry.px(1024.0), @geometry.px(768.0)), +) + +///| +/// A headless `Platform` backed by `TestDispatcher` and `TestWindow`s +/// (GPUI: `TestPlatform`). +pub struct TestPlatform { + priv dispatcher : @executor.TestDispatcher + priv default_bounds : @geometry.Bounds[@geometry.Pixels] + priv default_scale_factor : Double + priv windows : Map[@platform.WindowId, TestWindow] + priv mut active_window : TestWindow? + priv mut active_cursor : @style.CursorStyle + priv mut clipboard : @platform.ClipboardItem? + priv opened_urls : Array[String] + priv mut run_called : Bool + priv mut quit_called : Bool +} + +///| +pub fn TestPlatform::new( + dispatcher? : @executor.TestDispatcher, + default_bounds? : @geometry.Bounds[@geometry.Pixels], + default_scale_factor~ : Double = 1.0, +) -> TestPlatform { + { + dispatcher: dispatcher.unwrap_or(@executor.TestDispatcher::new()), + default_bounds: default_bounds.unwrap_or(default_test_bounds), + default_scale_factor, + windows: {}, + active_window: None, + active_cursor: Arrow, + clipboard: None, + opened_urls: [], + run_called: false, + quit_called: false, + } +} + +///| +pub impl @platform.Platform for TestPlatform with fn dispatcher(self) { + let d : &@executor.Dispatcher = self.dispatcher + d +} + +///| +pub impl @platform.Platform for TestPlatform with fn default_window_bounds(self) { + self.default_bounds +} + +///| +pub impl @platform.Platform for TestPlatform with fn open_window( + self, + id, + params, +) { + let window = TestWindow::new(id, self, params, self.default_scale_factor) + self.windows[id] = window + if params.focus { + let previous = self.active_window + self.active_window = Some(window) + if previous is Some(prev) && prev.id != id { + @executor.Dispatcher::dispatch(self.dispatcher, fn() { + if !prev.closed { + prev.simulate_active_status_change(false) + } + }) + } + } + let pw : &@platform.PlatformWindow = window + pw +} + +///| +pub impl @platform.Platform for TestPlatform with fn run( + self, + on_finish_launching, +) { + self.run_called = true + on_finish_launching() +} + +///| +pub impl @platform.Platform for TestPlatform with fn quit(self) { + self.quit_called = true +} + +///| +pub impl @platform.Platform for TestPlatform with fn active_window(self) { + match self.active_window { + Some(win) if !win.closed => Some(win.id) + _ => None + } +} + +///| +pub impl @platform.Platform for TestPlatform with fn set_cursor_style( + self, + style, +) { + self.active_cursor = style +} + +///| +pub impl @platform.Platform for TestPlatform with fn read_from_clipboard(self) { + self.clipboard +} + +///| +pub impl @platform.Platform for TestPlatform with fn write_to_clipboard( + self, + item, +) { + self.clipboard = Some(item) +} + +///| +pub impl @platform.Platform for TestPlatform with fn open_url(self, url) { + self.opened_urls.push(url) +} + +// --------------------------------------------------------------------------- +// Inspection and simulation helpers +// --------------------------------------------------------------------------- + +///| +pub fn TestPlatform::test_dispatcher( + self : TestPlatform, +) -> @executor.TestDispatcher { + self.dispatcher +} + +///| +pub fn TestPlatform::window( + self : TestPlatform, + id : @platform.WindowId, +) -> TestWindow? { + self.windows.get(id) +} + +///| +pub fn TestPlatform::windows(self : TestPlatform) -> Array[TestWindow] { + let out = [] + for _, win in self.windows { + out.push(win) + } + out +} + +///| +pub fn TestPlatform::cursor_style(self : TestPlatform) -> @style.CursorStyle { + self.active_cursor +} + +///| +pub fn TestPlatform::opened_url(self : TestPlatform) -> String? { + self.opened_urls.last() +} + +///| +pub fn TestPlatform::opened_urls(self : TestPlatform) -> Array[String] { + self.opened_urls +} + +///| +pub fn TestPlatform::did_run(self : TestPlatform) -> Bool { + self.run_called +} + +///| +pub fn TestPlatform::did_quit(self : TestPlatform) -> Bool { + self.quit_called +} + +///| +/// Transfers active window status, notifying the previous and new windows on +/// the dispatcher (GPUI: `TestPlatform::set_active_window`). +pub fn TestPlatform::set_active_window( + self : TestPlatform, + window : TestWindow?, +) -> Unit { + let previous = self.active_window + self.active_window = window + let same = match (previous, window) { + (Some(prev), Some(curr)) => prev.id == curr.id + (None, None) => true + _ => false + } + if same { + return + } + @executor.Dispatcher::dispatch(self.dispatcher, fn() { + if previous is Some(prev) && !prev.closed { + prev.simulate_active_status_change(false) + } + if window is Some(win) && !win.closed { + win.simulate_active_status_change(true) + } + }) +} + +///| +/// Delivers one scheduled frame for every open window that currently has a +/// frame scheduled, returning how many frames ran. +pub fn TestPlatform::pump_scheduled_frames(self : TestPlatform) -> Int32 { + let open = [] + for _, win in self.windows { + if !win.closed && win.frame_scheduled { + open.push(win) + } + } + let mut pumped : Int32 = 0 + for win in open { + if win.simulate_scheduled_frame() { + pumped = pumped + 1 + } + } + pumped +} diff --git a/src/platform/test/test_context.mbt b/src/platform/test/test_context.mbt new file mode 100644 index 0000000..39289c3 --- /dev/null +++ b/src/platform/test/test_context.mbt @@ -0,0 +1,646 @@ +// High-level test harnesses, ported from gpui/src/app/test_context.rs +// (`TestAppContext` and `VisualTestContext`). + +///| +priv enum EmptyView { + EmptyView +} + +///| +impl @window.Render for EmptyView with fn render(_self, _window, _cx) { + @window.empty() +} + +///| +/// Owns a `TestPlatform` and `Application`, pumping tasks and scheduled +/// frames together for deterministic integration tests (GPUI: +/// `TestAppContext`). +pub struct TestAppContext { + platform : TestPlatform + application : @window.Application + priv mut skip_drawing : Bool +} + +///| +pub fn TestAppContext::new( + default_bounds? : @geometry.Bounds[@geometry.Pixels], + default_scale_factor~ : Double = 1.0, +) -> TestAppContext { + let platform = TestPlatform::new(default_bounds?, default_scale_factor~) + TestAppContext::with_platform(platform) +} + +///| +pub fn TestAppContext::with_platform(platform : TestPlatform) -> TestAppContext { + let p : &@platform.Platform = platform + let application = @window.Application::with_platform(p) + { platform, application, skip_drawing: false, } +} + +///| +pub fn TestAppContext::app(self : TestAppContext) -> @app.App { + self.application.app() +} + +///| +pub fn TestAppContext::application( + self : TestAppContext, +) -> @window.Application { + self.application +} + +///| +pub fn TestAppContext::platform(self : TestAppContext) -> TestPlatform { + self.platform +} + +///| +pub fn TestAppContext::dispatcher( + self : TestAppContext, +) -> @executor.TestDispatcher { + self.platform.test_dispatcher() +} + +///| +pub fn TestAppContext::foreground_executor( + self : TestAppContext, +) -> @executor.Executor { + self.application.app().foreground_executor() +} + +///| +pub fn TestAppContext::background_executor( + self : TestAppContext, +) -> @executor.Executor { + self.application.app().background_executor() +} + +///| +pub fn TestAppContext::windows( + self : TestAppContext, +) -> Array[@window.AnyWindowHandle] { + self.application.windows() +} + +///| +pub fn TestAppContext::active_window( + self : TestAppContext, +) -> @window.AnyWindowHandle? { + self.application.active_window() +} + +///| +pub fn TestAppContext::test_window( + self : TestAppContext, + handle : @window.AnyWindowHandle, +) -> TestWindow { + match self.platform.window(handle.window_id()) { + Some(win) => win + None => abort("no TestWindow for \{handle.window_id()}") + } +} + +///| +/// Disables (or re-enables) automatic frame pumping in `run_until_parked` +/// (GPUI: `TestAppContext::skip_drawing`). +pub fn TestAppContext::skip_drawing( + self : TestAppContext, + skip~ : Bool = true, +) -> Unit { + self.skip_drawing = skip +} + +///| +pub fn TestAppContext::pump_frames(self : TestAppContext) -> Int32 { + self.platform.pump_scheduled_frames() +} + +///| +/// Drains all ready tasks and pumps scheduled frames until neither tasks nor +/// scheduled frames remain (GPUI: `TestAppContext::run_until_parked`). Aborts +/// after 100 frame pump passes to catch runaway redraw loops. +pub fn TestAppContext::run_until_parked(self : TestAppContext) -> Unit { + let max_passes = 100 + let mut passes = 0 + while true { + self.platform.test_dispatcher().run_until_parked() + if self.skip_drawing { + break + } + let pumped = self.platform.pump_scheduled_frames() + if pumped == 0 { + break + } + passes = passes + 1 + if passes >= max_passes { + abort( + "TestAppContext::run_until_parked: runaway redraw loop (> \{max_passes} frame pumps)", + ) + } + } +} + +///| +/// Advances the virtual clock by `ms`, running timers, tasks and scheduled +/// frames (GPUI: `TestAppContext::advance_clock`). +pub fn TestAppContext::advance_clock(self : TestAppContext, ms : Int32) -> Unit { + self.run_until_parked() + self.platform.test_dispatcher().advance_clock(ms) + self.run_until_parked() +} + +///| +pub fn[R] TestAppContext::update( + self : TestAppContext, + f : (@app.App) -> R, +) -> R { + let result = self.application.app().update(f) + self.run_until_parked() + result +} + +///| +pub fn[R] TestAppContext::read(self : TestAppContext, f : (@app.App) -> R) -> R { + f(self.application.app()) +} + +///| +pub fn[T] TestAppContext::new_entity( + self : TestAppContext, + build : (@app.Context[T]) -> T, +) -> @app.Entity[T] { + self.update(fn(app) { app.new_entity(build) }) +} + +///| +pub fn[T, R] TestAppContext::update_entity( + self : TestAppContext, + entity : @app.Entity[T], + f : (T, @app.Context[T]) -> R, +) -> R { + self.update(fn(app) { app.update_entity(entity, f) }) +} + +///| +pub fn[T] TestAppContext::read_entity( + self : TestAppContext, + entity : @app.Entity[T], +) -> T { + self.application.app().read_entity(entity) +} + +///| +pub fn[R] TestAppContext::spawn( + self : TestAppContext, + f : async (@app.AsyncApp) -> R, +) -> @executor.Task[R] { + self.application.app().spawn(f) +} + +///| +pub fn[G] TestAppContext::set_global( + self : TestAppContext, + key : @app.GlobalKey[G], + value : G, +) -> Unit { + self.update(fn(app) { app.set_global(key, value) }) +} + +///| +pub fn[G] TestAppContext::read_global( + self : TestAppContext, + key : @app.GlobalKey[G], +) -> G { + self.application.app().global(key) +} + +///| +pub fn[G] TestAppContext::has_global( + self : TestAppContext, + key : @app.GlobalKey[G], +) -> Bool { + self.application.app().has_global(key) +} + +///| +pub fn[G, R] TestAppContext::update_global( + self : TestAppContext, + key : @app.GlobalKey[G], + f : (G, @app.App) -> R, +) -> R { + self.update(fn(app) { app.update_global(key, f) }) +} + +///| +pub fn TestAppContext::write_to_clipboard( + self : TestAppContext, + item : @platform.ClipboardItem, +) -> Unit { + self.application.write_to_clipboard(item) +} + +///| +pub fn TestAppContext::read_from_clipboard( + self : TestAppContext, +) -> @platform.ClipboardItem? { + self.application.read_from_clipboard() +} + +///| +pub fn TestAppContext::cursor_style( + self : TestAppContext, +) -> @style.CursorStyle { + self.platform.cursor_style() +} + +///| +pub fn TestAppContext::opened_url(self : TestAppContext) -> String? { + self.platform.opened_url() +} + +///| +pub fn TestAppContext::refresh(self : TestAppContext) -> Unit { + self.application.refresh_windows() + self.run_until_parked() +} + +///| +pub fn TestAppContext::quit(self : TestAppContext) -> Unit { + self.application.quit() +} + +///| +pub fn[V : @window.Render] TestAppContext::open_window( + self : TestAppContext, + options? : @platform.WindowOptions, + build_root : (@window.Window, @app.App) -> @app.Entity[V], +) -> @window.WindowHandle[V] { + let opts = options.unwrap_or(Default::default()) + let handle = self.application.open_window(opts, build_root) + self.run_until_parked() + handle +} + +///| +pub fn[V : @window.Render] TestAppContext::add_window( + self : TestAppContext, + size? : @geometry.Size[@geometry.Pixels], + scale_factor? : Double, + title? : String, + build_view : (@window.Window, @app.Context[V]) -> V, +) -> @window.WindowHandle[V] { + let options : @platform.WindowOptions = match size { + Some(s) => @platform.WindowOptions::with_size(s, scale_factor?, title?) + None => { ..Default::default(), scale_factor, title, } + } + self.open_window(options~, fn(window, app) { + app.new_entity(fn(cx) { build_view(window, cx) }) + }) +} + +///| +pub fn[V : @window.Render] TestAppContext::add_window_view( + self : TestAppContext, + size? : @geometry.Size[@geometry.Pixels], + scale_factor? : Double, + title? : String, + build_view : (@window.Window, @app.Context[V]) -> V, +) -> (@app.Entity[V], VisualTestContext) { + let handle = self.add_window(size?, scale_factor?, title?, build_view) + let vcx = VisualTestContext::from_window(handle.to_any(), self) + (handle.entity(), vcx) +} + +///| +pub fn TestAppContext::add_empty_window( + self : TestAppContext, + size? : @geometry.Size[@geometry.Pixels], + scale_factor? : Double, +) -> VisualTestContext { + let (_, vcx) = self.add_window_view(size?, scale_factor?, fn(_, _) { + EmptyView::EmptyView + }) + vcx +} + +// --------------------------------------------------------------------------- +// VisualTestContext +// --------------------------------------------------------------------------- + +///| +/// Window-scoped test driver combining a `TestAppContext` with one +/// `AnyWindowHandle` (GPUI: `VisualTestContext`). +pub struct VisualTestContext { + cx : TestAppContext + window_handle : @window.AnyWindowHandle +} + +///| +pub fn VisualTestContext::from_window( + window_handle : @window.AnyWindowHandle, + cx : TestAppContext, +) -> VisualTestContext { + { cx, window_handle, } +} + +///| +pub fn VisualTestContext::window_handle( + self : VisualTestContext, +) -> @window.AnyWindowHandle { + self.window_handle +} + +///| +pub fn VisualTestContext::window_id( + self : VisualTestContext, +) -> @platform.WindowId { + self.window_handle.window_id() +} + +///| +pub fn VisualTestContext::app(self : VisualTestContext) -> @app.App { + self.cx.app() +} + +///| +pub fn VisualTestContext::test_window(self : VisualTestContext) -> TestWindow { + self.cx.test_window(self.window_handle) +} + +///| +pub fn VisualTestContext::window(self : VisualTestContext) -> @window.Window { + match self.cx.application.window(self.window_id()) { + Some(win) => win + None => abort("window \{self.window_id()} is closed") + } +} + +///| +pub fn VisualTestContext::is_closed(self : VisualTestContext) -> Bool { + self.test_window().is_closed() +} + +///| +pub fn VisualTestContext::window_title(self : VisualTestContext) -> String? { + self.test_window().title() +} + +///| +pub fn VisualTestContext::is_active(self : VisualTestContext) -> Bool { + @platform.PlatformWindow::is_active(self.test_window()) +} + +///| +pub fn VisualTestContext::is_hovered(self : VisualTestContext) -> Bool { + @platform.PlatformWindow::is_hovered(self.test_window()) +} + +///| +pub fn VisualTestContext::bounds( + self : VisualTestContext, +) -> @geometry.Bounds[@geometry.Pixels] { + @platform.PlatformWindow::bounds(self.test_window()) +} + +///| +pub fn VisualTestContext::scale_factor(self : VisualTestContext) -> Double { + @platform.PlatformWindow::scale_factor(self.test_window()) +} + +///| +pub fn VisualTestContext::cursor_style( + self : VisualTestContext, +) -> @style.CursorStyle { + self.cx.cursor_style() +} + +///| +pub fn VisualTestContext::write_to_clipboard( + self : VisualTestContext, + item : @platform.ClipboardItem, +) -> Unit { + self.cx.write_to_clipboard(item) +} + +///| +pub fn VisualTestContext::read_from_clipboard( + self : VisualTestContext, +) -> @platform.ClipboardItem? { + self.cx.read_from_clipboard() +} + +///| +pub fn VisualTestContext::run_until_parked(self : VisualTestContext) -> Unit { + self.cx.run_until_parked() +} + +///| +pub fn VisualTestContext::advance_clock( + self : VisualTestContext, + ms : Int32, +) -> Unit { + self.cx.advance_clock(ms) +} + +///| +pub fn[R] VisualTestContext::update( + self : VisualTestContext, + f : (@window.Window, @app.App) -> R, +) -> R { + let window = self.window() + let result = self.app().update(fn(app) { f(window, app) }) + self.cx.run_until_parked() + result +} + +///| +pub fn[R] VisualTestContext::read( + self : VisualTestContext, + f : (@app.App) -> R, +) -> R { + self.cx.read(f) +} + +///| +pub fn[T, R] VisualTestContext::update_entity( + self : VisualTestContext, + entity : @app.Entity[T], + f : (T, @app.Context[T]) -> R, +) -> R { + self.cx.update_entity(entity, f) +} + +///| +pub fn[T] VisualTestContext::new_entity( + self : VisualTestContext, + build : (@app.Context[T]) -> T, +) -> @app.Entity[T] { + self.cx.new_entity(build) +} + +///| +pub fn[V : @window.Render] VisualTestContext::replace_root_view( + self : VisualTestContext, + build : (@window.Window, @app.Context[V]) -> V, +) -> @app.Entity[V] { + self.update(fn(window, _) { window.replace_root_view(build) }) +} + +///| +pub fn VisualTestContext::draw(self : VisualTestContext) -> @scene.Scene { + let scene = self.window().draw() + self.cx.run_until_parked() + scene +} + +///| +pub fn VisualTestContext::scene(self : VisualTestContext) -> @scene.Scene { + match self.test_window().last_scene() { + Some(scene) => scene + None => self.window().scene() + } +} + +///| +pub fn VisualTestContext::drawn_scenes( + self : VisualTestContext, +) -> Array[@scene.Scene] { + self.test_window().drawn_scenes() +} + +///| +pub fn VisualTestContext::draw_count(self : VisualTestContext) -> Int32 { + self.test_window().draw_count() +} + +///| +pub fn VisualTestContext::simulate_input( + self : VisualTestContext, + event : @input.PlatformInput, +) -> @input.DispatchEventResult { + let result = self.test_window().simulate_input(event) + self.cx.run_until_parked() + result +} + +///| +pub fn VisualTestContext::simulate_mouse_move( + self : VisualTestContext, + position : @geometry.Point[@geometry.Pixels], + button? : @input.MouseButton, + modifiers~ : @input.Modifiers = Default::default(), +) -> @input.DispatchEventResult { + self.simulate_input( + MouseMove({ position, pressed_button: button, modifiers, }), + ) +} + +///| +pub fn VisualTestContext::simulate_mouse_down( + self : VisualTestContext, + position : @geometry.Point[@geometry.Pixels], + button~ : @input.MouseButton = Left, + modifiers~ : @input.Modifiers = Default::default(), + click_count~ : Int32 = 1, +) -> @input.DispatchEventResult { + self.simulate_input( + MouseDown({ position, button, modifiers, click_count, first_mouse: false, }), + ) +} + +///| +pub fn VisualTestContext::simulate_mouse_up( + self : VisualTestContext, + position : @geometry.Point[@geometry.Pixels], + button~ : @input.MouseButton = Left, + modifiers~ : @input.Modifiers = Default::default(), + click_count~ : Int32 = 1, +) -> @input.DispatchEventResult { + self.simulate_input(MouseUp({ position, button, modifiers, click_count, })) +} + +///| +pub fn VisualTestContext::simulate_click( + self : VisualTestContext, + position : @geometry.Point[@geometry.Pixels], + button~ : @input.MouseButton = Left, + modifiers~ : @input.Modifiers = Default::default(), +) -> Unit { + ignore(self.simulate_mouse_down(position, button~, modifiers~)) + ignore(self.simulate_mouse_up(position, button~, modifiers~)) +} + +///| +pub fn VisualTestContext::simulate_scroll_wheel( + self : VisualTestContext, + position : @geometry.Point[@geometry.Pixels], + delta : @input.ScrollDelta, + modifiers~ : @input.Modifiers = Default::default(), +) -> @input.DispatchEventResult { + self.simulate_input(ScrollWheel({ position, delta, modifiers, })) +} + +///| +pub fn VisualTestContext::simulate_mouse_exit( + self : VisualTestContext, + position~ : @geometry.Point[@geometry.Pixels] = @geometry.point( + @geometry.px(0.0), + @geometry.px(0.0), + ), + modifiers~ : @input.Modifiers = Default::default(), +) -> @input.DispatchEventResult { + self.simulate_input( + MouseExited({ position, pressed_button: None, modifiers, }), + ) +} + +///| +pub fn VisualTestContext::simulate_modifiers_change( + self : VisualTestContext, + modifiers : @input.Modifiers, +) -> @input.DispatchEventResult { + self.simulate_input(ModifiersChanged({ modifiers, })) +} + +///| +pub fn VisualTestContext::simulate_resize( + self : VisualTestContext, + size : @geometry.Size[@geometry.Pixels], +) -> Unit { + self.test_window().simulate_resize(size) + self.cx.run_until_parked() +} + +///| +pub fn VisualTestContext::simulate_scale_factor_change( + self : VisualTestContext, + scale_factor : Double, +) -> Unit { + self.test_window().simulate_scale_factor_change(scale_factor) + self.cx.run_until_parked() +} + +///| +pub fn VisualTestContext::simulate_active_status_change( + self : VisualTestContext, + active : Bool, +) -> Unit { + self.test_window().simulate_active_status_change(active) + self.cx.run_until_parked() +} + +///| +pub fn VisualTestContext::simulate_hover_status_change( + self : VisualTestContext, + hovered : Bool, +) -> Unit { + self.test_window().simulate_hover_status_change(hovered) + self.cx.run_until_parked() +} + +///| +pub fn VisualTestContext::simulate_close(self : VisualTestContext) -> Bool { + let closed = self.test_window().simulate_close_requested() + self.cx.run_until_parked() + closed +} diff --git a/src/platform/test/test_platform_test.mbt b/src/platform/test/test_platform_test.mbt new file mode 100644 index 0000000..a62f2e1 --- /dev/null +++ b/src/platform/test/test_platform_test.mbt @@ -0,0 +1,498 @@ +///| +fn px(v : Double) -> @geometry.Pixels { + @geometry.px(v) +} + +///| +fn pt(x : Double, y : Double) -> @geometry.Point[@geometry.Pixels] { + @geometry.point(px(x), px(y)) +} + +///| +fn sz(w : Double, h : Double) -> @geometry.Size[@geometry.Pixels] { + @geometry.size(px(w), px(h)) +} + +///| +fn sp(v : Double) -> @geometry.ScaledPixels { + @geometry.ScaledPixels(v) +} + +///| +/// A minimal element that paints a solid quad across its layout bounds and +/// optionally handles mouse events and hover. +priv struct BoxElement { + color : @color.Rgba + hover_color : @color.Rgba? + on_down : ((@input.MouseDownEvent, @window.Window, @app.App) -> Unit)? + on_scroll : ((@input.ScrollWheelEvent, @window.Window, @app.App) -> Unit)? + mut hitbox : @window.Hitbox? +} + +///| +fn box_el( + color : @color.Rgba, + hover_color? : @color.Rgba, + on_down? : (@input.MouseDownEvent, @window.Window, @app.App) -> Unit, + on_scroll? : (@input.ScrollWheelEvent, @window.Window, @app.App) -> Unit, +) -> @window.AnyElement { + @window.AnyElement::new({ + color, + hover_color, + on_down, + on_scroll, + hitbox: None, + }) +} + +///| +impl @window.Element for BoxElement with fn request_layout(_self, window, _app) { + window.request_layout(Default::default(), []) +} + +///| +impl @window.Element for BoxElement with fn prepaint(self, bounds, window, _app) { + if self.hover_color is Some(_) || + self.on_down is Some(_) || + self.on_scroll is Some(_) { + self.hitbox = Some(window.insert_hitbox(bounds, Normal)) + } +} + +///| +impl @window.Element for BoxElement with fn paint(self, bounds, window, _app) { + let hovered = match self.hitbox { + Some(hitbox) => hitbox.is_hovered(window) + None => false + } + let bg = match (self.hover_color, hovered) { + (Some(hc), true) => hc + _ => self.color + } + if self.hitbox is Some(hitbox) { + if self.on_down is Some(cb) { + window.on_mouse_event(fn(event, phase, win, app) { + if phase == Bubble && event is MouseDown(down) && hitbox.is_hovered(win) { + cb(down, win, app) + } + }) + } + if self.on_scroll is Some(cb) { + window.on_mouse_event(fn(event, phase, win, app) { + if phase == Bubble && + event is ScrollWheel(scroll) && + hitbox.is_hovered(win) { + cb(scroll, win, app) + } + }) + } + } + window.paint_quad(@window.fill(bounds, bg.to_background())) +} + +///| +struct TestView { + mut count : Int32 + hover_bg : @color.Rgba? + prevent : Bool + stop : Bool + log : Array[String] +} + +///| +impl @window.Render for TestView with fn render(self, _window, cx) { + box_el( + @color.rgb(0x112233), + hover_color?=self.hover_bg, + on_down=@window.listener(cx, fn(view, down, window, cx) { + view.count = view.count + 1 + let btn = if down.button == Left { "Left" } else { "Other" } + view.log.push("down:\{btn}:\{down.modifiers.shift}") + if view.prevent { + window.prevent_default() + } + if view.stop { + window.stop_propagation() + } + cx.notify() + }), + on_scroll=@window.listener(cx, fn(view, scroll, _window, _cx) { + view.log.push("scroll:\{scroll.position.x.to_double()}") + }), + ) +} + +///| +enum PlainView { + PlainView +} + +///| +impl @window.Render for PlainView with fn render(_self, _window, _cx) { + box_el(@color.rgb(0xabcdef)) +} + +///| +enum RunawayView { + RunawayView +} + +///| +impl @window.Render for RunawayView with fn render(_self, window, _cx) { + window.refresh() + box_el(@color.rgb(0x000000)) +} + +///| +test "Application run, quit, and TestPlatform flags" { + let platform = @test.TestPlatform::new() + let app = @window.Application::with_platform(platform) + assert_false(platform.did_run()) + assert_false(platform.did_quit()) + let launched = Ref(false) + let found_app = Ref(false) + app.run(fn(a) { + launched.val = true + found_app.val = @window.application_for(a.app()) is Some(_) + a.quit() + }) + assert_true(launched.val) + assert_true(found_app.val) + assert_true(platform.did_run()) + assert_true(platform.did_quit()) +} + +///| +test "explicit frame scheduling on TestPlatform and TestWindow" { + let platform = @test.TestPlatform::new() + let app = @window.Application::with_platform(platform) + let view : Ref[@app.Entity[TestView]?] = Ref(None) + let unrelated : Ref[@app.Entity[PlainView]?] = Ref(None) + let handle = app.open_window( + @platform.WindowOptions::with_size(sz(300.0, 200.0), title="Manual"), + fn(_window, cx_app) { + unrelated.val = Some(cx_app.new_entity(fn(_) { PlainView })) + let v : @app.Entity[TestView] = cx_app.new_entity(fn(_) { + { count: 0, hover_bg: None, prevent: false, stop: false, log: [], } + }) + view.val = Some(v) + v + }, + ) + let tw = platform.window(handle.window_id()).unwrap() + assert_true(tw.frame_scheduled()) + assert_eq(tw.draw_count(), 0) + assert_true(tw.simulate_scheduled_frame()) + assert_false(tw.frame_scheduled()) + assert_eq(tw.draw_count(), 1) + assert_false(tw.simulate_scheduled_frame()) + + // Unrelated entity notification must not schedule a frame. + unrelated.val.unwrap().update(app.app(), fn(_, cx) { cx.notify() }) + assert_false(tw.frame_scheduled()) + + // Notifying rendered view re-schedules a frame. + view.val + .unwrap() + .update(app.app(), fn(v, cx) { + v.count = 1 + cx.notify() + }) + assert_true(tw.frame_scheduled()) + assert_true(tw.simulate_scheduled_frame()) + assert_eq(tw.draw_count(), 2) +} + +///| +test "resize, scale factor, and programmatic Window::resize avoid recursion" { + let cx = @test.TestAppContext::new() + let vcx = cx.add_empty_window(size=sz(200.0, 100.0)) + ignore(vcx.replace_root_view(fn(_, _) { PlainView })) + let before = vcx.draw_count() + vcx.simulate_resize(sz(320.0, 180.0)) + assert_eq(vcx.draw_count(), before + 1) + assert_eq(vcx.bounds().size, sz(320.0, 180.0)) + assert_eq( + vcx.scene().quads[0].bounds, + @geometry.bounds( + @geometry.point(sp(0.0), sp(0.0)), + @geometry.size(sp(320.0), sp(180.0)), + ), + ) + + vcx.simulate_scale_factor_change(2.0) + assert_eq(vcx.scale_factor(), 2.0) + assert_eq( + vcx.scene().quads[0].bounds, + @geometry.bounds( + @geometry.point(sp(0.0), sp(0.0)), + @geometry.size(sp(640.0), sp(360.0)), + ), + ) + + // Programmatic resize updates platform window bounds and schedules redraw without loop. + vcx.update(fn(win, _) { win.resize(sz(400.0, 200.0)) }) + assert_eq(vcx.bounds().size, sz(400.0, 200.0)) + assert_eq(vcx.scale_factor(), 2.0) + assert_eq( + vcx.scene().quads[0].bounds, + @geometry.bounds( + @geometry.point(sp(0.0), sp(0.0)), + @geometry.size(sp(800.0), sp(400.0)), + ), + ) + vcx.update(fn(win, _) { win.resize(sz(400.0, 200.0), scale_factor=1.5) }) + assert_eq(vcx.window().scale_factor(), 1.5) + assert_eq( + vcx.scene().quads[0].bounds, + @geometry.bounds( + @geometry.point(sp(0.0), sp(0.0)), + @geometry.size(sp(600.0), sp(300.0)), + ), + ) +} + +///| +test "title, cursor style, clipboard, and open_url" { + let cx = @test.TestAppContext::new() + let (_, vcx) = cx.add_window_view(size=sz(100.0, 100.0), title="Initial", fn( + _, + _, + ) { + PlainView + }) + assert_eq(vcx.window_title(), Some("Initial")) + vcx.update(fn(win, _) { + win.set_window_title("Updated") + win.set_cursor_style(PointingHand) + win.write_to_clipboard( + @platform.ClipboardItem::new_string_with_metadata("abc", "text"), + ) + }) + assert_eq(vcx.window_title(), Some("Updated")) + assert_eq(vcx.cursor_style(), @style.CursorStyle::PointingHand) + assert_eq(vcx.read_from_clipboard().unwrap().text(), Some("abc")) + assert_eq(cx.read_from_clipboard().unwrap().metadata(), Some("text")) + + cx.application().open_url("https://example.com") + assert_eq(cx.opened_url(), Some("https://example.com")) +} + +///| +test "multi-window activation and focus transfer" { + let cx = @test.TestAppContext::new() + let log : Array[String] = [] + let (_, vcx1) = cx.add_window_view(size=sz(100.0, 100.0), fn(win, _) { + win.on_window_active_change(fn(w, _) { + log.push("w1:\{w.is_window_active()}") + }) + PlainView + }) + assert_true(vcx1.is_active()) + assert_eq(cx.active_window(), Some(vcx1.window_handle())) + + let (_, vcx2) = cx.add_window_view(size=sz(100.0, 100.0), fn(win, _) { + win.on_window_active_change(fn(w, _) { + log.push("w2:\{w.is_window_active()}") + }) + PlainView + }) + assert_false(vcx1.is_active()) + assert_true(vcx2.is_active()) + assert_eq(cx.active_window(), Some(vcx2.window_handle())) + assert_eq(log, ["w1:false"]) + + vcx1.update(fn(win, _) { win.activate_window() }) + assert_true(vcx1.is_active()) + assert_false(vcx2.is_active()) + assert_eq(cx.active_window(), Some(vcx1.window_handle())) + assert_eq(log, ["w1:false", "w2:false", "w1:true"]) +} + +///| +test "MouseExited, hover status change, ModifiersChanged, and DispatchEventResult" { + let cx = @test.TestAppContext::new() + let (view, vcx) = cx.add_window_view(size=sz(100.0, 100.0), fn(_, _) { + { + count: 0, + hover_bg: Some(@color.rgb(0x00ff00)), + prevent: true, + stop: true, + log: [], + } + }) + assert_eq( + vcx.scene().quads[0].background, + @color.rgb(0x112233).to_background(), + ) + + ignore(vcx.simulate_mouse_move(pt(50.0, 50.0))) + assert_eq( + vcx.scene().quads[0].background, + @color.rgb(0x00ff00).to_background(), + ) + + // MouseExited clears hovered hitboxes and marks window dirty -> redraws unhovered. + ignore(vcx.simulate_mouse_exit(position=pt(200.0, 200.0))) + assert_eq( + vcx.scene().quads[0].background, + @color.rgb(0x112233).to_background(), + ) + + // Re-hover then lose window hover via platform hover status change. + ignore(vcx.simulate_mouse_move(pt(50.0, 50.0))) + assert_eq( + vcx.scene().quads[0].background, + @color.rgb(0x00ff00).to_background(), + ) + vcx.simulate_hover_status_change(false) + assert_false(vcx.is_hovered()) + assert_eq( + vcx.scene().quads[0].background, + @color.rgb(0x112233).to_background(), + ) + + // ModifiersChanged updates window modifiers and dirties/redraws on change. + let draws_before_mod = vcx.draw_count() + let shift_mods : @input.Modifiers = { ..Default::default(), shift: true, } + ignore(vcx.simulate_modifiers_change(shift_mods)) + assert_eq(vcx.window().modifiers(), shift_mods) + assert_eq(vcx.draw_count(), draws_before_mod + 1) + + // stop_propagation + prevent_default reflected in DispatchEventResult. + let result = vcx.simulate_mouse_down(pt(50.0, 50.0), modifiers=shift_mods) + assert_false(result.propagate) + assert_true(result.default_prevented) + assert_eq(cx.read_entity(view).log, ["down:Left:true"]) + + // ScrollWheel delivery. + ignore( + vcx.simulate_scroll_wheel( + pt(25.0, 25.0), + @input.ScrollDelta::Pixels(pt(0.0, -10.0)), + ), + ) + assert_eq(cx.read_entity(view).log, ["down:Left:true", "scroll:25"]) +} + +///| +test "window close veto, on_close, root release, and idempotence" { + let cx = @test.TestAppContext::new() + let can_close = Ref(false) + let events : Array[String] = [] + let handle = cx.add_window(size=sz(100.0, 100.0), fn(win, ctx) { + ctx.on_release(fn(_, _) { events.push("released") }).detach() + win.on_should_close(fn(_, _) { can_close.val }) + win.on_close(fn(_) { events.push("on_close") }) + PlainView + }) + let vcx = @test.VisualTestContext::from_window(handle.to_any(), cx) + assert_eq(cx.windows().length(), 1) + + // Vetoed close leaves window open and view alive. + assert_false(vcx.simulate_close()) + assert_false(vcx.is_closed()) + assert_false(handle.entity().is_released()) + assert_eq(events, []) + + // Allowed close runs on_close, releases root view, removes window from Application. + can_close.val = true + assert_true(vcx.simulate_close()) + assert_true(vcx.is_closed()) + assert_eq(cx.windows().length(), 0) + assert_true(handle.entity().is_released()) + assert_eq(events, ["on_close", "released"]) + assert_eq(handle.update(cx.application(), fn(_, _, _) { 1 }), None) + + // Idempotent repeat close calls do nothing extra. + vcx.test_window().simulate_close() + assert_eq(events, ["on_close", "released"]) +} + +///| +test "async task and virtual clock drive automatic redraws" { + let cx = @test.TestAppContext::new() + let (view, vcx) = cx.add_window_view(size=sz(120.0, 80.0), fn(_, ctx) { + let weak : @app.WeakEntity[TestView] = ctx.weak_entity() + ctx + .spawn(async fn(_, async_app) { + async_app.background_executor().sleep(50) + ignore( + weak.update(async_app.app, fn(v : TestView, cx) { + v.count = v.count + 10 + cx.notify() + }), + ) + }) + .detach() + { count: 1, hover_bg: None, prevent: false, stop: false, log: [], } + }) + assert_eq(vcx.draw_count(), 1) + assert_eq(cx.read_entity(view).count, 1) + + cx.advance_clock(50) + assert_eq(cx.read_entity(view).count, 11) + assert_eq(vcx.draw_count(), 2) +} + +///| +test "replace_root_view and skip_drawing" { + let cx = @test.TestAppContext::new() + let released = Ref(false) + let (first, vcx) = cx.add_window_view(size=sz(100.0, 100.0), fn(_, ctx) { + ctx.on_release(fn(_, _) { released.val = true }).detach() + PlainView + }) + assert_false(released.val) + let second = vcx.replace_root_view(fn(_, _) { + { count: 42, hover_bg: None, prevent: false, stop: false, log: [], } + }) + assert_true(first.is_released()) + assert_true(released.val) + assert_eq(cx.read_entity(second).count, 42) + assert_eq( + vcx.scene().quads[0].background, + @color.rgb(0x112233).to_background(), + ) + + // skip_drawing prevents automatic frame pumping until re-enabled. + cx.skip_drawing() + let count_before = vcx.draw_count() + cx.update_entity(second, fn(v, ctx) { + v.count = 43 + ctx.notify() + }) + assert_eq(vcx.draw_count(), count_before) + assert_true(vcx.test_window().frame_scheduled()) + cx.skip_drawing(skip=false) + cx.run_until_parked() + assert_eq(vcx.draw_count(), count_before + 1) +} + +///| +test "panic on drawing a closed window" { + let cx = @test.TestAppContext::new() + let vcx = cx.add_empty_window(size=sz(50.0, 50.0)) + let win = vcx.window() + win.close() + ignore(win.draw()) +} + +///| +test "panic on dispatching input on a closed window" { + let cx = @test.TestAppContext::new() + let vcx = cx.add_empty_window(size=sz(50.0, 50.0)) + let win = vcx.window() + win.close() + ignore( + win.dispatch_input( + MouseMove({ ..Default::default(), position: pt(5.0, 5.0), }), + ), + ) +} + +///| +test "panic on runaway redraw loop" { + let cx = @test.TestAppContext::new() + ignore(cx.add_window(size=sz(50.0, 50.0), fn(_, _) { RunawayView })) +} diff --git a/src/platform/test/window.mbt b/src/platform/test/window.mbt new file mode 100644 index 0000000..fda5592 --- /dev/null +++ b/src/platform/test/window.mbt @@ -0,0 +1,429 @@ +// Headless test window, ported from gpui/src/platform/test/window.rs. + +///| +/// A headless `PlatformWindow` for tests: records presented `Scene`s and +/// provides simulation hooks for frames, input, resizing, focus and closing +/// (GPUI: `TestWindow`). +pub struct TestWindow { + priv id : @platform.WindowId + priv platform : TestPlatform + priv mut bounds : @geometry.Bounds[@geometry.Pixels] + priv mut scale_factor : Double + priv mut title : String? + priv mut active : Bool + priv mut hovered : Bool + priv mut mouse_position : @geometry.Point[@geometry.Pixels] + priv mut modifiers : @input.Modifiers + priv mut closed : Bool + priv mut frame_scheduled : Bool + priv mut frame_schedule_count : Int32 + priv drawn_scenes : Array[@scene.Scene] + priv mut request_frame_callback : (() -> Unit)? + priv mut input_callback : ((@input.PlatformInput) -> @input.DispatchEventResult)? + priv mut resize_callback : ((@geometry.Size[@geometry.Pixels], Double) -> Unit)? + priv mut active_status_change_callback : ((Bool) -> Unit)? + priv mut hover_status_change_callback : ((Bool) -> Unit)? + priv mut should_close_callback : (() -> Bool)? + priv mut close_callback : (() -> Unit)? +} + +///| +fn TestWindow::new( + id : @platform.WindowId, + platform : TestPlatform, + params : @platform.WindowParams, + default_scale_factor : Double, +) -> TestWindow { + { + id, + platform, + bounds: params.bounds, + scale_factor: params.scale_factor.unwrap_or(default_scale_factor), + title: params.title, + active: params.focus, + hovered: false, + mouse_position: @geometry.point(@geometry.px(0.0), @geometry.px(0.0)), + modifiers: Default::default(), + closed: false, + frame_scheduled: false, + frame_schedule_count: 0, + drawn_scenes: [], + request_frame_callback: None, + input_callback: None, + resize_callback: None, + active_status_change_callback: None, + hover_status_change_callback: None, + should_close_callback: None, + close_callback: None, + } +} + +///| +fn TestWindow::clear_callbacks(self : TestWindow) -> Unit { + self.request_frame_callback = None + self.input_callback = None + self.resize_callback = None + self.active_status_change_callback = None + self.hover_status_change_callback = None + self.should_close_callback = None + self.close_callback = None +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn bounds(self) { + self.bounds +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn content_size(self) { + self.bounds.size +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn scale_factor(self) { + self.scale_factor +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn mouse_position(self) { + self.mouse_position +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn modifiers(self) { + self.modifiers +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn is_active(self) { + self.active +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn is_hovered(self) { + self.hovered +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn set_title(self, title) { + self.title = Some(title) +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn activate(self) { + if !self.closed { + self.platform.set_active_window(Some(self)) + } +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn resize(self, size) { + self.bounds = { ..self.bounds, size, } +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn draw(self, scene) { + self.drawn_scenes.push(scene) +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn schedule_frame(self) { + if !self.closed { + self.frame_scheduled = true + self.frame_schedule_count = self.frame_schedule_count + 1 + } +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn close(self) { + if self.closed { + return + } + self.closed = true + self.frame_scheduled = false + self.clear_callbacks() + if self.platform.active_window is Some(active) && active.id == self.id { + self.platform.active_window = None + } +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn on_request_frame( + self, + callback, +) { + self.request_frame_callback = Some(callback) +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn on_input( + self, + callback, +) { + self.input_callback = Some(callback) +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn on_resize( + self, + callback, +) { + self.resize_callback = Some(callback) +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn on_active_status_change( + self, + callback, +) { + self.active_status_change_callback = Some(callback) +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn on_hover_status_change( + self, + callback, +) { + self.hover_status_change_callback = Some(callback) +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn on_should_close( + self, + callback, +) { + self.should_close_callback = Some(callback) +} + +///| +pub impl @platform.PlatformWindow for TestWindow with fn on_close( + self, + callback, +) { + self.close_callback = Some(callback) +} + +// --------------------------------------------------------------------------- +// Inspection helpers +// --------------------------------------------------------------------------- + +///| +pub fn TestWindow::window_id(self : TestWindow) -> @platform.WindowId { + self.id +} + +///| +pub fn TestWindow::title(self : TestWindow) -> String? { + self.title +} + +///| +pub fn TestWindow::is_closed(self : TestWindow) -> Bool { + self.closed +} + +///| +pub fn TestWindow::frame_scheduled(self : TestWindow) -> Bool { + self.frame_scheduled +} + +///| +pub fn TestWindow::frame_schedule_count(self : TestWindow) -> Int32 { + self.frame_schedule_count +} + +///| +pub fn TestWindow::drawn_scenes(self : TestWindow) -> Array[@scene.Scene] { + self.drawn_scenes +} + +///| +pub fn TestWindow::draw_count(self : TestWindow) -> Int32 { + self.drawn_scenes.length() +} + +///| +pub fn TestWindow::last_scene(self : TestWindow) -> @scene.Scene? { + self.drawn_scenes.last() +} + +///| +pub fn TestWindow::clear_drawn_scenes(self : TestWindow) -> Unit { + self.drawn_scenes.clear() +} + +// --------------------------------------------------------------------------- +// Simulation hooks +// --------------------------------------------------------------------------- + +///| +/// Delivers one frame if one was scheduled; returns whether a frame ran +/// (GPUI: `TestWindow::simulate_scheduled_frame`). +pub fn TestWindow::simulate_scheduled_frame(self : TestWindow) -> Bool { + if self.closed || !self.frame_scheduled { + return false + } + self.frame_scheduled = false + match self.request_frame_callback { + Some(callback) => { + callback() + true + } + None => { + self.frame_scheduled = true + false + } + } +} + +///| +/// Unconditionally invokes the registered frame callback, as a display-link +/// tick would (GPUI: `TestWindow::simulate_frame_request`). +pub fn TestWindow::simulate_frame_request(self : TestWindow) -> Unit { + if self.closed { + return + } + self.frame_scheduled = false + if self.request_frame_callback is Some(callback) { + callback() + } +} + +///| +/// Simulates a `PlatformInput` event arriving from the OS/browser +/// (GPUI: `TestWindow::simulate_input`). +pub fn TestWindow::simulate_input( + self : TestWindow, + event : @input.PlatformInput, +) -> @input.DispatchEventResult { + if self.closed { + return { propagate: true, default_prevented: false, } + } + self.modifiers = event.modifiers() + match event { + MouseDown(e) => self.mouse_position = e.position + MouseUp(e) => self.mouse_position = e.position + MouseMove(e) => self.mouse_position = e.position + ScrollWheel(e) => self.mouse_position = e.position + MouseExited(e) => self.mouse_position = e.position + ModifiersChanged(_) => () + } + match self.input_callback { + Some(callback) => callback(event) + None => { propagate: true, default_prevented: false, } + } +} + +///| +/// Simulates a user/OS resize of the window (GPUI: `TestWindow::simulate_resize`). +pub fn TestWindow::simulate_resize( + self : TestWindow, + size : @geometry.Size[@geometry.Pixels], +) -> Unit { + if self.closed { + return + } + self.bounds = { ..self.bounds, size, } + if self.resize_callback is Some(callback) { + callback(size, self.scale_factor) + } +} + +///| +/// Simulates a display scale-factor change +/// (GPUI: `TestWindow::simulate_scale_factor_change`). +pub fn TestWindow::simulate_scale_factor_change( + self : TestWindow, + scale_factor : Double, +) -> Unit { + if self.closed { + return + } + self.scale_factor = scale_factor + if self.resize_callback is Some(callback) { + callback(self.bounds.size, scale_factor) + } +} + +///| +/// Simulates a window focus/activation change +/// (GPUI: `TestWindow::simulate_active_status_change`). +pub fn TestWindow::simulate_active_status_change( + self : TestWindow, + active : Bool, +) -> Unit { + if self.closed { + return + } + self.active = active + if active { + self.platform.active_window = Some(self) + } else if self.platform.active_window is Some(curr) && curr.id == self.id { + self.platform.active_window = None + } + if self.active_status_change_callback is Some(callback) { + callback(active) + } +} + +///| +/// Simulates the pointer entering or leaving the window surface. +pub fn TestWindow::simulate_hover_status_change( + self : TestWindow, + hovered : Bool, +) -> Unit { + if self.closed { + return + } + self.hovered = hovered + if self.hover_status_change_callback is Some(callback) { + callback(hovered) + } +} + +///| +/// Queries whether a close should proceed. Returns `true` if no handler is +/// registered. +pub fn TestWindow::simulate_should_close(self : TestWindow) -> Bool { + if self.closed { + return true + } + match self.should_close_callback { + Some(callback) => callback() + None => true + } +} + +///| +/// Simulates the OS closing this window unconditionally and invoking the +/// registered `on_close` callback (GPUI: `TestWindow::simulate_close`). +pub fn TestWindow::simulate_close(self : TestWindow) -> Unit { + if self.closed { + return + } + let callback = self.close_callback + self.closed = true + self.frame_scheduled = false + self.clear_callbacks() + if self.platform.active_window is Some(curr) && curr.id == self.id { + self.platform.active_window = None + } + if callback is Some(callback) { + callback() + } +} + +///| +/// Simulates a user-initiated close request: asks `on_should_close`, closes +/// if allowed, and returns whether the window closed. +pub fn TestWindow::simulate_close_requested(self : TestWindow) -> Bool { + if self.closed { + return false + } + if self.simulate_should_close() { + self.simulate_close() + true + } else { + false + } +} diff --git a/src/platform/types.mbt b/src/platform/types.mbt new file mode 100644 index 0000000..8519c46 --- /dev/null +++ b/src/platform/types.mbt @@ -0,0 +1,175 @@ +// Core value types shared between GPUI windows and platform implementations, +// ported from gpui/src/platform.rs. + +///| +/// Identifies an open window within an application (GPUI: `WindowId`). +#derive(Eq, Compare, Hash, Debug) +pub(all) struct WindowId(Int32) + +///| +pub impl Show for WindowId with fn output(self, logger) { + logger.write_string("WindowId(\{self.0})") +} + +///| +/// Requested window state and bounds (GPUI: `WindowBounds`). +#derive(Eq, Debug) +pub(all) enum WindowBounds { + Windowed(@geometry.Bounds[@geometry.Pixels]) + Maximized(@geometry.Bounds[@geometry.Pixels]) + Fullscreen(@geometry.Bounds[@geometry.Pixels]) +} + +///| +pub impl Default for WindowBounds with fn default() { + Windowed(Default::default()) +} + +///| +/// Returns the logical bounds stored in this `WindowBounds`. +pub fn WindowBounds::get_bounds( + self : WindowBounds, +) -> @geometry.Bounds[@geometry.Pixels] { + match self { + Windowed(bounds) | Maximized(bounds) | Fullscreen(bounds) => bounds + } +} + +///| +/// Configuration passed when opening a window (GPUI: `WindowOptions`). +#derive(Eq, Debug) +pub(all) struct WindowOptions { + window_bounds : WindowBounds? + title : String? + focus : Bool + show : Bool + scale_factor : Double? + rem_size : @geometry.Pixels +} + +///| +pub impl Default for WindowOptions with fn default() { + { + window_bounds: None, + title: None, + focus: true, + show: true, + scale_factor: None, + rem_size: @geometry.px(16.0), + } +} + +///| +/// Convenience constructor for a windowed `WindowOptions` of `size` at the +/// origin. +pub fn WindowOptions::with_size( + size : @geometry.Size[@geometry.Pixels], + scale_factor? : Double, + title? : String, + rem_size~ : @geometry.Pixels = @geometry.px(16.0), +) -> WindowOptions { + { + ..Default::default(), + window_bounds: Some( + Windowed( + @geometry.bounds( + @geometry.point(@geometry.px(0.0), @geometry.px(0.0)), + size, + ), + ), + ), + title, + scale_factor, + rem_size, + } +} + +///| +/// Resolved parameters handed to `Platform::open_window` (GPUI: +/// `WindowParams`). +#derive(Eq, Debug) +pub(all) struct WindowParams { + bounds : @geometry.Bounds[@geometry.Pixels] + title : String? + focus : Bool + show : Bool + scale_factor : Double? +} + +///| +/// A plain-text clipboard entry with optional metadata (GPUI: +/// `ClipboardString`). +#derive(Eq, Debug) +pub(all) struct ClipboardString { + text : String + metadata : String? +} + +///| +pub fn ClipboardString::new(text : String) -> ClipboardString { + { text, metadata: None, } +} + +///| +pub fn ClipboardString::new_with_metadata( + text : String, + metadata : String, +) -> ClipboardString { + { text, metadata: Some(metadata), } +} + +///| +/// One item inside a `ClipboardItem` (GPUI: `ClipboardEntry`, text subset). +#derive(Eq, Debug) +pub(all) enum ClipboardEntry { + String(ClipboardString) +} + +///| +/// Data placed on or read from the system clipboard (GPUI: `ClipboardItem`). +#derive(Eq, Debug) +pub(all) struct ClipboardItem { + entries : Array[ClipboardEntry] +} + +///| +/// Creates a `ClipboardItem` containing one plain-text entry. +pub fn ClipboardItem::new_string(text : String) -> ClipboardItem { + { entries: [String(ClipboardString::new(text))], } +} + +///| +/// Creates a `ClipboardItem` containing one plain-text entry with metadata. +pub fn ClipboardItem::new_string_with_metadata( + text : String, + metadata : String, +) -> ClipboardItem { + { entries: [String(ClipboardString::new_with_metadata(text, metadata))], } +} + +///| +/// Joins all text entries with `\n`, or returns `None` if there are none. +pub fn ClipboardItem::text(self : ClipboardItem) -> String? { + let texts = [] + for entry in self.entries { + match entry { + String(s) => texts.push(s.text) + } + } + if texts.is_empty() { + None + } else { + Some(texts.join("\n")) + } +} + +///| +/// Returns the metadata of the first text entry, if any. +pub fn ClipboardItem::metadata(self : ClipboardItem) -> String? { + for entry in self.entries { + match entry { + String(s) => return s.metadata + } + } + None +} diff --git a/src/window/application.mbt b/src/window/application.mbt new file mode 100644 index 0000000..26a346d --- /dev/null +++ b/src/window/application.mbt @@ -0,0 +1,294 @@ +// Platform-backed Application lifecycle and window handles, ported from +// gpui/src/app.rs (`Application`, `open_window`, `windows`, `quit`) and +// gpui/src/window.rs (`AnyWindowHandle`, `WindowHandle`). + +///| +/// 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`). +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) +} diff --git a/src/window/element.mbt b/src/window/element.mbt index 66d3cc3..b3b92ae 100644 --- a/src/window/element.mbt +++ b/src/window/element.mbt @@ -110,6 +110,7 @@ pub(open) trait Render { pub struct AnyView { entity_id : @app.EntityId priv render_fn : (Window, @app.App) -> AnyElement + priv release_fn : (@app.App) -> Unit } ///| @@ -121,6 +122,7 @@ pub fn[V : Render] AnyView::from_entity(entity : @app.Entity[V]) -> AnyView { Render::render(state, window, cx) }) }, + release_fn: fn(app) { app.release(entity) }, } } diff --git a/src/window/moon.pkg b/src/window/moon.pkg index f704bdc..8ff52c9 100644 --- a/src/window/moon.pkg +++ b/src/window/moon.pkg @@ -6,6 +6,7 @@ import { "experiments/gpui/layout", "experiments/gpui/input", "experiments/gpui/app", + "experiments/gpui/platform", "moonbitlang/core/hashset", "moonbitlang/core/cmp", "moonbitlang/core/debug", diff --git a/src/window/pkg.generated.mbti b/src/window/pkg.generated.mbti index a78d3ec..d5edc1e 100644 --- a/src/window/pkg.generated.mbti +++ b/src/window/pkg.generated.mbti @@ -7,12 +7,15 @@ import { "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 @@ -42,6 +45,36 @@ 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 @@ -77,8 +110,12 @@ pub(all) struct PaintQuad { 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 @@ -87,33 +124,60 @@ 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 diff --git a/src/window/window.mbt b/src/window/window.mbt index 5446ce2..b02c0c2 100644 --- a/src/window/window.mbt +++ b/src/window/window.mbt @@ -1,11 +1,11 @@ // The window, ported from gpui/src/window.rs: the frame lifecycle (layout, // prepaint, paint), the content-mask/offset/opacity stacks, hitboxes and -// hit-testing, element state, mouse dispatch, and view invalidation. +// hit-testing, element state, mouse dispatch, view invalidation, and +// PlatformWindow integration. // -// Not ported yet (see docs/PORTING.md): the platform window (M7/M8), focus, -// the key dispatch tree and actions (M5/M10), view caching and -// `Scene::replay`-based reuse, deferred draws, tooltips, drag and drop, and -// text (M9). A window is headless: `draw` returns the frame's `Scene`. +// Not ported yet (see docs/PORTING.md): focus, the key dispatch tree and +// actions (M5/M10), view caching and `Scene::replay`-based reuse, deferred +// draws, tooltips, drag and drop, and text (M9). ///| #derive(Eq, Debug) @@ -64,23 +64,38 @@ pub fn[S] ElementStateKey::new(name : String) -> ElementStateKey[S] { { id, name, slot: { val: None, }, } } +///| +/// Negative ids for standalone headless `Window::new` so they never collide +/// with `Application::open_window` ids (1, 2, ...). +let next_standalone_window_id : Ref[Int32] = { val: -1, } + ///| priv struct MouseListener { callback : (@input.MouseEvent, @input.DispatchPhase, Window, @app.App) -> Unit } ///| -/// A headless window (GPUI: `Window`). `draw` lays out and paints the root -/// view into a `Scene`; `dispatch_mouse_event` delivers input. +/// A window (GPUI: `Window`): either standalone headless (`Window::new`) or +/// backed by a `PlatformWindow` (`Application::open_window`). `draw` lays out +/// and paints the root view into a `Scene`; `dispatch_input` / +/// `dispatch_mouse_event` deliver input. pub struct Window { + priv id : @platform.WindowId priv app : @app.App + priv platform : &@platform.Platform? + priv platform_window : &@platform.PlatformWindow? priv mut viewport_size : @geometry.Size[@geometry.Pixels] priv mut scale_factor : Double priv mut rem_size : @geometry.Pixels + priv mut title : String? + priv mut active : Bool + priv mut hovered : Bool + priv mut modifiers : @input.Modifiers priv layout_engine : @layout.LayoutEngine priv mut root : AnyView? priv mut phase : DrawPhase priv mut dirty : Bool + priv mut closed : Bool priv mut drawn_frames : Int32 priv content_mask_stack : Array[@geometry.ContentMask[@geometry.Pixels]] priv element_offset_stack : Array[@geometry.Point[@geometry.Pixels]] @@ -97,29 +112,58 @@ pub struct Window { priv mut next_rendered_views : @hashset.HashSet[@app.EntityId] priv mut rendered_views : @hashset.HashSet[@app.EntityId] priv mut mouse_position : @geometry.Point[@geometry.Pixels] + priv mut pointer_inside : Bool priv mut hovered_hitboxes : Array[Int32] priv mut propagate_event : Bool + priv mut default_prevented : Bool priv mut notify_subscription : @app.Subscription? + priv mut should_close_handler : ((Window, @app.App) -> Bool)? + priv close_callbacks : Array[(@app.App) -> Unit] + priv activation_observers : Array[(Window, @app.App) -> Unit] + priv mut on_closed_internal : (() -> Unit)? } ///| -/// A window of `viewport_size` logical pixels showing nothing yet. Set its -/// content with `set_root_view`. -pub fn Window::new( +fn Window::mark_dirty(self : Window) -> Unit { + self.dirty = true + if self.platform_window is Some(pw) && !self.closed { + pw.schedule_frame() + } +} + +///| +fn Window::create( + id : @platform.WindowId, app : @app.App, viewport_size : @geometry.Size[@geometry.Pixels], - scale_factor~ : Double = 1.0, - rem_size~ : @geometry.Pixels = @geometry.px(16.0), + scale_factor : Double, + rem_size : @geometry.Pixels, + platform : &@platform.Platform?, + platform_window : &@platform.PlatformWindow?, + title : String?, + active : Bool, + hovered : Bool, + mouse_position : @geometry.Point[@geometry.Pixels], + modifiers : @input.Modifiers, + on_closed_internal : (() -> Unit)?, ) -> Window { let window : Window = { + id, app, + platform, + platform_window, viewport_size, scale_factor, rem_size, + title, + active, + hovered, + modifiers, layout_engine: @layout.LayoutEngine::new(), root: None, phase: Idle, dirty: true, + closed: false, drawn_frames: 0, content_mask_stack: [], element_offset_stack: [], @@ -135,23 +179,151 @@ pub fn Window::new( rendered_element_states: {}, next_rendered_views: @hashset.HashSet([]), rendered_views: @hashset.HashSet([]), - mouse_position: @geometry.point(@geometry.px(0.0), @geometry.px(0.0)), + mouse_position, + pointer_inside: hovered, hovered_hitboxes: [], propagate_event: true, + default_prevented: false, notify_subscription: None, + should_close_handler: None, + close_callbacks: [], + activation_observers: [], + on_closed_internal, } - // Invalidate when a view rendered in the last frame is notified (GPUI: - // `WindowInvalidator::invalidate_view`). + // Invalidate when a view rendered in the last frame (or currently being + // rendered) is notified (GPUI: `WindowInvalidator::invalidate_view`). window.notify_subscription = Some( app.observe_notifications(fn(entity_id) { - if window.rendered_views.contains(entity_id) { - window.dirty = true + if window.rendered_views.contains(entity_id) || + (window.phase != Idle && window.next_rendered_views.contains(entity_id)) { + window.mark_dirty() } }), ) window } +///| +/// A standalone headless window of `viewport_size` logical pixels showing +/// nothing yet. Set its content with `set_root_view`. +pub fn Window::new( + app : @app.App, + viewport_size : @geometry.Size[@geometry.Pixels], + scale_factor~ : Double = 1.0, + rem_size~ : @geometry.Pixels = @geometry.px(16.0), +) -> Window { + let id = @platform.WindowId(next_standalone_window_id.val) + next_standalone_window_id.val = next_standalone_window_id.val - 1 + Window::create( + id, + app, + viewport_size, + scale_factor, + rem_size, + None, + None, + None, + true, + false, + @geometry.point(@geometry.px(0.0), @geometry.px(0.0)), + Default::default(), + None, + ) +} + +///| +/// Constructs a window backed by `platform` and `platform_window` and wires +/// all platform callbacks (`Application::open_window`). +fn Window::from_platform( + id : @platform.WindowId, + app : @app.App, + platform : &@platform.Platform, + platform_window : &@platform.PlatformWindow, + rem_size~ : @geometry.Pixels = @geometry.px(16.0), + title? : String, + on_closed? : () -> Unit, +) -> Window { + let window = Window::create( + id, + app, + platform_window.content_size(), + platform_window.scale_factor(), + rem_size, + Some(platform), + Some(platform_window), + title, + platform_window.is_active(), + platform_window.is_hovered(), + platform_window.mouse_position(), + platform_window.modifiers(), + on_closed, + ) + if title is Some(t) { + platform_window.set_title(t) + } + platform_window.on_request_frame(fn() { + if !window.closed && window.phase == Idle { + ignore(window.draw_if_dirty()) + } + }) + platform_window.on_input(fn(input) { + if window.closed { + { propagate: true, default_prevented: false, } + } else { + window.dispatch_input(input) + } + }) + platform_window.on_resize(fn(size, factor) { + if !window.closed { + window.viewport_size = size + window.scale_factor = factor + window.mark_dirty() + } + }) + platform_window.on_active_status_change(fn(active) { + if !window.closed { + window.active = active + window.modifiers = platform_window.modifiers() + let observers = window.activation_observers.copy() + if !observers.is_empty() { + window.app.update(fn(app) { + for callback in observers { + callback(window, app) + } + }) + } + window.mark_dirty() + } + }) + platform_window.on_hover_status_change(fn(hovered) { + if !window.closed { + window.hovered = hovered + window.pointer_inside = hovered + if hovered { + window.hovered_hitboxes = hit_test_hitboxes( + window.rendered_hitboxes, + window.mouse_position, + ) + } else if !window.hovered_hitboxes.is_empty() { + window.hovered_hitboxes = [] + } + window.mark_dirty() + } + }) + platform_window.on_should_close(fn() { + if window.closed { + true + } else { + match window.should_close_handler { + Some(handler) => window.app.update(fn(app) { handler(window, app) }) + None => true + } + } + }) + platform_window.on_close(fn() { window.close() }) + window +} + ///| /// Sets the view the window renders (GPUI: the root view of /// `open_window`). @@ -159,18 +331,92 @@ pub fn[V : Render] Window::set_root_view( self : Window, view : @app.Entity[V], ) -> Unit { + guard !self.closed else { abort("set_root_view called on a closed window") } self.root = Some(AnyView::from_entity(view)) - self.dirty = true + self.mark_dirty() } ///| -/// Stops listening to the app. Call when the window goes away. +/// Replaces the window's root view with a newly constructed view, releasing +/// the previous root view (GPUI: `replace_root`). +pub fn[V : Render] Window::replace_root_view( + self : Window, + build : (Window, @app.Context[V]) -> V, +) -> @app.Entity[V] { + guard !self.closed else { + abort("replace_root_view called on a closed window") + } + let previous = self.root + let view = self.app.new_entity(fn(cx) { build(self, cx) }) + self.set_root_view(view) + if previous is Some(prev) && prev.entity_id != view.entity_id() { + (prev.release_fn)(self.app) + } + view +} + +///| +pub fn Window::root_view(self : Window) -> AnyView? { + self.root +} + +///| +/// Stops listening to the app, runs `on_close` callbacks, releases the root +/// view, and tears down any backing `PlatformWindow`. Idempotent. pub fn Window::close(self : Window) -> Unit { + if self.closed { + return + } + self.closed = true if self.notify_subscription is Some(subscription) { subscription.unsubscribe() } self.notify_subscription = None - self.root = None + let callbacks = self.close_callbacks.copy() + self.close_callbacks.clear() + if !callbacks.is_empty() { + self.app.update(fn(app) { + for callback in callbacks { + callback(app) + } + }) + } + self.activation_observers.clear() + self.should_close_handler = None + if self.root is Some(root) { + self.root = None + (root.release_fn)(self.app) + } + if self.on_closed_internal is Some(on_closed) { + self.on_closed_internal = None + on_closed() + } + if self.platform_window is Some(pw) { + pw.close() + } +} + +///| +/// Closes and removes this window (GPUI: `remove_window`). +pub fn Window::remove_window(self : Window) -> Unit { + self.close() +} + +///| +pub fn Window::window_id(self : Window) -> @platform.WindowId { + self.id +} + +///| +pub fn Window::bounds(self : Window) -> @geometry.Bounds[@geometry.Pixels] { + match self.platform_window { + Some(pw) => pw.bounds() + None => + @geometry.bounds( + @geometry.point(@geometry.px(0.0), @geometry.px(0.0)), + self.viewport_size, + ) + } } ///| @@ -195,6 +441,107 @@ pub fn Window::mouse_position( self.mouse_position } +///| +pub fn Window::modifiers(self : Window) -> @input.Modifiers { + self.modifiers +} + +///| +pub fn Window::is_window_active(self : Window) -> Bool { + self.active +} + +///| +pub fn Window::is_window_hovered(self : Window) -> Bool { + self.hovered +} + +///| +pub fn Window::is_closed(self : Window) -> Bool { + self.closed +} + +///| +pub fn Window::window_title(self : Window) -> String? { + self.title +} + +///| +pub fn Window::set_window_title(self : Window, title : String) -> Unit { + self.title = Some(title) + if self.platform_window is Some(pw) && !self.closed { + pw.set_title(title) + } +} + +///| +pub fn Window::activate_window(self : Window) -> Unit { + if self.platform_window is Some(pw) && !self.closed { + pw.activate() + } +} + +///| +pub fn Window::set_cursor_style( + self : Window, + style : @style.CursorStyle, +) -> Unit { + if self.platform is Some(platform) { + platform.set_cursor_style(style) + } +} + +///| +pub fn Window::read_from_clipboard(self : Window) -> @platform.ClipboardItem? { + match self.platform { + Some(platform) => platform.read_from_clipboard() + None => None + } +} + +///| +pub fn Window::write_to_clipboard( + self : Window, + item : @platform.ClipboardItem, +) -> Unit { + if self.platform is Some(platform) { + platform.write_to_clipboard(item) + } +} + +///| +/// Marks the current input event's default action as prevented (GPUI: +/// `prevent_default`). +pub fn Window::prevent_default(self : Window) -> Unit { + self.default_prevented = true +} + +///| +pub fn Window::default_prevented(self : Window) -> Bool { + self.default_prevented +} + +///| +pub fn Window::on_should_close( + self : Window, + handler : (Window, @app.App) -> Bool, +) -> Unit { + self.should_close_handler = Some(handler) +} + +///| +pub fn Window::on_close(self : Window, callback : (@app.App) -> Unit) -> Unit { + self.close_callbacks.push(callback) +} + +///| +pub fn Window::on_window_active_change( + self : Window, + callback : (Window, @app.App) -> Unit, +) -> Unit { + self.activation_observers.push(callback) +} + ///| /// Resizes the viewport (and optionally changes the scale factor); the next /// frame is laid out again. @@ -207,19 +554,22 @@ pub fn Window::resize( if scale_factor is Some(factor) { self.scale_factor = factor } - self.dirty = true + if self.platform_window is Some(pw) && !self.closed { + pw.resize(viewport_size) + } + self.mark_dirty() } ///| pub fn Window::set_rem_size(self : Window, rem_size : @geometry.Pixels) -> Unit { self.rem_size = rem_size - self.dirty = true + self.mark_dirty() } ///| /// Marks the window for redraw (GPUI: `refresh`). pub fn Window::refresh(self : Window) -> Unit { - self.dirty = true + self.mark_dirty() } ///| @@ -260,14 +610,17 @@ fn Window::assert_phase( ///| /// Draws a frame: renders the root view, lays it out to fill the viewport, -/// prepaints and paints it. Returns the frame's scene. Effects queued while -/// drawing flush afterwards (GPUI: `Window::draw`). +/// prepaints and paints it. Returns the frame's scene and presents it to the +/// `PlatformWindow` if one is attached. Effects queued while drawing flush +/// afterwards (GPUI: `Window::draw`). pub fn Window::draw(self : Window) -> @scene.Scene { + guard !self.closed else { abort("Window::draw called on a closed window") } guard self.phase == Idle else { abort("Window::draw called while drawing") } guard self.root is Some(root) else { abort("Window::draw: no root view (call set_root_view first)") } self.app.update(fn(app) { + self.dirty = false self.layout_engine.clear() self.next_scene = @scene.Scene::new() self.next_hitboxes = [] @@ -293,6 +646,11 @@ pub fn Window::draw(self : Window) -> @scene.Scene { ) self.phase = Prepaint element.prepaint(self, app) + self.hovered_hitboxes = if self.pointer_inside { + hit_test_hitboxes(self.next_hitboxes, self.mouse_position) + } else { + [] + } self.phase = Paint element.paint(self, app) self.phase = Idle @@ -304,10 +662,10 @@ pub fn Window::draw(self : Window) -> @scene.Scene { self.rendered_element_states = self.next_element_states self.rendered_views = self.next_rendered_views self.drawn_frames = self.drawn_frames + 1 - self.dirty = false - // Hover state may have changed with the new layout. - self.hovered_hitboxes = self.hit_test(self.mouse_position) }) + if self.platform_window is Some(pw) && !self.closed { + pw.draw(self.rendered_scene) + } self.rendered_scene } @@ -533,7 +891,7 @@ pub fn[S, R] Window::with_element_state( } // --------------------------------------------------------------------------- -// Hitboxes and mouse input +// Hitboxes and input dispatch // --------------------------------------------------------------------------- ///| @@ -558,13 +916,13 @@ pub fn Window::insert_hitbox( ///| /// The ids of the hitboxes under `position`, topmost first, stopping below a /// `BlockMouse` hitbox (GPUI: `Frame::hit_test`). -fn Window::hit_test( - self : Window, +fn hit_test_hitboxes( + hitboxes : Array[Hitbox], position : @geometry.Point[@geometry.Pixels], ) -> Array[Int32] { let hits = [] - for i = self.rendered_hitboxes.length() - 1; i >= 0; i = i - 1 { - let hitbox = self.rendered_hitboxes[i] + for i = hitboxes.length() - 1; i >= 0; i = i - 1 { + let hitbox = hitboxes[i] let visible = hitbox.bounds.intersect(hitbox.content_mask.bounds) if visible.contains(position) { hits.push(hitbox.id) @@ -603,16 +961,22 @@ pub fn Window::dispatch_mouse_event( self : Window, event : @input.MouseEvent, ) -> Bool { + guard !self.closed else { + abort("dispatch_mouse_event called on a closed window") + } guard self.phase == Idle else { abort("dispatch_mouse_event called while drawing") } self.mouse_position = event.position() - let hovered = self.hit_test(self.mouse_position) + self.modifiers = event.modifiers() + self.pointer_inside = true + let hovered = hit_test_hitboxes(self.rendered_hitboxes, self.mouse_position) if hovered != self.hovered_hitboxes { self.hovered_hitboxes = hovered - self.dirty = true + self.mark_dirty() } self.propagate_event = true + self.default_prevented = false let listeners = self.rendered_mouse_listeners self.app.update(fn(app) { for listener in listeners { @@ -630,3 +994,40 @@ pub fn Window::dispatch_mouse_event( }) self.propagate_event } + +///| +/// Delivers a `PlatformInput` event to the window (GPUI: +/// `Window::dispatch_event`). +pub fn Window::dispatch_input( + self : Window, + event : @input.PlatformInput, +) -> @input.DispatchEventResult { + guard !self.closed else { abort("dispatch_input called on a closed window") } + guard self.phase == Idle else { abort("dispatch_input called while drawing") } + self.propagate_event = true + self.default_prevented = false + match event { + MouseDown(e) => ignore(self.dispatch_mouse_event(MouseDown(e))) + MouseUp(e) => ignore(self.dispatch_mouse_event(MouseUp(e))) + MouseMove(e) => ignore(self.dispatch_mouse_event(MouseMove(e))) + ScrollWheel(e) => ignore(self.dispatch_mouse_event(ScrollWheel(e))) + MouseExited(e) => { + self.mouse_position = e.position + self.modifiers = e.modifiers + self.pointer_inside = false + if !self.hovered_hitboxes.is_empty() { + self.hovered_hitboxes = [] + self.mark_dirty() + } + } + ModifiersChanged(e) => + if self.modifiers != e.modifiers { + self.modifiers = e.modifiers + self.mark_dirty() + } + } + { + propagate: self.propagate_event, + default_prevented: self.default_prevented, + } +}