Porting plan + first pure slice: geometry, color, scene #1

Merged
nandi merged 3 commits from feat/geometry-color-scene into main 2026-11-29 06:14:37 +00:00
24 changed files with 5856 additions and 1 deletions
Showing only changes of commit 8c0685fe01 - Show all commits

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
_build/
.mooncakes/
target/
.repos/
.context/
+222
View File
@@ -0,0 +1,222 @@
Copyright 2022 - 2025 Zed Industries, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+20
View File
@@ -0,0 +1,20 @@
moon-gpui
=========
This project is a MoonBit port of GPUI, the GPU-accelerated UI framework of
the Zed editor:
https://github.com/zed-industries/zed/tree/main/crates/gpui
Copyright 2022 - 2025 Zed Industries, Inc.
Licensed under the Apache License, Version 2.0.
Source files in this repository are derived from GPUI's Rust sources (the
reference snapshot is zed-industries/zed commit
f98c2c100d217ace3ca99564cfc4573612d43d47). They have been translated to
MoonBit and modified; each package documents where it deviates from the
original. See docs/PORTING.md for the mapping between GPUI modules and the
MoonBit packages.
This port is distributed under the same license, the Apache License,
Version 2.0 (see LICENSE). It is not affiliated with or endorsed by Zed
Industries.
+25 -1
View File
@@ -1,3 +1,27 @@
# moon-gpui # moon-gpui
Port of Zed's GPUI GPU-accelerated UI framework to MoonBit A port of [GPUI](https://github.com/zed-industries/zed/tree/main/crates/gpui),
the GPU-accelerated UI framework of the Zed editor, to
[MoonBit](https://www.moonbitlang.com).
Status: **early**. The pure-logic foundation is in place; nothing renders yet.
See [docs/PORTING.md](docs/PORTING.md) for the architecture mapping and the
roadmap.
| Package | GPUI source | Status |
| --- | --- | --- |
| `experiments/gpui/geometry` | `geometry.rs`, `ContentMask` | Ported (units, Point/Size/Bounds/Edges/Corners, lengths) |
| `experiments/gpui/color` | `color.rs` | Ported (Rgba/Hsla, hex parsing, Background) |
| `experiments/gpui/scene` | `scene.rs`, `bounds_tree.rs` | Ported (primitives, draw ordering, layers, batching, replay) |
All packages are pure MoonBit and are tested on every backend:
```sh
moon check --target all
moon test --target all
moon fmt
```
## License
Apache-2.0, like GPUI itself. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
+452
View File
@@ -0,0 +1,452 @@
# Porting GPUI to MoonBit
This document is the plan for porting [GPUI](https://github.com/zed-industries/zed/tree/main/crates/gpui)
(Zed's UI framework, Apache-2.0) to MoonBit. It covers how GPUI is built,
how its modules map to MoonBit packages, which parts are pure logic and which
are platform code, the backend strategy, where Rust idioms need a different
design, and an ordered roadmap.
Reference snapshot: `zed-industries/zed` @ `f98c2c100d21` (2026-11-24). The
`gpui` crate is about 98k lines of Rust. Platform code lives in sibling
crates: `gpui_platform`, `gpui_macos`, `gpui_linux`, `gpui_windows`,
`gpui_web`, `gpui_wgpu`, and `gpui_macros`.
---
## 1. GPUI architecture in one page
```mermaid
flowchart TD
App["App (entities, globals, effects, keymap, actions)"] --> Window
Window["Window (frame loop, focus, dispatch tree, element state)"] --> Element
Element["Element tree: div(), text, img, list ... (Styled + Interactive)"] --> Taffy["Layout (taffy flexbox/grid)"]
Element --> Scene["Scene (Quad, Shadow, Path, Underline, Sprites)"]
Window --> TextSystem["Text system (shape, wrap, glyph atlas)"]
Scene --> PlatformWindow
App --> Platform["Platform trait: windows, executors, clipboard, text system"]
Platform --> PlatformWindow["PlatformWindow: draw(scene), input callbacks"]
PlatformWindow --> Renderer["Renderer (Metal / wgpu / Blade)"]
```
**App, Context and Entity** (`app.rs`, `app/entity_map.rs`, `app/context.rs`)
- All state lives in *entities* owned by `App`. `EntityMap` stores
`Box<dyn Any>` values in a slot map. An `Entity<T>` is a refcounted, typed
handle (an id plus `PhantomData<T>`), and `WeakEntity<T>` is its weak form.
- `update_entity` *leases* the value: it removes it from the map, runs the
closure with `&mut T` and `&mut Context<T>`, and puts it back. A re-entrant
update of the same entity panics.
- `Context<T>` derefs to `App` and adds entity-scoped helpers: `notify`,
`emit`, `observe`, `subscribe`, `spawn`, `listener`, `on_release`, and the
`*_in(window)` variants.
- Side effects go through an `Effect` queue (`Notify`, `Emit`,
`RefreshWindows`, `NotifyGlobalObservers`, `Defer`, `EntityCreated`). The
queue is flushed when the outermost `App::update` returns.
- Subscriptions are `SubscriberSet`s. A callback that returns `false`
unsubscribes itself.
- Globals are a `TypeId → Box<dyn Any>` map.
- `notify` marks individual views dirty. During a draw, each window records
which entities it read (`AccessedEntities`).
**Window** (`window.rs`, 11k lines)
- `draw()` runs three phases over the root view's element tree:
1. `request_layout`, then compute layout with taffy.
2. `prepaint`: hitboxes, the dispatch tree, focus, and element state.
3. `paint`: emits primitives into the `Scene`.
- Frames are double-buffered (`rendered_frame` and `next_frame`).
- Cached views reuse their prepaint and paint *ranges* from the previous
frame (`Scene::replay`).
- Element state is keyed by `(GlobalElementId, TypeId)`.
**Element** (`element.rs`, `elements/*`)
- The `Element` trait has two associated state types,
`RequestLayoutState` and `PrepaintState`, and three phase methods.
- `AnyElement` is a type-erased element in an arena.
- `IntoElement`, `ParentElement`, `Render`/`RenderOnce`, `View`, and `AnyView`
build the tree.
- `div()` (5.9k lines) carries an `Interactivity`: a base
`StyleRefinement`, state styles (hover, active, focus, group), about 20
listener lists, scrolling, drag and drop, and tooltips.
**Style and layout** (`style.rs`, `styled.rs`, `taffy.rs`)
- `Style` is a CSS-like struct.
- `#[derive(Refineable)]` generates `StyleRefinement`, a copy of the struct
with every field optional.
- `Styled` provides hundreds of Tailwind-style builder methods. Most are
macro-generated (`gpui_macros::style_helpers!`).
- Layout is taffy 0.15 (flexbox, block, and grid), wrapped by
`TaffyLayoutEngine` with measured leaves (text) and a cache.
**Scene** (`scene.rs`, `bounds_tree.rs`)
- Per-kind primitive arrays. Each primitive gets a draw `order` from an
R-tree: one more than the highest overlapping order, unless the kinds may
share a level.
- Layers group primitives into one ordering unit.
- `finish()` sorts the arrays. `batches()` merges them into
`PrimitiveBatch`es for the renderer.
**Platform** (`platform.rs`, plus one crate per OS)
- `Platform` has about 90 methods: windows, executors, the text system,
clipboard, menus, and paths.
- `PlatformWindow` has about 100 methods: `draw(&Scene)`, input and resize
callbacks, and the IME handler.
- Other platform traits: `PlatformDispatcher` (runs tasks), `PlatformTextSystem`
(font ids, shaping via `layout_line`, glyph rasterization), and
`PlatformAtlas` (glyph, SVG, and image tiles).
- The `gpui_web` crate already targets the browser. It uses a `<canvas>`, the
`gpui_wgpu` renderer (WebGPU with a WebGL2 fallback), cosmic-text for text,
and DOM event translation. It has a hidden `<textarea>` for IME and a
`setTimeout`-based dispatcher.
**Text** (`text_system.rs`, `text_system/*`)
- Fonts → `FontId`. The platform shapes a line into a `LineLayout` (runs of
positioned glyphs).
- GPUI itself wraps lines (`LineWrapper`), caches layouts per frame, and
paints glyphs as sprites from the atlas.
**Input** (`action.rs`, `keymap*.rs`, `key_dispatch.rs`, `interactive.rs`)
- Actions are `dyn Action` values. They are registered globally with the
`inventory` crate and dispatched by `TypeId`.
- The keymap maps keystroke sequences and a context predicate (`"Editor &&
mode == full"`) to actions.
- The dispatch tree is rebuilt every frame. Key events are tried in this
order: key listeners, then keymap bindings, then action listeners (capture,
then bubble), then global listeners, then the IME input handler.
**Executors** (`executor.rs`, `platform_scheduler.rs`, the `scheduler` crate)
- `BackgroundExecutor` and `ForegroundExecutor` spawn futures and return a
`Task<T>`. Dropping the task cancels the work.
- `AsyncApp` is a weak handle to the app that can be held across `.await`.
---
## 2. Module map: GPUI to MoonBit packages
The module is `experiments/gpui` with sources under `src/`. Packages are
fine-grained, so pure logic can be tested on every backend and platform code
stays isolated.
| MoonBit package | GPUI source | Kind | Status |
| --- | --- | --- | --- |
| `geometry` | `geometry.rs`, `ContentMask` (window.rs) | pure | **done** |
| `color` | `color.rs`, `colors.rs` | pure | **done** (`colors.rs` theme defaults pending) |
| `scene` | `scene.rs`, `bounds_tree.rs`, `AtlasTile` (platform.rs) | pure | **done** (see deviations) |
| `style` | `style.rs`, `styled.rs`, Refineable | pure | next |
| `layout` | `taffy.rs` (+ a taffy port) | pure | next |
| `keymap` | `keymap.rs`, `keymap/*`, `platform/keystroke.rs` | pure | planned |
| `action` | `action.rs` | pure | planned |
| `app` | `app.rs`, `app/*`, `subscription.rs`, `global.rs`, `gpui.rs` traits | pure | planned |
| `executor` | `executor.rs`, `platform_scheduler.rs`, `scheduler` crate | pure core + platform hooks | planned |
| `element` | `element.rs`, `view.rs`, `elements/div.rs`, `interactive.rs` | pure | planned |
| `window` | `window.rs`, `key_dispatch.rs`, `tab_stop.rs` | pure (talks to platform traits) | planned |
| `text` | `text_system.rs`, `text_system/*` | mixed: wrapping/caching pure, shaping platform | planned |
| `platform` | `platform.rs` (traits only), `interactive.rs` input types | pure (interfaces) | planned |
| `platform/test` | `platform/test/*` | pure | planned: headless platform for tests |
| `platform/web` | `gpui_web` | **js only** | planned |
| `renderer/canvas2d` | (new) | **js only** | planned |
| `renderer/software` | (new; optional) | pure | candidate |
| `renderer/wgpu` | `gpui_wgpu` | native (+ js WebGPU) | later |
| `platform/native/*` | `gpui_macos`, `gpui_linux`, `gpui_windows` | native only | later |
| `elements/*` | `elements/{text,img,svg,list,uniform_list,anchored,deferred,canvas,animation}.rs` | pure | later |
A facade package (`experiments/gpui` re-exporting the common API, similar to
GPUI's `prelude.rs`) should come once there are enough packages to make
`@gpui.div()` worth having.
### What is pure logic and what is platform code
```mermaid
flowchart LR
subgraph pure["Pure MoonBit: every backend, unit-testable without a GPU"]
geometry --> color --> scene
geometry --> style --> layout
keymap --> action
app --> executor_core[executor core]
element --> window
text_wrap[text: wrapping, line cache]
end
subgraph platform["Platform-specific"]
web["platform/web: DOM events, rAF, canvas (js)"]
r2d["renderer/canvas2d (js)"]
shaping["text shaping + rasterization: canvas measureText or moon_cosmic"]
native["native windowing + wgpu (native)"]
end
window --> platform_traits[platform traits] --> web & native
scene --> r2d
```
Pure, portable, and testable without a GPU:
- Geometry, color, and style resolution.
- Flexbox and grid layout.
- The entity, context, subscription, and effect model.
- The executor queue logic, driven by a fake clock in tests (GPUI's
`TestScheduler` is the model).
- Keystroke parsing, the keymap and context predicates, and action dispatch.
- Scene building, ordering, and batching.
- Element trees, hit-testing, focus, and the dispatch tree.
- Line wrapping and truncation.
- The whole `Window::draw` pipeline against a test platform. Assertions run
on the resulting `Scene`.
Platform-specific:
- Window creation and the event loop (the browser `requestAnimationFrame` or a
native event loop).
- Input event translation and IME.
- The GPU or Canvas2D renderer.
- Font loading, shaping, and glyph rasterization. These can also be pure;
see the text system below.
- Clipboard, cursors, menus, and file dialogs.
---
## 3. Existing MoonBit packages (mooncakes.io survey, 2026-11-24)
The **Backends** column is what each package declares
(`supported_targets` or FFI); "all" means no restriction. The check column
records what I verified with toolchain `moon 0.1.20261119`.
| Need | Package | Backends | Notes |
| --- | --- | --- | --- |
| Flexbox/grid layout | `Milky2018/moon_taffy@0.5.3` | all (pure) | Port of taffy 0.5.2 (GPUI uses 0.15). **Does not compile on the current toolchain**: 32 errors in `style/style_json.mbt` from the new explicit trait-method `extend` rule. Needs an upstream fix or a vendored patch. |
| Flexbox (alt.) | `NoahLiu/yoga-mbt@0.1.1` | pure | Yoga-style flexbox only, with no grid. |
| Text shaping/layout | `Milky2018/moon_cosmic@0.3.9` | all (pure) | Port of cosmic-text on `moon_swash`, `moon_skrifa`, and `moon_zeno`. **Checks on js and native.** It is what `gpui_web`/`gpui_wgpu` use upstream (cosmic-text), so it fits well. |
| Font parsing | `Milky2018/moon_skrifa`, `mizchi/font`, `bikallem/freetype` | pure | |
| 2D rasterizer | `Milky2018/moon_zeno`, `TryAndRun-TvT/tiny-skia-moon` (wasm/wasm-gc only), `mizchi/canvas` (pure, PNG out) | mixed | For a pure software renderer and golden-image tests. |
| Unicode | `moonbit-community/unicode-segmentation`, `unicode-bidi`, `kawaz/grapheme`, `moonbit-community/unicodewidth` | pure | For word boundaries in the line wrapper and for grapheme-aware cursor movement. |
| Browser APIs | `mizchi/js_browser@0.13.0` (MIT), `dijdzv/websys`, `peter-jerry-ye/canvas` | **js only** | DOM, Canvas2D, events, and rAF. |
| WebGPU | `Milky2018/wgpu_mbt@0.16.2` | **native only** | wgpu-native C API bindings; macOS is supported, Linux and Windows are experimental. `tonyfettes/webgpu` and `emadurandal/rhodonite_webgpu` cover browser WebGPU. |
| Windowing | `Milky2018/window@0.6.2` (winit port, **native, macOS only**), `mizchi/glfw`, `klaseca/sdl`, `laplaceliu/tycho_window` (Xlib) | native only | |
| Async | `moonbitlang/async@0.22.10` | **native** (some wasm) | Not usable on js. Core has a `moonbitlang/core/async` package; its js story needs checking before the executor milestone. |
| Taffy-free layout ref | `Frank-III/onebit-tui` | native | Uses Yoga through FFI. Not useful here. |
Recommendation: depend on `moon_cosmic` for text when that milestone
arrives. For layout, **fork/vendor `moon_taffy`** (Apache-2.0) and fix it for
the toolchain, or send the fix upstream. Writing flexbox from scratch would
be the costlier path.
---
## 4. Backend recommendation
**Primary target: `js` (browser)**, with a Canvas2D renderer first.
1. Browser rendering needs no native toolchain: the result is a `<canvas>`
and a page. The upstream `gpui_web` crate shows that GPUI's platform traits
fit the browser: rAF frames, DOM events, and a hidden textarea for IME.
2. Canvas2D can draw every GPUI primitive closely enough for a first
milestone:
- Rounded rectangles with borders: `roundRect`, `fill`, `stroke`.
- Box shadows: `shadowBlur`, `shadowColor`, then fill.
- Gradients: `createLinearGradient`.
- Paths: `Path2D` with the even-odd or non-zero fill rule.
- Underlines: lines, or a wavy path.
- Sprites: `drawImage` from an atlas canvas.
- Clipping: `clip()` to the content mask.
Text can either go through Canvas2D `fillText`, with `measureText`
implementing `PlatformTextSystem.layout_line`, or be shaped by
`moon_cosmic` and drawn as atlas sprites. The first is fastest to build;
the second gives identical results on every backend.
3. All pure packages run on `js` as well as on wasm-gc and native. We test
them on all four targets (`moon test --target all`; there is no CI yet), so the core stays
backend-neutral.
4. A **WebGPU renderer** on js (reusing GPUI's WGSL shaders from
`gpui_wgpu/shaders.wgsl`) and a **native** platform (`wgpu_mbt` plus a
windowing binding) can follow. They plug in behind the same
`Platform`/`PlatformWindow`/`Renderer` interfaces.
Alternative considered: wasm-gc in the browser. It is faster and smaller, but
the FFI to JavaScript is clumsier and the browser-binding packages target js.
We can revisit this once the js platform works; the pure core already
compiles for wasm-gc.
The `Platform` interface is a MoonBit trait, or a record of closures, holding
the **core subset**:
- `open_window`, `run`, `quit`
- Executor hooks: `dispatch`, `dispatch_after`, `now`
- `text_system`
- Clipboard read and write
- `set_cursor_style`
`PlatformWindow` likewise holds only the core:
- `bounds`, `scale_factor`, `mouse_position`, `modifiers`
- `draw(scene)`, `request_frame`
- `on_input`, `on_resize`, `on_request_frame`
- `set_input_handler`, `sprite_atlas`
The other roughly 150 methods (menus, tabs, thermal state, credentials, and
so on) are added only when an element needs them. Unsupported operations
**fail loudly**: `abort` or `raise`, never a silent no-op.
---
## 5. Rust idioms that need a different MoonBit design
| Rust in GPUI | Problem in MoonBit | Proposed design |
| --- | --- | --- |
| `Box<dyn Any>` + `TypeId` + downcast (entities, globals, events, actions, element state, drag payloads) | No `Any` or `TypeId` | **Typed keys created at registration**: `EntityKey[T]`, `GlobalKey[T]`, and `EventKey[E]` each wrap a unique `Int` and are allocated once per type (`let counter_key : GlobalKey[Counter] = GlobalKey::new("Counter")`). Storage is `Map[Int, Erased]`, where `Erased` is a closure-captured value. Typed access goes through a key whose type parameter fixes `T`, with a runtime id check that aborts on mismatch. Events are delivered to closures registered against an `EventKey[E]`, so no downcast is needed at the call site. |
| `Entity<T>` with `PhantomData<T>`, refcount via `Clone`/`Drop` | GC, no `Drop` | `Entity[T]` holds an id and a reference to a typed cell (`Ref[T]`). Typed access needs no map lookup, and the map holds only erased bookkeeping. **Liveness:** with a GC there is no drop hook, so release is explicit (`App::release(entity)` or the window owning its views), and release listeners run then. Subscriptions return a `Subscription` with `unsubscribe()`. Decide this early; see the design questions. |
| `Context<'a, T>` derefs to `&mut App`; leasing for `&mut T` | No lifetimes, no `Deref` | `Context[T]` is a struct `{ app : App, entity : Entity[T] }` passed by reference, with App methods duplicated or forwarded explicitly. Leasing is unnecessary for memory safety, but **keep the re-entrancy check** (abort on a nested `update` of the same entity) so behavior matches GPUI. |
| `trait Element { type RequestLayoutState; type PrepaintState; ... }` | No associated types | Elements keep per-frame state in **their own mutable fields**, set in `request_layout` and read in `prepaint` and `paint`; `div` already works this way. The trait becomes `trait Element { request_layout(Self, Window, App) -> LayoutId; prepaint(Self, Bounds, Window, App) -> Unit; paint(Self, Bounds, Window, App) -> Unit }`, and `AnyElement` is `&Element`. |
| `impl IntoElement` returns, `IntoElement::Element` | No RPIT, no associated types | `render` returns `AnyElement`. `IntoElement` becomes `into_any_element(Self) -> AnyElement`, implemented for `Div`, `String`, and so on. |
| `Along::Unit`, `Refineable::Refinement`, `VisualContext::Result<T>` | Associated types | Plain generic methods (as done in `geometry`), hand-written or generated `StyleRefinement`, and concrete return types. |
| `impl Mul<f32> for Pixels` (heterogeneous operators) | `Mul` is `Self * Self` | A separate `MulScalar` trait with `mul_scalar(Double)`, as done in `geometry`. `Pixels / Pixels -> f32` becomes `Pixels::ratio`. |
| Trait methods callable as methods | The current toolchain requires an explicit `extend` | Packages add `pub extend T with Trait::{method}` for ergonomic calls, or call `Trait::method(x)`. |
| Proc macros: `Refineable`, `style_helpers!` and 8 other style macros, `actions!`, `#[derive(Action)]`, `IntoElement`, `Render` | No macros | **Code generation**: a small generator script (kept in `tools/`) emits `styled_generated.mbt` and the refinement structs, and its output is committed. `actions!` becomes explicit `Action` impls, or one enum per namespace plus a `register_actions(registry)` call. |
| `inventory::submit!` global action registry | No link-time registration | Explicit `ActionRegistry::register(name, build)` at app start-up. |
| `async`/`await`, `AsyncFnOnce`, `Task<T>` cancels on drop, `!Send` executors | MoonBit async is young; `moonbitlang/async` is native-only | Single-threaded **foreground executor** built on a run queue and a timer heap, driven by the platform (`setTimeout`/rAF on js). `Task[T]` has an explicit `cancel()` and a `detach()`. The background executor starts as an alias of the foreground one on js. Use MoonBit `async fn` where the toolchain supports it on the target, and callbacks otherwise. A deterministic `TestScheduler` drives tests. |
| `Rc<RefCell<..>>` sharing (scroll handles, focus maps, text layouts) | No borrow checker needed | Plain mutable structs / `Ref[T]`. |
| Arenas for elements and events | GC | Ordinary allocation. |
| `#[repr(C)]` primitives with padding for GPU upload | No layout control | Clean MoonBit records. Each renderer packs into `FixedArray[Float]` or bytes explicitly. |
| `f32` everywhere | `Float` is emulated on js; `Double` is native everywhere | Logical units use `Double`. Converting to f32 is the renderer's job. |
| `SmallVec`, `SharedString`, `Arc<str>` | Not needed | `Array`, `String`. |
---
## 6. Roadmap
Each milestone is a vertical slice merged as its own PR with tests on all
backends. Pure milestones come first so most of GPUI can be tested headless
before any pixels appear.
```mermaid
gantt
dateFormat X
axisFormat %s
section Pure core
M0 geometry/color/scene :done, m0, 0, 1
M1 style + refinement + Styled :m1, after m0, 2
M2 layout (taffy) bridge :m2, after m1, 2
M3 app/entity/effects :m3, after m0, 2
M4 executor + test scheduler :m4, after m3, 1
M5 keymap/actions/keystrokes :m5, after m0, 1
M6 element/div/window draw :m6, after m2, 3
section Platform
M7 test platform + headless draw :m7, after m6, 1
M8 web platform + canvas2d :m8, after m7, 3
M9 text system :m9, after m8, 3
M10 input, focus, IME :m10, after m9, 2
M11 more elements :m11, after m10, 3
M12 wgpu / native :m12, after m11, 4
```
- **M0 (this PR).** `geometry`, `color`, and `scene`: units, rects, colors,
primitives, the bounds tree, layers, batching, and replay.
- **M1: style.**
- `Style`, `TextStyle`, `Fill`, `BoxShadow`, and the enums (`Display`,
`Position`, `Overflow`, flex and alignment enums, `Visibility`,
`CursorStyle`, `WhiteSpace`, and so on).
- `StyleRefinement` and `TextStyleRefinement` with `refine`.
- The `Styled` trait and the generated Tailwind helpers (`p_2`, `w_full`,
`rounded_md`, `shadow_lg`, ...).
- Tests: refinement cascade semantics, and helper values matching GPUI's
(for example `p_2 == rems(0.5)`).
- **M2: layout.**
- Vendor and fix `moon_taffy`, or port the taffy flexbox, block, and grid
algorithms needed.
- `LayoutEngine` with `request_layout`, `request_measured_layout`,
`compute_layout`, and `layout_bounds`, plus `Style` → taffy conversion
with rem and scale resolution.
- Tests: a corpus of flexbox cases (taffy's generated tests).
- **M3: app model.**
- `App`, `Entity[T]`/`WeakEntity[T]`, and `Context[T]`.
- `notify`, `observe`, `subscribe`/`emit` with typed event keys, globals,
and observers.
- The effect queue and `flush_effects` semantics: deferral, and dedup of
notifications.
- Tests ported from GPUI's `app` tests.
- **M4: executor.**
- Foreground executor, timers, and `Task[T]` (cancel and detach).
- `TestScheduler` with a virtual clock and `run_until_parked`.
- `spawn` from `Context`.
- **M5: input model.**
- `Keystroke::parse`, `Modifiers`.
- `KeyContext` and the predicate parser and evaluator.
- `Keymap::bindings_for_input` with precedence, `NoAction`, and pending
multi-stroke matching.
- `ActionRegistry`.
- Tests ported from `keymap.rs` and `keymap/context.rs`.
- **M6: elements and window.**
- `Element`/`AnyElement`/`IntoElement`/`ParentElement`, `Render`, and
views.
- `div` with styles, hover and active styles, mouse listeners, and
scrolling.
- `Window::draw` (request_layout → prepaint → paint), element ids and
state, hitboxes, the content-mask stack, and the dispatch tree.
- Tests: build a tree, draw against the test platform, assert on the
Scene.
- **M7: test platform.** A headless `Platform`/`PlatformWindow` that records
scenes and injects input events, mirroring GPUI's `TestPlatform` and
`VisualTestContext`. This is the base for most later tests.
- **M8: web platform + Canvas2D renderer (first pixels).**
- A `<canvas>` window, rAF-driven frames, resize, and DPR.
- DOM pointer, wheel, and key events → `PlatformInput`.
- Canvas2D drawing of every primitive kind.
- An example app (`examples/hello_world`, after GPUI's) served by a tiny
HTML page.
- **M9: text.**
- The `PlatformTextSystem` interface, `LineLayout`, `ShapedLine`, and
`WrappedLine`.
- The pure `LineWrapper` port.
- Shaping through `moon_cosmic` (pure) or Canvas `measureText` (decision
below).
- The glyph atlas and `MonochromeSprite` painting.
- Text elements: `StyledText` and `&str` children.
- **M10: interaction.**
- Focus handles and tab stops.
- Key dispatch through the keymap to actions.
- `InputHandler` with a hidden-textarea IME on the web.
- Clipboard.
- Drag and drop of typed payloads.
- **M11: elements.** `img` and `svg` (atlas `PolychromeSprite`), `list` and
`uniform_list`, `anchored`, `deferred`, `canvas`, `animation`, and
tooltips.
- **M12: GPU and native.**
- A WebGPU renderer on js reusing GPUI's WGSL, with tiled path rasterization
replacing the simplified `PaintedPath`.
- A native platform on `wgpu_mbt` plus a windowing binding (macOS first).
### Deviations already taken in M0
- `Pixels`, `ScaledPixels`, `Rems`, and colors are `Double`-based (GPUI:
`f32`). `Pixels::round` keeps Rust's round-half-away-from-zero on every
backend.
- `PaintedPath` stores flattened polygon contours. GPUI stores tiled paths
built with lyon, which is renderer-milestone work.
- Not yet ported:
- `PaintSurface` (macOS video surfaces).
- `PaintNativeView` (embedded native views).
- Sprite animations (`TimedTransformation`).
- `Scene::batches()` returns an `Array` rather than a lazy iterator.
- `Hsla::fade_out` returns a new color instead of mutating.
- `Bounds::extend` is `Bounds::extend_by`, because `extend` is a keyword.
- `Corners::corner` aborts for side-center anchors instead of panicking in
`unreachable!`; the behavior is the same, failing loudly.
---
## 7. Open design questions
1. **Entity liveness without `Drop`.** Should entities be released explicitly
(`release()`, or ownership through windows and views)? The alternative is
for strong handles to be ordinary GC references and drop GPUI's release
semantics (`on_release`, dropped-entity cleanup), which is simpler but
diverges. *Recommendation: explicit release for entities that have release
listeners or are observed, with views released when their window closes.*
2. **Text shaping on the web.** Shape with `moon_cosmic`, which is pure,
deterministic, the same on every backend, matches upstream `gpui_web`, and
needs bundled fonts. Or use browser Canvas `measureText`/`fillText`, which
gives system fonts and is quick to build, but has no glyph-level shaping
output and cannot be tested headless. *Recommendation: `moon_cosmic`, with
Canvas text only as an emoji/CJK fallback, as upstream does.*
3. **Layout engine.** Vendor and fix `moon_taffy` 0.5 (which needs toolchain
fixes, and whose API differs from taffy 0.15), or port taffy 0.15's
algorithms directly. *Recommendation: vendor `moon_taffy` now and upstream
the fixes.*
4. **First renderer.** Canvas2D on js (fastest to pixels), WebGPU on js
(closest to GPUI, reusing the WGSL shaders), or a pure software rasterizer
(golden-image tests on every backend). *Recommendation: Canvas2D first,
WebGPU second.*
5. **API surface naming.** Keep GPUI names verbatim where possible (`div()`,
`px()`, `rems()`, `.flex().p_2().bg(...)`), so Rust GPUI code ports
mechanically? *Recommendation: yes.*
6. **Module name.** `experiments/gpui` for now; publishing to mooncakes would
need an owner namespace.
+18
View File
@@ -0,0 +1,18 @@
// MoonBit port of Zed's GPUI. See docs/PORTING.md.
name = "experiments/gpui"
version = "0.1.0"
readme = "README.md"
repository = "https://git.site.latha.org/experiments/moon-gpui"
license = "Apache-2.0"
keywords = [ "gui", "ui", "gpui", "layout", "graphics" ]
description = "A MoonBit port of GPUI, Zed's GPU-accelerated UI framework"
source = "src"
preferred_target = "js"
+517
View File
@@ -0,0 +1,517 @@
// Colors and backgrounds, ported from gpui/src/color.rs.
//
// Deviations from GPUI:
// - Channels are `Double` (GPUI: `f32`), see geometry/units.mbt.
// - Values are immutable; `Hsla::fade_out` returns a new color instead of
// mutating in place.
// - serde (de)serialization is replaced by `Rgba::parse` / `Rgba::to_hex`.
///|
/// A color in the sRGB color space with straight (non-premultiplied) alpha.
/// Channels are in `0.0..=1.0`.
#derive(Eq, Default, Debug)
pub(all) struct Rgba {
r : Double
g : Double
b : Double
a : Double
}
///|
/// A color as hue, saturation, lightness and alpha, all in `0.0..=1.0`.
#derive(Eq, Compare, Default, Debug)
pub(all) struct Hsla {
h : Double
s : Double
l : Double
a : Double
}
///|
fn clamp01(value : Double) -> Double {
if value < 0.0 {
0.0
} else if value > 1.0 {
1.0
} else {
value
}
}
///|
fn byte_at(hex : UInt32, shift : Int32) -> Double {
((hex >> shift) & 0xFF).reinterpret_as_int().to_double() / 255.0
}
///|
/// An opaque color from a `0xRRGGBB` value.
pub fn rgb(hex : UInt32) -> Rgba {
{ r: byte_at(hex, 16), g: byte_at(hex, 8), b: byte_at(hex, 0), a: 1.0, }
}
///|
/// A color from a `0xRRGGBBAA` value.
pub fn rgba(hex : UInt32) -> Rgba {
{
r: byte_at(hex, 24),
g: byte_at(hex, 16),
b: byte_at(hex, 8),
a: byte_at(hex, 0),
}
}
///|
/// Truncating float-to-byte conversion, like Rust's `(x * 255.0) as u32`.
fn channel_to_byte_trunc(value : Double) -> UInt32 {
let scaled = value * 255.0
if scaled.is_nan() || scaled <= 0.0 {
0
} else {
scaled.to_int().reinterpret_as_uint()
}
}
///|
/// Packs into `0xRRGGBBAA`, truncating each channel (GPUI's `From<Rgba> for
/// u32`).
pub fn Rgba::to_u32(self : Rgba) -> UInt32 {
(channel_to_byte_trunc(self.r) << 24) |
(channel_to_byte_trunc(self.g) << 16) |
(channel_to_byte_trunc(self.b) << 8) |
channel_to_byte_trunc(self.a)
}
///|
/// Blends `other` over `self` (straight alpha, keeps `self`'s alpha).
pub fn Rgba::blend(self : Rgba, other : Rgba) -> Rgba {
if other.a >= 1.0 {
other
} else if other.a <= 0.0 {
self
} else {
{
r: self.r * (1.0 - other.a) + other.r * other.a,
g: self.g * (1.0 - other.a) + other.g * other.a,
b: self.b * (1.0 - other.a) + other.b * other.a,
a: self.a,
}
}
}
///|
/// Replaces the alpha channel (clamped to `0.0..=1.0`).
pub fn Rgba::alpha(self : Rgba, a : Double) -> Rgba {
{ ..self, a: clamp01(a), }
}
///|
/// Multiplies the alpha channel by `factor` (clamped to `0.0..=1.0`).
pub fn Rgba::opacity(self : Rgba, factor : Double) -> Rgba {
{ ..self, a: self.a * clamp01(factor), }
}
///|
fn hex_byte(value : Double) -> String {
let byte = (value * 255.0).round().to_int()
let byte = if byte < 0 { 0 } else if byte > 255 { 255 } else { byte }
let digits = "0123456789abcdef"
let hi = digits.exact_view(start=byte / 16, end=byte / 16 + 1)
let lo = digits.exact_view(start=byte % 16, end=byte % 16 + 1)
"\{hi}\{lo}"
}
///|
/// Formats as `#rrggbbaa` (GPUI's serde representation), rounding channels.
pub fn Rgba::to_hex(self : Rgba) -> String {
"#\{hex_byte(self.r)}\{hex_byte(self.g)}\{hex_byte(self.b)}\{hex_byte(self.a)}"
}
///|
pub impl Show for Rgba with fn output(self, logger) {
logger.write_string(self.to_hex())
}
///|
#derive(Debug)
pub suberror ColorParseError {
ColorParseError(input~ : String, reason~ : String)
}
///|
fn hex_digit(input : String, c : Char) -> UInt32 raise ColorParseError {
match c {
'0'..<='9' => (c.to_int() - '0'.to_int()).reinterpret_as_uint()
'a'..<='f' => (c.to_int() - 'a'.to_int() + 10).reinterpret_as_uint()
'A'..<='F' => (c.to_int() - 'A'.to_int() + 10).reinterpret_as_uint()
_ => raise ColorParseError(input~, reason="invalid hex digit '\{c}'")
}
}
///|
/// Parses `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa` (surrounding whitespace
/// allowed). Mirrors GPUI's `TryFrom<&str> for Rgba`.
pub fn Rgba::parse(input : String) -> Rgba raise ColorParseError {
let expected = "Expected #rgb, #rgba, #rrggbb, or #rrggbbaa"
let trimmed = input.trim()
guard trimmed.strip_prefix("#") is Some(hex) else {
raise ColorParseError(input~, reason=expected)
}
let digits : Array[UInt32] = []
for c in hex {
digits.push(hex_digit(input, c))
}
let (r, g, b, a) = match digits.length() {
3 | 4 => {
let dup = fn(v : UInt32) -> UInt32 { (v << 4) | v }
let a = if digits.length() == 4 { dup(digits[3]) } else { 0xff }
(dup(digits[0]), dup(digits[1]), dup(digits[2]), a)
}
6 | 8 => {
let pair = fn(i : Int32) -> UInt32 { (digits[i] << 4) | digits[i + 1] }
let a = if digits.length() == 8 { pair(6) } else { 0xff }
(pair(0), pair(2), pair(4), a)
}
_ => raise ColorParseError(input~, reason=expected)
}
rgba((r << 24) | (g << 16) | (b << 8) | a)
}
///|
/// Converts to the HSL representation.
pub fn Rgba::to_hsla(self : Rgba) -> Hsla {
let r = self.r
let g = self.g
let b = self.b
let max = @cmp.maximum(r, @cmp.maximum(g, b))
let min = @cmp.minimum(r, @cmp.minimum(g, b))
let delta = max - min
let l = (max + min) / 2.0
let s = if l == 0.0 || l == 1.0 {
0.0
} else if l < 0.5 {
delta / (2.0 * l)
} else {
delta / (2.0 - 2.0 * l)
}
let h = if delta == 0.0 {
0.0
} else if max == r {
rem_euclid((g - b) / delta, 6.0) / 6.0
} else if max == g {
((b - r) / delta + 2.0) / 6.0
} else {
((r - g) / delta + 4.0) / 6.0
}
{ h, s, l, a: self.a, }
}
///|
fn rem_euclid(value : Double, modulus : Double) -> Double {
let r = value % modulus
if r < 0.0 {
r + modulus.abs()
} else {
r
}
}
///|
/// Converts to RGB.
pub fn Hsla::to_rgb(self : Hsla) -> Rgba {
let h = self.h
let s = self.s
let l = self.l
let c = (1.0 - (2.0 * l - 1.0).abs()) * s
let x = c * (1.0 - (h * 6.0 % 2.0 - 1.0).abs())
let m = l - c / 2.0
let cm = c + m
let xm = x + m
let (r, g, b) = match (h * 6.0).floor().to_int() {
0 | 6 => (cm, xm, m)
1 => (xm, cm, m)
2 => (m, cm, xm)
3 => (m, xm, cm)
4 => (xm, m, cm)
_ => (cm, m, xm)
}
{ r: clamp01(r), g: clamp01(g), b: clamp01(b), a: self.a, }
}
///|
/// Creates a color, clamping each channel to `0.0..=1.0`.
pub fn hsla(h : Double, s : Double, l : Double, a : Double) -> Hsla {
{ h: clamp01(h), s: clamp01(s), l: clamp01(l), a: clamp01(a), }
}
///|
pub fn black() -> Hsla {
{ h: 0.0, s: 0.0, l: 0.0, a: 1.0, }
}
///|
pub fn transparent_black() -> Hsla {
{ h: 0.0, s: 0.0, l: 0.0, a: 0.0, }
}
///|
pub fn transparent_white() -> Hsla {
{ h: 0.0, s: 0.0, l: 1.0, a: 0.0, }
}
///|
pub fn opaque_grey(lightness : Double, opacity : Double) -> Hsla {
{ h: 0.0, s: 0.0, l: clamp01(lightness), a: clamp01(opacity), }
}
///|
pub fn white() -> Hsla {
{ h: 0.0, s: 0.0, l: 1.0, a: 1.0, }
}
///|
pub fn red() -> Hsla {
{ h: 0.0, s: 1.0, l: 0.5, a: 1.0, }
}
///|
pub fn blue() -> Hsla {
{ h: 0.6666666667, s: 1.0, l: 0.5, a: 1.0, }
}
///|
pub fn green() -> Hsla {
{ h: 0.3333333333, s: 1.0, l: 0.25, a: 1.0, }
}
///|
pub fn yellow() -> Hsla {
{ h: 0.1666666667, s: 1.0, l: 0.5, a: 1.0, }
}
///|
pub fn Hsla::is_transparent(self : Hsla) -> Bool {
self.a == 0.0
}
///|
pub fn Hsla::is_opaque(self : Hsla) -> Bool {
self.a == 1.0
}
///|
/// Blends `other` over `self` in RGB space.
pub fn Hsla::blend(self : Hsla, other : Hsla) -> Hsla {
if other.a >= 1.0 {
other
} else if other.a <= 0.0 {
self
} else {
self.to_rgb().blend(other.to_rgb()).to_hsla()
}
}
///|
pub fn Hsla::grayscale(self : Hsla) -> Hsla {
{ ..self, s: 0.0, }
}
///|
/// Reduces alpha by `factor` (`0.0` keeps the color, `1.0` makes it fully
/// transparent). Returns a new color; GPUI mutates in place.
pub fn Hsla::fade_out(self : Hsla, factor : Double) -> Hsla {
{ ..self, a: self.a * (1.0 - clamp01(factor)), }
}
///|
/// Multiplies alpha by `factor` (clamped to `0.0..=1.0`).
pub fn Hsla::opacity(self : Hsla, factor : Double) -> Hsla {
{ ..self, a: self.a * clamp01(factor), }
}
///|
/// Replaces alpha (clamped to `0.0..=1.0`).
pub fn Hsla::alpha(self : Hsla, a : Double) -> Hsla {
{ ..self, a: clamp01(a), }
}
///|
/// `hsla(h°, s%, l%, a)`, matching GPUI's `Display for Hsla`.
pub impl Show for Hsla with fn output(self, logger) {
let fmt2 = fn(v : Double) -> String {
let scaled = (v * 100.0).round() / 100.0
scaled.to_string()
}
logger.write_string(
"hsla(\{fmt2(self.h * 360.0)}, \{fmt2(self.s * 100.0)}%, \{fmt2(self.l * 100.0)}%, \{fmt2(self.a)})",
)
}
// ---------------------------------------------------------------------------
// Backgrounds
// ---------------------------------------------------------------------------
///|
/// Which kind of fill a `Background` describes.
#derive(Eq, Debug)
pub(all) enum BackgroundTag {
Solid
LinearGradient
PatternSlash
Checkerboard
}
///|
/// The color space gradients are interpolated in.
#derive(Eq, Debug)
pub(all) enum ColorSpace {
Srgb
Oklab
}
///|
pub impl Default for BackgroundTag with fn default() {
Solid
}
///|
pub impl Default for ColorSpace with fn default() {
Srgb
}
///|
pub impl Show for ColorSpace with fn output(self, logger) {
match self {
Srgb => logger.write_string("sRGB")
Oklab => logger.write_string("Oklab")
}
}
///|
/// A color stop of a linear gradient; `percentage` is in `0.0..=1.0`.
#derive(Eq, Default, Debug)
pub(all) struct LinearColorStop {
color : Hsla
percentage : Double
}
///|
pub fn linear_color_stop(color : Hsla, percentage : Double) -> LinearColorStop {
{ color, percentage, }
}
///|
pub fn LinearColorStop::opacity(
self : LinearColorStop,
factor : Double,
) -> LinearColorStop {
{ ..self, color: self.color.opacity(factor), }
}
///|
/// A fill: solid color, two-stop linear gradient, or pattern.
///
/// Mirrors GPUI's GPU-facing `#[repr(C)]` layout: the meaning of
/// `gradient_angle_or_pattern_height` and `colors` depends on `tag`.
#derive(Eq, Default, Debug)
pub(all) struct Background {
tag : BackgroundTag
color_space : ColorSpace
solid : Hsla
gradient_angle_or_pattern_height : Double
colors : (LinearColorStop, LinearColorStop)
}
///|
pub fn solid_background(color : Hsla) -> Background {
{ ..Default::default(), solid: color, }
}
///|
/// A linear gradient at `angle` degrees between two stops.
pub fn linear_gradient(
angle : Double,
from : LinearColorStop,
to : LinearColorStop,
) -> Background {
{
..Default::default(),
tag: LinearGradient,
gradient_angle_or_pattern_height: angle,
colors: (from, to),
}
}
///|
/// Diagonal stripes of `width` separated by `interval` (both in `0.0..=1.0`
/// of the pattern height, packed as GPUI's shader expects).
pub fn pattern_slash(
color : Hsla,
width : Double,
interval : Double,
) -> Background {
let width_scaled = (width * 255.0).to_int()
let interval_scaled = (interval * 255.0).to_int()
let height = (width_scaled * 0xFFFF + interval_scaled).to_double()
{
..Default::default(),
tag: PatternSlash,
solid: color,
gradient_angle_or_pattern_height: height,
}
}
///|
pub fn checkerboard(color : Hsla, size : Double) -> Background {
{
..Default::default(),
tag: Checkerboard,
solid: color,
gradient_angle_or_pattern_height: size,
}
}
///|
pub fn Hsla::to_background(self : Hsla) -> Background {
solid_background(self)
}
///|
pub fn Rgba::to_background(self : Rgba) -> Background {
solid_background(self.to_hsla())
}
///|
pub fn Background::as_solid(self : Background) -> Hsla? {
if self.tag == Solid {
Some(self.solid)
} else {
None
}
}
///|
pub fn Background::with_color_space(
self : Background,
color_space : ColorSpace,
) -> Background {
{ ..self, color_space, }
}
///|
pub fn Background::opacity(self : Background, factor : Double) -> Background {
{
..self,
solid: self.solid.opacity(factor),
colors: (self.colors.0.opacity(factor), self.colors.1.opacity(factor)),
}
}
///|
pub fn Background::is_transparent(self : Background) -> Bool {
match self.tag {
Solid | PatternSlash | Checkerboard => self.solid.is_transparent()
LinearGradient =>
self.colors.0.color.is_transparent() &&
self.colors.1.color.is_transparent()
}
}
+167
View File
@@ -0,0 +1,167 @@
///|
fn parse_ok(input : String) -> @color.Rgba {
@color.Rgba::parse(input) catch {
e => abort("unexpected parse failure for \{input}: \{@debug.to_string(e)}")
}
}
///|
fn parse_fails(input : String) -> Bool {
(Ok(@color.Rgba::parse(input)) catch { e => Err(e) }) is Err(_)
}
///|
fn close(a : Double, b : Double) -> Bool {
(a - b).abs() < 1.0e-6
}
///|
fn rgba_close(a : @color.Rgba, b : @color.Rgba) -> Bool {
close(a.r, b.r) && close(a.g, b.g) && close(a.b, b.b) && close(a.a, b.a)
}
///|
/// Ports of GPUI's `test_deserialize_*_hex_to_rgba` tests.
test "parse hex colors" {
let expected = @color.rgba(0xff0099ff)
assert_eq(parse_ok("#f09"), expected)
assert_eq(parse_ok("#f09f"), expected)
assert_eq(parse_ok("#ff0099"), expected)
assert_eq(parse_ok("#ff0099ff"), expected)
assert_eq(parse_ok(" #f5f5f5ff "), @color.rgba(0xf5f5f5ff))
assert_eq(parse_ok("#DeAdbEeF"), @color.rgba(0xdeadbeef))
assert_eq(parse_ok("#f098").a, 136.0 / 255.0)
}
///|
test "parse rejects malformed colors" {
assert_true(parse_fails("ff0099"))
assert_true(parse_fails("#ff009"))
assert_true(parse_fails("#gg0099"))
assert_true(parse_fails("#"))
assert_true(parse_fails("x#fff"))
}
///|
test "rgb and rgba constructors" {
let c = @color.rgb(0x336699)
assert_eq(c.a, 1.0)
assert_eq(c.r, 51.0 / 255.0)
assert_eq(c.to_u32(), 0x336699ff)
assert_eq(@color.rgba(0x12345678).to_u32(), 0x12345678)
assert_eq(@color.rgba(0x12345678).to_hex(), "#12345678")
inspect(@color.rgb(0xff0000), content="#ff0000ff")
}
///|
/// Port of GPUI's `test_rgba_alpha`.
test "rgba alpha clamps" {
let color : @color.Rgba = { r: 0.2, g: 0.6, b: 1.0, a: 0.8, }
assert_eq(color.alpha(0.25).a, 0.25)
assert_eq(color.alpha(1.5).a, 1.0)
}
///|
/// Port of GPUI's `test_rgba_opacity`.
test "rgba opacity clamps factor" {
let color : @color.Rgba = { r: 0.2, g: 0.6, b: 1.0, a: 0.8, }
assert_true(close(color.opacity(0.5).a, 0.4))
assert_eq(color.opacity(2.0).a, 0.8)
}
///|
test "rgba blend" {
let base = @color.rgb(0x000000)
let half_white : @color.Rgba = { r: 1.0, g: 1.0, b: 1.0, a: 0.5, }
let blended = base.blend(half_white)
assert_true(rgba_close(blended, { r: 0.5, g: 0.5, b: 0.5, a: 1.0, }))
assert_eq(base.blend(@color.rgb(0x123456)), @color.rgb(0x123456))
assert_eq(base.blend(@color.rgba(0x12345600)), base)
}
///|
test "hsla <-> rgba round trips" {
let colors = [
@color.rgb(0xff0000),
@color.rgb(0x00ff00),
@color.rgb(0x0000ff),
@color.rgb(0xffffff),
@color.rgb(0x000000),
@color.rgb(0x336699),
@color.rgb(0xdeadbe),
@color.rgba(0x80808080),
]
for c in colors {
assert_true(rgba_close(c.to_hsla().to_rgb(), c))
}
assert_true(rgba_close(@color.red().to_rgb(), @color.rgb(0xff0000)))
assert_true(rgba_close(@color.blue().to_rgb(), @color.rgb(0x0000ff)))
assert_true(rgba_close(@color.white().to_rgb(), @color.rgb(0xffffff)))
let h = @color.rgb(0x00ff00).to_hsla()
assert_true(close(h.h, 1.0 / 3.0))
assert_eq(h.s, 1.0)
assert_eq(h.l, 0.5)
}
///|
test "hsla helpers" {
assert_eq(@color.hsla(1.5, -1.0, 0.5, 2.0), {
h: 1.0,
s: 0.0,
l: 0.5,
a: 1.0,
})
let c = @color.hsla(0.5, 0.5, 0.5, 0.8)
assert_eq(c.opacity(0.5).a, 0.4)
assert_eq(c.alpha(0.1).a, 0.1)
assert_true(close(c.fade_out(0.25).a, 0.6))
assert_eq(c.grayscale().s, 0.0)
assert_true(@color.transparent_black().is_transparent())
assert_true(@color.black().is_opaque())
assert_eq(@color.black().blend(@color.white()), @color.white())
assert_eq(@color.black().blend(@color.transparent_white()), @color.black())
inspect(@color.red(), content="hsla(0, 100%, 50%, 1)")
// Hsla is totally ordered (GPUI derives Ord via total_cmp).
assert_true(@color.red() < @color.blue())
}
///|
/// Port of GPUI's `test_background_solid`.
test "background solid" {
let color = @color.rgba(0xff0099ff).to_hsla()
let background = color.to_background()
assert_eq(background.tag, Solid)
assert_eq(background.solid, color)
assert_eq(background.opacity(0.5).solid, color.opacity(0.5))
assert_false(background.is_transparent())
let cleared = { ..background, solid: @color.hsla(0.0, 0.0, 0.0, 0.0), }
assert_true(cleared.is_transparent())
assert_eq(background.as_solid(), Some(color))
}
///|
/// Port of GPUI's `test_background_linear_gradient`.
test "background linear gradient" {
let from = @color.linear_color_stop(@color.rgba(0xff0099ff).to_hsla(), 0.0)
let to = @color.linear_color_stop(@color.rgba(0x00ff99ff).to_hsla(), 1.0)
let background = @color.linear_gradient(90.0, from, to)
assert_eq(background.tag, LinearGradient)
assert_eq(background.colors.0, from)
assert_eq(background.colors.1, to)
assert_eq(background.opacity(0.5).colors.0, from.opacity(0.5))
assert_eq(background.opacity(0.5).colors.1, to.opacity(0.5))
assert_false(background.is_transparent())
assert_true(background.opacity(0.0).is_transparent())
assert_eq(background.as_solid(), None)
assert_eq(background.with_color_space(Oklab).color_space, Oklab)
}
///|
test "pattern backgrounds" {
let slash = @color.pattern_slash(@color.red(), 1.0, 0.0)
assert_eq(slash.tag, PatternSlash)
assert_eq(slash.gradient_angle_or_pattern_height, (255 * 0xFFFF).to_double())
let board = @color.checkerboard(@color.black(), 8.0)
assert_eq(board.tag, Checkerboard)
assert_eq(board.gradient_angle_or_pattern_height, 8.0)
}
+7
View File
@@ -0,0 +1,7 @@
import {
"moonbitlang/core/cmp",
}
import {
"moonbitlang/core/debug",
} for "test"
+124
View File
@@ -0,0 +1,124 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/color"
import {
"moonbitlang/core/debug",
}
// Values
pub fn black() -> Hsla
pub fn blue() -> Hsla
pub fn checkerboard(Hsla, Double) -> Background
pub fn green() -> Hsla
pub fn hsla(Double, Double, Double, Double) -> Hsla
pub fn linear_color_stop(Hsla, Double) -> LinearColorStop
pub fn linear_gradient(Double, LinearColorStop, LinearColorStop) -> Background
pub fn opaque_grey(Double, Double) -> Hsla
pub fn pattern_slash(Hsla, Double, Double) -> Background
pub fn red() -> Hsla
pub fn rgb(UInt32) -> Rgba
pub fn rgba(UInt32) -> Rgba
pub fn solid_background(Hsla) -> Background
pub fn transparent_black() -> Hsla
pub fn transparent_white() -> Hsla
pub fn white() -> Hsla
pub fn yellow() -> Hsla
// Errors
#derive(@debug.Debug)
pub suberror ColorParseError {
ColorParseError(input~ : String, reason~ : String)
}
// Types and methods
#derive(Default, Eq, @debug.Debug)
pub(all) struct Background {
tag : BackgroundTag
color_space : ColorSpace
solid : Hsla
gradient_angle_or_pattern_height : Double
colors : (LinearColorStop, LinearColorStop)
}
pub fn Background::as_solid(Self) -> Hsla?
pub fn Background::is_transparent(Self) -> Bool
pub fn Background::opacity(Self, Double) -> Self
pub fn Background::with_color_space(Self, ColorSpace) -> Self
#derive(Eq, @debug.Debug)
pub(all) enum BackgroundTag {
Solid
LinearGradient
PatternSlash
Checkerboard
}
pub impl Default for BackgroundTag
#derive(Eq, @debug.Debug)
pub(all) enum ColorSpace {
Srgb
Oklab
}
pub impl Default for ColorSpace
pub impl Show for ColorSpace
#derive(Compare, Default, Eq, @debug.Debug)
pub(all) struct Hsla {
h : Double
s : Double
l : Double
a : Double
}
pub fn Hsla::alpha(Self, Double) -> Self
pub fn Hsla::blend(Self, Self) -> Self
pub fn Hsla::fade_out(Self, Double) -> Self
pub fn Hsla::grayscale(Self) -> Self
pub fn Hsla::is_opaque(Self) -> Bool
pub fn Hsla::is_transparent(Self) -> Bool
pub fn Hsla::opacity(Self, Double) -> Self
pub fn Hsla::to_background(Self) -> Background
pub fn Hsla::to_rgb(Self) -> Rgba
pub impl Show for Hsla
#derive(Default, Eq, @debug.Debug)
pub(all) struct LinearColorStop {
color : Hsla
percentage : Double
}
pub fn LinearColorStop::opacity(Self, Double) -> Self
#derive(Default, Eq, @debug.Debug)
pub(all) struct Rgba {
r : Double
g : Double
b : Double
a : Double
}
pub fn Rgba::alpha(Self, Double) -> Self
pub fn Rgba::blend(Self, Self) -> Self
pub fn Rgba::opacity(Self, Double) -> Self
pub fn Rgba::parse(String) -> Self raise ColorParseError
pub fn Rgba::to_background(Self) -> Background
pub fn Rgba::to_hex(Self) -> String
pub fn Rgba::to_hsla(Self) -> Hsla
pub fn Rgba::to_u32(Self) -> UInt32
pub impl Show for Rgba
// Type aliases
// Traits
+503
View File
@@ -0,0 +1,503 @@
// Bounds, Anchor and ContentMask, ported from gpui/src/geometry.rs and
// gpui/src/window.rs (ContentMask).
///|
/// A rectangle given by its top-left origin and its size.
#derive(Eq, Hash, Default, Debug)
pub(all) struct Bounds[T] {
origin : Point[T]
size : Size[T]
}
///|
pub fn[T] bounds(origin : Point[T], size : Size[T]) -> Bounds[T] {
{ origin, size, }
}
///|
pub fn[T] Bounds::new(origin : Point[T], size : Size[T]) -> Bounds[T] {
{ origin, size, }
}
///|
pub fn[T : Sub] Bounds::from_corners(
top_left : Point[T],
bottom_right : Point[T],
) -> Bounds[T] {
{
origin: top_left,
size: {
width: bottom_right.x - top_left.x,
height: bottom_right.y - top_left.y,
},
}
}
///|
/// A position in a rectangle: one of its four corners or the middle of one of
/// its four sides.
#derive(Eq, Hash, Debug)
pub(all) enum Anchor {
TopLeft
TopRight
BottomLeft
BottomRight
TopCenter
BottomCenter
LeftCenter
RightCenter
}
///|
pub fn Anchor::opposite(self : Anchor) -> Anchor {
match self {
TopLeft => BottomRight
TopRight => BottomLeft
BottomLeft => TopRight
BottomRight => TopLeft
TopCenter => BottomCenter
BottomCenter => TopCenter
LeftCenter => RightCenter
RightCenter => LeftCenter
}
}
///|
/// The anchor on the other side along `axis`.
pub fn Anchor::other_side_along(self : Anchor, axis : Axis) -> Anchor {
match axis {
Vertical =>
match self {
TopLeft => BottomLeft
TopRight => BottomRight
BottomLeft => TopLeft
BottomRight => TopRight
TopCenter => BottomCenter
BottomCenter => TopCenter
LeftCenter => LeftCenter
RightCenter => RightCenter
}
Horizontal =>
match self {
TopLeft => TopRight
TopRight => TopLeft
BottomLeft => BottomRight
BottomRight => BottomLeft
TopCenter => TopCenter
BottomCenter => BottomCenter
LeftCenter => RightCenter
RightCenter => LeftCenter
}
}
}
///|
pub fn Anchor::is_center(self : Anchor) -> Bool {
self is (TopCenter | BottomCenter | LeftCenter | RightCenter)
}
///|
pub fn Anchor::is_bottom(self : Anchor) -> Bool {
self is (BottomCenter | BottomLeft | BottomRight)
}
///|
/// Creates bounds of `size` such that `anchor` of the result lies at `origin`.
pub fn[T : Sub + Half] Bounds::from_anchor_and_size(
anchor : Anchor,
origin : Point[T],
size : Size[T],
) -> Bounds[T] {
let origin : Point[T] = match anchor {
TopLeft => origin
TopRight => { x: origin.x - size.width, y: origin.y, }
BottomLeft => { x: origin.x, y: origin.y - size.height, }
BottomRight => { x: origin.x - size.width, y: origin.y - size.height, }
TopCenter => { x: origin.x - Half::half(size.width), y: origin.y, }
BottomCenter =>
{ x: origin.x - Half::half(size.width), y: origin.y - size.height, }
LeftCenter => { x: origin.x, y: origin.y - Half::half(size.height), }
RightCenter =>
{ x: origin.x - size.width, y: origin.y - Half::half(size.height), }
}
{ origin, size, }
}
///|
/// Creates bounds of `size` centered on `center`.
pub fn[T : Sub + Half] Bounds::centered_at(
center : Point[T],
size : Size[T],
) -> Bounds[T] {
{
origin: {
x: center.x - Half::half(size.width),
y: center.y - Half::half(size.height),
},
size,
}
}
///|
pub fn[T] Bounds::top(self : Bounds[T]) -> T {
self.origin.y
}
///|
pub fn[T : Add] Bounds::bottom(self : Bounds[T]) -> T {
self.origin.y + self.size.height
}
///|
pub fn[T] Bounds::left(self : Bounds[T]) -> T {
self.origin.x
}
///|
pub fn[T : Add] Bounds::right(self : Bounds[T]) -> T {
self.origin.x + self.size.width
}
///|
pub fn[T : Add] Bounds::top_right(self : Bounds[T]) -> Point[T] {
{ x: self.origin.x + self.size.width, y: self.origin.y, }
}
///|
pub fn[T : Add] Bounds::bottom_right(self : Bounds[T]) -> Point[T] {
{ x: self.origin.x + self.size.width, y: self.origin.y + self.size.height, }
}
///|
pub fn[T : Add] Bounds::bottom_left(self : Bounds[T]) -> Point[T] {
{ x: self.origin.x, y: self.origin.y + self.size.height, }
}
///|
pub fn[T : Add + Half] Bounds::top_center(self : Bounds[T]) -> Point[T] {
{ x: self.origin.x + Half::half(self.size.width), y: self.origin.y, }
}
///|
pub fn[T : Add + Half] Bounds::bottom_center(self : Bounds[T]) -> Point[T] {
{
x: self.origin.x + Half::half(self.size.width),
y: self.origin.y + self.size.height,
}
}
///|
pub fn[T : Add + Half] Bounds::left_center(self : Bounds[T]) -> Point[T] {
{ x: self.origin.x, y: self.origin.y + Half::half(self.size.height), }
}
///|
pub fn[T : Add + Half] Bounds::right_center(self : Bounds[T]) -> Point[T] {
{
x: self.origin.x + self.size.width,
y: self.origin.y + Half::half(self.size.height),
}
}
///|
pub fn[T : Add + Half] Bounds::center(self : Bounds[T]) -> Point[T] {
{
x: self.origin.x + Half::half(self.size.width),
y: self.origin.y + Half::half(self.size.height),
}
}
///|
/// The point of these bounds at the given anchor.
pub fn[T : Add + Half] Bounds::corner(
self : Bounds[T],
anchor : Anchor,
) -> Point[T] {
match anchor {
TopLeft => self.origin
TopRight => self.top_right()
BottomLeft => self.bottom_left()
BottomRight => self.bottom_right()
TopCenter => self.top_center()
BottomCenter => self.bottom_center()
LeftCenter => self.left_center()
RightCenter => self.right_center()
}
}
///|
/// Width plus height; used as the insertion cost heuristic in the scene's
/// bounds tree.
pub fn[T : Add] Bounds::half_perimeter(self : Bounds[T]) -> T {
self.size.width + self.size.height
}
///|
/// Whether the two rectangles overlap (touching edges do not count).
pub fn[T : Add + Compare] Bounds::intersects(
self : Bounds[T],
other : Bounds[T],
) -> Bool {
let my_lower_right = self.bottom_right()
let their_lower_right = other.bottom_right()
self.origin.x < their_lower_right.x &&
my_lower_right.x > other.origin.x &&
self.origin.y < their_lower_right.y &&
my_lower_right.y > other.origin.y
}
///|
/// The overlapping region. If the rectangles do not overlap the result is
/// empty (zero or negative size clamped to zero).
pub fn[T : Add + Sub + Compare] Bounds::intersect(
self : Bounds[T],
other : Bounds[T],
) -> Bounds[T] {
let upper_left = self.origin.max(other.origin)
let bottom_right = self
.bottom_right()
.min(other.bottom_right())
.max(upper_left)
Bounds::from_corners(upper_left, bottom_right)
}
///|
/// The smallest rectangle containing both.
pub fn[T : Add + Sub + Compare] Bounds::union(
self : Bounds[T],
other : Bounds[T],
) -> Bounds[T] {
let top_left = self.origin.min(other.origin)
let bottom_right = self.bottom_right().max(other.bottom_right())
Bounds::from_corners(top_left, bottom_right)
}
///|
/// Like `union`, but empty bounds are ignored.
pub fn[T : Add + Sub + Compare + Default] Bounds::join(
self : Bounds[T],
other : Bounds[T],
) -> Bounds[T] {
if self.is_empty() {
other
} else if other.is_empty() {
self
} else {
self.union(other)
}
}
///|
/// Whether the width or height is not positive.
pub fn[T : Compare + Default] Bounds::is_empty(self : Bounds[T]) -> Bool {
let zero : T = Default::default()
self.size.width <= zero || self.size.height <= zero
}
///|
/// Whether `point` is inside (left/top edges inclusive, right/bottom
/// exclusive).
pub fn[T : Add + Compare] Bounds::contains(
self : Bounds[T],
point : Point[T],
) -> Bool {
point.x >= self.origin.x &&
point.x < self.origin.x + self.size.width &&
point.y >= self.origin.y &&
point.y < self.origin.y + self.size.height
}
///|
pub fn[T : Add + Compare] Bounds::is_contained_within(
self : Bounds[T],
other : Bounds[T],
) -> Bool {
other.contains(self.origin) && other.contains(self.bottom_right())
}
///|
/// `point` relative to the origin, or `None` if it lies outside.
pub fn[T : Add + Sub + Compare] Bounds::localize(
self : Bounds[T],
point : Point[T],
) -> Point[T]? {
if self.contains(point) {
Some(point.relative_to(self.origin))
} else {
None
}
}
///|
/// Grows the bounds by `amount` on every side.
pub fn[T : Add + Sub] Bounds::dilate(self : Bounds[T], amount : T) -> Bounds[T] {
let double = amount + amount
{
origin: { x: self.origin.x - amount, y: self.origin.y - amount, },
size: {
width: self.size.width + double,
height: self.size.height + double,
},
}
}
///|
/// Shrinks the bounds by `amount` on every side.
pub fn[T : Add + Sub + Neg] Bounds::inset(
self : Bounds[T],
amount : T,
) -> Bounds[T] {
self.dilate(-amount)
}
///|
/// Grows each side by the corresponding edge amount.
pub fn[T : Add + Sub] Bounds::extend_by(
self : Bounds[T],
amount : Edges[T],
) -> Bounds[T] {
{
origin: { x: self.origin.x - amount.left, y: self.origin.y - amount.top, },
size: {
width: self.size.width + amount.left + amount.right,
height: self.size.height + amount.top + amount.bottom,
},
}
}
///|
/// The space between these bounds and the enclosing `outer` bounds.
pub fn[T : Add + Sub] Bounds::space_within(
self : Bounds[T],
outer : Bounds[T],
) -> Edges[T] {
{
top: self.top() - outer.top(),
right: outer.right() - self.right(),
bottom: outer.bottom() - self.bottom(),
left: self.left() - outer.left(),
}
}
///|
pub fn[T, U] Bounds::map(self : Bounds[T], f : (T) -> U) -> Bounds[U] {
{ origin: self.origin.map(f), size: self.size.map(f), }
}
///|
pub fn[T] Bounds::map_origin(self : Bounds[T], f : (T) -> T) -> Bounds[T] {
{ origin: self.origin.map(f), size: self.size, }
}
///|
pub fn[T] Bounds::map_size(self : Bounds[T], f : (T) -> T) -> Bounds[T] {
{ origin: self.origin, size: self.size.map(f), }
}
///|
/// Translates the bounds by `offset`.
pub fn[T : Add] Bounds::translate(
self : Bounds[T],
offset : Point[T],
) -> Bounds[T] {
{ origin: self.origin + offset, size: self.size, }
}
///|
pub fn[T : MulScalar] Bounds::mul_scalar(
self : Bounds[T],
factor : Double,
) -> Bounds[T] {
{
origin: self.origin.mul_scalar(factor),
size: self.size.mul_scalar(factor),
}
}
///|
pub impl[T : IsZero] IsZero for Bounds[T] with fn is_zero(self) {
IsZero::is_zero(self.size)
}
///|
pub impl[T : Show + Add] Show for Bounds[T] with fn output(self, logger) {
logger.write_string("Bounds { ")
Show::output(self.origin, logger)
logger.write_string(" - ")
Show::output(self.bottom_right(), logger)
logger.write_string(" }")
}
///|
/// Rounds half away from zero, like Rust's `f32::round`, on every backend.
fn round_half_away(value : Double) -> Double {
if value >= 0.0 {
(value + 0.5).floor()
} else {
-(-value + 0.5).floor()
}
}
///|
pub fn Bounds::scale(
self : Bounds[Pixels],
factor : Double,
) -> Bounds[ScaledPixels] {
{ origin: self.origin.scale(factor), size: self.size.scale(factor), }
}
///|
pub fn Bounds::to_device_pixels(
self : Bounds[Pixels],
factor : Double,
) -> Bounds[DevicePixels] {
{
origin: {
x: DevicePixels(round_half_away(self.origin.x.0 * factor).to_int()),
y: DevicePixels(round_half_away(self.origin.y.0 * factor).to_int()),
},
size: self.size.to_device_pixels(factor),
}
}
///|
pub fn Bounds::to_pixels(
self : Bounds[DevicePixels],
scale_factor : Double,
) -> Bounds[Pixels] {
{
origin: {
x: Pixels(self.origin.x.0.to_double() / scale_factor),
y: Pixels(self.origin.y.0.to_double() / scale_factor),
},
size: self.size.to_pixels(scale_factor),
}
}
// ---------------------------------------------------------------------------
// ContentMask
// ---------------------------------------------------------------------------
///|
/// The region that painting is clipped to.
#derive(Eq, Hash, Default, Debug)
pub(all) struct ContentMask[T] {
bounds : Bounds[T]
}
///|
pub fn ContentMask::scale(
self : ContentMask[Pixels],
factor : Double,
) -> ContentMask[ScaledPixels] {
{ bounds: self.bounds.scale(factor), }
}
///|
/// The intersection of two content masks.
pub fn[T : Add + Sub + Compare] ContentMask::intersect(
self : ContentMask[T],
other : ContentMask[T],
) -> ContentMask[T] {
{ bounds: self.bounds.intersect(other.bounds), }
}
+281
View File
@@ -0,0 +1,281 @@
// Edges and Corners, ported from gpui/src/geometry.rs.
///|
/// Per-side values (padding, margins, border widths, ...).
#derive(Eq, Hash, Default, Debug)
pub(all) struct Edges[T] {
top : T
right : T
bottom : T
left : T
}
///|
pub fn[T] Edges::all(value : T) -> Edges[T] {
{ top: value, right: value, bottom: value, left: value, }
}
///|
pub fn[T] Edges::new(top~ : T, right~ : T, bottom~ : T, left~ : T) -> Edges[T] {
{ top, right, bottom, left, }
}
///|
pub fn[T, U] Edges::map(self : Edges[T], f : (T) -> U) -> Edges[U] {
{
top: f(self.top),
right: f(self.right),
bottom: f(self.bottom),
left: f(self.left),
}
}
///|
pub fn[T] Edges::any(self : Edges[T], predicate : (T) -> Bool) -> Bool {
predicate(self.top) ||
predicate(self.right) ||
predicate(self.bottom) ||
predicate(self.left)
}
///|
/// The start and end edge along `axis` (left/right for horizontal, top/bottom
/// for vertical).
pub fn[T] Edges::along(self : Edges[T], axis : Axis) -> (T, T) {
match axis {
Horizontal => (self.left, self.right)
Vertical => (self.top, self.bottom)
}
}
///|
pub fn[T] Edges::apply_along(
self : Edges[T],
axis : Axis,
f : ((T, T)) -> (T, T),
) -> Edges[T] {
match axis {
Horizontal => {
let (left, right) = f((self.left, self.right))
{ top: self.top, right, bottom: self.bottom, left, }
}
Vertical => {
let (top, bottom) = f((self.top, self.bottom))
{ top, right: self.right, bottom, left: self.left, }
}
}
}
///|
pub fn[T : MulScalar] Edges::mul_scalar(
self : Edges[T],
factor : Double,
) -> Edges[T] {
self.map(fn(v) { v.mul_scalar(factor) })
}
///|
pub impl[T : Add] Add for Edges[T] with fn add(self, other) {
{
top: self.top + other.top,
right: self.right + other.right,
bottom: self.bottom + other.bottom,
left: self.left + other.left,
}
}
///|
/// Component-wise product.
pub impl[T : Mul] Mul for Edges[T] with fn mul(self, other) {
{
top: self.top * other.top,
right: self.right * other.right,
bottom: self.bottom * other.bottom,
left: self.left * other.left,
}
}
///|
pub impl[T : IsZero] IsZero for Edges[T] with fn is_zero(self) {
self.top.is_zero() &&
self.right.is_zero() &&
self.bottom.is_zero() &&
self.left.is_zero()
}
///|
pub fn Edges::auto() -> Edges[Length] {
Edges::all(Auto)
}
///|
pub fn Edges::zero_length() -> Edges[Length] {
Edges::all(pixels_zero.to_length())
}
///|
pub fn Edges::zero_definite() -> Edges[DefiniteLength] {
Edges::all(pixels_zero.to_definite())
}
///|
pub fn Edges::zero_absolute() -> Edges[AbsoluteLength] {
Edges::all(pixels_zero.to_absolute())
}
///|
/// Resolves relative lengths against `parent_size` (horizontal edges against
/// the width, vertical edges against the height, as in CSS/GPUI).
pub fn Edges::definite_to_pixels(
self : Edges[DefiniteLength],
parent_size : Size[AbsoluteLength],
rem_size : Pixels,
) -> Edges[Pixels] {
{
top: self.top.to_pixels(parent_size.height, rem_size),
right: self.right.to_pixels(parent_size.width, rem_size),
bottom: self.bottom.to_pixels(parent_size.height, rem_size),
left: self.left.to_pixels(parent_size.width, rem_size),
}
}
///|
pub fn Edges::absolute_to_pixels(
self : Edges[AbsoluteLength],
rem_size : Pixels,
) -> Edges[Pixels] {
self.map(fn(v) { v.to_pixels(rem_size) })
}
///|
pub fn Edges::scale(
self : Edges[Pixels],
factor : Double,
) -> Edges[ScaledPixels] {
self.map(fn(v) { v.scale(factor) })
}
///|
/// The largest edge.
pub fn Edges::max(self : Edges[Pixels]) -> Pixels {
max_of(max_of(self.top, self.right), max_of(self.bottom, self.left))
}
// ---------------------------------------------------------------------------
// Corners
// ---------------------------------------------------------------------------
///|
/// Per-corner values (corner radii).
#derive(Eq, Hash, Default, Debug)
pub(all) struct Corners[T] {
top_left : T
top_right : T
bottom_right : T
bottom_left : T
}
///|
pub fn[T] Corners::all(value : T) -> Corners[T] {
{
top_left: value,
top_right: value,
bottom_right: value,
bottom_left: value,
}
}
///|
pub fn[T] Corners::new(
top_left~ : T,
top_right~ : T,
bottom_right~ : T,
bottom_left~ : T,
) -> Corners[T] {
{ top_left, top_right, bottom_right, bottom_left, }
}
///|
/// The value for the given corner. Fails loudly for side-center anchors, which
/// have no corner value.
pub fn[T] Corners::corner(self : Corners[T], anchor : Anchor) -> T {
match anchor {
TopLeft => self.top_left
TopRight => self.top_right
BottomLeft => self.bottom_left
BottomRight => self.bottom_right
_ => abort("Corners::corner: \{@debug.to_string(anchor)} is not a corner")
}
}
///|
pub fn[T, U] Corners::map(self : Corners[T], f : (T) -> U) -> Corners[U] {
{
top_left: f(self.top_left),
top_right: f(self.top_right),
bottom_right: f(self.bottom_right),
bottom_left: f(self.bottom_left),
}
}
///|
pub fn[T : MulScalar] Corners::mul_scalar(
self : Corners[T],
factor : Double,
) -> Corners[T] {
self.map(fn(v) { v.mul_scalar(factor) })
}
///|
/// Clamps each radius to at most half of the quad's shorter side.
pub fn[T : Compare + Half] Corners::clamp_radii_for_quad_size(
self : Corners[T],
size : Size[T],
) -> Corners[T] {
let max = Half::half(min_of(size.width, size.height))
self.map(fn(radius) { min_of(radius, max) })
}
///|
/// Component-wise product.
pub impl[T : Mul] Mul for Corners[T] with fn mul(self, other) {
{
top_left: self.top_left * other.top_left,
top_right: self.top_right * other.top_right,
bottom_right: self.bottom_right * other.bottom_right,
bottom_left: self.bottom_left * other.bottom_left,
}
}
///|
pub impl[T : IsZero] IsZero for Corners[T] with fn is_zero(self) {
self.top_left.is_zero() &&
self.top_right.is_zero() &&
self.bottom_right.is_zero() &&
self.bottom_left.is_zero()
}
///|
pub fn Corners::absolute_to_pixels(
self : Corners[AbsoluteLength],
rem_size : Pixels,
) -> Corners[Pixels] {
self.map(fn(v) { v.to_pixels(rem_size) })
}
///|
pub fn Corners::scale(
self : Corners[Pixels],
factor : Double,
) -> Corners[ScaledPixels] {
self.map(fn(v) { v.scale(factor) })
}
///|
/// The largest radius.
pub fn Corners::max(self : Corners[Pixels]) -> Pixels {
max_of(
max_of(self.top_left, self.top_right),
max_of(self.bottom_right, self.bottom_left),
)
}
+43
View File
@@ -0,0 +1,43 @@
// Trait-method promotions so `px(1.0).half()` etc. work as methods.
///|
pub extend Pixels with Half::{half}
///|
pub extend Pixels with IsZero::{is_zero}
///|
pub extend Pixels with MulScalar::{mul_scalar}
///|
pub extend ScaledPixels with Half::{half}
///|
pub extend ScaledPixels with IsZero::{is_zero}
///|
pub extend ScaledPixels with MulScalar::{mul_scalar}
///|
pub extend DevicePixels with Half::{half}
///|
pub extend DevicePixels with IsZero::{is_zero}
///|
pub extend Rems with Half::{half}
///|
pub extend Rems with IsZero::{is_zero}
///|
pub extend Rems with MulScalar::{mul_scalar}
///|
pub extend AbsoluteLength with IsZero::{is_zero}
///|
pub extend DefiniteLength with IsZero::{is_zero}
///|
pub extend Length with IsZero::{is_zero}
+358
View File
@@ -0,0 +1,358 @@
///|
fn b(
x : Double,
y : Double,
w : Double,
h : Double,
) -> @geometry.Bounds[Double] {
{ origin: { x, y, }, size: { width: w, height: h, }, }
}
///|
/// Port of GPUI's `test_pixels_to_i32`: truncation, saturation, NaN -> 0.
test "pixels to int truncates and saturates" {
let cases : Array[(Double, Int32)] = [
(12.9, 12),
(-12.9, -12),
(3.4028234663852886e38, 2147483647),
(-3.4028234663852886e38, -2147483648),
(@double.infinity, 2147483647),
(@double.neg_infinity, -2147483648),
(@double.not_a_number, 0),
]
for case in cases {
let (value, expected) = case
assert_eq(@geometry.px(value).to_int(), expected)
}
}
///|
/// Port of GPUI's `test_bounds_join`.
test "bounds join ignores empty bounds" {
let bounds = b(5.0, 5.0, 5.0, 5.0)
let other = b(20.0, 0.0, 5.0, 5.0)
assert_eq(bounds.join(other), bounds.union(other))
let empty = b(0.0, 0.0, 0.0, 10.0)
assert_eq(bounds.join(empty), bounds)
assert_eq(empty.join(bounds), bounds)
let default_bounds : @geometry.Bounds[Double] = Default::default()
assert_eq(default_bounds.join(bounds), bounds)
assert_not_eq(bounds.union(empty), bounds)
}
///|
/// Port of GPUI's `test_bounds_intersects`.
test "bounds intersects" {
let bounds1 = b(0.0, 0.0, 5.0, 5.0)
let bounds2 = b(4.0, 4.0, 5.0, 5.0)
let bounds3 = b(10.0, 10.0, 5.0, 5.0)
assert_true(bounds1.intersects(bounds2))
assert_false(bounds1.intersects(bounds3))
assert_true(bounds1.intersects(bounds1))
// Touching edges do not intersect.
assert_false(b(0.0, 0.0, 5.0, 5.0).intersects(b(5.0, 0.0, 5.0, 5.0)))
}
///|
test "bounds intersect and union" {
let a = b(0.0, 0.0, 10.0, 10.0)
let c = b(5.0, 5.0, 10.0, 10.0)
assert_eq(a.intersect(c), b(5.0, 5.0, 5.0, 5.0))
assert_eq(a.union(c), b(0.0, 0.0, 15.0, 15.0))
// Disjoint bounds intersect to an empty rectangle anchored at the max origin.
let far = b(20.0, 20.0, 1.0, 1.0)
let none = a.intersect(far)
assert_true(none.is_empty())
assert_eq(none, b(20.0, 20.0, 0.0, 0.0))
}
///|
test "bounds contains is half-open" {
let a = b(0.0, 0.0, 10.0, 10.0)
assert_true(a.contains({ x: 0.0, y: 0.0, }))
assert_true(a.contains({ x: 9.999, y: 5.0, }))
assert_false(a.contains({ x: 10.0, y: 5.0, }))
assert_false(a.contains({ x: 5.0, y: -0.1, }))
assert_eq(a.localize({ x: 3.0, y: 4.0, }), Some({ x: 3.0, y: 4.0, }))
assert_eq(
b(10.0, 10.0, 5.0, 5.0).localize({ x: 12.0, y: 11.0, }),
Some({ x: 2.0, y: 1.0, }),
)
assert_eq(a.localize({ x: 30.0, y: 4.0, }), None)
assert_true(b(1.0, 1.0, 2.0, 2.0).is_contained_within(a))
}
///|
test "bounds corners and centers" {
let a = b(10.0, 20.0, 30.0, 40.0)
assert_eq(a.top(), 20.0)
assert_eq(a.bottom(), 60.0)
assert_eq(a.left(), 10.0)
assert_eq(a.right(), 40.0)
assert_eq(a.center(), { x: 25.0, y: 40.0, })
assert_eq(a.corner(TopRight), { x: 40.0, y: 20.0, })
assert_eq(a.corner(BottomLeft), { x: 10.0, y: 60.0, })
assert_eq(a.corner(BottomCenter), { x: 25.0, y: 60.0, })
assert_eq(a.corner(LeftCenter), { x: 10.0, y: 40.0, })
assert_eq(a.half_perimeter(), 70.0)
}
///|
test "bounds from anchor and size" {
let size : @geometry.Size[Double] = { width: 10.0, height: 4.0, }
let origin : @geometry.Point[Double] = { x: 100.0, y: 100.0, }
for
anchor in [
@geometry.Anchor::TopLeft,
TopRight,
BottomLeft,
BottomRight,
TopCenter,
BottomCenter,
LeftCenter,
RightCenter,
] {
let placed = @geometry.Bounds::from_anchor_and_size(anchor, origin, size)
assert_eq(placed.size, size)
// The requested anchor of the result is at `origin`.
assert_eq(placed.corner(anchor), origin)
}
assert_eq(
@geometry.Bounds::centered_at(origin, size),
b(95.0, 98.0, 10.0, 4.0),
)
}
///|
test "anchor opposite and other side" {
for
anchor in [
@geometry.Anchor::TopLeft,
TopRight,
BottomLeft,
BottomRight,
TopCenter,
BottomCenter,
LeftCenter,
RightCenter,
] {
assert_eq(anchor.opposite().opposite(), anchor)
assert_eq(
anchor.other_side_along(Horizontal).other_side_along(Horizontal),
anchor,
)
assert_eq(
anchor.other_side_along(Vertical).other_side_along(Vertical),
anchor,
)
}
assert_eq(@geometry.Anchor::TopLeft.other_side_along(Vertical), BottomLeft)
assert_eq(@geometry.Anchor::LeftCenter.other_side_along(Vertical), LeftCenter)
assert_true(@geometry.Anchor::BottomRight.is_bottom())
assert_false(@geometry.Anchor::TopCenter.is_bottom())
assert_true(@geometry.Anchor::TopCenter.is_center())
}
///|
test "dilate inset extend space_within" {
let a = b(10.0, 10.0, 10.0, 10.0)
assert_eq(a.dilate(2.0), b(8.0, 8.0, 14.0, 14.0))
assert_eq(a.inset(2.0), b(12.0, 12.0, 6.0, 6.0))
let edges = @geometry.Edges::new(top=1.0, right=2.0, bottom=3.0, left=4.0)
assert_eq(a.extend_by(edges), b(6.0, 9.0, 16.0, 14.0))
let outer = b(0.0, 0.0, 30.0, 30.0)
assert_eq(
a.space_within(outer),
@geometry.Edges::new(top=10.0, right=10.0, bottom=10.0, left=10.0),
)
}
///|
test "point helpers" {
let p : @geometry.Point[Double] = { x: 3.0, y: 7.0, }
let q : @geometry.Point[Double] = { x: 5.0, y: 1.0, }
assert_eq(p.max(q), { x: 5.0, y: 7.0, })
assert_eq(p.min(q), { x: 3.0, y: 1.0, })
assert_eq(p + q, { x: 8.0, y: 8.0, })
assert_eq(p - q, { x: -2.0, y: 6.0, })
assert_eq(-p, { x: -3.0, y: -7.0, })
assert_eq(p.along(Horizontal), 3.0)
assert_eq(p.apply_along(Vertical, fn(y) { y * 2.0 }), { x: 3.0, y: 14.0, })
assert_eq(
@geometry.point(10.0, -10.0).clamp(
@geometry.point(0.0, 0.0),
@geometry.point(5.0, 5.0),
),
@geometry.point(5.0, 0.0),
)
assert_eq(
@geometry.point(@geometry.px(3.0), @geometry.px(4.0)).magnitude(),
5.0,
)
}
///|
test "size helpers" {
let s : @geometry.Size[Double] = { width: 4.0, height: 6.0, }
assert_eq(s.center(), { x: 2.0, y: 3.0, })
assert_eq(s.along(Vertical), 6.0)
assert_eq(s.max({ width: 5.0, height: 1.0, }), { width: 5.0, height: 6.0, })
assert_eq(s.min({ width: 5.0, height: 1.0, }), { width: 4.0, height: 1.0, })
assert_eq(s.mul_scalar(0.5), { width: 2.0, height: 3.0, })
assert_true(
@geometry.IsZero::is_zero(
({ width: 0.0, height: 0.0, } : @geometry.Size[Double]),
),
)
assert_false(
@geometry.IsZero::is_zero(
({ width: 0.0, height: 1.0, } : @geometry.Size[Double]),
),
)
}
///|
test "pixels arithmetic and display" {
let a = @geometry.px(10.0)
let c = @geometry.px(4.0)
assert_eq(a + c, @geometry.px(14.0))
assert_eq(a - c, @geometry.px(6.0))
assert_eq(-a, @geometry.px(-10.0))
assert_eq(a.mul_scalar(1.5), @geometry.px(15.0))
assert_eq(a.ratio(c), 2.5)
assert_eq(a.half(), @geometry.px(5.0))
assert_true(a > c)
assert_eq(@geometry.Pixels::sum([a, c, c]), @geometry.px(18.0))
inspect(a, content="10px")
inspect(@geometry.rems(1.5), content="1.5rem")
// Rust's `round` rounds half away from zero on every backend.
assert_eq(@geometry.px(2.5).round(), @geometry.px(3.0))
assert_eq(@geometry.px(-2.5).round(), @geometry.px(-3.0))
assert_eq(@geometry.px(-0.4).floor(), @geometry.px(-1.0))
assert_eq(@geometry.px(-0.4).ceil().to_double(), 0.0)
assert_eq(@geometry.px(-3.0).signum(), -1.0)
}
///|
test "device pixel conversions" {
let logical : @geometry.Bounds[@geometry.Pixels] = {
origin: { x: @geometry.px(1.25), y: @geometry.px(2.0), },
size: { width: @geometry.px(10.25), height: @geometry.px(3.0), },
}
let device = logical.to_device_pixels(2.0)
assert_eq(device.origin, {
x: @geometry.DevicePixels(3),
y: @geometry.DevicePixels(4),
})
assert_eq(device.size, {
width: @geometry.DevicePixels(21),
height: @geometry.DevicePixels(6),
})
let back = device.to_pixels(2.0)
assert_eq(back.origin.x, @geometry.px(1.5))
let scaled = logical.scale(2.0)
assert_eq(scaled.size.width, @geometry.ScaledPixels(20.5))
assert_eq(
@geometry.ScaledPixels(20.5).to_device_pixels(),
@geometry.DevicePixels(21),
)
assert_eq(@geometry.DevicePixels(10).to_bytes(4), 40)
}
///|
test "lengths resolve to pixels" {
let rem_size = @geometry.px(16.0)
// Ported from the doc examples of AbsoluteLength/DefiniteLength.
let in_px = @geometry.px(42.0).to_absolute()
let in_rems = @geometry.rems(2.0).to_absolute()
assert_eq(in_px.to_pixels(rem_size), @geometry.px(42.0))
assert_eq(in_rems.to_pixels(rem_size), @geometry.px(32.0))
assert_eq(in_px.to_rems(@geometry.px(21.0)), @geometry.rems(2.0))
let base = @geometry.px(100.0).to_absolute()
assert_eq(
@geometry.px(42.0).to_definite().to_pixels(base, rem_size),
@geometry.px(42.0),
)
assert_eq(
@geometry.rems(2.0).to_definite().to_pixels(base, rem_size),
@geometry.px(32.0),
)
assert_eq(
@geometry.relative(0.5).to_pixels(base, rem_size),
@geometry.px(50.0),
)
assert_eq(
@geometry.relative(0.5).to_pixels(
@geometry.rems(10.0).to_absolute(),
rem_size,
),
@geometry.px(80.0),
)
assert_true(
@geometry.IsZero::is_zero((Default::default() : @geometry.Length)),
)
assert_false(@geometry.IsZero::is_zero(@geometry.auto()))
inspect(@geometry.relative(0.25), content="25%")
inspect(@geometry.auto(), content="auto")
}
///|
test "length parsing" {
assert_eq(@geometry.Pixels::parse("12.5px"), @geometry.px(12.5))
assert_eq(@geometry.Rems::parse(" 2rem "), @geometry.rems(2.0))
assert_eq(
@geometry.AbsoluteLength::parse("3rem"),
@geometry.rems(3.0).to_absolute(),
)
assert_eq(@geometry.DefiniteLength::parse("50%"), @geometry.relative(0.5))
assert_eq(@geometry.Length::parse("auto"), Auto)
assert_eq(@geometry.Length::parse("7px"), @geometry.px(7.0).to_length())
let bad = Ok(@geometry.Length::parse("7 parsecs")) catch { e => Err(e) }
assert_true(bad is Err(LengthParseError(input="7 parsecs", ..)))
let empty = Ok(@geometry.Pixels::parse("px")) catch { e => Err(e) }
assert_true(empty is Err(_))
}
///|
test "edges and corners" {
let edges = @geometry.Edges::new(top=1.0, right=2.0, bottom=3.0, left=4.0)
assert_eq(
edges + @geometry.Edges::all(1.0),
@geometry.Edges::new(top=2.0, right=3.0, bottom=4.0, left=5.0),
)
assert_eq(edges.along(Horizontal), (4.0, 2.0))
assert_eq(edges.along(Vertical), (1.0, 3.0))
assert_true(edges.any(fn(v) { v > 3.5 }))
assert_false(edges.any(fn(v) { v > 4.0 }))
let px_edges = edges.map(@geometry.px)
assert_eq(px_edges.max(), @geometry.px(4.0))
let parent : @geometry.Size[@geometry.AbsoluteLength] = {
width: @geometry.px(200.0).to_absolute(),
height: @geometry.px(100.0).to_absolute(),
}
let padding = @geometry.Edges::all(@geometry.relative(0.1))
assert_eq(
padding.definite_to_pixels(parent, @geometry.px(16.0)),
@geometry.Edges::new(
top=@geometry.px(10.0),
right=@geometry.px(20.0),
bottom=@geometry.px(10.0),
left=@geometry.px(20.0),
),
)
let radii = @geometry.Corners::new(
top_left=@geometry.px(2.0),
top_right=@geometry.px(50.0),
bottom_right=@geometry.px(0.0),
bottom_left=@geometry.px(8.0),
)
let clamped = radii.clamp_radii_for_quad_size({
width: @geometry.px(20.0),
height: @geometry.px(10.0),
})
assert_eq(clamped.top_right, @geometry.px(5.0))
assert_eq(clamped.top_left, @geometry.px(2.0))
assert_eq(clamped.bottom_left, @geometry.px(5.0))
assert_eq(radii.max(), @geometry.px(50.0))
assert_eq(radii.corner(BottomLeft), @geometry.px(8.0))
}
+9
View File
@@ -0,0 +1,9 @@
import {
"moonbitlang/core/math",
"moonbitlang/core/string",
"moonbitlang/core/debug",
}
import {
"moonbitlang/core/double",
} for "test"
+358
View File
@@ -0,0 +1,358 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/geometry"
import {
"moonbitlang/core/debug",
}
// Values
pub fn auto() -> Length
pub fn[T] bounds(Point[T], Size[T]) -> Bounds[T]
pub fn percentage(Double) -> Percentage
pub fn phi() -> DefiniteLength
pub let pixels_max : Pixels
pub let pixels_min : Pixels
pub let pixels_zero : Pixels
pub fn[T] point(T, T) -> Point[T]
pub fn px(Double) -> Pixels
pub fn radians(Double) -> Radians
pub fn relative(Double) -> DefiniteLength
pub fn rems(Double) -> Rems
pub fn[T] size(T, T) -> Size[T]
// Errors
#derive(@debug.Debug)
pub suberror LengthParseError {
LengthParseError(input~ : String, expected~ : String)
}
// Types and methods
#derive(Eq, Hash, @debug.Debug)
pub(all) enum AbsoluteLength {
Pixels(Pixels)
Rems(Rems)
}
pub fn AbsoluteLength::is_zero(Self) -> Bool
pub fn AbsoluteLength::parse(String) -> Self raise LengthParseError
pub fn AbsoluteLength::to_definite(Self) -> DefiniteLength
pub fn AbsoluteLength::to_pixels(Self, Pixels) -> Pixels
pub fn AbsoluteLength::to_rems(Self, Pixels) -> Rems
pub impl IsZero for AbsoluteLength
pub impl Default for AbsoluteLength
pub impl Show for AbsoluteLength
#derive(Eq, Hash, @debug.Debug)
pub(all) enum Anchor {
TopLeft
TopRight
BottomLeft
BottomRight
TopCenter
BottomCenter
LeftCenter
RightCenter
}
pub fn Anchor::is_bottom(Self) -> Bool
pub fn Anchor::is_center(Self) -> Bool
pub fn Anchor::opposite(Self) -> Self
pub fn Anchor::other_side_along(Self, Axis) -> Self
#derive(Eq, Hash, @debug.Debug)
pub(all) enum Axis {
Vertical
Horizontal
}
pub fn Axis::invert(Self) -> Self
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct Bounds[T] {
origin : Point[T]
size : Size[T]
}
pub fn[T : Add] Bounds::bottom(Self[T]) -> T
pub fn[T : Add + Half] Bounds::bottom_center(Self[T]) -> Point[T]
pub fn[T : Add] Bounds::bottom_left(Self[T]) -> Point[T]
pub fn[T : Add] Bounds::bottom_right(Self[T]) -> Point[T]
pub fn[T : Add + Half] Bounds::center(Self[T]) -> Point[T]
pub fn[T : Sub + Half] Bounds::centered_at(Point[T], Size[T]) -> Self[T]
pub fn[T : Add + Compare] Bounds::contains(Self[T], Point[T]) -> Bool
pub fn[T : Add + Half] Bounds::corner(Self[T], Anchor) -> Point[T]
pub fn[T : Add + Sub] Bounds::dilate(Self[T], T) -> Self[T]
pub fn[T : Add + Sub] Bounds::extend_by(Self[T], Edges[T]) -> Self[T]
pub fn[T : Sub + Half] Bounds::from_anchor_and_size(Anchor, Point[T], Size[T]) -> Self[T]
pub fn[T : Sub] Bounds::from_corners(Point[T], Point[T]) -> Self[T]
pub fn[T : Add] Bounds::half_perimeter(Self[T]) -> T
pub fn[T : Add + Sub + Neg] Bounds::inset(Self[T], T) -> Self[T]
pub fn[T : Add + Sub + Compare] Bounds::intersect(Self[T], Self[T]) -> Self[T]
pub fn[T : Add + Compare] Bounds::intersects(Self[T], Self[T]) -> Bool
pub fn[T : Add + Compare] Bounds::is_contained_within(Self[T], Self[T]) -> Bool
pub fn[T : Compare + Default] Bounds::is_empty(Self[T]) -> Bool
pub fn[T : Add + Sub + Compare + Default] Bounds::join(Self[T], Self[T]) -> Self[T]
pub fn[T] Bounds::left(Self[T]) -> T
pub fn[T : Add + Half] Bounds::left_center(Self[T]) -> Point[T]
pub fn[T : Add + Sub + Compare] Bounds::localize(Self[T], Point[T]) -> Point[T]?
pub fn[T, U] Bounds::map(Self[T], (T) -> U) -> Self[U]
pub fn[T] Bounds::map_origin(Self[T], (T) -> T) -> Self[T]
pub fn[T] Bounds::map_size(Self[T], (T) -> T) -> Self[T]
pub fn[T : MulScalar] Bounds::mul_scalar(Self[T], Double) -> Self[T]
pub fn[T] Bounds::new(Point[T], Size[T]) -> Self[T]
pub fn[T : Add] Bounds::right(Self[T]) -> T
pub fn[T : Add + Half] Bounds::right_center(Self[T]) -> Point[T]
pub fn Bounds::scale(Self[Pixels], Double) -> Self[ScaledPixels]
pub fn[T : Add + Sub] Bounds::space_within(Self[T], Self[T]) -> Edges[T]
pub fn Bounds::to_device_pixels(Self[Pixels], Double) -> Self[DevicePixels]
pub fn Bounds::to_pixels(Self[DevicePixels], Double) -> Self[Pixels]
pub fn[T] Bounds::top(Self[T]) -> T
pub fn[T : Add + Half] Bounds::top_center(Self[T]) -> Point[T]
pub fn[T : Add] Bounds::top_right(Self[T]) -> Point[T]
pub fn[T : Add] Bounds::translate(Self[T], Point[T]) -> Self[T]
pub fn[T : Add + Sub + Compare] Bounds::union(Self[T], Self[T]) -> Self[T]
pub impl[T : IsZero] IsZero for Bounds[T]
pub impl[T : Show + Add] Show for Bounds[T]
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct ContentMask[T] {
bounds : Bounds[T]
}
pub fn[T : Add + Sub + Compare] ContentMask::intersect(Self[T], Self[T]) -> Self[T]
pub fn ContentMask::scale(Self[Pixels], Double) -> Self[ScaledPixels]
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct Corners[T] {
top_left : T
top_right : T
bottom_right : T
bottom_left : T
}
pub fn Corners::absolute_to_pixels(Self[AbsoluteLength], Pixels) -> Self[Pixels]
pub fn[T] Corners::all(T) -> Self[T]
pub fn[T : Compare + Half] Corners::clamp_radii_for_quad_size(Self[T], Size[T]) -> Self[T]
pub fn[T] Corners::corner(Self[T], Anchor) -> T
pub fn[T, U] Corners::map(Self[T], (T) -> U) -> Self[U]
pub fn Corners::max(Self[Pixels]) -> Pixels
pub fn[T : MulScalar] Corners::mul_scalar(Self[T], Double) -> Self[T]
pub fn[T] Corners::new(top_left~ : T, top_right~ : T, bottom_right~ : T, bottom_left~ : T) -> Self[T]
pub fn Corners::scale(Self[Pixels], Double) -> Self[ScaledPixels]
pub impl[T : IsZero] IsZero for Corners[T]
pub impl[T : Mul] Mul for Corners[T]
#derive(Eq, Hash, @debug.Debug)
pub(all) enum DefiniteLength {
Absolute(AbsoluteLength)
Fraction(Double)
}
pub fn DefiniteLength::is_zero(Self) -> Bool
pub fn DefiniteLength::parse(String) -> Self raise LengthParseError
pub fn DefiniteLength::to_length(Self) -> Length
pub fn DefiniteLength::to_pixels(Self, AbsoluteLength, Pixels) -> Pixels
pub impl IsZero for DefiniteLength
pub impl Default for DefiniteLength
pub impl Show for DefiniteLength
#derive(Compare, Default, Eq, Hash, @debug.Debug)
pub(all) struct DevicePixels(Int32)
pub fn DevicePixels::half(Self) -> Self
pub fn DevicePixels::is_zero(Self) -> Bool
pub fn DevicePixels::to_bytes(Self, Int32) -> Int32
pub fn DevicePixels::to_int(Self) -> Int32
pub fn DevicePixels::to_scaled_pixels(Self) -> ScaledPixels
pub impl Half for DevicePixels
pub impl IsZero for DevicePixels
pub impl Add for DevicePixels
pub impl Mul for DevicePixels
pub impl Neg for DevicePixels
pub impl Show for DevicePixels
pub impl Sub for DevicePixels
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct Edges[T] {
top : T
right : T
bottom : T
left : T
}
pub fn Edges::absolute_to_pixels(Self[AbsoluteLength], Pixels) -> Self[Pixels]
pub fn[T] Edges::all(T) -> Self[T]
pub fn[T] Edges::along(Self[T], Axis) -> (T, T)
pub fn[T] Edges::any(Self[T], (T) -> Bool) -> Bool
pub fn[T] Edges::apply_along(Self[T], Axis, ((T, T)) -> (T, T)) -> Self[T]
pub fn Edges::auto() -> Self[Length]
pub fn Edges::definite_to_pixels(Self[DefiniteLength], Size[AbsoluteLength], Pixels) -> Self[Pixels]
pub fn[T, U] Edges::map(Self[T], (T) -> U) -> Self[U]
pub fn Edges::max(Self[Pixels]) -> Pixels
pub fn[T : MulScalar] Edges::mul_scalar(Self[T], Double) -> Self[T]
pub fn[T] Edges::new(top~ : T, right~ : T, bottom~ : T, left~ : T) -> Self[T]
pub fn Edges::scale(Self[Pixels], Double) -> Self[ScaledPixels]
pub fn Edges::zero_absolute() -> Self[AbsoluteLength]
pub fn Edges::zero_definite() -> Self[DefiniteLength]
pub fn Edges::zero_length() -> Self[Length]
pub impl[T : IsZero] IsZero for Edges[T]
pub impl[T : Add] Add for Edges[T]
pub impl[T : Mul] Mul for Edges[T]
#derive(Eq, Hash, @debug.Debug)
pub(all) enum Length {
Definite(DefiniteLength)
Auto
}
pub fn Length::is_zero(Self) -> Bool
pub fn Length::parse(String) -> Self raise LengthParseError
pub impl IsZero for Length
pub impl Default for Length
pub impl Show for Length
#derive(Compare, Default, Eq, @debug.Debug)
pub(all) struct Percentage(Double)
pub fn Percentage::to_radians(Self) -> Radians
#derive(Compare, Default, Eq, Hash, @debug.Debug)
pub(all) struct Pixels(Double)
pub fn Pixels::abs(Self) -> Self
pub fn Pixels::ceil(Self) -> Self
pub fn Pixels::floor(Self) -> Self
pub fn Pixels::half(Self) -> Self
pub fn Pixels::is_zero(Self) -> Bool
pub fn Pixels::mul_scalar(Self, Double) -> Self
pub fn Pixels::parse(String) -> Self raise LengthParseError
pub fn Pixels::pow(Self, Double) -> Self
pub fn Pixels::ratio(Self, Self) -> Double
pub fn Pixels::round(Self) -> Self
pub fn Pixels::scale(Self, Double) -> ScaledPixels
pub fn Pixels::signum(Self) -> Double
pub fn Pixels::sum(Array[Self]) -> Self
pub fn Pixels::to_absolute(Self) -> AbsoluteLength
pub fn Pixels::to_definite(Self) -> DefiniteLength
pub fn Pixels::to_double(Self) -> Double
pub fn Pixels::to_int(Self) -> Int32
pub fn Pixels::to_length(Self) -> Length
pub impl Half for Pixels
pub impl IsZero for Pixels
pub impl MulScalar for Pixels
pub impl Add for Pixels
pub impl Div for Pixels
pub impl Mod for Pixels
pub impl Mul for Pixels
pub impl Neg for Pixels
pub impl Show for Pixels
pub impl Sub for Pixels
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct Point[T] {
x : T
y : T
}
pub fn[T] Point::along(Self[T], Axis) -> T
pub fn[T] Point::apply_along(Self[T], Axis, (T) -> T) -> Self[T]
pub fn[T : Compare] Point::clamp(Self[T], Self[T], Self[T]) -> Self[T]
pub fn Point::magnitude(Self[Pixels]) -> Double
pub fn[T, U] Point::map(Self[T], (T) -> U) -> Self[U]
pub fn[T : Compare] Point::max(Self[T], Self[T]) -> Self[T]
pub fn[T : Compare] Point::min(Self[T], Self[T]) -> Self[T]
pub fn[T : MulScalar] Point::mul_scalar(Self[T], Double) -> Self[T]
pub fn[T] Point::new(T, T) -> Self[T]
pub fn[T : Sub] Point::relative_to(Self[T], Self[T]) -> Self[T]
pub fn Point::scale(Self[Pixels], Double) -> Self[ScaledPixels]
pub fn[T] Point::to_size(Self[T]) -> Size[T]
pub impl[T : IsZero] IsZero for Point[T]
pub impl[T : Add] Add for Point[T]
pub impl[T : Neg] Neg for Point[T]
pub impl[T : Show] Show for Point[T]
pub impl[T : Sub] Sub for Point[T]
#derive(Compare, Default, Eq, @debug.Debug)
pub(all) struct Radians(Double)
#derive(Compare, Default, Eq, Hash, @debug.Debug)
pub(all) struct Rems(Double)
pub fn Rems::from_pixels(Pixels, Pixels) -> Self
pub fn Rems::half(Self) -> Self
pub fn Rems::is_zero(Self) -> Bool
pub fn Rems::mul_scalar(Self, Double) -> Self
pub fn Rems::parse(String) -> Self raise LengthParseError
pub fn Rems::to_absolute(Self) -> AbsoluteLength
pub fn Rems::to_definite(Self) -> DefiniteLength
pub fn Rems::to_length(Self) -> Length
pub fn Rems::to_pixels(Self, Pixels) -> Pixels
pub impl Half for Rems
pub impl IsZero for Rems
pub impl MulScalar for Rems
pub impl Add for Rems
pub impl Neg for Rems
pub impl Show for Rems
pub impl Sub for Rems
#derive(Compare, Default, Eq, Hash, @debug.Debug)
pub(all) struct ScaledPixels(Double)
pub fn ScaledPixels::ceil(Self) -> Self
pub fn ScaledPixels::floor(Self) -> Self
pub fn ScaledPixels::half(Self) -> Self
pub fn ScaledPixels::is_zero(Self) -> Bool
pub fn ScaledPixels::mul_scalar(Self, Double) -> Self
pub fn ScaledPixels::round(Self) -> Self
pub fn ScaledPixels::to_device_pixels(Self) -> DevicePixels
pub fn ScaledPixels::to_double(Self) -> Double
pub impl Half for ScaledPixels
pub impl IsZero for ScaledPixels
pub impl MulScalar for ScaledPixels
pub impl Add for ScaledPixels
pub impl Div for ScaledPixels
pub impl Mul for ScaledPixels
pub impl Neg for ScaledPixels
pub impl Show for ScaledPixels
pub impl Sub for ScaledPixels
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct Size[T] {
width : T
height : T
}
pub fn[T] Size::along(Self[T], Axis) -> T
pub fn[T] Size::apply_along(Self[T], Axis, (T) -> T) -> Self[T]
pub fn Size::auto() -> Self[Length]
pub fn[T : Half] Size::center(Self[T]) -> Point[T]
pub fn Size::full() -> Self[Length]
pub fn[T, U] Size::map(Self[T], (T) -> U) -> Self[U]
pub fn[T : Compare] Size::max(Self[T], Self[T]) -> Self[T]
pub fn[T : Compare] Size::min(Self[T], Self[T]) -> Self[T]
pub fn[T : MulScalar] Size::mul_scalar(Self[T], Double) -> Self[T]
pub fn[T] Size::new(T, T) -> Self[T]
pub fn Size::scale(Self[Pixels], Double) -> Self[ScaledPixels]
pub fn Size::to_device_pixels(Self[Pixels], Double) -> Self[DevicePixels]
pub fn Size::to_pixels(Self[DevicePixels], Double) -> Self[Pixels]
pub fn[T] Size::to_point(Self[T]) -> Point[T]
pub impl[T : IsZero] IsZero for Size[T]
pub impl[T : Add] Add for Size[T]
pub impl[T : Show] Show for Size[T]
pub impl[T : Sub] Sub for Size[T]
// Type aliases
// Traits
pub trait Half {
fn half(Self) -> Self
}
pub impl Half for Int32
pub impl Half for Double
pub trait IsZero {
fn is_zero(Self) -> Bool
}
pub impl IsZero for Int32
pub impl IsZero for Double
pub trait MulScalar {
fn mul_scalar(Self, Double) -> Self
}
pub impl MulScalar for Double
+323
View File
@@ -0,0 +1,323 @@
// Axis, Point and Size, ported from gpui/src/geometry.rs.
//
// GPUI's `Along` trait has an associated `Unit` type; MoonBit traits have no
// associated types, so `along`/`apply_along` are plain generic methods on each
// container instead.
///|
/// Axis in a 2D cartesian space.
#derive(Eq, Hash, Debug)
pub(all) enum Axis {
/// The y axis, or up and down.
Vertical
/// The x axis, or left and right.
Horizontal
}
///|
pub fn Axis::invert(self : Axis) -> Axis {
match self {
Vertical => Horizontal
Horizontal => Vertical
}
}
///|
fn[T : Compare] max_of(a : T, b : T) -> T {
if a >= b {
a
} else {
b
}
}
///|
fn[T : Compare] min_of(a : T, b : T) -> T {
if a <= b {
a
} else {
b
}
}
// ---------------------------------------------------------------------------
// Point
// ---------------------------------------------------------------------------
///|
/// A location in 2D space.
#derive(Eq, Hash, Default, Debug)
pub(all) struct Point[T] {
x : T
y : T
}
///|
pub fn[T] point(x : T, y : T) -> Point[T] {
{ x, y, }
}
///|
pub fn[T] Point::new(x : T, y : T) -> Point[T] {
{ x, y, }
}
///|
pub fn[T, U] Point::map(self : Point[T], f : (T) -> U) -> Point[U] {
{ x: f(self.x), y: f(self.y), }
}
///|
pub fn[T] Point::along(self : Point[T], axis : Axis) -> T {
match axis {
Horizontal => self.x
Vertical => self.y
}
}
///|
pub fn[T] Point::apply_along(
self : Point[T],
axis : Axis,
f : (T) -> T,
) -> Point[T] {
match axis {
Horizontal => { x: f(self.x), y: self.y, }
Vertical => { x: self.x, y: f(self.y), }
}
}
///|
/// Component-wise maximum.
pub fn[T : Compare] Point::max(self : Point[T], other : Point[T]) -> Point[T] {
{ x: max_of(self.x, other.x), y: max_of(self.y, other.y), }
}
///|
/// Component-wise minimum.
pub fn[T : Compare] Point::min(self : Point[T], other : Point[T]) -> Point[T] {
{ x: min_of(self.x, other.x), y: min_of(self.y, other.y), }
}
///|
/// Clamps each component between the corresponding components of `min` and
/// `max`.
pub fn[T : Compare] Point::clamp(
self : Point[T],
min : Point[T],
max : Point[T],
) -> Point[T] {
self.max(min).min(max)
}
///|
/// This point expressed relative to `origin`.
pub fn[T : Sub] Point::relative_to(
self : Point[T],
origin : Point[T],
) -> Point[T] {
{ x: self.x - origin.x, y: self.y - origin.y, }
}
///|
pub fn[T : MulScalar] Point::mul_scalar(
self : Point[T],
factor : Double,
) -> Point[T] {
{ x: self.x.mul_scalar(factor), y: self.y.mul_scalar(factor), }
}
///|
pub impl[T : Add] Add for Point[T] with fn add(self, other) {
{ x: self.x + other.x, y: self.y + other.y, }
}
///|
pub impl[T : Sub] Sub for Point[T] with fn sub(self, other) {
{ x: self.x - other.x, y: self.y - other.y, }
}
///|
pub impl[T : Neg] Neg for Point[T] with fn neg(self) {
{ x: -self.x, y: -self.y, }
}
///|
pub impl[T : IsZero] IsZero for Point[T] with fn is_zero(self) {
self.x.is_zero() && self.y.is_zero()
}
///|
pub impl[T : Show] Show for Point[T] with fn output(self, logger) {
logger.write_string("(")
self.x.output(logger)
logger.write_string(", ")
self.y.output(logger)
logger.write_string(")")
}
///|
pub fn Point::scale(
self : Point[Pixels],
factor : Double,
) -> Point[ScaledPixels] {
{ x: self.x.scale(factor), y: self.y.scale(factor), }
}
///|
/// Euclidean distance from the origin.
pub fn Point::magnitude(self : Point[Pixels]) -> Double {
(self.x.0 * self.x.0 + self.y.0 * self.y.0).sqrt()
}
///|
pub fn[T] Point::to_size(self : Point[T]) -> Size[T] {
{ width: self.x, height: self.y, }
}
// ---------------------------------------------------------------------------
// Size
// ---------------------------------------------------------------------------
///|
/// A 2D size.
#derive(Eq, Hash, Default, Debug)
pub(all) struct Size[T] {
width : T
height : T
}
///|
pub fn[T] size(width : T, height : T) -> Size[T] {
{ width, height, }
}
///|
pub fn[T] Size::new(width : T, height : T) -> Size[T] {
{ width, height, }
}
///|
pub fn[T, U] Size::map(self : Size[T], f : (T) -> U) -> Size[U] {
{ width: f(self.width), height: f(self.height), }
}
///|
pub fn[T] Size::along(self : Size[T], axis : Axis) -> T {
match axis {
Horizontal => self.width
Vertical => self.height
}
}
///|
pub fn[T] Size::apply_along(
self : Size[T],
axis : Axis,
f : (T) -> T,
) -> Size[T] {
match axis {
Horizontal => { width: f(self.width), height: self.height, }
Vertical => { width: self.width, height: f(self.height), }
}
}
///|
pub fn[T : Half] Size::center(self : Size[T]) -> Point[T] {
{ x: self.width.half(), y: self.height.half(), }
}
///|
pub fn[T : Compare] Size::max(self : Size[T], other : Size[T]) -> Size[T] {
{
width: max_of(self.width, other.width),
height: max_of(self.height, other.height),
}
}
///|
pub fn[T : Compare] Size::min(self : Size[T], other : Size[T]) -> Size[T] {
{
width: min_of(self.width, other.width),
height: min_of(self.height, other.height),
}
}
///|
pub fn[T : MulScalar] Size::mul_scalar(
self : Size[T],
factor : Double,
) -> Size[T] {
{
width: self.width.mul_scalar(factor),
height: self.height.mul_scalar(factor),
}
}
///|
pub fn[T] Size::to_point(self : Size[T]) -> Point[T] {
{ x: self.width, y: self.height, }
}
///|
pub impl[T : Add] Add for Size[T] with fn add(self, other) {
{ width: self.width + other.width, height: self.height + other.height, }
}
///|
pub impl[T : Sub] Sub for Size[T] with fn sub(self, other) {
{ width: self.width - other.width, height: self.height - other.height, }
}
///|
/// A size is zero only if both dimensions are zero (GPUI semantics).
pub impl[T : IsZero] IsZero for Size[T] with fn is_zero(self) {
self.width.is_zero() && self.height.is_zero()
}
///|
pub impl[T : Show] Show for Size[T] with fn output(self, logger) {
self.width.output(logger)
logger.write_string(" × ")
self.height.output(logger)
}
///|
pub fn Size::scale(self : Size[Pixels], factor : Double) -> Size[ScaledPixels] {
{ width: self.width.scale(factor), height: self.height.scale(factor), }
}
///|
/// Converts to device pixels, rounding each dimension.
pub fn Size::to_device_pixels(
self : Size[Pixels],
scale_factor : Double,
) -> Size[DevicePixels] {
{
width: DevicePixels(round_half_away(self.width.0 * scale_factor).to_int()),
height: DevicePixels(round_half_away(self.height.0 * scale_factor).to_int()),
}
}
///|
pub fn Size::to_pixels(
self : Size[DevicePixels],
scale_factor : Double,
) -> Size[Pixels] {
{
width: Pixels(self.width.0.to_double() / scale_factor),
height: Pixels(self.height.0.to_double() / scale_factor),
}
}
///|
/// A size of 100% in both dimensions.
pub fn Size::full() -> Size[Length] {
{ width: relative(1.0).to_length(), height: relative(1.0).to_length(), }
}
///|
/// A size that is `auto` in both dimensions.
pub fn Size::auto() -> Size[Length] {
{ width: Auto, height: Auto, }
}
+719
View File
@@ -0,0 +1,719 @@
// Units of measure, ported from gpui/src/geometry.rs (Pixels, ScaledPixels,
// DevicePixels, Rems, Radians, Percentage, AbsoluteLength, DefiniteLength,
// Length).
//
// Deviation from GPUI: logical units wrap `Double` instead of `f32`. MoonBit's
// `Double` is the native number type on every backend (and the one
// `Milky2018/moon_taffy` uses), while `Float` is emulated on the JS backend.
// Conversion to f32 happens at the renderer boundary.
///|
/// Arithmetic helper: halve a value. Mirrors GPUI's `Half` trait.
pub trait Half {
fn half(Self) -> Self
}
///|
/// Mirrors GPUI's `IsZero` trait.
pub trait IsZero {
fn is_zero(Self) -> Bool
}
///|
/// Multiplication / division by a unitless scalar. GPUI expresses these as
/// `impl Mul<f32> for Pixels`; MoonBit's `Mul` is homogeneous (`Self * Self`),
/// so scalar scaling gets its own trait.
pub trait MulScalar {
fn mul_scalar(Self, Double) -> Self
}
///|
pub impl Half for Double with fn half(self) {
self / 2.0
}
///|
pub impl Half for Int32 with fn half(self) {
self / 2
}
///|
pub impl IsZero for Double with fn is_zero(self) {
self == 0.0
}
///|
pub impl IsZero for Int32 with fn is_zero(self) {
self == 0
}
///|
pub impl MulScalar for Double with fn mul_scalar(self, factor) {
self * factor
}
// ---------------------------------------------------------------------------
// Pixels
// ---------------------------------------------------------------------------
///|
/// Logical pixels, independent of the display's scale factor.
#derive(Eq, Compare, Hash, Default, Debug)
pub(all) struct Pixels(Double)
///|
pub fn px(value : Double) -> Pixels {
Pixels(value)
}
///|
pub let pixels_zero : Pixels = Pixels(0.0)
///|
/// Largest finite pixel value (GPUI uses `f32::MAX`).
pub let pixels_max : Pixels = Pixels(3.4028234663852886e38)
///|
pub let pixels_min : Pixels = Pixels(-3.4028234663852886e38)
///|
pub fn Pixels::to_double(self : Pixels) -> Double {
self.0
}
///|
/// Truncates toward zero, like Rust's `as i32`.
pub fn Pixels::to_int(self : Pixels) -> Int32 {
self.0.to_int()
}
///|
pub fn Pixels::floor(self : Pixels) -> Pixels {
Pixels(self.0.floor())
}
///|
pub fn Pixels::round(self : Pixels) -> Pixels {
Pixels(round_half_away(self.0))
}
///|
pub fn Pixels::ceil(self : Pixels) -> Pixels {
Pixels(self.0.ceil())
}
///|
pub fn Pixels::abs(self : Pixels) -> Pixels {
Pixels(self.0.abs())
}
///|
pub fn Pixels::signum(self : Pixels) -> Double {
if self.0 > 0.0 || (self.0 == 0.0 && 1.0 / self.0 > 0.0) {
1.0
} else if self.0.is_nan() {
self.0
} else {
-1.0
}
}
///|
pub fn Pixels::pow(self : Pixels, exponent : Double) -> Pixels {
Pixels(@math.pow(self.0, exponent))
}
///|
/// Converts to device-scaled pixels by multiplying with the window's scale
/// factor.
pub fn Pixels::scale(self : Pixels, factor : Double) -> ScaledPixels {
ScaledPixels(self.0 * factor)
}
///|
/// The ratio between two pixel values (GPUI: `impl Div for Pixels`).
pub fn Pixels::ratio(self : Pixels, other : Pixels) -> Double {
self.0 / other.0
}
///|
pub impl Add for Pixels with fn add(self, other) {
Pixels(self.0 + other.0)
}
///|
pub impl Sub for Pixels with fn sub(self, other) {
Pixels(self.0 - other.0)
}
///|
pub impl Neg for Pixels with fn neg(self) {
Pixels(-self.0)
}
///|
/// Component-wise product. Used by `Edges`/`Corners` multiplication.
pub impl Mul for Pixels with fn mul(self, other) {
Pixels(self.0 * other.0)
}
///|
pub impl Div for Pixels with fn div(self, other) {
Pixels(self.0 / other.0)
}
///|
pub impl Mod for Pixels with fn mod(self, other) {
Pixels(self.0 % other.0)
}
///|
pub impl Half for Pixels with fn half(self) {
Pixels(self.0 / 2.0)
}
///|
pub impl IsZero for Pixels with fn is_zero(self) {
self.0 == 0.0
}
///|
pub impl MulScalar for Pixels with fn mul_scalar(self, factor) {
Pixels(self.0 * factor)
}
///|
pub impl Show for Pixels with fn output(self, logger) {
logger.write_string(self.0.to_string())
logger.write_string("px")
}
///|
pub fn Pixels::sum(values : Array[Pixels]) -> Pixels {
let mut total = 0.0
for value in values {
total = total + value.0
}
Pixels(total)
}
// ---------------------------------------------------------------------------
// ScaledPixels
// ---------------------------------------------------------------------------
///|
/// Pixels multiplied by the display's scale factor; what the renderer sees.
#derive(Eq, Compare, Hash, Default, Debug)
pub(all) struct ScaledPixels(Double)
///|
pub fn ScaledPixels::to_double(self : ScaledPixels) -> Double {
self.0
}
///|
pub fn ScaledPixels::floor(self : ScaledPixels) -> ScaledPixels {
ScaledPixels(self.0.floor())
}
///|
pub fn ScaledPixels::round(self : ScaledPixels) -> ScaledPixels {
ScaledPixels(round_half_away(self.0))
}
///|
pub fn ScaledPixels::ceil(self : ScaledPixels) -> ScaledPixels {
ScaledPixels(self.0.ceil())
}
///|
/// Truncating conversion (GPUI: `From<ScaledPixels> for DevicePixels`, which
/// uses `ceil`).
pub fn ScaledPixels::to_device_pixels(self : ScaledPixels) -> DevicePixels {
DevicePixels(self.0.ceil().to_int())
}
///|
pub impl Add for ScaledPixels with fn add(self, other) {
ScaledPixels(self.0 + other.0)
}
///|
pub impl Sub for ScaledPixels with fn sub(self, other) {
ScaledPixels(self.0 - other.0)
}
///|
pub impl Neg for ScaledPixels with fn neg(self) {
ScaledPixels(-self.0)
}
///|
pub impl Mul for ScaledPixels with fn mul(self, other) {
ScaledPixels(self.0 * other.0)
}
///|
pub impl Div for ScaledPixels with fn div(self, other) {
ScaledPixels(self.0 / other.0)
}
///|
pub impl Half for ScaledPixels with fn half(self) {
ScaledPixels(self.0 / 2.0)
}
///|
pub impl IsZero for ScaledPixels with fn is_zero(self) {
self.0 == 0.0
}
///|
pub impl MulScalar for ScaledPixels with fn mul_scalar(self, factor) {
ScaledPixels(self.0 * factor)
}
///|
pub impl Show for ScaledPixels with fn output(self, logger) {
logger.write_string(self.0.to_string())
logger.write_string("px (scaled)")
}
// ---------------------------------------------------------------------------
// DevicePixels
// ---------------------------------------------------------------------------
///|
/// Physical pixels on the display (integral).
#derive(Eq, Compare, Hash, Default, Debug)
pub(all) struct DevicePixels(Int32)
///|
pub fn DevicePixels::to_int(self : DevicePixels) -> Int32 {
self.0
}
///|
/// Number of bytes needed to store this many pixels.
pub fn DevicePixels::to_bytes(
self : DevicePixels,
bytes_per_pixel : Int32,
) -> Int32 {
self.0 * bytes_per_pixel
}
///|
pub fn DevicePixels::to_scaled_pixels(self : DevicePixels) -> ScaledPixels {
ScaledPixels(self.0.to_double())
}
///|
pub impl Add for DevicePixels with fn add(self, other) {
DevicePixels(self.0 + other.0)
}
///|
pub impl Sub for DevicePixels with fn sub(self, other) {
DevicePixels(self.0 - other.0)
}
///|
pub impl Neg for DevicePixels with fn neg(self) {
DevicePixels(-self.0)
}
///|
pub impl Mul for DevicePixels with fn mul(self, other) {
DevicePixels(self.0 * other.0)
}
///|
pub impl Half for DevicePixels with fn half(self) {
DevicePixels(self.0 / 2)
}
///|
pub impl IsZero for DevicePixels with fn is_zero(self) {
self.0 == 0
}
///|
pub impl Show for DevicePixels with fn output(self, logger) {
logger.write_string(self.0.to_string())
logger.write_string("px (device)")
}
// ---------------------------------------------------------------------------
// Rems
// ---------------------------------------------------------------------------
///|
/// A length relative to the window's root font size (`rem_size`).
#derive(Eq, Compare, Hash, Default, Debug)
pub(all) struct Rems(Double)
///|
pub fn rems(value : Double) -> Rems {
Rems(value)
}
///|
pub fn Rems::to_pixels(self : Rems, rem_size : Pixels) -> Pixels {
Pixels(self.0 * rem_size.0)
}
///|
pub fn Rems::from_pixels(length : Pixels, rem_size : Pixels) -> Rems {
Rems(length.0 / rem_size.0)
}
///|
pub impl Add for Rems with fn add(self, other) {
Rems(self.0 + other.0)
}
///|
pub impl Sub for Rems with fn sub(self, other) {
Rems(self.0 - other.0)
}
///|
pub impl Neg for Rems with fn neg(self) {
Rems(-self.0)
}
///|
pub impl Half for Rems with fn half(self) {
Rems(self.0 / 2.0)
}
///|
pub impl IsZero for Rems with fn is_zero(self) {
self.0 == 0.0
}
///|
pub impl MulScalar for Rems with fn mul_scalar(self, factor) {
Rems(self.0 * factor)
}
///|
pub impl Show for Rems with fn output(self, logger) {
logger.write_string(self.0.to_string())
logger.write_string("rem")
}
// ---------------------------------------------------------------------------
// Radians / Percentage
// ---------------------------------------------------------------------------
///|
#derive(Eq, Compare, Default, Debug)
pub(all) struct Radians(Double)
///|
pub fn radians(value : Double) -> Radians {
Radians(value)
}
///|
/// A percentage in `0.0..=1.0`, stored as a fraction.
#derive(Eq, Compare, Default, Debug)
pub(all) struct Percentage(Double)
///|
/// Creates a percentage, failing loudly outside `0.0..=1.0` (GPUI asserts in
/// debug builds).
pub fn percentage(value : Double) -> Percentage {
guard value >= 0.0 && value <= 1.0 else {
abort("percentage must be between 0 and 1, got \{value}")
}
Percentage(value)
}
///|
/// A percentage of a full turn.
pub fn Percentage::to_radians(self : Percentage) -> Radians {
Radians(self.0 * 2.0 * @math.PI)
}
// ---------------------------------------------------------------------------
// AbsoluteLength / DefiniteLength / Length
// ---------------------------------------------------------------------------
///|
/// A length that resolves to pixels given only the rem size.
#derive(Eq, Hash, Debug)
pub(all) enum AbsoluteLength {
Pixels(Pixels)
Rems(Rems)
}
///|
pub impl Default for AbsoluteLength with fn default() {
AbsoluteLength::Pixels(pixels_zero)
}
///|
pub fn AbsoluteLength::to_pixels(
self : AbsoluteLength,
rem_size : Pixels,
) -> Pixels {
match self {
Pixels(p) => p
Rems(r) => r.to_pixels(rem_size)
}
}
///|
pub fn AbsoluteLength::to_rems(
self : AbsoluteLength,
rem_size : Pixels,
) -> Rems {
match self {
Pixels(p) => Rems(p.0 / rem_size.0)
Rems(r) => r
}
}
///|
pub impl IsZero for AbsoluteLength with fn is_zero(self) {
match self {
Pixels(p) => p.is_zero()
Rems(r) => r.is_zero()
}
}
///|
pub impl Show for AbsoluteLength with fn output(self, logger) {
match self {
Pixels(p) => Show::output(p, logger)
Rems(r) => Show::output(r, logger)
}
}
///|
/// A length that resolves given a base size (fractions are relative to it).
#derive(Eq, Hash, Debug)
pub(all) enum DefiniteLength {
Absolute(AbsoluteLength)
/// A fraction of the parent's size, e.g. `0.5` for 50%.
Fraction(Double)
}
///|
pub impl Default for DefiniteLength with fn default() {
DefiniteLength::Absolute(Default::default())
}
///|
pub fn DefiniteLength::to_pixels(
self : DefiniteLength,
base_size : AbsoluteLength,
rem_size : Pixels,
) -> Pixels {
match self {
Absolute(size) => size.to_pixels(rem_size)
Fraction(fraction) =>
match base_size {
Pixels(p) => p.mul_scalar(fraction)
Rems(r) => r.to_pixels(rem_size).mul_scalar(fraction)
}
}
}
///|
pub impl IsZero for DefiniteLength with fn is_zero(self) {
match self {
Absolute(length) => length.is_zero()
Fraction(fraction) => fraction == 0.0
}
}
///|
pub impl Show for DefiniteLength with fn output(self, logger) {
match self {
Absolute(length) => Show::output(length, logger)
Fraction(fraction) => {
logger.write_string((fraction * 100.0).to_string())
logger.write_string("%")
}
}
}
///|
/// A length that may also be `auto` (resolved by layout).
#derive(Eq, Hash, Debug)
pub(all) enum Length {
Definite(DefiniteLength)
Auto
}
///|
pub impl Default for Length with fn default() {
Length::Definite(Default::default())
}
///|
pub impl IsZero for Length with fn is_zero(self) {
match self {
Definite(length) => length.is_zero()
Auto => false
}
}
///|
pub impl Show for Length with fn output(self, logger) {
match self {
Definite(length) => Show::output(length, logger)
Auto => logger.write_string("auto")
}
}
///|
/// A fraction of the parent size (`relative(0.5)` is 50%).
pub fn relative(fraction : Double) -> DefiniteLength {
Fraction(fraction)
}
///|
/// The golden ratio as a relative length.
pub fn phi() -> DefiniteLength {
relative(1.618033988749895)
}
///|
pub fn auto() -> Length {
Auto
}
///|
pub fn Pixels::to_absolute(self : Pixels) -> AbsoluteLength {
AbsoluteLength::Pixels(self)
}
///|
pub fn Pixels::to_definite(self : Pixels) -> DefiniteLength {
Absolute(AbsoluteLength::Pixels(self))
}
///|
pub fn Pixels::to_length(self : Pixels) -> Length {
Definite(self.to_definite())
}
///|
pub fn Rems::to_absolute(self : Rems) -> AbsoluteLength {
AbsoluteLength::Rems(self)
}
///|
pub fn Rems::to_definite(self : Rems) -> DefiniteLength {
Absolute(AbsoluteLength::Rems(self))
}
///|
pub fn Rems::to_length(self : Rems) -> Length {
Definite(self.to_definite())
}
///|
pub fn AbsoluteLength::to_definite(self : AbsoluteLength) -> DefiniteLength {
Absolute(self)
}
///|
pub fn DefiniteLength::to_length(self : DefiniteLength) -> Length {
Definite(self)
}
// ---------------------------------------------------------------------------
// Parsing ("12px", "1.5rem", "50%", "auto"), mirroring GPUI's TryFrom<&str>.
// ---------------------------------------------------------------------------
///|
#derive(Debug)
pub suberror LengthParseError {
LengthParseError(input~ : String, expected~ : String)
}
///|
fn parse_number(
input : String,
digits : StringView,
expected : String,
) -> Double raise LengthParseError {
let text = digits.to_owned()
if text.is_empty() {
raise LengthParseError(input~, expected~)
}
@string.parse_double(text) catch {
_ => raise LengthParseError(input~, expected~)
}
}
///|
pub fn Pixels::parse(input : String) -> Pixels raise LengthParseError {
let expected = "number with 'px' suffix"
let trimmed = input.trim()
guard trimmed.strip_suffix("px") is Some(digits) else {
raise LengthParseError(input~, expected~)
}
Pixels(parse_number(input, digits, expected))
}
///|
pub fn Rems::parse(input : String) -> Rems raise LengthParseError {
let expected = "number with 'rem' suffix"
let trimmed = input.trim()
guard trimmed.strip_suffix("rem") is Some(digits) else {
raise LengthParseError(input~, expected~)
}
Rems(parse_number(input, digits, expected))
}
///|
pub fn AbsoluteLength::parse(
input : String,
) -> AbsoluteLength raise LengthParseError {
let expected = "number with 'px' or 'rem' suffix"
let trimmed = input.trim()
if trimmed.strip_suffix("rem") is Some(digits) {
AbsoluteLength::Rems(Rems(parse_number(input, digits, expected)))
} else if trimmed.strip_suffix("px") is Some(digits) {
AbsoluteLength::Pixels(Pixels(parse_number(input, digits, expected)))
} else {
raise LengthParseError(input~, expected~)
}
}
///|
pub fn DefiniteLength::parse(
input : String,
) -> DefiniteLength raise LengthParseError {
let expected = "number with 'px', 'rem', or '%' suffix"
let trimmed = input.trim()
if trimmed.strip_suffix("%") is Some(digits) {
Fraction(parse_number(input, digits, expected) / 100.0)
} else {
Absolute(
AbsoluteLength::parse(input) catch {
_ => raise LengthParseError(input~, expected~)
},
)
}
}
///|
pub fn Length::parse(input : String) -> Length raise LengthParseError {
let expected = "'auto' or number with 'px', 'rem', or '%' suffix"
if input.trim() == "auto" {
Auto
} else {
Definite(
DefiniteLength::parse(input) catch {
_ => raise LengthParseError(input~, expected~)
},
)
}
}
+246
View File
@@ -0,0 +1,246 @@
// Port of gpui/src/bounds_tree.rs: an R-tree-like structure that assigns draw
// orders. Each inserted rectangle gets an order one greater than the highest
// order of any earlier rectangle it overlaps (or the same order, if the
// overlapped primitive's kind may share a level with the new one). Primitives
// with the same order never overlap, so they can be batched freely.
///|
let max_children : Int32 = 12
///|
#derive(Eq, Compare)
priv struct Key {
ordering : Int32
kind : PrimitiveKind
}
///|
priv enum NodeKind {
Leaf(Key)
Internal(Array[Int32])
}
///|
priv struct Node[U] {
mut bounds : @geometry.Bounds[U]
mut max_key : Key
kind : NodeKind
}
///|
/// Assigns draw orders to rectangles; see the module comment.
pub struct BoundsTree[U] {
priv nodes : Array[Node[U]]
priv mut root : Int32?
priv mut max_leaf : Int32?
priv insert_path : Array[Int32]
}
///|
pub fn[U] BoundsTree::new() -> BoundsTree[U] {
{ nodes: [], root: None, max_leaf: None, insert_path: [], }
}
///|
pub fn[U] BoundsTree::clear(self : BoundsTree[U]) -> Unit {
self.nodes.clear()
self.root = None
self.max_leaf = None
self.insert_path.clear()
}
///|
/// Inserts `new_bounds` and returns its draw order (starting at 1).
pub fn[U : Add + Sub + Compare] BoundsTree::insert(
self : BoundsTree[U],
new_bounds : @geometry.Bounds[U],
kind : PrimitiveKind,
max_shared_kind : PrimitiveKind,
) -> Int32 {
let ordering = match self.find_max_key(new_bounds) {
None => 1
Some(max_key) =>
if max_key.kind <= max_shared_kind {
max_key.ordering
} else {
max_key.ordering + 1
}
}
let key = { ordering, kind, }
let new_leaf = self.insert_leaf(new_bounds, key)
match self.max_leaf {
None => self.max_leaf = Some(new_leaf)
Some(old) =>
if self.nodes[old].max_key < key {
self.max_leaf = Some(new_leaf)
}
}
ordering
}
///|
fn[U : Add + Compare] BoundsTree::find_max_key(
self : BoundsTree[U],
query : @geometry.Bounds[U],
) -> Key? {
guard self.root is Some(root) else { return None }
// Fast path: the most recent maximum often overlaps the query.
if self.max_leaf is Some(max_idx) {
let max_node = self.nodes[max_idx]
if query.intersects(max_node.bounds) {
return Some(max_node.max_key)
}
}
let stack = [root]
let mut max_found : Key? = None
while stack.pop() is Some(idx) {
let node = self.nodes[idx]
if max_found is Some(found) && node.max_key <= found {
continue
}
if !query.intersects(node.bounds) {
continue
}
match node.kind {
Leaf(key) =>
max_found = match max_found {
Some(found) if found >= key => Some(found)
_ => Some(key)
}
Internal(children) =>
for child in children {
let child_key = self.nodes[child].max_key
let worth_visiting = match max_found {
None => true
Some(found) => child_key > found
}
if worth_visiting {
stack.push(child)
}
}
}
}
max_found
}
///|
fn[U : Add + Sub + Compare] BoundsTree::insert_leaf(
self : BoundsTree[U],
bounds : @geometry.Bounds[U],
key : Key,
) -> Int32 {
let new_leaf = self.nodes.length()
self.nodes.push({ bounds, max_key: key, kind: Leaf(key), })
guard self.root is Some(root) else {
self.root = Some(new_leaf)
return new_leaf
}
if self.nodes[root].kind is Leaf(_) {
let root_node = self.nodes[root]
let children = if key > root_node.max_key {
[root, new_leaf]
} else {
[new_leaf, root]
}
let new_root = self.nodes.length()
self.nodes.push({
bounds: root_node.bounds.union(bounds),
max_key: if root_node.max_key >= key {
root_node.max_key
} else {
key
},
kind: Internal(children),
})
self.root = Some(new_root)
return new_leaf
}
self.insert_path.clear()
let mut current = root
while true {
guard self.nodes[current].kind is Internal(children) else {
abort("BoundsTree: should only traverse internal nodes")
}
self.insert_path.push(current)
// Choose the child whose bounds grow the least (half-perimeter heuristic).
let mut best_child = children[0]
let mut best_pos = 0
let mut best_cost = bounds
.union(self.nodes[best_child].bounds)
.half_perimeter()
for pos in 1..<children.length() {
let child = children[pos]
let cost = bounds.union(self.nodes[child].bounds).half_perimeter()
if cost < best_cost {
best_cost = cost
best_child = child
best_pos = pos
}
}
if self.nodes[best_child].kind is Internal(_) {
current = best_child
continue
}
if children.length() < max_children {
// Add the leaf directly; keep the child with the max key last.
let node = self.nodes[current]
children.push(new_leaf)
if key <= node.max_key {
let last = children.length() - 1
children.swap(last - 1, last)
}
node.bounds = node.bounds.union(bounds)
if key > node.max_key {
node.max_key = key
}
} else {
// Full: replace the best leaf with an internal node holding both.
let sibling = self.nodes[best_child]
let new_children = if key > sibling.max_key {
[best_child, new_leaf]
} else {
[new_leaf, best_child]
}
let new_internal = self.nodes.length()
let new_internal_max = if sibling.max_key >= key {
sibling.max_key
} else {
key
}
self.nodes.push({
bounds: sibling.bounds.union(bounds),
max_key: new_internal_max,
kind: Internal(new_children),
})
let parent = self.nodes[current]
children[best_pos] = new_internal
if new_internal_max > parent.max_key {
children.swap(best_pos, children.length() - 1)
}
}
break
}
// Propagate bounds and max keys up the insertion path.
let mut updated_child : Int32? = None
for i = self.insert_path.length() - 1; i >= 0; i = i - 1 {
let node_idx = self.insert_path[i]
let node = self.nodes[node_idx]
node.bounds = node.bounds.union(bounds)
if node.max_key < key {
node.max_key = key
if updated_child is Some(child) && node.kind is Internal(children) {
let last = children.length() - 1
for pos, c in children {
if c == child {
if pos != last {
children.swap(pos, last)
}
break
}
}
}
}
updated_child = Some(node_idx)
}
new_leaf
}
+9
View File
@@ -0,0 +1,9 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/color",
"moonbitlang/core/math",
}
import {
"moonbitlang/core/random",
} for "test"
+209
View File
@@ -0,0 +1,209 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/scene"
import {
"experiments/gpui/color",
"experiments/gpui/geometry",
"moonbitlang/core/debug",
}
// Values
pub fn quad_depth(Int32, Double) -> Double
pub fn quad_depth_scale(Int32) -> Double
// Errors
// Types and methods
#derive(Eq, Hash, @debug.Debug)
pub(all) struct AtlasTextureId {
index : Int32
kind : AtlasTextureKind
}
#derive(Compare, Eq, Hash, @debug.Debug)
pub(all) enum AtlasTextureKind {
Monochrome
Polychrome
Subpixel
}
#derive(Eq, Hash, @debug.Debug)
pub(all) struct AtlasTile {
texture_id : AtlasTextureId
tile_id : Int32
padding : Int32
bounds : @geometry.Bounds[@geometry.DevicePixels]
}
#derive(Eq, Hash, @debug.Debug)
pub(all) enum BorderStyle {
Solid
Dashed
}
pub impl Default for BorderStyle
pub struct BoundsTree[U] {
// private fields
}
pub fn[U] BoundsTree::clear(Self[U]) -> Unit
pub fn[U : Add + Sub + Compare] BoundsTree::insert(Self[U], @geometry.Bounds[U], PrimitiveKind, PrimitiveKind) -> Int32
pub fn[U] BoundsTree::new() -> Self[U]
#derive(Eq, @debug.Debug)
pub(all) struct MonochromeSprite {
order : Int32
tile : AtlasTile
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
color : @color.Hsla
transformation : TransformationMatrix
}
#derive(Eq, @debug.Debug)
pub(all) struct PaintedPath {
order : Int32
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
color : @color.Background
even_odd : Bool
contours : Array[Array[@geometry.Point[@geometry.ScaledPixels]]]
}
pub fn PaintedPath::new(Array[Array[@geometry.Point[@geometry.Pixels]]], Double, @geometry.ContentMask[@geometry.Pixels], @color.Background, even_odd? : Bool) -> Self
#derive(Eq, @debug.Debug)
pub(all) struct PolychromeSprite {
order : Int32
tile : AtlasTile
grayscale : Bool
opacity : Double
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
corner_radii : @geometry.Corners[@geometry.ScaledPixels]
}
#derive(Eq, @debug.Debug)
pub(all) enum Primitive {
Shadow(Shadow)
Quad(Quad)
Path(PaintedPath)
Underline(Underline)
MonochromeSprite(MonochromeSprite)
SubpixelSprite(SubpixelSprite)
PolychromeSprite(PolychromeSprite)
}
pub fn Primitive::bounds(Self) -> @geometry.Bounds[@geometry.ScaledPixels]
pub fn Primitive::clipped_bounds(Self) -> @geometry.Bounds[@geometry.ScaledPixels]
pub fn Primitive::content_mask(Self) -> @geometry.ContentMask[@geometry.ScaledPixels]
pub fn Primitive::kind(Self) -> PrimitiveKind
#derive(Eq, @debug.Debug)
pub(all) enum PrimitiveBatch {
Shadows(start~ : Int32, end~ : Int32)
Quads(start~ : Int32, end~ : Int32)
Paths(start~ : Int32, end~ : Int32)
Underlines(start~ : Int32, end~ : Int32)
MonochromeSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
SubpixelSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
PolychromeSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
}
pub fn PrimitiveBatch::label(Self) -> String
#derive(Compare, Eq, Hash, @debug.Debug)
pub(all) enum PrimitiveKind {
Shadow
Quad
Path
Underline
MonochromeSprite
SubpixelSprite
PolychromeSprite
}
pub fn PrimitiveKind::max_shared_kind(Self) -> Self
#derive(Default, Eq, @debug.Debug)
pub(all) struct Quad {
order : Int32
border_style : BorderStyle
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
background : @color.Background
border_color : @color.Hsla
corner_radii : @geometry.Corners[@geometry.ScaledPixels]
border_widths : @geometry.Edges[@geometry.ScaledPixels]
}
pub struct Scene {
shadows : Array[Shadow]
quads : Array[Quad]
paths : Array[PaintedPath]
underlines : Array[Underline]
monochrome_sprites : Array[MonochromeSprite]
subpixel_sprites : Array[SubpixelSprite]
polychrome_sprites : Array[PolychromeSprite]
// private fields
}
pub fn Scene::batches(Self) -> Array[PrimitiveBatch]
pub fn Scene::clear(Self) -> Unit
pub fn Scene::finish(Self) -> Unit
pub fn Scene::insert_primitive(Self, Primitive) -> Unit
pub fn Scene::len(Self) -> Int32
pub fn Scene::new() -> Self
pub fn Scene::pop_layer(Self) -> Unit
pub fn Scene::push_layer(Self) -> Unit
pub fn Scene::replay(Self, Self, Int32, Int32) -> Unit
#derive(Default, Eq, @debug.Debug)
pub(all) struct Shadow {
order : Int32
blur_radius : @geometry.ScaledPixels
bounds : @geometry.Bounds[@geometry.ScaledPixels]
corner_radii : @geometry.Corners[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
color : @color.Hsla
shape_bounds : @geometry.Bounds[@geometry.ScaledPixels]
shape_corner_radii : @geometry.Corners[@geometry.ScaledPixels]
inset : Bool
}
#derive(Eq, @debug.Debug)
pub(all) struct SubpixelSprite {
order : Int32
tile : AtlasTile
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
color : @color.Hsla
transformation : TransformationMatrix
}
#derive(Eq, @debug.Debug)
pub(all) struct TransformationMatrix {
xx : Double
xy : Double
yx : Double
yy : Double
tx : Double
ty : Double
}
pub fn TransformationMatrix::apply(Self, @geometry.Point[@geometry.Pixels]) -> @geometry.Point[@geometry.Pixels]
pub fn TransformationMatrix::compose(Self, Self) -> Self
pub fn TransformationMatrix::rotate(Self, @geometry.Radians) -> Self
pub fn TransformationMatrix::scale(Self, @geometry.Size[Double]) -> Self
pub fn TransformationMatrix::transform_bounds(Self, @geometry.Bounds[@geometry.ScaledPixels]) -> @geometry.Bounds[@geometry.ScaledPixels]
pub fn TransformationMatrix::translate(Self, @geometry.Point[@geometry.ScaledPixels]) -> Self
pub fn TransformationMatrix::unit() -> Self
pub impl Default for TransformationMatrix
#derive(Default, Eq, @debug.Debug)
pub(all) struct Underline {
order : Int32
bounds : @geometry.Bounds[@geometry.ScaledPixels]
content_mask : @geometry.ContentMask[@geometry.ScaledPixels]
color : @color.Hsla
thickness : @geometry.ScaledPixels
wavy : Bool
}
// Type aliases
// Traits
+437
View File
@@ -0,0 +1,437 @@
// Scene primitives, ported from gpui/src/scene.rs (and AtlasTile & co. from
// gpui/src/platform.rs).
//
// Deviations from GPUI (see docs/PORTING.md, "Scene"):
// - Primitives are plain immutable records; GPUI's `#[repr(C)]` padding fields
// (`pad`, `PaddedBool32`) are dropped. A renderer packs them into GPU
// buffers explicitly.
// - `PaintedPath` stores flattened polygon contours instead of GPUI's tiled
// path representation (`PathTiles`, built by lyon in `path_builder.rs`);
// tiling belongs to the renderer milestone.
// - `PaintSurface` (macOS CVPixelBuffer) and `PaintNativeView` (embedded native
// views) are not ported yet. Sprite animations are not ported yet.
///|
type ScaledPixels = @geometry.ScaledPixels
///|
type Bounds = @geometry.Bounds[ScaledPixels]
///|
type ContentMask = @geometry.ContentMask[ScaledPixels]
///|
/// The kind of a primitive. The declaration order is significant: it breaks
/// ties between primitives with equal draw order (GPUI derives `Ord`).
#derive(Eq, Compare, Hash, Debug)
pub(all) enum PrimitiveKind {
Shadow
Quad
Path
Underline
MonochromeSprite
SubpixelSprite
PolychromeSprite
}
///|
/// The highest kind that may share a draw order with this kind without being
/// drawn in the wrong order. Glyph sprites can share a level with underlines
/// and with each other because they are always drawn after them.
pub fn PrimitiveKind::max_shared_kind(self : PrimitiveKind) -> PrimitiveKind {
match self {
MonochromeSprite => Underline
SubpixelSprite => MonochromeSprite
PolychromeSprite => SubpixelSprite
kind => kind
}
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum BorderStyle {
Solid
Dashed
}
///|
pub impl Default for BorderStyle with fn default() {
Solid
}
///|
/// A 2D affine transformation: `[[xx, xy], [yx, yy]]` rotation/scale plus a
/// translation `(tx, ty)`.
#derive(Eq, Debug)
pub(all) struct TransformationMatrix {
xx : Double
xy : Double
yx : Double
yy : Double
tx : Double
ty : Double
}
///|
pub fn TransformationMatrix::unit() -> TransformationMatrix {
{ xx: 1.0, xy: 0.0, yx: 0.0, yy: 1.0, tx: 0.0, ty: 0.0, }
}
///|
pub impl Default for TransformationMatrix with fn default() {
TransformationMatrix::unit()
}
///|
/// `self` followed by `other` applied first (matrix product `self * other`).
pub fn TransformationMatrix::compose(
self : TransformationMatrix,
other : TransformationMatrix,
) -> TransformationMatrix {
if other == TransformationMatrix::unit() {
return self
}
{
xx: self.xx * other.xx + self.xy * other.yx,
xy: self.xx * other.xy + self.xy * other.yy,
yx: self.yx * other.xx + self.yy * other.yx,
yy: self.yx * other.xy + self.yy * other.yy,
tx: self.tx + self.xx * other.tx + self.xy * other.ty,
ty: self.ty + self.yx * other.tx + self.yy * other.ty,
}
}
///|
pub fn TransformationMatrix::translate(
self : TransformationMatrix,
point : @geometry.Point[ScaledPixels],
) -> TransformationMatrix {
self.compose({ ..TransformationMatrix::unit(), tx: point.x.0, ty: point.y.0, })
}
///|
pub fn TransformationMatrix::rotate(
self : TransformationMatrix,
angle : @geometry.Radians,
) -> TransformationMatrix {
let cos = @math.cos(angle.0)
let sin = @math.sin(angle.0)
self.compose({ xx: cos, xy: -sin, yx: sin, yy: cos, tx: 0.0, ty: 0.0, })
}
///|
pub fn TransformationMatrix::scale(
self : TransformationMatrix,
size : @geometry.Size[Double],
) -> TransformationMatrix {
self.compose({
xx: size.width,
xy: 0.0,
yx: 0.0,
yy: size.height,
tx: 0.0,
ty: 0.0,
})
}
///|
/// Applies the transformation to a point.
pub fn TransformationMatrix::apply(
self : TransformationMatrix,
point : @geometry.Point[@geometry.Pixels],
) -> @geometry.Point[@geometry.Pixels] {
{
x: @geometry.px(self.tx + self.xx * point.x.0 + self.xy * point.y.0),
y: @geometry.px(self.ty + self.yx * point.x.0 + self.yy * point.y.0),
}
}
///|
/// The axis-aligned bounding box of the transformed bounds.
pub fn TransformationMatrix::transform_bounds(
self : TransformationMatrix,
bounds : Bounds,
) -> Bounds {
if self == TransformationMatrix::unit() {
return bounds
}
let transform = fn(
corner : @geometry.Point[ScaledPixels],
) -> @geometry.Point[ScaledPixels] {
{
x: ScaledPixels(self.xx * corner.x.0 + self.xy * corner.y.0 + self.tx),
y: ScaledPixels(self.yx * corner.x.0 + self.yy * corner.y.0 + self.ty),
}
}
let first = transform(bounds.origin)
let mut top_left = first
let mut bottom_right = first
for
corner in [bounds.top_right(), bounds.bottom_left(), bounds.bottom_right()] {
let p = transform(corner)
top_left = top_left.min(p)
bottom_right = bottom_right.max(p)
}
@geometry.Bounds::from_corners(top_left, bottom_right)
}
// ---------------------------------------------------------------------------
// Atlas references (GPUI: platform.rs). Will move to the platform package once
// it exists; kept here because sprites reference them.
// ---------------------------------------------------------------------------
///|
#derive(Eq, Compare, Hash, Debug)
pub(all) enum AtlasTextureKind {
Monochrome
Polychrome
Subpixel
}
///|
#derive(Eq, Hash, Debug)
pub(all) struct AtlasTextureId {
/// The index of this texture in the atlas.
index : Int32
/// The kind of content stored in this texture.
kind : AtlasTextureKind
}
///|
/// A rectangle allocated in an atlas texture.
#derive(Eq, Hash, Debug)
pub(all) struct AtlasTile {
texture_id : AtlasTextureId
tile_id : Int32
/// Padding around the tile content, in device pixels.
padding : Int32
bounds : @geometry.Bounds[@geometry.DevicePixels]
}
// ---------------------------------------------------------------------------
// Primitives
// ---------------------------------------------------------------------------
///|
/// A rectangle with optional rounded corners, borders and a fill.
#derive(Eq, Default, Debug)
pub(all) struct Quad {
order : Int32
border_style : BorderStyle
bounds : Bounds
content_mask : ContentMask
background : @color.Background
border_color : @color.Hsla
corner_radii : @geometry.Corners[ScaledPixels]
border_widths : @geometry.Edges[ScaledPixels]
}
///|
/// A (box) shadow cast by, or inset into, a rounded rectangle.
#derive(Eq, Default, Debug)
pub(all) struct Shadow {
order : Int32
blur_radius : ScaledPixels
bounds : Bounds
corner_radii : @geometry.Corners[ScaledPixels]
content_mask : ContentMask
color : @color.Hsla
/// The shape casting the shadow (used to clip inset shadows).
shape_bounds : Bounds
shape_corner_radii : @geometry.Corners[ScaledPixels]
inset : Bool
}
///|
/// A straight or wavy text underline (also used for strikethrough).
#derive(Eq, Default, Debug)
pub(all) struct Underline {
order : Int32
bounds : Bounds
content_mask : ContentMask
color : @color.Hsla
thickness : ScaledPixels
wavy : Bool
}
///|
/// A single-channel (alpha mask) sprite tinted with `color`, e.g. a glyph.
#derive(Eq, Debug)
pub(all) struct MonochromeSprite {
order : Int32
tile : AtlasTile
bounds : Bounds
content_mask : ContentMask
color : @color.Hsla
transformation : TransformationMatrix
}
///|
/// A glyph rendered with per-channel (subpixel) coverage.
#derive(Eq, Debug)
pub(all) struct SubpixelSprite {
order : Int32
tile : AtlasTile
bounds : Bounds
content_mask : ContentMask
color : @color.Hsla
transformation : TransformationMatrix
}
///|
/// A full-color sprite, e.g. an image or an emoji.
#derive(Eq, Debug)
pub(all) struct PolychromeSprite {
order : Int32
tile : AtlasTile
grayscale : Bool
opacity : Double
bounds : Bounds
content_mask : ContentMask
corner_radii : @geometry.Corners[ScaledPixels]
}
///|
/// A filled vector path made of closed polygon contours.
#derive(Eq, Debug)
pub(all) struct PaintedPath {
order : Int32
/// Bounding box of all contours.
bounds : Bounds
content_mask : ContentMask
color : @color.Background
/// Even-odd fill rule if true, non-zero winding otherwise.
even_odd : Bool
contours : Array[Array[@geometry.Point[ScaledPixels]]]
}
///|
/// Creates a path primitive from contours given in logical pixels.
///
/// Fails loudly if there are no points: an empty path has no bounds and would
/// silently disappear.
pub fn PaintedPath::new(
contours : Array[Array[@geometry.Point[@geometry.Pixels]]],
scale_factor : Double,
content_mask : @geometry.ContentMask[@geometry.Pixels],
color : @color.Background,
even_odd~ : Bool = false,
) -> PaintedPath {
let scaled = contours.map(fn(contour) {
contour.map(fn(p) { p.scale(scale_factor) })
})
let mut top_left : @geometry.Point[ScaledPixels]? = None
let mut bottom_right : @geometry.Point[ScaledPixels]? = None
for contour in scaled {
for p in contour {
top_left = Some(
match top_left {
None => p
Some(tl) => tl.min(p)
},
)
bottom_right = Some(
match bottom_right {
None => p
Some(br) => br.max(p)
},
)
}
}
guard top_left is Some(tl) && bottom_right is Some(br) else {
abort("PaintedPath::new: path has no points")
}
{
order: 0,
bounds: @geometry.Bounds::from_corners(tl, br),
content_mask: content_mask.scale(scale_factor),
color,
even_odd,
contours: scaled,
}
}
///|
/// Any primitive that can be inserted into a `Scene`.
#derive(Eq, Debug)
pub(all) enum Primitive {
Shadow(Shadow)
Quad(Quad)
Path(PaintedPath)
Underline(Underline)
MonochromeSprite(MonochromeSprite)
SubpixelSprite(SubpixelSprite)
PolychromeSprite(PolychromeSprite)
}
///|
pub fn Primitive::kind(self : Primitive) -> PrimitiveKind {
match self {
Shadow(_) => PrimitiveKind::Shadow
Quad(_) => PrimitiveKind::Quad
Path(_) => PrimitiveKind::Path
Underline(_) => PrimitiveKind::Underline
MonochromeSprite(_) => PrimitiveKind::MonochromeSprite
SubpixelSprite(_) => PrimitiveKind::SubpixelSprite
PolychromeSprite(_) => PrimitiveKind::PolychromeSprite
}
}
///|
pub fn Primitive::bounds(self : Primitive) -> Bounds {
match self {
Shadow(p) => p.bounds
Quad(p) => p.bounds
Path(p) => p.bounds
Underline(p) => p.bounds
MonochromeSprite(p) => p.bounds
SubpixelSprite(p) => p.bounds
PolychromeSprite(p) => p.bounds
}
}
///|
pub fn Primitive::content_mask(self : Primitive) -> ContentMask {
match self {
Shadow(p) => p.content_mask
Quad(p) => p.content_mask
Path(p) => p.content_mask
Underline(p) => p.content_mask
MonochromeSprite(p) => p.content_mask
SubpixelSprite(p) => p.content_mask
PolychromeSprite(p) => p.content_mask
}
}
///|
fn Primitive::transformation(self : Primitive) -> TransformationMatrix {
match self {
MonochromeSprite(p) => p.transformation
SubpixelSprite(p) => p.transformation
_ => TransformationMatrix::unit()
}
}
///|
/// The bounds actually affected by this primitive: transformed bounds clipped
/// to the content mask.
pub fn Primitive::clipped_bounds(self : Primitive) -> Bounds {
self
.transformation()
.transform_bounds(self.bounds())
.intersect(self.content_mask().bounds)
}
///|
/// The same primitive with its draw order replaced.
fn Primitive::with_order(self : Primitive, order : Int32) -> Primitive {
match self {
Shadow(p) => Shadow({ ..p, order, })
Quad(p) => Quad({ ..p, order, })
Path(p) => Path({ ..p, order, })
Underline(p) => Underline({ ..p, order, })
MonochromeSprite(p) => MonochromeSprite({ ..p, order, })
SubpixelSprite(p) => SubpixelSprite({ ..p, order, })
PolychromeSprite(p) => PolychromeSprite({ ..p, order, })
}
}
+425
View File
@@ -0,0 +1,425 @@
// Port of `Scene` from gpui/src/scene.rs: collects primitives for one frame,
// assigns draw orders via `BoundsTree`, and groups them into batches a
// renderer can draw with one pipeline/texture binding each.
///|
priv enum PaintOperation {
Op(Primitive)
StartLayer
EndLayer
}
///|
priv struct Layer {
/// Index ranges `[start, end)` into `paint_operations`.
ranges : Array[(Int32, Int32)]
mut bounds : Bounds
mut max_kind : PrimitiveKind
mut max_shared_kind : PrimitiveKind
}
///|
/// The primitives painted in one frame, sorted for rendering by `finish`.
pub struct Scene {
priv paint_operations : Array[PaintOperation]
priv primitive_bounds : BoundsTree[ScaledPixels]
priv layer_stack : Array[Int32]
priv layers : Array[Layer]
shadows : Array[Shadow]
quads : Array[Quad]
paths : Array[PaintedPath]
underlines : Array[Underline]
monochrome_sprites : Array[MonochromeSprite]
subpixel_sprites : Array[SubpixelSprite]
polychrome_sprites : Array[PolychromeSprite]
}
///|
pub fn Scene::new() -> Scene {
{
paint_operations: [],
primitive_bounds: BoundsTree::new(),
layer_stack: [],
layers: [],
shadows: [],
quads: [],
paths: [],
underlines: [],
monochrome_sprites: [],
subpixel_sprites: [],
polychrome_sprites: [],
}
}
///|
pub fn Scene::clear(self : Scene) -> Unit {
self.paint_operations.clear()
self.primitive_bounds.clear()
self.layer_stack.clear()
self.layers.clear()
self.shadows.clear()
self.quads.clear()
self.paths.clear()
self.underlines.clear()
self.monochrome_sprites.clear()
self.subpixel_sprites.clear()
self.polychrome_sprites.clear()
}
///|
/// Number of recorded paint operations (primitives plus layer markers). Views
/// use ranges of these to replay cached paints into the next frame.
pub fn Scene::len(self : Scene) -> Int32 {
self.paint_operations.length()
}
///|
/// Starts a layer: primitives inserted until the matching `pop_layer` are
/// ordered as one unit, above everything they overlap that came before.
pub fn Scene::push_layer(self : Scene) -> Unit {
self.layer_stack.push(self.layers.length())
self.layers.push({
ranges: [],
bounds: Default::default(),
max_kind: PrimitiveKind::Shadow,
// The highest kind, i.e. "no restriction yet" for the minimum below.
max_shared_kind: PrimitiveKind::PolychromeSprite,
})
self.paint_operations.push(StartLayer)
}
///|
pub fn Scene::pop_layer(self : Scene) -> Unit {
guard self.layer_stack.pop() is Some(_) else {
abort("Scene::pop_layer without matching push_layer")
}
if self.layer_stack.is_empty() {
let layers = self.layers.copy()
self.layers.clear()
for layer in layers {
self.insert_layer(layer)
}
}
self.paint_operations.push(EndLayer)
}
///|
fn Scene::insert_layer(self : Scene, layer : Layer) -> Unit {
if layer.ranges.is_empty() {
return
}
let order = self.primitive_bounds.insert(
layer.bounds,
layer.max_kind,
layer.max_shared_kind,
)
for range in layer.ranges {
let (start, end) = range
for index in start..<end {
if self.paint_operations[index] is Op(primitive) {
self.push_primitive(primitive, order)
}
}
}
}
///|
/// Adds a primitive. Primitives whose clipped bounds are empty are dropped
/// (they would not be visible).
pub fn Scene::insert_primitive(self : Scene, primitive : Primitive) -> Unit {
let clipped_bounds = primitive.clipped_bounds()
if clipped_bounds.is_empty() {
return
}
let kind = primitive.kind()
match self.layer_stack.last() {
Some(layer_index) => {
let layer = self.layers[layer_index]
layer.bounds = layer.bounds.join(clipped_bounds)
if kind > layer.max_kind {
layer.max_kind = kind
}
if kind.max_shared_kind() < layer.max_shared_kind {
layer.max_shared_kind = kind.max_shared_kind()
}
let index = self.paint_operations.length()
match layer.ranges.last() {
Some((start, end)) if end == index =>
layer.ranges[layer.ranges.length() - 1] = (start, end + 1)
_ => layer.ranges.push((index, index + 1))
}
}
None => {
let order = self.primitive_bounds.insert(
clipped_bounds,
kind,
kind.max_shared_kind(),
)
self.push_primitive(primitive, order)
}
}
self.paint_operations.push(Op(primitive))
}
///|
fn Scene::push_primitive(
self : Scene,
primitive : Primitive,
order : Int32,
) -> Unit {
match primitive.with_order(order) {
Shadow(p) => self.shadows.push(p)
Quad(p) => self.quads.push(p)
Path(p) => self.paths.push(p)
Underline(p) => self.underlines.push(p)
MonochromeSprite(p) => self.monochrome_sprites.push(p)
SubpixelSprite(p) => self.subpixel_sprites.push(p)
PolychromeSprite(p) => self.polychrome_sprites.push(p)
}
}
///|
/// Re-inserts the paint operations `[start, end)` of `prev_scene` (used to
/// reuse the paint output of cached views).
pub fn Scene::replay(
self : Scene,
prev_scene : Scene,
start : Int32,
end : Int32,
) -> Unit {
guard start >= 0 &&
start <= end &&
end <= prev_scene.paint_operations.length() else {
abort(
"Scene::replay: range \{start}..\{end} out of bounds (len \{prev_scene.paint_operations.length()})",
)
}
for index in start..<end {
match prev_scene.paint_operations[index] {
Op(primitive) => self.insert_primitive(primitive)
StartLayer => self.push_layer()
EndLayer => self.pop_layer()
}
}
}
///|
/// Stable sort by `(major, minor)`; equal keys keep their insertion order.
fn[T] sort_by_order(items : Array[T], key : (T) -> (Int32, Int32)) -> Unit {
let keyed = items.mapi(fn(i, item) {
let (major, minor) = key(item)
(major, minor, i)
})
keyed.sort()
let sorted = keyed.map(fn(k) { items[k.2] })
for i, item in sorted {
items[i] = item
}
}
///|
/// Finishes the frame: sorts every primitive list by draw order (sprites also
/// by texture, so batches can bind one texture). Fails loudly if layers are
/// unbalanced.
pub fn Scene::finish(self : Scene) -> Unit {
guard self.layer_stack.is_empty() else {
abort("Scene::finish: unbalanced scene layers")
}
sort_by_order(self.shadows, fn(p) { (p.order, 0) })
sort_by_order(self.quads, fn(p) { (p.order, 0) })
sort_by_order(self.paths, fn(p) { (p.order, 0) })
sort_by_order(self.underlines, fn(p) { (p.order, 0) })
sort_by_order(self.monochrome_sprites, fn(p) {
(p.order, p.tile.texture_id.index)
})
sort_by_order(self.subpixel_sprites, fn(p) {
(p.order, p.tile.texture_id.index)
})
sort_by_order(self.polychrome_sprites, fn(p) {
(p.order, p.tile.texture_id.index)
})
}
// ---------------------------------------------------------------------------
// Batching
// ---------------------------------------------------------------------------
///|
/// A run of primitives of one kind that can be drawn together. Ranges are
/// `[start, end)` into the corresponding `Scene` array.
#derive(Eq, Debug)
pub(all) enum PrimitiveBatch {
Shadows(start~ : Int32, end~ : Int32)
Quads(start~ : Int32, end~ : Int32)
Paths(start~ : Int32, end~ : Int32)
Underlines(start~ : Int32, end~ : Int32)
MonochromeSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
SubpixelSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
PolychromeSprites(texture_id~ : AtlasTextureId, start~ : Int32, end~ : Int32)
}
///|
/// A short human-readable description, e.g. `"quads (3)"`.
pub fn PrimitiveBatch::label(self : PrimitiveBatch) -> String {
match self {
Shadows(start~, end~) => "shadows (\{end - start})"
Quads(start~, end~) => "quads (\{end - start})"
Paths(start~, end~) => "paths (\{end - start})"
Underlines(start~, end~) => "underlines (\{end - start})"
MonochromeSprites(texture_id~, start~, end~) =>
"monochrome sprites (\{end - start}) on atlas \{texture_id.index}"
SubpixelSprites(texture_id~, start~, end~) =>
"subpixel sprites (\{end - start}) on atlas \{texture_id.index}"
PolychromeSprites(texture_id~, start~, end~) =>
"polychrome sprites (\{end - start}) on atlas \{texture_id.index}"
}
}
///|
let all_kinds : Array[PrimitiveKind] = [
Shadow,
Quad,
Path,
Underline,
MonochromeSprite,
SubpixelSprite,
PolychromeSprite,
]
///|
fn Scene::count_of(self : Scene, kind : PrimitiveKind) -> Int32 {
match kind {
Shadow => self.shadows.length()
Quad => self.quads.length()
Path => self.paths.length()
Underline => self.underlines.length()
MonochromeSprite => self.monochrome_sprites.length()
SubpixelSprite => self.subpixel_sprites.length()
PolychromeSprite => self.polychrome_sprites.length()
}
}
///|
fn Scene::order_at(self : Scene, kind : PrimitiveKind, index : Int32) -> Int32 {
match kind {
Shadow => self.shadows[index].order
Quad => self.quads[index].order
Path => self.paths[index].order
Underline => self.underlines[index].order
MonochromeSprite => self.monochrome_sprites[index].order
SubpixelSprite => self.subpixel_sprites[index].order
PolychromeSprite => self.polychrome_sprites[index].order
}
}
///|
fn Scene::texture_at(
self : Scene,
kind : PrimitiveKind,
index : Int32,
) -> AtlasTextureId? {
match kind {
MonochromeSprite => Some(self.monochrome_sprites[index].tile.texture_id)
SubpixelSprite => Some(self.subpixel_sprites[index].tile.texture_id)
PolychromeSprite => Some(self.polychrome_sprites[index].tile.texture_id)
_ => None
}
}
///|
fn kind_index(kind : PrimitiveKind) -> Int32 {
match kind {
Shadow => 0
Quad => 1
Path => 2
Underline => 3
MonochromeSprite => 4
SubpixelSprite => 5
PolychromeSprite => 6
}
}
///|
let no_order : Int32 = 2147483647
///|
/// Groups the (finished) scene into batches in painting order. Mirrors GPUI's
/// `BatchIterator`: repeatedly take the kind with the lowest `(order, kind)`
/// head, and extend the batch while its next element still sorts before the
/// head of every other kind (and, for sprites, uses the same texture).
pub fn Scene::batches(self : Scene) -> Array[PrimitiveBatch] {
let cursors = all_kinds.map(fn(_) { 0 })
let batches = []
let head = fn(kind : PrimitiveKind) -> (Int32, PrimitiveKind) {
let i = cursors[kind_index(kind)]
if i < self.count_of(kind) {
(self.order_at(kind, i), kind)
} else {
(no_order, kind)
}
}
while true {
let heads = all_kinds.map(head)
heads.sort()
let (first_order, batch_kind) = heads[0]
if first_order == no_order {
break
}
let limit = heads[1]
let k = kind_index(batch_kind)
let start = cursors[k]
let texture_id = self.texture_at(batch_kind, start)
let count = self.count_of(batch_kind)
let mut end = start + 1
while end < count &&
(self.order_at(batch_kind, end), batch_kind) < limit &&
self.texture_at(batch_kind, end) == texture_id {
end = end + 1
}
cursors[k] = end
let batch = match (batch_kind, texture_id) {
(Shadow, _) => Shadows(start~, end~)
(Quad, _) => Quads(start~, end~)
(Path, _) => Paths(start~, end~)
(Underline, _) => Underlines(start~, end~)
(MonochromeSprite, Some(texture_id)) =>
MonochromeSprites(texture_id~, start~, end~)
(SubpixelSprite, Some(texture_id)) =>
SubpixelSprites(texture_id~, start~, end~)
(PolychromeSprite, Some(texture_id)) =>
PolychromeSprites(texture_id~, start~, end~)
(_, None) => abort("Scene::batches: sprite without texture")
}
batches.push(batch)
}
batches
}
// ---------------------------------------------------------------------------
// Depth helpers used by renderers that z-test quads.
// ---------------------------------------------------------------------------
///|
/// Scale such that `quad_depth(i, scale)` stays below 1.0 for every quad.
pub fn quad_depth_scale(quad_count : Int32) -> Double {
let capped = if quad_count < (1 << 24) - 1 {
quad_count
} else {
(1 << 24) - 1
}
let mut denominator = 1
while denominator < capped + 1 {
denominator = denominator * 2
}
1.0 / denominator.to_double()
}
///|
pub fn quad_depth(quad_id : Int32, scale : Double) -> Double {
let depth = (quad_id + 1).to_double() * scale
if depth < 1.0 {
depth
} else {
1.0
}
}
+379
View File
@@ -0,0 +1,379 @@
///|
fn sb(
x : Double,
y : Double,
w : Double,
h : Double,
) -> @geometry.Bounds[@geometry.ScaledPixels] {
{
origin: { x: ScaledPixels(x), y: ScaledPixels(y), },
size: { width: ScaledPixels(w), height: ScaledPixels(h), },
}
}
///|
fn quad_at(x : Double, y~ : Double = 0.0) -> @scene.Primitive {
let bounds = sb(x, y, 10.0, 10.0)
Quad({ ..Default::default(), bounds, content_mask: { bounds, }, })
}
///|
fn shadow_at(x : Double) -> @scene.Primitive {
let bounds = sb(x, 0.0, 10.0, 10.0)
Shadow({ ..Default::default(), bounds, content_mask: { bounds, }, })
}
///|
fn underline_at(x : Double) -> @scene.Primitive {
let bounds = sb(x, 0.0, 10.0, 10.0)
Underline({
..Default::default(),
bounds,
content_mask: { bounds, },
thickness: ScaledPixels(1.0),
})
}
///|
fn glyph_at(x : Double, texture : Int32) -> @scene.Primitive {
let bounds = sb(x, 0.0, 10.0, 10.0)
MonochromeSprite({
order: 0,
tile: {
texture_id: { index: texture, kind: Monochrome, },
tile_id: 0,
padding: 0,
bounds: Default::default(),
},
bounds,
content_mask: { bounds, },
color: @color.black(),
transformation: @scene.TransformationMatrix::unit(),
})
}
///|
fn labels(scene : @scene.Scene) -> Array[String] {
scene.finish()
scene.batches().map(fn(batch) { batch.label() })
}
///|
/// Port of GPUI's bounds_tree `test_insert`.
test "bounds tree assigns increasing orders to overlapping bounds" {
let tree : @scene.BoundsTree[Double] = @scene.BoundsTree::new()
let b = fn(x : Double, y : Double) -> @geometry.Bounds[Double] {
{ origin: { x, y, }, size: { width: 10.0, height: 10.0, }, }
}
assert_eq(tree.insert(b(0.0, 0.0), Quad, Shadow), 1)
assert_eq(tree.insert(b(5.0, 5.0), Quad, Shadow), 2)
assert_eq(tree.insert(b(10.0, 10.0), Quad, Shadow), 3)
// Non-overlapping bounds reuse orders.
assert_eq(tree.insert(b(20.0, 20.0), Quad, Shadow), 1)
assert_eq(tree.insert(b(40.0, 40.0), Quad, Shadow), 1)
assert_eq(tree.insert(b(25.0, 25.0), Quad, Shadow), 2)
}
///|
/// Port of GPUI's bounds_tree `test_random_iterations`: compare against a
/// brute-force computation of the expected ordering.
test "bounds tree matches brute force on random input" {
let kinds : Array[@scene.PrimitiveKind] = [Shadow, Quad, Path, Underline]
for seed in 1..<=200 {
let seed_bytes = Bytes::makei(32, fn(i) { (seed * 31 + i).to_byte() })
let rng = @random.Rand::chacha8(seed=seed_bytes)
let tree : @scene.BoundsTree[Double] = @scene.BoundsTree::new()
let expected : Array[
(@geometry.Bounds[Double], Int32, @scene.PrimitiveKind),
] = []
let count = rng.int(limit=100) + 1
for _ in 0..<count {
let bounds : @geometry.Bounds[Double] = {
origin: {
x: rng.double(min=-100.0, max=100.0),
y: rng.double(min=-100.0, max=100.0),
},
size: {
width: rng.double(min=0.0, max=50.0),
height: rng.double(min=0.0, max=50.0),
},
}
let kind = kinds[rng.int(limit=kinds.length())]
let max_shared_kind = kinds[rng.int(limit=kinds.length())]
let mut max_intersecting : (Int32, @scene.PrimitiveKind)? = None
for entry in expected {
let (other, ordering, other_kind) = entry
if other.intersects(bounds) {
max_intersecting = match max_intersecting {
Some(current) if current >= (ordering, other_kind) => Some(current)
_ => Some((ordering, other_kind))
}
}
}
let expected_ordering = match max_intersecting {
None => 1
Some((ordering, max_kind)) =>
if max_kind <= max_shared_kind {
ordering
} else {
ordering + 1
}
}
expected.push((bounds, expected_ordering, kind))
assert_eq(tree.insert(bounds, kind, max_shared_kind), expected_ordering)
}
}
}
///|
test "primitive kind order and sharing" {
assert_true(@scene.PrimitiveKind::Shadow < Quad)
assert_true(@scene.PrimitiveKind::Quad < Path)
assert_true(@scene.PrimitiveKind::Underline < MonochromeSprite)
assert_true(@scene.PrimitiveKind::SubpixelSprite < PolychromeSprite)
assert_eq(@scene.PrimitiveKind::MonochromeSprite.max_shared_kind(), Underline)
assert_eq(@scene.PrimitiveKind::Quad.max_shared_kind(), Quad)
}
///|
test "same-kind overlaps share an order and keep paint order" {
let scene = @scene.Scene::new()
scene.insert_primitive(quad_at(100.0))
scene.insert_primitive(quad_at(0.0))
scene.insert_primitive(quad_at(5.0))
scene.finish()
// A kind may share a level with itself: within a batch, instances are drawn
// in insertion order, so overlapping quads need no new order.
assert_eq(scene.quads.map(fn(q) { q.order }), [1, 1, 1])
assert_eq(scene.quads.map(fn(q) { q.bounds.origin.x.0 }), [100.0, 0.0, 5.0])
assert_eq(scene.batches(), [Quads(start=0, end=3)])
}
///|
test "a higher kind below forces a new order" {
let scene = @scene.Scene::new()
scene.insert_primitive(underline_at(0.0))
scene.insert_primitive(quad_at(5.0))
scene.insert_primitive(quad_at(50.0))
scene.finish()
assert_eq(scene.quads.map(fn(q) { q.order }), [1, 2])
assert_eq(scene.quads.map(fn(q) { q.bounds.origin.x.0 }), [50.0, 5.0])
}
///|
test "batches interleave kinds by order" {
let scene = @scene.Scene::new()
scene.insert_primitive(quad_at(0.0))
scene.insert_primitive(shadow_at(0.0))
scene.insert_primitive(quad_at(0.0))
assert_eq(labels(scene), ["quads (1)", "shadows (1)", "quads (1)"])
}
///|
test "shadows sort before quads at the same order" {
let scene = @scene.Scene::new()
scene.insert_primitive(quad_at(0.0))
scene.insert_primitive(shadow_at(50.0))
assert_eq(labels(scene), ["shadows (1)", "quads (1)"])
}
///|
test "glyphs share an order with underlines and batch by texture" {
let scene = @scene.Scene::new()
let wide = sb(0.0, 0.0, 100.0, 10.0)
scene.insert_primitive(
Underline({
..Default::default(),
bounds: wide,
content_mask: { bounds: wide, },
thickness: ScaledPixels(1.0),
}),
)
scene.insert_primitive(glyph_at(0.0, 0))
scene.insert_primitive(glyph_at(20.0, 1))
scene.insert_primitive(glyph_at(40.0, 0))
scene.finish()
// Monochrome sprites may share a level with underlines.
assert_eq(scene.underlines[0].order, 1)
assert_eq(scene.monochrome_sprites.map(fn(s) { s.order }), [1, 1, 1])
// Sorted by texture within the order, so each atlas is bound once.
assert_eq(scene.batches().map(fn(b) { b.label() }), [
"underlines (1)", "monochrome sprites (2) on atlas 0", "monochrome sprites (1) on atlas 1",
])
}
///|
test "overlapping glyphs are ordered (sprites cannot share with themselves)" {
let scene = @scene.Scene::new()
scene.insert_primitive(glyph_at(0.0, 0))
scene.insert_primitive(glyph_at(5.0, 0))
scene.finish()
assert_eq(scene.monochrome_sprites.map(fn(s) { s.order }), [1, 2])
assert_eq(scene.batches().length(), 1)
}
///|
test "primitives clipped to nothing are dropped" {
let scene = @scene.Scene::new()
let bounds = sb(0.0, 0.0, 10.0, 10.0)
scene.insert_primitive(
Quad({
..Default::default(),
bounds,
content_mask: { bounds: sb(50.0, 50.0, 5.0, 5.0), },
}),
)
scene.insert_primitive(
Quad({
..Default::default(),
bounds: sb(0.0, 0.0, 0.0, 10.0),
content_mask: { bounds, },
}),
)
assert_eq(scene.len(), 0)
assert_eq(labels(scene), [])
}
///|
test "a layer is ordered as one unit" {
let scene = @scene.Scene::new()
scene.insert_primitive(underline_at(0.0))
scene.push_layer()
// The second quad does not overlap the underline itself, but the layer as a
// whole does, so both quads are lifted above it.
scene.insert_primitive(quad_at(5.0))
scene.insert_primitive(quad_at(5.0, y=50.0))
scene.pop_layer()
// Control: outside a layer, a quad that does not overlap the underline
// stays at order 1.
scene.insert_primitive(quad_at(200.0))
scene.finish()
assert_eq(scene.quads.map(fn(q) { (q.order, q.bounds.origin.x.0) }), [
(1, 200.0),
(2, 5.0),
(2, 5.0),
])
assert_eq(scene.len(), 6)
assert_eq(labels(scene), ["quads (1)", "underlines (1)", "quads (2)"])
}
///|
test "nested layers resolve when the outermost layer pops" {
let scene = @scene.Scene::new()
scene.push_layer()
scene.insert_primitive(quad_at(0.0))
scene.push_layer()
scene.insert_primitive(shadow_at(0.0))
scene.pop_layer()
assert_eq(scene.quads.length(), 0)
scene.pop_layer()
scene.finish()
assert_eq(scene.quads.length(), 1)
assert_eq(scene.shadows.length(), 1)
// The inner layer overlaps the outer one, so it is drawn above it.
assert_true(scene.shadows[0].order > scene.quads[0].order)
}
///|
test "replay reproduces a range of paint operations" {
let prev = @scene.Scene::new()
prev.insert_primitive(quad_at(0.0))
prev.push_layer()
prev.insert_primitive(shadow_at(0.0))
prev.pop_layer()
prev.insert_primitive(quad_at(0.0))
let next = @scene.Scene::new()
next.replay(prev, 0, prev.len())
assert_eq(next.len(), prev.len())
assert_eq(labels(next), labels(prev))
let partial = @scene.Scene::new()
partial.replay(prev, 1, 4)
assert_eq(labels(partial), ["shadows (1)"])
}
///|
test "clear resets the scene" {
let scene = @scene.Scene::new()
scene.insert_primitive(quad_at(0.0))
scene.clear()
assert_eq(scene.len(), 0)
scene.insert_primitive(quad_at(0.0))
scene.finish()
assert_eq(scene.quads[0].order, 1)
}
///|
test "transformation matrix" {
let unit = @scene.TransformationMatrix::unit()
assert_eq(unit.compose(unit), unit)
let moved = unit.translate({ x: ScaledPixels(10.0), y: ScaledPixels(5.0), })
assert_eq(moved.apply({ x: @geometry.px(1.0), y: @geometry.px(2.0), }), {
x: @geometry.px(11.0),
y: @geometry.px(7.0),
})
let scaled = unit.scale({ width: 2.0, height: 3.0, })
assert_eq(
scaled.transform_bounds(sb(1.0, 1.0, 2.0, 2.0)),
sb(2.0, 3.0, 4.0, 6.0),
)
// A quarter turn maps the box (0,0)-(2,1) onto (-1,0)-(0,2).
let rotated = unit.rotate(@geometry.radians(@math.PI / 2.0))
let rb = rotated.transform_bounds(sb(0.0, 0.0, 2.0, 1.0))
assert_true((rb.origin.x.0 - -1.0).abs() < 1.0e-9)
assert_true((rb.size.height.0 - 2.0).abs() < 1.0e-9)
}
///|
test "transformed sprites are clipped by their transformed bounds" {
let bounds = sb(0.0, 0.0, 10.0, 10.0)
let sprite : @scene.Primitive = match glyph_at(0.0, 0) {
MonochromeSprite(s) =>
@scene.Primitive::MonochromeSprite({
..s,
content_mask: { bounds: sb(0.0, 0.0, 100.0, 100.0), },
transformation: @scene.TransformationMatrix::unit().translate({
x: ScaledPixels(50.0),
y: ScaledPixels(0.0),
}),
})
_ => abort("unreachable")
}
assert_eq(sprite.bounds(), bounds)
assert_eq(sprite.clipped_bounds(), sb(50.0, 0.0, 10.0, 10.0))
}
///|
test "painted path bounds and scaling" {
let mask : @geometry.ContentMask[@geometry.Pixels] = {
bounds: {
origin: @geometry.point(@geometry.px(0.0), @geometry.px(0.0)),
size: @geometry.size(@geometry.px(100.0), @geometry.px(100.0)),
},
}
let triangle = [
@geometry.point(@geometry.px(10.0), @geometry.px(10.0)),
@geometry.point(@geometry.px(30.0), @geometry.px(10.0)),
@geometry.point(@geometry.px(20.0), @geometry.px(25.0)),
]
let path = @scene.PaintedPath::new(
[triangle],
2.0,
mask,
@color.red().to_background(),
)
assert_eq(path.bounds, sb(20.0, 20.0, 40.0, 30.0))
assert_eq(path.content_mask.bounds, sb(0.0, 0.0, 200.0, 200.0))
assert_false(path.even_odd)
let scene = @scene.Scene::new()
scene.insert_primitive(Path(path))
assert_eq(labels(scene), ["paths (1)"])
}
///|
test "quad depth" {
assert_eq(@scene.quad_depth_scale(0), 1.0)
assert_eq(@scene.quad_depth_scale(3), 0.25)
assert_eq(@scene.quad_depth_scale(4), 0.125)
assert_eq(@scene.quad_depth(0, 0.25), 0.25)
assert_eq(@scene.quad_depth(10, 0.25), 1.0)
}