Merge pull request 'Porting plan + first pure slice: geometry, color, scene' (#1) from feat/geometry-color-scene into main
CI / moon fmt, check, test (push) Successful in 18s

This commit was merged in pull request #1.
This commit is contained in:
nandi committed 2026-11-29 06:14:36 +00:00
commit dc3645fa58
45 files changed
+51523 -1

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
name: CI
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
jobs:
moon:
name: moon fmt, check, test
runs-on: depot-ubuntu-24.04-4
# bookworm: glibc >= 2.34 is needed to link moon native tests; the image also provides
# node for actions/checkout and the js backend, and cc for the native backend.
container: node:20-bookworm
steps:
- uses: actions/checkout@v4
- name: Install MoonBit CLI
run: |
curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
echo "$HOME/.moon/bin" >> "$GITHUB_PATH"
- name: moon fmt --check, check, test
run: |
set -eu
moon version --all
moon update
moon fmt --check
moon check --target all
moon test --target all
+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.
+62 -1
View File
@@ -1,3 +1,64 @@
# 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) |
| `experiments/gpui/font` | font descriptors in `text_system.rs` | Ported (`Font`, weights, styles, features, fallbacks) |
| `experiments/gpui/style` | `style.rs`, `styled.rs`, Refineable, gpui_macros style helpers | Ported (`Style`/`StyleRefinement`, the full `Styled` fluent API) |
## Example
Nothing renders yet. `src/examples/card` resolves a style written with
GPUI's fluent API, paints it into a `Scene` by hand, and prints the draw
batches:
```sh
moon run src/examples/card --target js
```
```moonbit
@style.StyleRefinement::new()
.flex().flex_col().gap_2().p_4()
.w(@geometry.px(320.0))
.rounded_lg().border_1().border_color(@color.rgb(0xd0d7de))
.bg(@color.rgb(0xffffff)).shadow_md()
.text_color(@color.rgb(0x1f2328)).text_sm()
```
The first example that renders in the browser comes with milestone M8; see
the roadmap.
## Generated code
`src/style/style_generated.mbt`, `styled_generated.mbt` and
`styled_extend_generated.mbt` are generated by `tools/gen_style.py`, which
stands in for GPUI's Rust macros. Do not edit them by hand; change the
script or `src/style/styled.mbt`, then run:
```sh
python3 tools/gen_style.py && moon fmt
```
## Testing
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).
+480
View File
@@ -0,0 +1,480 @@
# 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) |
| `font` | `Font`, `FontWeight`, `FontStyle`, `FontFeatures`, `FontFallbacks` (text_system.rs) | pure | **done** (descriptors only) |
| `style` | `style.rs`, `styled.rs`, Refineable, gpui_macros style helpers | pure | **done** (generated by `tools/gen_style.py`) |
| `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 |
| `examples/*` | `examples/*` | executables | `card` (headless, prints a scene report) |
| `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 (done).**
- `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.
---
### Deviations taken in M1 (style)
- `Style`, `TextStyle` and all nested refinements are immutable values.
`Style::refined` returns a new style. Only `StyleRefinement` (what
`Styled::style()` returns) is mutable, because it is the builder.
Nested updates are written as `style.text = { ..style.text, color: ... }`.
- `Styled` is one trait with 3,213 methods: about 140 hand-written in
`src/style/styled.mbt`, the rest generated as GPUI's macros would generate
them. GPUI's `text_style()` accessor (`&mut TextStyleRefinement`) is
omitted.
- `impl Into<X>` parameters became trait objects: `&IntoLength`,
`&IntoDefiniteLength`, `&IntoAbsoluteLength`, `&IntoHsla`, and `&IntoFill`.
- `AlignSelf`, `JustifyContent`, and the other alias types are not separate
types. Fields use `AlignItems` and `AlignContent` directly.
- `combine_highlights` takes and returns `Array[HighlightRange]` rather than
iterators. Ranges covered by several highlights combine them in the order
the highlights were given; GPUI uses HashSet iteration order.
- The refinement `Cascade` and `Style::paint` (which needs `Window`) wait for
M6. The conversion to taffy styles waits for M2.
## 7. Design decisions
Decided on 2026-11-24, following the recommendations below.
1. **Entity liveness without `Drop`.** Entities with release listeners or
observers are released explicitly. Views are released when their window
closes.
2. **Text shaping on the web.** Shape with `moon_cosmic`, which is pure, the
same on every backend, and matches upstream `gpui_web`, using bundled
fonts. Canvas text is used only as an emoji/CJK fallback, as upstream does.
3. **Layout engine.** Vendor `moon_taffy`, fix it for the current toolchain,
and send the fixes upstream.
4. **First renderer.** Canvas2D on js first, then WebGPU reusing GPUI's WGSL
shaders.
5. **API surface naming.** Keep GPUI names verbatim (`div()`, `px()`,
`rems()`, `.flex().p_2().bg(...)`), so GPUI code ports mechanically.
6. **Module name.** `experiments/gpui` for now. Publishing to mooncakes
needs an owner namespace; revisit before the first release.
## 8. Toolchain notes (moon 0.1.20261119)
- Trait methods are callable with dot syntax only after an explicit
`pub extend Type with Trait::{m1, m2}`. A type parameter with several
bounds needs `Trait::method(x)`. This is why every `Styled` implementor
needs the generated `extend` list.
- Derives use `#derive(...)` before the declaration.
- `extend` is a keyword (so `Bounds::extend` became `Bounds::extend_by`), and
`try?` was removed.
- `moon fmt` migrates code to the newest syntax: it writes `impl T with fn m`
and turns `Int` into `Int32`. Generators must accept the formatted form.
Always run `python3 tools/gen_style.py && moon fmt` together.
- A value converts implicitly to a trait object (`&IntoLength`) at a call
site. That is how GPUI's `impl Into<Length>` parameters are expressed.
- Test-only imports go in `import { ... } for "test"` in `moon.pkg`.
+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"
+537
View File
@@ -0,0 +1,537 @@
// 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, Hash, 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()
}
}
// ---------------------------------------------------------------------------
// Conversions standing in for GPUI's `impl Into<Hsla>` parameters.
// ---------------------------------------------------------------------------
///|
/// Anything usable where GPUI takes `impl Into<Hsla>`: `Hsla` and `Rgba`.
pub(open) trait IntoHsla {
fn into_hsla(Self) -> Hsla
}
///|
pub impl IntoHsla for Hsla with fn into_hsla(self) {
self
}
///|
pub impl IntoHsla for Rgba with fn into_hsla(self) {
self.to_hsla()
}
+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"
+129
View File
@@ -0,0 +1,129 @@
// 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, Hash, @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 IntoHsla for Hsla
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 IntoHsla for Rgba
pub impl Show for Rgba
// Type aliases
// Traits
pub(open) trait IntoHsla {
fn into_hsla(Self) -> Hsla
}
+132
View File
@@ -0,0 +1,132 @@
// A headless example of what exists so far (M0 + M1): describe a "card" with
// GPUI's fluent style API, resolve it, and paint it into a Scene by hand.
// There is no layout engine or renderer yet, so bounds are fixed and the
// output is a text report of the scene's draw batches.
//
// Run with: moon run src/examples/card --target js
///|
/// The card's style, written exactly as in GPUI:
/// `div().flex().p_4().rounded_lg().border_1().shadow_md().bg(...)`.
fn card_style() -> @style.StyleRefinement {
@style.StyleRefinement::new()
.flex()
.flex_col()
.gap_2()
.p_4()
.w(@geometry.px(320.0))
.rounded_lg()
.border_1()
.border_color(@color.rgb(0xd0d7de))
.bg(@color.rgb(0xffffff))
.shadow_md()
.text_color(@color.rgb(0x1f2328))
.text_sm()
}
///|
/// Paints the resolved style's background, border and shadows, the way
/// GPUI's `Style::paint` will once the Window exists (M6).
fn paint_card(
scene : @scene.Scene,
style : @style.Style,
bounds : @geometry.Bounds[@geometry.Pixels],
rem_size : @geometry.Pixels,
scale_factor : Double,
) -> Unit {
let corner_radii = style.corner_radii
.absolute_to_pixels(rem_size)
.clamp_radii_for_quad_size(bounds.size)
let mask : @geometry.ContentMask[@geometry.Pixels] = {
bounds: bounds.dilate(@geometry.px(64.0)),
}
for shadow in style.box_shadow {
let shadow_bounds = bounds
.translate(shadow.offset)
.dilate(shadow.spread_radius)
scene.insert_primitive(
Shadow({
order: 0,
blur_radius: shadow.blur_radius.scale(scale_factor),
bounds: shadow_bounds.scale(scale_factor),
corner_radii: corner_radii.scale(scale_factor),
content_mask: mask.scale(scale_factor),
color: shadow.color,
shape_bounds: bounds.scale(scale_factor),
shape_corner_radii: corner_radii.scale(scale_factor),
inset: false,
}),
)
}
let background = match style.background {
Some(fill) => fill.color().unwrap()
None => Default::default()
}
scene.insert_primitive(
Quad({
order: 0,
border_style: style.border_style,
bounds: bounds.scale(scale_factor),
content_mask: mask.scale(scale_factor),
background,
border_color: style.border_color.unwrap_or(@color.transparent_black()),
corner_radii: corner_radii.scale(scale_factor),
border_widths: style.border_widths
.absolute_to_pixels(rem_size)
.scale(scale_factor),
}),
)
}
///|
/// Builds the report printed by `main`.
fn report() -> String {
let rem_size = @geometry.px(16.0)
let scale_factor = 2.0
let style = (Default::default() : @style.Style).refined(card_style())
let text = (Default::default() : @style.TextStyle).refined(style.text)
let bounds : @geometry.Bounds[@geometry.Pixels] = {
origin: @geometry.point(@geometry.px(40.0), @geometry.px(40.0)),
size: @geometry.size(@geometry.px(320.0), @geometry.px(120.0)),
}
let scene = @scene.Scene::new()
paint_card(scene, style, bounds, rem_size, scale_factor)
// A title underline, overlapping the card.
scene.insert_primitive(
Underline({
order: 0,
bounds: @geometry.bounds(
@geometry.point(@geometry.px(56.0), @geometry.px(76.0)),
@geometry.size(@geometry.px(120.0), @geometry.px(1.0)),
).scale(scale_factor),
content_mask: { bounds: bounds.scale(scale_factor), },
color: text.color,
thickness: @geometry.ScaledPixels(2.0),
wavy: false,
}),
)
scene.finish()
let lines = [
"card style",
" display: \{@debug.to_string(style.display)}, direction: \{@debug.to_string(style.flex_direction)}",
" width: \{style.size.width}, padding: \{style.padding.top}, gap: \{style.gap.width}",
" radius: \{style.corner_radii.top_left} = \{style.corner_radii.top_left.to_pixels(rem_size)}",
" shadows: \{style.box_shadow.length()}",
" text: \{text.font_size.to_pixels(rem_size)} \{text.font_family}, color \{text.color.to_rgb()}",
"scene at \{scale_factor}x",
]
for batch in scene.batches() {
lines.push(" \{batch.label()}")
}
for quad in scene.quads {
lines.push(
" quad order \{quad.order}: \{quad.bounds.size.width.0} x \{quad.bounds.size.height.0} device px",
)
}
lines.join("\n")
}
///|
fn main {
println(report())
}
+19
View File
@@ -0,0 +1,19 @@
///|
test "card report" {
inspect(
report(),
content=(
#|card style
#| display: Flex, direction: Column
#| width: 320px, padding: 1rem, gap: 0.5rem
#| radius: 0.5rem = 8px
#| shadows: 2
#| text: 14px .SystemUIFont, color #1f2328ff
#|scene at 2x
#| shadows (2)
#| quads (1)
#| underlines (1)
#| quad order 1: 640 x 240 device px
),
)
}
+9
View File
@@ -0,0 +1,9 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/color",
"experiments/gpui/scene",
"experiments/gpui/style",
"moonbitlang/core/debug",
}
pkgtype(kind: "executable")
+12
View File
@@ -0,0 +1,12 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/examples/card"
// Values
// Errors
// Types and methods
// Type aliases
// Traits
+146
View File
@@ -0,0 +1,146 @@
// Font descriptors, ported from gpui/src/text_system.rs and
// text_system/{font_features,font_fallbacks}.rs. Font loading, metrics and
// shaping belong to the text-system milestone (M9).
///|
/// The weight of a font, from 100 (thin) to 900 (black).
#derive(Eq, Compare, Hash, Debug)
pub(all) struct FontWeight(Double)
///|
pub let font_weight_thin : FontWeight = FontWeight(100.0)
///|
pub let font_weight_extra_light : FontWeight = FontWeight(200.0)
///|
pub let font_weight_light : FontWeight = FontWeight(300.0)
///|
pub let font_weight_normal : FontWeight = FontWeight(400.0)
///|
pub let font_weight_medium : FontWeight = FontWeight(500.0)
///|
pub let font_weight_semibold : FontWeight = FontWeight(600.0)
///|
pub let font_weight_bold : FontWeight = FontWeight(700.0)
///|
pub let font_weight_extra_bold : FontWeight = FontWeight(800.0)
///|
pub let font_weight_black : FontWeight = FontWeight(900.0)
///|
pub impl Default for FontWeight with fn default() {
font_weight_normal
}
///|
pub impl Show for FontWeight with fn output(self, logger) {
logger.write_string(self.0.to_string())
}
///|
/// The slant of a font face.
#derive(Eq, Hash, Debug)
pub(all) enum FontStyle {
Normal
Italic
Oblique
}
///|
pub impl Default for FontStyle with fn default() {
Normal
}
///|
/// OpenType feature settings, as `(tag, value)` pairs. Treat as immutable.
#derive(Eq, Hash, Default, Debug)
pub(all) struct FontFeatures(Array[(String, Int32)])
///|
/// Disables contextual alternates (`calt`), which turns off ligatures.
pub fn FontFeatures::disable_ligatures() -> FontFeatures {
FontFeatures([("calt", 0)])
}
///|
pub fn FontFeatures::tag_value_list(
self : FontFeatures,
) -> Array[(String, Int32)] {
self.0
}
///|
/// Whether `calt` is enabled; `None` if the feature is not set.
pub fn FontFeatures::is_calt_enabled(self : FontFeatures) -> Bool? {
for entry in self.0 {
let (tag, value) = entry
if tag == "calt" {
return Some(value == 1)
}
}
None
}
///|
/// Font families to try, in order, when the primary family lacks a glyph.
#derive(Eq, Hash, Default, Debug)
pub(all) struct FontFallbacks(Array[String])
///|
pub fn FontFallbacks::from_fonts(fonts : Array[String]) -> FontFallbacks {
FontFallbacks(fonts)
}
///|
pub fn FontFallbacks::fallback_list(self : FontFallbacks) -> Array[String] {
self.0
}
///|
/// The name GPUI uses for the platform's UI font.
pub let system_ui_font : String = ".SystemUIFont"
///|
/// A font: a family plus the properties used to select a face.
#derive(Eq, Hash, Debug)
pub(all) struct Font {
family : String
features : FontFeatures
fallbacks : FontFallbacks?
weight : FontWeight
style : FontStyle
}
///|
/// A regular-weight, upright font of `family`.
pub fn font(family : String) -> Font {
{
family,
features: Default::default(),
fallbacks: None,
weight: Default::default(),
style: Normal,
}
}
///|
pub impl Default for Font with fn default() {
font(system_ui_font)
}
///|
pub fn Font::bold(self : Font) -> Font {
{ ..self, weight: font_weight_bold, }
}
///|
pub fn Font::italic(self : Font) -> Font {
{ ..self, style: Italic, }
}
+24
View File
@@ -0,0 +1,24 @@
///|
test "font builders" {
let f = @font.font("Zed Sans").bold().italic()
assert_eq(f.family, "Zed Sans")
assert_eq(f.weight, @font.font_weight_bold)
assert_eq(f.style, Italic)
let d : @font.Font = Default::default()
assert_eq(d.family, ".SystemUIFont")
assert_eq(d.weight, @font.FontWeight(400.0))
assert_true(@font.font_weight_light < @font.font_weight_semibold)
}
///|
test "font features" {
assert_eq(
@font.FontFeatures::disable_ligatures().is_calt_enabled(),
Some(false),
)
assert_eq(@font.FontFeatures([("calt", 1)]).is_calt_enabled(), Some(true))
assert_eq((Default::default() : @font.FontFeatures).is_calt_enabled(), None)
assert_eq(@font.FontFallbacks::from_fonts(["A", "B"]).fallback_list(), [
"A", "B",
])
}
+1
View File
@@ -0,0 +1 @@
+72
View File
@@ -0,0 +1,72 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/gpui/font"
import {
"moonbitlang/core/debug",
}
// Values
pub fn font(String) -> Font
pub let font_weight_black : FontWeight
pub let font_weight_bold : FontWeight
pub let font_weight_extra_bold : FontWeight
pub let font_weight_extra_light : FontWeight
pub let font_weight_light : FontWeight
pub let font_weight_medium : FontWeight
pub let font_weight_normal : FontWeight
pub let font_weight_semibold : FontWeight
pub let font_weight_thin : FontWeight
pub let system_ui_font : String
// Errors
// Types and methods
#derive(Eq, Hash, @debug.Debug)
pub(all) struct Font {
family : String
features : FontFeatures
fallbacks : FontFallbacks?
weight : FontWeight
style : FontStyle
}
pub fn Font::bold(Self) -> Self
pub fn Font::italic(Self) -> Self
pub impl Default for Font
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct FontFallbacks(Array[String])
pub fn FontFallbacks::fallback_list(Self) -> Array[String]
pub fn FontFallbacks::from_fonts(Array[String]) -> Self
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct FontFeatures(Array[(String, Int32)])
pub fn FontFeatures::disable_ligatures() -> Self
pub fn FontFeatures::is_calt_enabled(Self) -> Bool?
pub fn FontFeatures::tag_value_list(Self) -> Array[(String, Int32)]
#derive(Eq, Hash, @debug.Debug)
pub(all) enum FontStyle {
Normal
Italic
Oblique
}
pub impl Default for FontStyle
#derive(Compare, Eq, Hash, @debug.Debug)
pub(all) struct FontWeight(Double)
pub impl Default for FontWeight
pub impl Show for FontWeight
// 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), }
}
+124
View File
@@ -0,0 +1,124 @@
// Conversion traits standing in for GPUI's `impl Into<Length>` (and friends)
// parameters. MoonBit converts a value to a trait object (`&IntoLength`)
// implicitly at a call site, so `div().w(px(10.0))`, `.w(rems(2.0))` and
// `.w(relative(0.5))` all work like in GPUI.
///|
/// Anything usable where GPUI takes `impl Into<Length>`.
pub(open) trait IntoLength {
fn into_length(Self) -> Length
}
///|
/// Anything usable where GPUI takes `impl Into<DefiniteLength>`.
pub(open) trait IntoDefiniteLength {
fn into_definite_length(Self) -> DefiniteLength
}
///|
/// Anything usable where GPUI takes `impl Into<AbsoluteLength>`.
pub(open) trait IntoAbsoluteLength {
fn into_absolute_length(Self) -> AbsoluteLength
}
///|
pub impl IntoLength for Length with fn into_length(self) {
self
}
///|
pub impl IntoLength for DefiniteLength with fn into_length(self) {
Definite(self)
}
///|
pub impl IntoLength for AbsoluteLength with fn into_length(self) {
Definite(Absolute(self))
}
///|
pub impl IntoLength for Pixels with fn into_length(self) {
self.to_length()
}
///|
pub impl IntoLength for Rems with fn into_length(self) {
self.to_length()
}
///|
pub impl IntoDefiniteLength for DefiniteLength with fn into_definite_length(
self,
) {
self
}
///|
pub impl IntoDefiniteLength for AbsoluteLength with fn into_definite_length(
self,
) {
Absolute(self)
}
///|
pub impl IntoDefiniteLength for Pixels with fn into_definite_length(self) {
self.to_definite()
}
///|
pub impl IntoDefiniteLength for Rems with fn into_definite_length(self) {
self.to_definite()
}
///|
pub impl IntoAbsoluteLength for AbsoluteLength with fn into_absolute_length(
self,
) {
self
}
///|
pub impl IntoAbsoluteLength for Pixels with fn into_absolute_length(self) {
self.to_absolute()
}
///|
pub impl IntoAbsoluteLength for Rems with fn into_absolute_length(self) {
self.to_absolute()
}
// ---------------------------------------------------------------------------
// Grid placement (GPUI: geometry.rs)
// ---------------------------------------------------------------------------
///|
/// Where a grid item starts or ends.
#derive(Eq, Hash, Debug)
pub(all) enum GridPlacement {
/// A grid line (1-based; negative counts from the end).
Line(Int32)
/// Span this many tracks.
Span(Int32)
Auto
}
///|
pub impl Default for GridPlacement with fn default() {
Auto
}
///|
/// A `[start, end)` pair of placements.
#derive(Eq, Hash, Default, Debug)
pub(all) struct GridRange {
start : GridPlacement
end : GridPlacement
}
///|
/// The placement of an item in a grid container.
#derive(Eq, Hash, Default, Debug)
pub(all) struct GridLocation {
row : GridRange
column : GridRange
}
+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}
+447
View File
@@ -0,0 +1,447 @@
///|
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))
}
///|
fn length_of(value : &@geometry.IntoLength) -> @geometry.Length {
value.into_length()
}
///|
fn definite_of(
value : &@geometry.IntoDefiniteLength,
) -> @geometry.DefiniteLength {
value.into_definite_length()
}
///|
fn absolute_of(
value : &@geometry.IntoAbsoluteLength,
) -> @geometry.AbsoluteLength {
value.into_absolute_length()
}
///|
test "length conversion traits" {
assert_eq(length_of(@geometry.px(3.0)), @geometry.px(3.0).to_length())
assert_eq(length_of(@geometry.rems(2.0)), @geometry.rems(2.0).to_length())
assert_eq(
length_of(@geometry.relative(0.5)),
@geometry.relative(0.5).to_length(),
)
assert_eq(length_of(@geometry.auto()), Auto)
assert_eq(
length_of(@geometry.px(1.0).to_absolute()),
@geometry.px(1.0).to_length(),
)
assert_eq(definite_of(@geometry.px(3.0)), @geometry.px(3.0).to_definite())
assert_eq(definite_of(@geometry.relative(0.1)), @geometry.relative(0.1))
assert_eq(
definite_of(@geometry.rems(1.0).to_absolute()),
@geometry.rems(1.0).to_definite(),
)
assert_eq(absolute_of(@geometry.rems(1.0)), @geometry.rems(1.0).to_absolute())
assert_eq(absolute_of(@geometry.px(2.0)), @geometry.px(2.0).to_absolute())
}
///|
test "geometry refinements" {
let p = @geometry.point(1.0, 2.0)
assert_eq(p.refined({ x: Some(5.0), y: None, }), @geometry.point(5.0, 2.0))
let a : @geometry.PointRefinement[Double] = { x: Some(1.0), y: None, }
let b : @geometry.PointRefinement[Double] = { x: Some(3.0), y: Some(4.0), }
assert_eq(a.refined(b), b)
assert_eq(b.refined(a), { x: Some(1.0), y: Some(4.0), })
assert_false(
(Default::default() : @geometry.PointRefinement[Double]).is_some(),
)
let edges = @geometry.Edges::all(0.0).refined({
..Default::default(),
left: Some(2.0),
})
assert_eq(
edges,
@geometry.Edges::new(top=0.0, right=0.0, bottom=0.0, left=2.0),
)
let size = @geometry.size(1.0, 1.0).refined({
width: None,
height: Some(9.0),
})
assert_eq(size, @geometry.size(1.0, 9.0))
let corners = @geometry.Corners::all(0.0).refined({
..Default::default(),
top_right: Some(4.0),
})
assert_eq(corners.top_right, 4.0)
assert_eq(corners.top_left, 0.0)
let er : @geometry.EdgesRefinement[Double] = {
..Default::default(),
top: Some(1.0),
}
assert_true(er.is_some())
let cr : @geometry.CornersRefinement[Double] = Default::default()
assert_false(cr.is_some())
let sr : @geometry.SizeRefinement[Double] = {
width: Some(1.0),
height: None,
}
assert_eq(sr.refined({ width: None, height: Some(2.0), }), {
width: Some(1.0),
height: Some(2.0),
})
}
+9
View File
@@ -0,0 +1,9 @@
import {
"moonbitlang/core/math",
"moonbitlang/core/string",
"moonbitlang/core/debug",
}
import {
"moonbitlang/core/double",
} for "test"
+442
View File
@@ -0,0 +1,442 @@
// 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 IntoAbsoluteLength for AbsoluteLength
pub impl IntoDefiniteLength for AbsoluteLength
pub impl IntoLength for AbsoluteLength
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[T] Corners::refined(Self[T], CornersRefinement[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(Default, Eq, Hash, @debug.Debug)
pub(all) struct CornersRefinement[T] {
top_left : T?
top_right : T?
bottom_right : T?
bottom_left : T?
}
pub fn[T] CornersRefinement::is_some(Self[T]) -> Bool
pub fn[T] CornersRefinement::refined(Self[T], Self[T]) -> Self[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 IntoDefiniteLength for DefiniteLength
pub impl IntoLength for DefiniteLength
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[T] Edges::refined(Self[T], EdgesRefinement[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(Default, Eq, Hash, @debug.Debug)
pub(all) struct EdgesRefinement[T] {
top : T?
right : T?
bottom : T?
left : T?
}
pub fn[T] EdgesRefinement::is_some(Self[T]) -> Bool
pub fn[T] EdgesRefinement::refined(Self[T], Self[T]) -> Self[T]
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct GridLocation {
row : GridRange
column : GridRange
}
#derive(Eq, Hash, @debug.Debug)
pub(all) enum GridPlacement {
Line(Int32)
Span(Int32)
Auto
}
pub impl Default for GridPlacement
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct GridRange {
start : GridPlacement
end : GridPlacement
}
#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 IntoLength for Length
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 IntoAbsoluteLength for Pixels
pub impl IntoDefiniteLength for Pixels
pub impl IntoLength 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] Point::refined(Self[T], PointRefinement[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(Default, Eq, Hash, @debug.Debug)
pub(all) struct PointRefinement[T] {
x : T?
y : T?
}
pub fn[T] PointRefinement::is_some(Self[T]) -> Bool
pub fn[T] PointRefinement::refined(Self[T], Self[T]) -> Self[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 IntoAbsoluteLength for Rems
pub impl IntoDefiniteLength for Rems
pub impl IntoLength 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[T] Size::refined(Self[T], SizeRefinement[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]
#derive(Default, Eq, Hash, @debug.Debug)
pub(all) struct SizeRefinement[T] {
width : T?
height : T?
}
pub fn[T] SizeRefinement::is_some(Self[T]) -> Bool
pub fn[T] SizeRefinement::refined(Self[T], Self[T]) -> Self[T]
// Type aliases
// Traits
pub trait Half {
fn half(Self) -> Self
}
pub impl Half for Int32
pub impl Half for Double
pub(open) trait IntoAbsoluteLength {
fn into_absolute_length(Self) -> AbsoluteLength
}
pub(open) trait IntoDefiniteLength {
fn into_definite_length(Self) -> DefiniteLength
}
pub(open) trait IntoLength {
fn into_length(Self) -> Length
}
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, }
}
+172
View File
@@ -0,0 +1,172 @@
// Refinements of the geometry containers: the same shape with every field
// optional. GPUI derives these with `#[derive(Refineable)]`
// (PointRefinement, SizeRefinement, EdgesRefinement, CornersRefinement).
//
// Refinements here are immutable values: `refined` returns a new value.
///|
#derive(Eq, Hash, Default, Debug)
pub(all) struct PointRefinement[T] {
x : T?
y : T?
}
///|
#derive(Eq, Hash, Default, Debug)
pub(all) struct SizeRefinement[T] {
width : T?
height : T?
}
///|
#derive(Eq, Hash, Default, Debug)
pub(all) struct EdgesRefinement[T] {
top : T?
right : T?
bottom : T?
left : T?
}
///|
#derive(Eq, Hash, Default, Debug)
pub(all) struct CornersRefinement[T] {
top_left : T?
top_right : T?
bottom_right : T?
bottom_left : T?
}
///|
fn[T] or_keep(value : T?, current : T) -> T {
match value {
Some(v) => v
None => current
}
}
///|
fn[T] or_else(value : T?, current : T?) -> T? {
match value {
Some(_) => value
None => current
}
}
///|
/// Overwrites the fields that `refinement` sets.
pub fn[T] Point::refined(
self : Point[T],
refinement : PointRefinement[T],
) -> Point[T] {
{ x: or_keep(refinement.x, self.x), y: or_keep(refinement.y, self.y), }
}
///|
/// Combines two refinements; fields set in `other` win.
pub fn[T] PointRefinement::refined(
self : PointRefinement[T],
other : PointRefinement[T],
) -> PointRefinement[T] {
{ x: or_else(other.x, self.x), y: or_else(other.y, self.y), }
}
///|
/// Whether any field is set.
pub fn[T] PointRefinement::is_some(self : PointRefinement[T]) -> Bool {
self.x is Some(_) || self.y is Some(_)
}
///|
pub fn[T] Size::refined(
self : Size[T],
refinement : SizeRefinement[T],
) -> Size[T] {
{
width: or_keep(refinement.width, self.width),
height: or_keep(refinement.height, self.height),
}
}
///|
pub fn[T] SizeRefinement::refined(
self : SizeRefinement[T],
other : SizeRefinement[T],
) -> SizeRefinement[T] {
{
width: or_else(other.width, self.width),
height: or_else(other.height, self.height),
}
}
///|
pub fn[T] SizeRefinement::is_some(self : SizeRefinement[T]) -> Bool {
self.width is Some(_) || self.height is Some(_)
}
///|
pub fn[T] Edges::refined(
self : Edges[T],
refinement : EdgesRefinement[T],
) -> Edges[T] {
{
top: or_keep(refinement.top, self.top),
right: or_keep(refinement.right, self.right),
bottom: or_keep(refinement.bottom, self.bottom),
left: or_keep(refinement.left, self.left),
}
}
///|
pub fn[T] EdgesRefinement::refined(
self : EdgesRefinement[T],
other : EdgesRefinement[T],
) -> EdgesRefinement[T] {
{
top: or_else(other.top, self.top),
right: or_else(other.right, self.right),
bottom: or_else(other.bottom, self.bottom),
left: or_else(other.left, self.left),
}
}
///|
pub fn[T] EdgesRefinement::is_some(self : EdgesRefinement[T]) -> Bool {
self.top is Some(_) ||
self.right is Some(_) ||
self.bottom is Some(_) ||
self.left is Some(_)
}
///|
pub fn[T] Corners::refined(
self : Corners[T],
refinement : CornersRefinement[T],
) -> Corners[T] {
{
top_left: or_keep(refinement.top_left, self.top_left),
top_right: or_keep(refinement.top_right, self.top_right),
bottom_right: or_keep(refinement.bottom_right, self.bottom_right),
bottom_left: or_keep(refinement.bottom_left, self.bottom_left),
}
}
///|
pub fn[T] CornersRefinement::refined(
self : CornersRefinement[T],
other : CornersRefinement[T],
) -> CornersRefinement[T] {
{
top_left: or_else(other.top_left, self.top_left),
top_right: or_else(other.top_right, self.top_right),
bottom_right: or_else(other.bottom_right, self.bottom_right),
bottom_left: or_else(other.bottom_left, self.bottom_left),
}
}
///|
pub fn[T] CornersRefinement::is_some(self : CornersRefinement[T]) -> Bool {
self.top_left is Some(_) ||
self.top_right is Some(_) ||
self.bottom_right is Some(_) ||
self.bottom_left is Some(_)
}
+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)
}
+7
View File
@@ -0,0 +1,7 @@
import {
"experiments/gpui/geometry",
"experiments/gpui/color",
"experiments/gpui/font",
"experiments/gpui/scene",
"moonbitlang/core/hashset",
}
File diff suppressed because it is too large. Load diff
+424
View File
@@ -0,0 +1,424 @@
// Hand-written parts of gpui/src/style.rs. The Style / TextStyle structs and
// their refinements are generated (style_generated.mbt, tools/gen_style.py).
//
// Not ported yet: `Style::paint` (needs Window, milestone M6) and the
// conversions to taffy styles (milestone M2).
///|
fn[T] refine_value(value : T?, current : T) -> T {
match value {
Some(v) => v
None => current
}
}
///|
fn[T] refine_option(value : T?, current : T?) -> T? {
match value {
Some(_) => value
None => current
}
}
///|
/// GPUI's defaults: block layout, visible, relative position, auto size, no
/// margin/padding/border, flex-grow 0, flex-shrink 1.
pub impl Default for Style with fn default() {
{
display: Block,
visibility: Visible,
overflow: { x: Visible, y: Visible, },
scrollbar_width: Default::default(),
allow_concurrent_scroll: false,
restrict_scroll_to_axis: false,
position: Relative,
inset: @geometry.Edges::auto(),
size: @geometry.Size::auto(),
min_size: @geometry.Size::auto(),
max_size: @geometry.Size::auto(),
aspect_ratio: Option::None,
margin: @geometry.Edges::zero_length(),
padding: @geometry.Edges::zero_definite(),
border_widths: @geometry.Edges::zero_absolute(),
align_items: Option::None,
align_self: Option::None,
align_content: Option::None,
justify_content: Option::None,
gap: Default::default(),
flex_direction: Row,
flex_wrap: NoWrap,
flex_basis: Auto,
flex_grow: 0.0,
flex_shrink: 1.0,
background: Option::None,
border_color: Option::None,
border_style: Default::default(),
corner_radii: Default::default(),
box_shadow: [],
text: Default::default(),
mouse_cursor: Option::None,
opacity: Option::None,
grid_cols: Option::None,
grid_rows: Option::None,
grid_location: Option::None,
debug: false,
debug_below: false,
}
}
///|
/// GPUI's default text style: black, the system UI font at 1rem, line height
/// φ (≈1.618) times the font size.
pub impl Default for TextStyle with fn default() {
{
color: @color.black(),
font_family: @font.system_ui_font,
font_features: Default::default(),
font_fallbacks: Option::None,
font_size: @geometry.rems(1.0).to_absolute(),
line_height: @geometry.phi(),
font_weight: Default::default(),
font_style: Default::default(),
background_color: Option::None,
underline: Option::None,
strikethrough: Option::None,
white_space: Normal,
text_overflow: Option::None,
text_align: Left,
line_clamp: Option::None,
}
}
///|
/// Whether the background is a fill that is not fully transparent.
pub fn Style::has_opaque_background(self : Style) -> Bool {
match self.background {
Some(fill) =>
match fill.color() {
Some(color) => !color.is_transparent()
Option::None => false
}
Option::None => false
}
}
///|
/// The text style refinement, if any field is set.
pub fn Style::text_style(self : Style) -> TextStyleRefinement? {
if self.text.is_some() {
Some(self.text)
} else {
Option::None
}
}
///|
/// The region children are clipped to when overflow is not visible: the
/// bounds, minus visible borders, on the clipped axes.
pub fn Style::overflow_mask(
self : Style,
bounds : @geometry.Bounds[@geometry.Pixels],
rem_size : @geometry.Pixels,
) -> @geometry.ContentMask[@geometry.Pixels]? {
let x_visible = self.overflow.x == Visible
let y_visible = self.overflow.y == Visible
if x_visible && y_visible {
return Option::None
}
let mut min = bounds.origin
let mut max = bounds.bottom_right()
let border_visible = match self.border_color {
Some(color) => !color.is_transparent()
Option::None => false
}
if border_visible {
let widths = self.border_widths.absolute_to_pixels(rem_size)
min = { x: min.x + widths.left, y: min.y + widths.top, }
max = { x: max.x - widths.right, y: max.y - widths.bottom, }
}
let clipped = if x_visible {
@geometry.Bounds::from_corners({ x: min.x, y: bounds.origin.y, }, {
x: max.x,
y: bounds.bottom_right().y,
})
} else if y_visible {
@geometry.Bounds::from_corners({ x: bounds.origin.x, y: min.y, }, {
x: bounds.bottom_right().x,
y: max.y,
})
} else {
@geometry.Bounds::from_corners(min, max)
}
Some({ bounds: clipped, })
}
///|
/// Whether a border would be painted: a visible color and a non-zero width.
pub fn Style::is_border_visible(self : Style) -> Bool {
let color_visible = match self.border_color {
Some(color) => !color.is_transparent()
Option::None => false
}
color_visible &&
self.border_widths.any(fn(width) { !@geometry.IsZero::is_zero(width) })
}
///|
/// The font this text style selects.
pub fn TextStyle::font(self : TextStyle) -> @font.Font {
{
family: self.font_family,
features: self.font_features,
fallbacks: self.font_fallbacks,
weight: self.font_weight,
style: self.font_style,
}
}
///|
/// The line height in pixels, rounded.
pub fn TextStyle::line_height_in_pixels(
self : TextStyle,
rem_size : @geometry.Pixels,
) -> @geometry.Pixels {
self.line_height.to_pixels(self.font_size, rem_size).round()
}
///|
/// Applies a highlight on top of this style.
pub fn TextStyle::highlight(
self : TextStyle,
style : HighlightStyle,
) -> TextStyle {
let mut result = self
if style.font_weight is Some(weight) {
result = { ..result, font_weight: weight, }
}
if style.font_style is Some(font_style) {
result = { ..result, font_style, }
}
if style.color is Some(color) {
result = { ..result, color: result.color.blend(color), }
}
if style.fade_out is Some(factor) {
result = { ..result, color: result.color.fade_out(factor), }
}
if style.background_color is Some(_) {
result = { ..result, background_color: style.background_color, }
}
if style.underline is Some(_) {
result = { ..result, underline: style.underline, }
}
if style.strikethrough is Some(_) {
result = { ..result, strikethrough: style.strikethrough, }
}
result
}
// ---------------------------------------------------------------------------
// HighlightStyle
// ---------------------------------------------------------------------------
///|
/// A partial text style used to highlight ranges (syntax highlighting,
/// search matches, ...).
#derive(Eq, Default, Debug)
pub(all) struct HighlightStyle {
color : @color.Hsla?
font_weight : @font.FontWeight?
font_style : @font.FontStyle?
background_color : @color.Hsla?
underline : UnderlineStyle?
strikethrough : StrikethroughStyle?
/// Fade the color out by this factor (0 to 1).
fade_out : Double?
}
///|
pub fn HighlightStyle::color(color : @color.Hsla) -> HighlightStyle {
{ ..Default::default(), color: Some(color), }
}
///|
/// The highlight equivalent of a full text style.
pub fn HighlightStyle::from_text_style(style : TextStyle) -> HighlightStyle {
{
color: Some(style.color),
font_weight: Some(style.font_weight),
font_style: Some(style.font_style),
background_color: style.background_color,
underline: style.underline,
strikethrough: style.strikethrough,
fade_out: Option::None,
}
}
///|
/// Layers `other` on top of `self`: colors blend, fades compound, other
/// fields set in `other` win.
pub fn HighlightStyle::highlight(
self : HighlightStyle,
other : HighlightStyle,
) -> HighlightStyle {
let color = match (self.color, other.color) {
(Some(color), Some(other_color)) => Some(color.blend(other_color))
(Option::None, Some(other_color)) => Some(other_color)
(current, Option::None) => current
}
let fade_out = match (self.fade_out, other.fade_out) {
(Some(dest), Some(source)) => {
let combined = dest * (1.0 + source)
Some(
if combined < 0.0 {
0.0
} else if combined > 1.0 {
1.0
} else {
combined
},
)
}
(Option::None, Some(source)) => Some(source)
(current, Option::None) => current
}
{
color,
font_weight: refine_option(other.font_weight, self.font_weight),
font_style: refine_option(other.font_style, self.font_style),
background_color: refine_option(
other.background_color,
self.background_color,
),
underline: refine_option(other.underline, self.underline),
strikethrough: refine_option(other.strikethrough, self.strikethrough),
fade_out,
}
}
///|
/// A half-open byte range `[start, end)` with a highlight.
#derive(Eq, Debug)
pub(all) struct HighlightRange {
start : Int32
end : Int32
style : HighlightStyle
}
///|
/// Merges two lists of highlighted ranges into non-overlapping ranges, each
/// carrying the combination of every highlight covering it. Port of GPUI's
/// `combine_highlights`.
pub fn combine_highlights(
a : Array[HighlightRange],
b : Array[HighlightRange],
) -> Array[HighlightRange] {
// (position, highlight id, is_start)
let endpoints : Array[(Int32, Int32, Bool)] = []
let highlights : Array[HighlightStyle] = []
for range in [..a, ..b] {
if range.start < range.end {
let id = highlights.length()
endpoints.push((range.start, id, true))
endpoints.push((range.end, id, false))
highlights.push(range.style)
}
}
// Stable by position; ties keep insertion order.
let keyed = endpoints.mapi(fn(i, e) { (e.0, i) })
keyed.sort()
let sorted = keyed.map(fn(k) { endpoints[k.1] })
let active : @hashset.HashSet[Int32] = @hashset.HashSet([])
let result = []
let mut index = 0
for endpoint in sorted {
let (position, id, is_start) = endpoint
let prev = index
index = position
if index > prev && !active.is_empty() {
// Combine in id order so the result does not depend on set iteration.
let ids = active.iter().collect()
ids.sort()
let mut style : HighlightStyle = Default::default()
for active_id in ids {
style = style.highlight(highlights[active_id])
}
result.push({ start: prev, end: index, style, })
}
if is_start {
active.add(id)
} else {
active.remove(id)
}
}
result
}
// ---------------------------------------------------------------------------
// ObjectFit
// ---------------------------------------------------------------------------
///|
/// How an image is fitted into its bounds (CSS `object-fit`).
#derive(Eq, Hash, Debug)
pub(all) enum ObjectFit {
Fill
Contain
Cover
ScaleDown
None
}
///|
/// Where an image of `image_size` device pixels is drawn inside `bounds`.
pub fn ObjectFit::get_bounds(
self : ObjectFit,
bounds : @geometry.Bounds[@geometry.Pixels],
image_size : @geometry.Size[@geometry.DevicePixels],
) -> @geometry.Bounds[@geometry.Pixels] {
let image_w = image_size.width.0.to_double()
let image_h = image_size.height.0.to_double()
let bounds_w = bounds.size.width.0
let bounds_h = bounds.size.height.0
let image_ratio = image_w / image_h
let bounds_ratio = bounds_w / bounds_h
let centered = fn(
w : Double,
h : Double,
) -> @geometry.Bounds[@geometry.Pixels] {
{
origin: {
x: @geometry.px(bounds.origin.x.0 + (bounds_w - w) / 2.0),
y: @geometry.px(bounds.origin.y.0 + (bounds_h - h) / 2.0),
},
size: { width: @geometry.px(w), height: @geometry.px(h), },
}
}
let contain = fn() {
if bounds_ratio > image_ratio {
centered(image_w * (bounds_h / image_h), bounds_h)
} else {
centered(bounds_w, image_h * (bounds_w / image_w))
}
}
match self {
Fill => bounds
Contain => contain()
ScaleDown =>
if image_w > bounds_w || image_h > bounds_h {
contain()
} else {
centered(image_w, image_h)
}
Cover =>
if bounds_ratio > image_ratio {
centered(bounds_w, image_h * (bounds_w / image_w))
} else {
centered(image_w * (bounds_h / image_h), bounds_h)
}
None =>
{
origin: bounds.origin,
size: { width: @geometry.px(image_w), height: @geometry.px(image_h), },
}
}
}
+572
View File
@@ -0,0 +1,572 @@
// GENERATED by tools/gen_style.py. DO NOT EDIT.
// Port of GPUI's derive(Refineable) / gpui_macros style helpers.
///|
/// The fully resolved style of an element (GPUI: `Style`).
/// Immutable; build one by refining `Style::default()`.
#derive(Eq, Debug)
pub(all) struct Style {
/// How the element is laid out (block, flex, grid, none).
display : Display
/// Whether the element is painted.
visibility : Visibility
/// Overflow behavior per axis.
overflow : @geometry.Point[Overflow]
/// Space reserved for scrollbars.
scrollbar_width : @geometry.AbsoluteLength
/// Whether both axes may scroll at once.
allow_concurrent_scroll : Bool
/// Whether scrolling is restricted to the dominant axis.
restrict_scroll_to_axis : Bool
/// Relative or absolute positioning.
position : Position
/// Offsets for positioned elements.
inset : @geometry.Edges[@geometry.Length]
/// Preferred size.
size : @geometry.Size[@geometry.Length]
/// Minimum size.
min_size : @geometry.Size[@geometry.Length]
/// Maximum size.
max_size : @geometry.Size[@geometry.Length]
/// Preferred width / height ratio.
aspect_ratio : Double?
/// Outer spacing.
margin : @geometry.Edges[@geometry.Length]
/// Inner spacing.
padding : @geometry.Edges[@geometry.DefiniteLength]
/// Border width per side.
border_widths : @geometry.Edges[@geometry.AbsoluteLength]
/// Cross-axis alignment of children.
align_items : AlignItems?
/// Cross-axis alignment of this element (GPUI: AlignSelf).
align_self : AlignItems?
/// Distribution of lines in a multi-line container.
align_content : AlignContent?
/// Main-axis distribution of children (GPUI: JustifyContent).
justify_content : AlignContent?
/// Gap between children (width: column gap, height: row gap).
gap : @geometry.Size[@geometry.DefiniteLength]
/// Main axis direction.
flex_direction : FlexDirection
/// Whether children wrap onto new lines.
flex_wrap : FlexWrap
/// Initial main size before growing or shrinking.
flex_basis : @geometry.Length
/// Share of free space to take.
flex_grow : Double
/// Share of negative space to give up.
flex_shrink : Double
/// Background fill.
background : Fill?
/// Border color.
border_color : @color.Hsla?
/// Solid or dashed border.
border_style : @scene.BorderStyle
/// Corner radii.
corner_radii : @geometry.Corners[@geometry.AbsoluteLength]
/// Box shadows, painted in order. Treat as immutable.
box_shadow : Array[BoxShadow]
/// Text style inherited by descendants.
text : TextStyleRefinement
/// Cursor shown while hovering.
mouse_cursor : CursorStyle?
/// Opacity multiplier for the element and its children.
opacity : Double?
/// Grid column template.
grid_cols : GridTemplate?
/// Grid row template.
grid_rows : GridTemplate?
/// Placement within a grid parent.
grid_location : @geometry.GridLocation?
/// Paint a debug outline around the element.
debug : Bool
/// Paint debug outlines around all descendants.
debug_below : Bool
}
///|
/// A partial `Style`: every field optional (GPUI: `StyleRefinement`).
/// Mutable, because it is the builder that `Styled` methods write to.
#derive(Eq, Debug)
pub(all) struct StyleRefinement {
mut display : Display?
mut visibility : Visibility?
mut overflow : @geometry.PointRefinement[Overflow]
mut scrollbar_width : @geometry.AbsoluteLength?
mut allow_concurrent_scroll : Bool?
mut restrict_scroll_to_axis : Bool?
mut position : Position?
mut inset : @geometry.EdgesRefinement[@geometry.Length]
mut size : @geometry.SizeRefinement[@geometry.Length]
mut min_size : @geometry.SizeRefinement[@geometry.Length]
mut max_size : @geometry.SizeRefinement[@geometry.Length]
mut aspect_ratio : Double?
mut margin : @geometry.EdgesRefinement[@geometry.Length]
mut padding : @geometry.EdgesRefinement[@geometry.DefiniteLength]
mut border_widths : @geometry.EdgesRefinement[@geometry.AbsoluteLength]
mut align_items : AlignItems?
mut align_self : AlignItems?
mut align_content : AlignContent?
mut justify_content : AlignContent?
mut gap : @geometry.SizeRefinement[@geometry.DefiniteLength]
mut flex_direction : FlexDirection?
mut flex_wrap : FlexWrap?
mut flex_basis : @geometry.Length?
mut flex_grow : Double?
mut flex_shrink : Double?
mut background : Fill?
mut border_color : @color.Hsla?
mut border_style : @scene.BorderStyle?
mut corner_radii : @geometry.CornersRefinement[@geometry.AbsoluteLength]
mut box_shadow : Array[BoxShadow]?
mut text : TextStyleRefinement
mut mouse_cursor : CursorStyle?
mut opacity : Double?
mut grid_cols : GridTemplate?
mut grid_rows : GridTemplate?
mut grid_location : @geometry.GridLocation?
mut debug : Bool?
mut debug_below : Bool?
}
///|
/// An empty refinement (no field set).
pub fn StyleRefinement::new() -> StyleRefinement {
{
display: None,
visibility: None,
overflow: Default::default(),
scrollbar_width: None,
allow_concurrent_scroll: None,
restrict_scroll_to_axis: None,
position: None,
inset: Default::default(),
size: Default::default(),
min_size: Default::default(),
max_size: Default::default(),
aspect_ratio: None,
margin: Default::default(),
padding: Default::default(),
border_widths: Default::default(),
align_items: None,
align_self: None,
align_content: None,
justify_content: None,
gap: Default::default(),
flex_direction: None,
flex_wrap: None,
flex_basis: None,
flex_grow: None,
flex_shrink: None,
background: None,
border_color: None,
border_style: None,
corner_radii: Default::default(),
box_shadow: None,
text: Default::default(),
mouse_cursor: None,
opacity: None,
grid_cols: None,
grid_rows: None,
grid_location: None,
debug: None,
debug_below: None,
}
}
///|
pub impl Default for StyleRefinement with fn default() {
StyleRefinement::new()
}
///|
/// A copy that can be mutated independently.
pub fn StyleRefinement::copy(self : StyleRefinement) -> StyleRefinement {
{
display: self.display,
visibility: self.visibility,
overflow: self.overflow,
scrollbar_width: self.scrollbar_width,
allow_concurrent_scroll: self.allow_concurrent_scroll,
restrict_scroll_to_axis: self.restrict_scroll_to_axis,
position: self.position,
inset: self.inset,
size: self.size,
min_size: self.min_size,
max_size: self.max_size,
aspect_ratio: self.aspect_ratio,
margin: self.margin,
padding: self.padding,
border_widths: self.border_widths,
align_items: self.align_items,
align_self: self.align_self,
align_content: self.align_content,
justify_content: self.justify_content,
gap: self.gap,
flex_direction: self.flex_direction,
flex_wrap: self.flex_wrap,
flex_basis: self.flex_basis,
flex_grow: self.flex_grow,
flex_shrink: self.flex_shrink,
background: self.background,
border_color: self.border_color,
border_style: self.border_style,
corner_radii: self.corner_radii,
box_shadow: self.box_shadow,
text: self.text,
mouse_cursor: self.mouse_cursor,
opacity: self.opacity,
grid_cols: self.grid_cols,
grid_rows: self.grid_rows,
grid_location: self.grid_location,
debug: self.debug,
debug_below: self.debug_below,
}
}
///|
/// Applies `other` on top of `self`, in place: fields set in `other` win.
pub fn StyleRefinement::refine(
self : StyleRefinement,
other : StyleRefinement,
) -> Unit {
if other.display is Some(_) {
self.display = other.display
}
if other.visibility is Some(_) {
self.visibility = other.visibility
}
self.overflow = self.overflow.refined(other.overflow)
if other.scrollbar_width is Some(_) {
self.scrollbar_width = other.scrollbar_width
}
if other.allow_concurrent_scroll is Some(_) {
self.allow_concurrent_scroll = other.allow_concurrent_scroll
}
if other.restrict_scroll_to_axis is Some(_) {
self.restrict_scroll_to_axis = other.restrict_scroll_to_axis
}
if other.position is Some(_) {
self.position = other.position
}
self.inset = self.inset.refined(other.inset)
self.size = self.size.refined(other.size)
self.min_size = self.min_size.refined(other.min_size)
self.max_size = self.max_size.refined(other.max_size)
if other.aspect_ratio is Some(_) {
self.aspect_ratio = other.aspect_ratio
}
self.margin = self.margin.refined(other.margin)
self.padding = self.padding.refined(other.padding)
self.border_widths = self.border_widths.refined(other.border_widths)
if other.align_items is Some(_) {
self.align_items = other.align_items
}
if other.align_self is Some(_) {
self.align_self = other.align_self
}
if other.align_content is Some(_) {
self.align_content = other.align_content
}
if other.justify_content is Some(_) {
self.justify_content = other.justify_content
}
self.gap = self.gap.refined(other.gap)
if other.flex_direction is Some(_) {
self.flex_direction = other.flex_direction
}
if other.flex_wrap is Some(_) {
self.flex_wrap = other.flex_wrap
}
if other.flex_basis is Some(_) {
self.flex_basis = other.flex_basis
}
if other.flex_grow is Some(_) {
self.flex_grow = other.flex_grow
}
if other.flex_shrink is Some(_) {
self.flex_shrink = other.flex_shrink
}
if other.background is Some(_) {
self.background = other.background
}
if other.border_color is Some(_) {
self.border_color = other.border_color
}
if other.border_style is Some(_) {
self.border_style = other.border_style
}
self.corner_radii = self.corner_radii.refined(other.corner_radii)
if other.box_shadow is Some(_) {
self.box_shadow = other.box_shadow
}
self.text = self.text.refined(other.text)
if other.mouse_cursor is Some(_) {
self.mouse_cursor = other.mouse_cursor
}
if other.opacity is Some(_) {
self.opacity = other.opacity
}
if other.grid_cols is Some(_) {
self.grid_cols = other.grid_cols
}
if other.grid_rows is Some(_) {
self.grid_rows = other.grid_rows
}
if other.grid_location is Some(_) {
self.grid_location = other.grid_location
}
if other.debug is Some(_) {
self.debug = other.debug
}
if other.debug_below is Some(_) {
self.debug_below = other.debug_below
}
}
///|
/// A new refinement: `self` with `other` applied on top.
pub fn StyleRefinement::refined(
self : StyleRefinement,
other : StyleRefinement,
) -> StyleRefinement {
let result = self.copy()
result.refine(other)
result
}
///|
/// Whether any field is set.
pub fn StyleRefinement::is_some(self : StyleRefinement) -> Bool {
self.display is Some(_) ||
self.visibility is Some(_) ||
self.overflow.is_some() ||
self.scrollbar_width is Some(_) ||
self.allow_concurrent_scroll is Some(_) ||
self.restrict_scroll_to_axis is Some(_) ||
self.position is Some(_) ||
self.inset.is_some() ||
self.size.is_some() ||
self.min_size.is_some() ||
self.max_size.is_some() ||
self.aspect_ratio is Some(_) ||
self.margin.is_some() ||
self.padding.is_some() ||
self.border_widths.is_some() ||
self.align_items is Some(_) ||
self.align_self is Some(_) ||
self.align_content is Some(_) ||
self.justify_content is Some(_) ||
self.gap.is_some() ||
self.flex_direction is Some(_) ||
self.flex_wrap is Some(_) ||
self.flex_basis is Some(_) ||
self.flex_grow is Some(_) ||
self.flex_shrink is Some(_) ||
self.background is Some(_) ||
self.border_color is Some(_) ||
self.border_style is Some(_) ||
self.corner_radii.is_some() ||
self.box_shadow is Some(_) ||
self.text.is_some() ||
self.mouse_cursor is Some(_) ||
self.opacity is Some(_) ||
self.grid_cols is Some(_) ||
self.grid_rows is Some(_) ||
self.grid_location is Some(_) ||
self.debug is Some(_) ||
self.debug_below is Some(_)
}
///|
/// `self` with every field set in `refinement` overwritten.
pub fn Style::refined(self : Style, refinement : StyleRefinement) -> Style {
{
display: refine_value(refinement.display, self.display),
visibility: refine_value(refinement.visibility, self.visibility),
overflow: self.overflow.refined(refinement.overflow),
scrollbar_width: refine_value(
refinement.scrollbar_width,
self.scrollbar_width,
),
allow_concurrent_scroll: refine_value(
refinement.allow_concurrent_scroll,
self.allow_concurrent_scroll,
),
restrict_scroll_to_axis: refine_value(
refinement.restrict_scroll_to_axis,
self.restrict_scroll_to_axis,
),
position: refine_value(refinement.position, self.position),
inset: self.inset.refined(refinement.inset),
size: self.size.refined(refinement.size),
min_size: self.min_size.refined(refinement.min_size),
max_size: self.max_size.refined(refinement.max_size),
aspect_ratio: refine_option(refinement.aspect_ratio, self.aspect_ratio),
margin: self.margin.refined(refinement.margin),
padding: self.padding.refined(refinement.padding),
border_widths: self.border_widths.refined(refinement.border_widths),
align_items: refine_option(refinement.align_items, self.align_items),
align_self: refine_option(refinement.align_self, self.align_self),
align_content: refine_option(refinement.align_content, self.align_content),
justify_content: refine_option(
refinement.justify_content,
self.justify_content,
),
gap: self.gap.refined(refinement.gap),
flex_direction: refine_value(refinement.flex_direction, self.flex_direction),
flex_wrap: refine_value(refinement.flex_wrap, self.flex_wrap),
flex_basis: refine_value(refinement.flex_basis, self.flex_basis),
flex_grow: refine_value(refinement.flex_grow, self.flex_grow),
flex_shrink: refine_value(refinement.flex_shrink, self.flex_shrink),
background: refine_option(refinement.background, self.background),
border_color: refine_option(refinement.border_color, self.border_color),
border_style: refine_value(refinement.border_style, self.border_style),
corner_radii: self.corner_radii.refined(refinement.corner_radii),
box_shadow: refine_value(refinement.box_shadow, self.box_shadow),
text: self.text.refined(refinement.text),
mouse_cursor: refine_option(refinement.mouse_cursor, self.mouse_cursor),
opacity: refine_option(refinement.opacity, self.opacity),
grid_cols: refine_option(refinement.grid_cols, self.grid_cols),
grid_rows: refine_option(refinement.grid_rows, self.grid_rows),
grid_location: refine_option(refinement.grid_location, self.grid_location),
debug: refine_value(refinement.debug, self.debug),
debug_below: refine_value(refinement.debug_below, self.debug_below),
}
}
///|
/// The resolved style of a run of text (GPUI: `TextStyle`).
#derive(Eq, Debug)
pub(all) struct TextStyle {
/// Text color.
color : @color.Hsla
/// Font family name.
font_family : String
/// OpenType features.
font_features : @font.FontFeatures
/// Fallback families.
font_fallbacks : @font.FontFallbacks?
/// Font size.
font_size : @geometry.AbsoluteLength
/// Line height; fractions are relative to the font size.
line_height : @geometry.DefiniteLength
/// Font weight.
font_weight : @font.FontWeight
/// Upright, italic or oblique.
font_style : @font.FontStyle
/// Background behind the glyphs.
background_color : @color.Hsla?
/// Underline decoration.
underline : UnderlineStyle?
/// Strikethrough decoration.
strikethrough : StrikethroughStyle?
/// Whether text wraps.
white_space : WhiteSpace
/// How overflowing text is truncated.
text_overflow : TextOverflow?
/// Horizontal alignment.
text_align : TextAlign
/// Maximum number of lines.
line_clamp : Int32?
}
///|
/// A partial `TextStyle` (GPUI: `TextStyleRefinement`). Immutable.
#derive(Eq, Default, Debug)
pub(all) struct TextStyleRefinement {
color : @color.Hsla?
font_family : String?
font_features : @font.FontFeatures?
font_fallbacks : @font.FontFallbacks?
font_size : @geometry.AbsoluteLength?
line_height : @geometry.DefiniteLength?
font_weight : @font.FontWeight?
font_style : @font.FontStyle?
background_color : @color.Hsla?
underline : UnderlineStyle?
strikethrough : StrikethroughStyle?
white_space : WhiteSpace?
text_overflow : TextOverflow?
text_align : TextAlign?
line_clamp : Int32?
}
///|
/// Combines two refinements; fields set in `other` win.
pub fn TextStyleRefinement::refined(
self : TextStyleRefinement,
other : TextStyleRefinement,
) -> TextStyleRefinement {
{
color: refine_option(other.color, self.color),
font_family: refine_option(other.font_family, self.font_family),
font_features: refine_option(other.font_features, self.font_features),
font_fallbacks: refine_option(other.font_fallbacks, self.font_fallbacks),
font_size: refine_option(other.font_size, self.font_size),
line_height: refine_option(other.line_height, self.line_height),
font_weight: refine_option(other.font_weight, self.font_weight),
font_style: refine_option(other.font_style, self.font_style),
background_color: refine_option(
other.background_color,
self.background_color,
),
underline: refine_option(other.underline, self.underline),
strikethrough: refine_option(other.strikethrough, self.strikethrough),
white_space: refine_option(other.white_space, self.white_space),
text_overflow: refine_option(other.text_overflow, self.text_overflow),
text_align: refine_option(other.text_align, self.text_align),
line_clamp: refine_option(other.line_clamp, self.line_clamp),
}
}
///|
/// Whether any field is set.
pub fn TextStyleRefinement::is_some(self : TextStyleRefinement) -> Bool {
self.color is Some(_) ||
self.font_family is Some(_) ||
self.font_features is Some(_) ||
self.font_fallbacks is Some(_) ||
self.font_size is Some(_) ||
self.line_height is Some(_) ||
self.font_weight is Some(_) ||
self.font_style is Some(_) ||
self.background_color is Some(_) ||
self.underline is Some(_) ||
self.strikethrough is Some(_) ||
self.white_space is Some(_) ||
self.text_overflow is Some(_) ||
self.text_align is Some(_) ||
self.line_clamp is Some(_)
}
///|
/// `self` with every field set in `refinement` overwritten.
pub fn TextStyle::refined(
self : TextStyle,
refinement : TextStyleRefinement,
) -> TextStyle {
{
color: refine_value(refinement.color, self.color),
font_family: refine_value(refinement.font_family, self.font_family),
font_features: refine_value(refinement.font_features, self.font_features),
font_fallbacks: refine_option(
refinement.font_fallbacks,
self.font_fallbacks,
),
font_size: refine_value(refinement.font_size, self.font_size),
line_height: refine_value(refinement.line_height, self.line_height),
font_weight: refine_value(refinement.font_weight, self.font_weight),
font_style: refine_value(refinement.font_style, self.font_style),
background_color: refine_option(
refinement.background_color,
self.background_color,
),
underline: refine_option(refinement.underline, self.underline),
strikethrough: refine_option(refinement.strikethrough, self.strikethrough),
white_space: refine_value(refinement.white_space, self.white_space),
text_overflow: refine_option(refinement.text_overflow, self.text_overflow),
text_align: refine_value(refinement.text_align, self.text_align),
line_clamp: refine_option(refinement.line_clamp, self.line_clamp),
}
}
+352
View File
@@ -0,0 +1,352 @@
///|
fn hl(
start : Int32,
end : Int32,
style : @style.HighlightStyle,
) -> @style.HighlightRange {
{ start, end, style, }
}
///|
fn color_hl(color : @color.Hsla) -> @style.HighlightStyle {
@style.HighlightStyle::color(color)
}
///|
/// Port of GPUI's `test_text_style_refinement`.
test "text style refinement through Style::refined" {
let style = (Default::default() : @style.Style)
.refined(@style.StyleRefinement::new().text_size(@geometry.px(20.0)))
.refined(
@style.StyleRefinement::new().font_weight(@font.font_weight_semibold),
)
let text = style.text_style().unwrap()
assert_eq(text.font_size, Some(@geometry.px(20.0).to_absolute()))
assert_eq(text.font_weight, Some(@font.font_weight_semibold))
}
///|
/// Port of GPUI's `test_basic_highlight_style_combination`.
test "highlight style combination" {
let empty : @style.HighlightStyle = Default::default()
assert_eq(empty.highlight(empty), empty)
let style_b : @style.HighlightStyle = {
color: Some(@color.red()),
strikethrough: Some({
thickness: @geometry.px(2.0),
color: Some(@color.blue()),
}),
fade_out: Some(0.0),
font_style: Some(Italic),
font_weight: Some(FontWeight(300.0)),
background_color: Some(@color.yellow()),
underline: Some({
thickness: @geometry.px(2.0),
color: Some(@color.red()),
wavy: true,
}),
}
assert_eq(empty.highlight(style_b), style_b)
assert_eq(style_b.highlight(empty), style_b)
let style_d : @style.HighlightStyle = {
color: Some(@color.blue().alpha(0.7)),
strikethrough: Some({
thickness: @geometry.px(4.0),
color: Some(@color.red()),
}),
fade_out: Some(0.0),
font_style: Some(Oblique),
font_weight: Some(FontWeight(800.0)),
background_color: Some(@color.green()),
underline: Some({ thickness: @geometry.px(4.0), color: None, wavy: false, }),
}
let expected : @style.HighlightStyle = {
..style_d,
color: Some(@color.red().blend(@color.blue().alpha(0.7))),
}
assert_eq(style_b.highlight(style_d), expected)
}
///|
/// Port of GPUI's `test_combine_highlights`.
test "combine highlights" {
let bold : @style.HighlightStyle = {
..Default::default(),
font_weight: Some(@font.font_weight_bold),
}
let italic : @style.HighlightStyle = {
..Default::default(),
font_style: Some(Italic),
}
let combined = @style.combine_highlights(
[
hl(0, 5, color_hl(@color.green())),
hl(4, 10, bold),
hl(15, 20, color_hl(@color.yellow())),
],
[
hl(2, 6, italic),
hl(1, 3, color_hl(@color.blue())),
hl(21, 23, color_hl(@color.red())),
],
)
assert_eq(combined, [
hl(0, 1, color_hl(@color.green())),
hl(1, 2, color_hl(@color.blue())),
hl(2, 3, { ..italic, color: Some(@color.blue()), }),
hl(3, 4, { ..italic, color: Some(@color.green()), }),
hl(4, 5, {
..italic,
color: Some(@color.green()),
font_weight: Some(@font.font_weight_bold),
}),
hl(5, 6, { ..italic, font_weight: Some(@font.font_weight_bold), }),
hl(6, 10, bold),
hl(15, 20, color_hl(@color.yellow())),
hl(21, 23, color_hl(@color.red())),
])
}
///|
test "style defaults match GPUI" {
let style : @style.Style = Default::default()
assert_eq(style.display, Block)
assert_eq(style.position, Relative)
assert_eq(style.size, @geometry.Size::auto())
assert_eq(style.inset, @geometry.Edges::auto())
assert_eq(style.margin, @geometry.Edges::zero_length())
assert_eq(style.flex_grow, 0.0)
assert_eq(style.flex_shrink, 1.0)
assert_eq(style.flex_basis, Auto)
assert_eq(style.text_style(), None)
assert_false(style.has_opaque_background())
let text : @style.TextStyle = Default::default()
assert_eq(text.font_family, ".SystemUIFont")
assert_eq(text.font_size, @geometry.rems(1.0).to_absolute())
// phi * 16px = 25.888 -> 26px.
assert_eq(text.line_height_in_pixels(@geometry.px(16.0)), @geometry.px(26.0))
assert_eq(text.font(), @font.font(".SystemUIFont"))
}
///|
test "refinement overwrites only the fields it sets" {
let refinement = @style.StyleRefinement::new()
.flex()
.w(@geometry.px(100.0))
.p_2()
.mt_neg_1()
.rounded_md()
.border_1()
.bg(@color.rgb(0x336699))
let style = (Default::default() : @style.Style).refined(refinement)
assert_eq(style.display, Flex)
assert_eq(style.size.width, @geometry.px(100.0).to_length())
assert_eq(style.size.height, Auto)
assert_eq(
style.padding,
@geometry.Edges::all(@geometry.rems(0.5).to_definite()),
)
assert_eq(style.margin.top, @geometry.rems(-0.25).to_length())
assert_eq(style.margin.bottom, @geometry.px(0.0).to_length())
assert_eq(
style.corner_radii,
@geometry.Corners::all(@geometry.rems(0.375).to_absolute()),
)
assert_eq(
style.border_widths,
@geometry.Edges::all(@geometry.px(1.0).to_absolute()),
)
assert_true(style.has_opaque_background())
// Later refinements win field by field.
let restyled = style.refined(@style.StyleRefinement::new().h_full().block())
assert_eq(restyled.display, Block)
assert_eq(restyled.size.width, @geometry.px(100.0).to_length())
assert_eq(restyled.size.height, @geometry.relative(1.0).to_length())
}
///|
test "refinement refine and copy" {
let base = @style.StyleRefinement::new().flex().text_color(@color.red())
let hover = @style.StyleRefinement::new().text_color(@color.blue()).italic()
let merged = base.refined(hover)
assert_eq(merged.display, Some(Flex))
assert_eq(merged.text.color, Some(@color.blue()))
assert_eq(merged.text.font_style, Some(Italic))
// `refined` does not mutate its receiver.
assert_eq(base.text.color, Some(@color.red()))
assert_eq(base.text.font_style, None)
let copy = base.copy()
copy.refine(hover)
assert_eq(copy, merged)
assert_not_eq(base, copy)
assert_true(base.is_some())
assert_false(@style.StyleRefinement::new().is_some())
}
///|
test "generated helpers use GPUI's scale" {
let r = @style.StyleRefinement::new()
ignore(r.p_4().gap_x_2().w_1_3().max_h_96().inset_neg_px().size_auto())
assert_eq(r.padding.left, Some(@geometry.rems(1.0).to_definite()))
assert_eq(r.gap.width, Some(@geometry.rems(0.5).to_definite()))
assert_eq(r.gap.height, None)
assert_eq(r.size.width, Some(Auto))
assert_eq(r.max_size.height, Some(@geometry.rems(24.0).to_length()))
assert_eq(r.inset.left, Some(@geometry.px(-1.0).to_length()))
let corners = @style.StyleRefinement::new().rounded_t_full()
assert_eq(
corners.corner_radii.top_left,
Some(@geometry.px(9999.0).to_absolute()),
)
assert_eq(corners.corner_radii.bottom_left, None)
let x = @style.StyleRefinement::new().border_x_2().cursor_pointer()
assert_eq(x.border_widths.left, Some(@geometry.px(2.0).to_absolute()))
assert_eq(x.border_widths.top, None)
assert_eq(x.mouse_cursor, Some(PointingHand))
// Custom values accept any length-like value.
let w = @style.StyleRefinement::new().w(@geometry.rems(3.0))
assert_eq(w.size.width, Some(@geometry.rems(3.0).to_length()))
let fraction = @style.StyleRefinement::new().w(@geometry.relative(0.25))
assert_eq(fraction.size.width, Some(@geometry.relative(0.25).to_length()))
let padded = @style.StyleRefinement::new().px(@geometry.px(3.0))
assert_eq(padded.padding.right, Some(@geometry.px(3.0).to_definite()))
}
///|
test "text helpers" {
let r = @style.StyleRefinement::new()
.text_sm()
.truncate()
.underline()
.text_decoration_wavy()
.text_decoration_color(@color.red())
.line_height(@geometry.relative(1.5))
assert_eq(r.text.font_size, Some(@geometry.rems(0.875).to_absolute()))
assert_eq(r.text.white_space, Some(Nowrap))
assert_eq(r.text.text_overflow, Some(Truncate("…")))
assert_eq(r.overflow.x, Some(Hidden))
assert_eq(
r.text.underline,
Some({
thickness: @geometry.px(1.0),
color: Some(@color.red()),
wavy: true,
}),
)
assert_eq(r.text.line_height, Some(@geometry.relative(1.5)))
let none = r.copy().text_decoration_none()
assert_eq(none.text.underline, None)
let font = @style.StyleRefinement::new().font(@font.font("Mono").bold())
assert_eq(font.text.font_family, Some("Mono"))
assert_eq(font.text.font_weight, Some(@font.font_weight_bold))
let clamped = @style.StyleRefinement::new().line_clamp(2)
assert_eq(clamped.text.line_clamp, Some(2))
assert_eq(clamped.overflow.y, Some(Hidden))
}
///|
test "flex, alignment, grid and shadow helpers" {
let r = @style.StyleRefinement::new()
.flex_1()
.flex_col()
.items_center()
.justify_between()
.content_stretch()
.self_end()
.grid_cols(3)
.col_span(2)
.row_start(1)
.shadow_md()
assert_eq(r.flex_grow, Some(1.0))
assert_eq(r.flex_basis, Some(@geometry.relative(0.0).to_length()))
assert_eq(r.flex_direction, Some(Column))
assert_eq(r.align_items, Some(Center))
assert_eq(r.justify_content, Some(SpaceBetween))
assert_eq(r.align_content, Some(Stretch))
assert_eq(r.align_self, Some(End))
assert_eq(r.grid_cols, Some({ repeat: 3, min_size: Zero, }))
assert_eq(
r.grid_location,
Some({
column: { start: Span(2), end: Span(2), },
row: { start: Line(1), end: Auto, },
}),
)
let shadows = r.box_shadow.unwrap()
assert_eq(shadows.length(), 2)
assert_eq(shadows[0].offset.y, @geometry.px(4.0))
assert_eq(shadows[0].spread_radius, @geometry.px(-1.0))
assert_eq(r.copy().content_normal().align_content, None)
}
///|
test "overflow mask" {
let bounds : @geometry.Bounds[@geometry.Pixels] = {
origin: @geometry.point(@geometry.px(10.0), @geometry.px(10.0)),
size: @geometry.size(@geometry.px(100.0), @geometry.px(50.0)),
}
let rem = @geometry.px(16.0)
let visible : @style.Style = Default::default()
assert_eq(visible.overflow_mask(bounds, rem), None)
let clipped = visible.refined(
@style.StyleRefinement::new()
.overflow_hidden()
.border_2()
.border_color(@color.black()),
)
// Borders are inset from the mask when visible.
assert_eq(clipped.overflow_mask(bounds, rem).unwrap().bounds, {
origin: @geometry.point(@geometry.px(12.0), @geometry.px(12.0)),
size: @geometry.size(@geometry.px(96.0), @geometry.px(46.0)),
})
assert_true(clipped.is_border_visible())
// Only the clipped axis is restricted.
let y_only = visible.refined(
@style.StyleRefinement::new().overflow_y_hidden(),
)
let mask = y_only.overflow_mask(bounds, rem).unwrap().bounds
assert_eq(mask, bounds)
}
///|
test "object fit" {
let bounds : @geometry.Bounds[@geometry.Pixels] = {
origin: @geometry.point(@geometry.px(0.0), @geometry.px(0.0)),
size: @geometry.size(@geometry.px(200.0), @geometry.px(100.0)),
}
let image : @geometry.Size[@geometry.DevicePixels] = {
width: DevicePixels(50),
height: DevicePixels(50),
}
let contain = @style.ObjectFit::Contain.get_bounds(bounds, image)
assert_eq(contain.origin.x, @geometry.px(50.0))
assert_eq(contain.size.width, @geometry.px(100.0))
let cover = @style.ObjectFit::Cover.get_bounds(bounds, image)
assert_eq(cover.size.width, @geometry.px(200.0))
assert_eq(cover.origin.y, @geometry.px(-50.0))
let scale_down = @style.ObjectFit::ScaleDown.get_bounds(bounds, image)
assert_eq(scale_down.size.width, @geometry.px(50.0))
assert_eq(scale_down.origin.x, @geometry.px(75.0))
assert_eq(@style.ObjectFit::Fill.get_bounds(bounds, image), bounds)
assert_eq(
@style.ObjectFit::None.get_bounds(bounds, image).size.height,
@geometry.px(50.0),
)
}
///|
test "fills accept colors and backgrounds" {
let from_hsla = @style.StyleRefinement::new().bg(@color.red())
let from_rgba = @style.StyleRefinement::new().bg(@color.rgb(0xff0000))
assert_eq(from_hsla.background, Some(Color(@color.red().to_background())))
assert_eq(from_rgba.background.unwrap().color().unwrap().tag, Solid)
let gradient = @color.linear_gradient(
90.0,
@color.linear_color_stop(@color.red(), 0.0),
@color.linear_color_stop(@color.blue(), 1.0),
)
assert_eq(
@style.StyleRefinement::new().bg(gradient).background,
Some(Color(gradient)),
)
}
+1045
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+315
View File
@@ -0,0 +1,315 @@
// Style enums and small value types, ported from gpui/src/style.rs (and
// CursorStyle from gpui/src/platform.rs).
///|
#derive(Eq, Hash, Debug)
pub(all) enum Display {
Block
Flex
Grid
None
}
///|
/// GPUI's `Display::default()` is `Flex` (note: `Style::default()` uses
/// `Block`).
pub impl Default for Display with fn default() {
Flex
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum Visibility {
Visible
Hidden
}
///|
pub impl Default for Visibility with fn default() {
Visible
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum Overflow {
/// Content is not clipped and does not affect layout size.
Visible
/// Content is clipped, but the element is not a scroll container.
Clip
/// Content is clipped.
Hidden
/// Content is clipped and scrollable.
Scroll
}
///|
pub impl Default for Overflow with fn default() {
Visible
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum Position {
Relative
Absolute
}
///|
pub impl Default for Position with fn default() {
Relative
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum FlexDirection {
Row
Column
RowReverse
ColumnReverse
}
///|
pub impl Default for FlexDirection with fn default() {
Row
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum FlexWrap {
NoWrap
Wrap
WrapReverse
}
///|
pub impl Default for FlexWrap with fn default() {
NoWrap
}
///|
/// Cross-axis alignment. GPUI's `AlignSelf`, `JustifyItems` and
/// `JustifySelf` are aliases of this type.
#derive(Eq, Hash, Debug)
pub(all) enum AlignItems {
Start
End
FlexStart
FlexEnd
Center
Baseline
Stretch
}
///|
/// Distribution of space. GPUI's `JustifyContent` is an alias of this type.
#derive(Eq, Hash, Debug)
pub(all) enum AlignContent {
Start
End
FlexStart
FlexEnd
Center
Stretch
SpaceBetween
SpaceEvenly
SpaceAround
}
///|
#derive(Eq, Compare, Hash, Debug)
pub(all) enum GridTemplateMinSize {
Zero
MinContent
MaxContent
}
///|
pub impl Default for GridTemplateMinSize with fn default() {
Zero
}
///|
/// `repeat(repeat, minmax(min_size, 1fr))` tracks.
#derive(Eq, Compare, Hash, Default, Debug)
pub(all) struct GridTemplate {
repeat : Int32
min_size : GridTemplateMinSize
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum WhiteSpace {
Normal
Nowrap
}
///|
pub impl Default for WhiteSpace with fn default() {
Normal
}
///|
/// How text that does not fit is truncated; the string is the marker to
/// insert (e.g. "…").
#derive(Eq, Hash, Debug)
pub(all) enum TextOverflow {
Truncate(String)
TruncateStart(String)
TruncateMiddle(String)
}
///|
#derive(Eq, Hash, Debug)
pub(all) enum TextAlign {
Left
Center
Right
}
///|
pub impl Default for TextAlign with fn default() {
Left
}
///|
/// The mouse cursor to show (GPUI: platform.rs).
#derive(Eq, Hash, Debug)
pub(all) enum CursorStyle {
Arrow
IBeam
Crosshair
ClosedHand
OpenHand
PointingHand
ResizeLeft
ResizeRight
ResizeLeftRight
ResizeUp
ResizeDown
ResizeUpDown
ResizeUpLeftDownRight
ResizeUpRightDownLeft
ResizeColumn
ResizeRow
IBeamCursorForVerticalLayout
OperationNotAllowed
DragLink
DragCopy
ContextualMenu
}
///|
pub impl Default for CursorStyle with fn default() {
Arrow
}
///|
#derive(Eq, Debug)
pub(all) struct BoxShadow {
color : @color.Hsla
offset : @geometry.Point[@geometry.Pixels]
blur_radius : @geometry.Pixels
spread_radius : @geometry.Pixels
inset : Bool
}
///|
/// A sharp drop shadow at the given offset; refine with the builder methods.
pub fn BoxShadow::new(
offset_x : @geometry.Pixels,
offset_y : @geometry.Pixels,
color : @color.Hsla,
) -> BoxShadow {
{
color,
offset: { x: offset_x, y: offset_y, },
blur_radius: @geometry.pixels_zero,
spread_radius: @geometry.pixels_zero,
inset: false,
}
}
///|
pub fn BoxShadow::blur_radius(
self : BoxShadow,
blur_radius : @geometry.Pixels,
) -> BoxShadow {
{ ..self, blur_radius, }
}
///|
pub fn BoxShadow::spread_radius(
self : BoxShadow,
spread_radius : @geometry.Pixels,
) -> BoxShadow {
{ ..self, spread_radius, }
}
///|
/// Makes this an inner shadow.
pub fn BoxShadow::inset(self : BoxShadow) -> BoxShadow {
{ ..self, inset: true, }
}
///|
#derive(Eq, Hash, Default, Debug)
pub(all) struct UnderlineStyle {
thickness : @geometry.Pixels
/// Defaults to the text color.
color : @color.Hsla?
wavy : Bool
}
///|
#derive(Eq, Hash, Default, Debug)
pub(all) struct StrikethroughStyle {
thickness : @geometry.Pixels
/// Defaults to the text color.
color : @color.Hsla?
}
///|
/// How an element's background is painted.
#derive(Eq, Debug)
pub(all) enum Fill {
Color(@color.Background)
}
///|
pub impl Default for Fill with fn default() {
Color(Default::default())
}
///|
pub fn Fill::color(self : Fill) -> @color.Background? {
match self {
Color(background) => Some(background)
}
}
///|
/// Anything usable where GPUI takes `impl Into<Fill>`: `Fill`, `Background`,
/// `Hsla` and `Rgba`.
pub(open) trait IntoFill {
fn into_fill(Self) -> Fill
}
///|
pub impl IntoFill for Fill with fn into_fill(self) {
self
}
///|
pub impl IntoFill for @color.Background with fn into_fill(self) {
Color(self)
}
///|
pub impl IntoFill for @color.Hsla with fn into_fill(self) {
Color(self.to_background())
}
///|
pub impl IntoFill for @color.Rgba with fn into_fill(self) {
Color(self.to_background())
}
+680
View File
@@ -0,0 +1,680 @@
#!/usr/bin/env python3
"""Generates the style refinement types and the `Styled` fluent API.
GPUI produces this code with Rust macros: `#[derive(Refineable)]`
(crates/refineable) and `gpui_macros::style_helpers!` plus the
`*_style_methods!` macros (crates/gpui_macros/src/styles.rs). MoonBit has no
macros, so this script emits the equivalent MoonBit source. The output is
committed; rerun after changing this script or `src/style/styled.mbt`:
python3 tools/gen_style.py && moon fmt
Outputs (all in src/style/):
style_generated.mbt Style, StyleRefinement, TextStyle,
TextStyleRefinement and their refine methods
styled_generated.mbt the `Styled` trait and generated helpers
styled_extend_generated.mbt promotes all `Styled` methods on
StyleRefinement
Other packages that implement `Styled` (e.g. `Div`) need the same `extend`
list; pass `--extend Type=path/to/file.mbt` to emit it there.
"""
import argparse
import os
import re
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STYLE_DIR = os.path.join(ROOT, "src", "style")
HANDWRITTEN = os.path.join(STYLE_DIR, "styled.mbt")
HEADER = (
"// GENERATED by tools/gen_style.py. DO NOT EDIT.\n"
"// Port of GPUI's derive(Refineable) / gpui_macros style helpers.\n\n"
)
G = "@geometry"
# ---------------------------------------------------------------------------
# Refineable structs
#
# kind:
# "plain" field T, refinement T? (set when Some)
# "option" field T?, refinement T? (set when Some)
# ("nested", RefinementType) refined recursively with `.refined(...)`
# ---------------------------------------------------------------------------
STYLE_FIELDS = [
("display", "Display", "plain", "How the element is laid out (block, flex, grid, none)."),
("visibility", "Visibility", "plain", "Whether the element is painted."),
("overflow", "@geometry.Point[Overflow]", ("nested", "@geometry.PointRefinement[Overflow]"), "Overflow behavior per axis."),
("scrollbar_width", "@geometry.AbsoluteLength", "plain", "Space reserved for scrollbars."),
("allow_concurrent_scroll", "Bool", "plain", "Whether both axes may scroll at once."),
("restrict_scroll_to_axis", "Bool", "plain", "Whether scrolling is restricted to the dominant axis."),
("position", "Position", "plain", "Relative or absolute positioning."),
("inset", "@geometry.Edges[@geometry.Length]", ("nested", "@geometry.EdgesRefinement[@geometry.Length]"), "Offsets for positioned elements."),
("size", "@geometry.Size[@geometry.Length]", ("nested", "@geometry.SizeRefinement[@geometry.Length]"), "Preferred size."),
("min_size", "@geometry.Size[@geometry.Length]", ("nested", "@geometry.SizeRefinement[@geometry.Length]"), "Minimum size."),
("max_size", "@geometry.Size[@geometry.Length]", ("nested", "@geometry.SizeRefinement[@geometry.Length]"), "Maximum size."),
("aspect_ratio", "Double?", "option", "Preferred width / height ratio."),
("margin", "@geometry.Edges[@geometry.Length]", ("nested", "@geometry.EdgesRefinement[@geometry.Length]"), "Outer spacing."),
("padding", "@geometry.Edges[@geometry.DefiniteLength]", ("nested", "@geometry.EdgesRefinement[@geometry.DefiniteLength]"), "Inner spacing."),
("border_widths", "@geometry.Edges[@geometry.AbsoluteLength]", ("nested", "@geometry.EdgesRefinement[@geometry.AbsoluteLength]"), "Border width per side."),
("align_items", "AlignItems?", "option", "Cross-axis alignment of children."),
("align_self", "AlignItems?", "option", "Cross-axis alignment of this element (GPUI: AlignSelf)."),
("align_content", "AlignContent?", "option", "Distribution of lines in a multi-line container."),
("justify_content", "AlignContent?", "option", "Main-axis distribution of children (GPUI: JustifyContent)."),
("gap", "@geometry.Size[@geometry.DefiniteLength]", ("nested", "@geometry.SizeRefinement[@geometry.DefiniteLength]"), "Gap between children (width: column gap, height: row gap)."),
("flex_direction", "FlexDirection", "plain", "Main axis direction."),
("flex_wrap", "FlexWrap", "plain", "Whether children wrap onto new lines."),
("flex_basis", "@geometry.Length", "plain", "Initial main size before growing or shrinking."),
("flex_grow", "Double", "plain", "Share of free space to take."),
("flex_shrink", "Double", "plain", "Share of negative space to give up."),
("background", "Fill?", "option", "Background fill."),
("border_color", "@color.Hsla?", "option", "Border color."),
("border_style", "@scene.BorderStyle", "plain", "Solid or dashed border."),
("corner_radii", "@geometry.Corners[@geometry.AbsoluteLength]", ("nested", "@geometry.CornersRefinement[@geometry.AbsoluteLength]"), "Corner radii."),
("box_shadow", "Array[BoxShadow]", "plain", "Box shadows, painted in order. Treat as immutable."),
("text", "TextStyleRefinement", ("nested", "TextStyleRefinement"), "Text style inherited by descendants."),
("mouse_cursor", "CursorStyle?", "option", "Cursor shown while hovering."),
("opacity", "Double?", "option", "Opacity multiplier for the element and its children."),
("grid_cols", "GridTemplate?", "option", "Grid column template."),
("grid_rows", "GridTemplate?", "option", "Grid row template."),
("grid_location", "@geometry.GridLocation?", "option", "Placement within a grid parent."),
("debug", "Bool", "plain", "Paint a debug outline around the element."),
("debug_below", "Bool", "plain", "Paint debug outlines around all descendants."),
]
TEXT_STYLE_FIELDS = [
("color", "@color.Hsla", "plain", "Text color."),
("font_family", "String", "plain", "Font family name."),
("font_features", "@font.FontFeatures", "plain", "OpenType features."),
("font_fallbacks", "@font.FontFallbacks?", "option", "Fallback families."),
("font_size", "@geometry.AbsoluteLength", "plain", "Font size."),
("line_height", "@geometry.DefiniteLength", "plain", "Line height; fractions are relative to the font size."),
("font_weight", "@font.FontWeight", "plain", "Font weight."),
("font_style", "@font.FontStyle", "plain", "Upright, italic or oblique."),
("background_color", "@color.Hsla?", "option", "Background behind the glyphs."),
("underline", "UnderlineStyle?", "option", "Underline decoration."),
("strikethrough", "StrikethroughStyle?", "option", "Strikethrough decoration."),
("white_space", "WhiteSpace", "plain", "Whether text wraps."),
("text_overflow", "TextOverflow?", "option", "How overflowing text is truncated."),
("text_align", "TextAlign", "plain", "Horizontal alignment."),
("line_clamp", "Int?", "option", "Maximum number of lines."),
]
def refinement_type(ty, kind):
if kind == "plain":
return f"{ty}?"
if kind == "option":
return ty
return kind[1]
def gen_style_structs():
out = [HEADER]
# --- Style -------------------------------------------------------------
out.append("///|\n/// The fully resolved style of an element (GPUI: `Style`).\n")
out.append("/// Immutable; build one by refining `Style::default()`.\n")
out.append("#derive(Eq, Debug)\npub(all) struct Style {\n")
for name, ty, kind, doc in STYLE_FIELDS:
out.append(f" /// {doc}\n {name} : {ty}\n")
out.append("}\n\n")
# --- StyleRefinement -----------------------------------------------------
out.append(
"///|\n/// A partial `Style`: every field optional (GPUI: `StyleRefinement`).\n"
"/// Mutable, because it is the builder that `Styled` methods write to.\n"
)
out.append("#derive(Eq, Debug)\npub(all) struct StyleRefinement {\n")
for name, ty, kind, doc in STYLE_FIELDS:
out.append(f" mut {name} : {refinement_type(ty, kind)}\n")
out.append("}\n\n")
out.append("///|\n/// An empty refinement (no field set).\n")
out.append("pub fn StyleRefinement::new() -> StyleRefinement {\n {\n")
for name, ty, kind, doc in STYLE_FIELDS:
value = "None" if kind in ("plain", "option") else "Default::default()"
out.append(f" {name}: {value},\n")
out.append(" }\n}\n\n")
out.append(
"///|\npub impl Default for StyleRefinement with default() {\n"
" StyleRefinement::new()\n}\n\n"
)
out.append("///|\n/// A copy that can be mutated independently.\n")
out.append("pub fn StyleRefinement::copy(self : StyleRefinement) -> StyleRefinement {\n {\n")
for name, *_ in STYLE_FIELDS:
out.append(f" {name}: self.{name},\n")
out.append(" }\n}\n\n")
out.append("///|\n/// Applies `other` on top of `self`, in place: fields set in `other` win.\n")
out.append(
"pub fn StyleRefinement::refine(\n self : StyleRefinement,\n other : StyleRefinement,\n) -> Unit {\n"
)
for name, ty, kind, doc in STYLE_FIELDS:
if kind in ("plain", "option"):
out.append(f" if other.{name} is Some(_) {{\n self.{name} = other.{name}\n }}\n")
else:
out.append(f" self.{name} = self.{name}.refined(other.{name})\n")
out.append("}\n\n")
out.append("///|\n/// A new refinement: `self` with `other` applied on top.\n")
out.append(
"pub fn StyleRefinement::refined(\n self : StyleRefinement,\n other : StyleRefinement,\n) -> StyleRefinement {\n"
" let result = self.copy()\n result.refine(other)\n result\n}\n\n"
)
out.append("///|\n/// Whether any field is set.\n")
out.append("pub fn StyleRefinement::is_some(self : StyleRefinement) -> Bool {\n")
conds = []
for name, ty, kind, doc in STYLE_FIELDS:
if kind in ("plain", "option"):
conds.append(f"self.{name} is Some(_)")
else:
conds.append(f"self.{name}.is_some()")
out.append(" " + " ||\n ".join(conds) + "\n}\n\n")
out.append("///|\n/// `self` with every field set in `refinement` overwritten.\n")
out.append("pub fn Style::refined(self : Style, refinement : StyleRefinement) -> Style {\n {\n")
for name, ty, kind, doc in STYLE_FIELDS:
if kind == "plain":
out.append(f" {name}: refine_value(refinement.{name}, self.{name}),\n")
elif kind == "option":
out.append(f" {name}: refine_option(refinement.{name}, self.{name}),\n")
else:
out.append(f" {name}: self.{name}.refined(refinement.{name}),\n")
out.append(" }\n}\n\n")
# --- TextStyle -----------------------------------------------------------
out.append("///|\n/// The resolved style of a run of text (GPUI: `TextStyle`).\n")
out.append("#derive(Eq, Debug)\npub(all) struct TextStyle {\n")
for name, ty, kind, doc in TEXT_STYLE_FIELDS:
out.append(f" /// {doc}\n {name} : {ty}\n")
out.append("}\n\n")
out.append("///|\n/// A partial `TextStyle` (GPUI: `TextStyleRefinement`). Immutable.\n")
out.append("#derive(Eq, Default, Debug)\npub(all) struct TextStyleRefinement {\n")
for name, ty, kind, doc in TEXT_STYLE_FIELDS:
out.append(f" {name} : {refinement_type(ty, kind)}\n")
out.append("}\n\n")
out.append("///|\n/// Combines two refinements; fields set in `other` win.\n")
out.append(
"pub fn TextStyleRefinement::refined(\n self : TextStyleRefinement,\n"
" other : TextStyleRefinement,\n) -> TextStyleRefinement {\n {\n"
)
for name, *_ in TEXT_STYLE_FIELDS:
out.append(f" {name}: refine_option(other.{name}, self.{name}),\n")
out.append(" }\n}\n\n")
out.append("///|\n/// Whether any field is set.\n")
out.append("pub fn TextStyleRefinement::is_some(self : TextStyleRefinement) -> Bool {\n")
out.append(
" "
+ " ||\n ".join(f"self.{name} is Some(_)" for name, *_ in TEXT_STYLE_FIELDS)
+ "\n}\n\n"
)
out.append("///|\n/// `self` with every field set in `refinement` overwritten.\n")
out.append(
"pub fn TextStyle::refined(\n self : TextStyle,\n refinement : TextStyleRefinement,\n) -> TextStyle {\n {\n"
)
for name, ty, kind, doc in TEXT_STYLE_FIELDS:
fn = "refine_value" if kind == "plain" else "refine_option"
out.append(f" {name}: {fn}(refinement.{name}, self.{name}),\n")
out.append(" }\n}\n")
return "".join(out)
# ---------------------------------------------------------------------------
# Styled helpers (gpui_macros/src/styles.rs)
# ---------------------------------------------------------------------------
# Container field -> length type stored in StyleRefinement.
CONTAINER_TYPES = {
"size": "Length",
"min_size": "Length",
"max_size": "Length",
"inset": "Length",
"margin": "Length",
"padding": "DefiniteLength",
"gap": "DefiniteLength",
"corner_radii": "AbsoluteLength",
"border_widths": "AbsoluteLength",
}
# Number of members of each container (Size: 2, Edges/Corners: 4).
CONTAINER_ARITY = {
"size": 2,
"min_size": 2,
"max_size": 2,
"gap": 2,
"inset": 4,
"margin": 4,
"padding": 4,
"corner_radii": 4,
"border_widths": 4,
}
PARAM_TYPES = {
"Length": ("@geometry.IntoLength", "into_length"),
"DefiniteLength": ("@geometry.IntoDefiniteLength", "into_definite_length"),
"AbsoluteLength": ("@geometry.IntoAbsoluteLength", "into_absolute_length"),
}
# (prefix, auto_allowed, fields, description)
BOX_PREFIXES = [
("w", True, ["size.width"], "the width"),
("h", True, ["size.height"], "the height"),
("size", True, ["size.width", "size.height"], "the width and height"),
("min_size", True, ["min_size.width", "min_size.height"], "the minimum width and height"),
("min_w", True, ["min_size.width"], "the minimum width"),
("min_h", True, ["min_size.height"], "the minimum height"),
("max_size", True, ["max_size.width", "max_size.height"], "the maximum width and height"),
("max_w", True, ["max_size.width"], "the maximum width"),
("max_h", True, ["max_size.height"], "the maximum height"),
("gap", False, ["gap.width", "gap.height"], "the gap between rows and columns"),
("gap_x", False, ["gap.width"], "the gap between columns"),
("gap_y", False, ["gap.height"], "the gap between rows"),
]
MARGIN_PREFIXES = [
("m", True, ["margin.top", "margin.bottom", "margin.left", "margin.right"], "the margin on all sides"),
("mt", True, ["margin.top"], "the top margin"),
("mb", True, ["margin.bottom"], "the bottom margin"),
("my", True, ["margin.top", "margin.bottom"], "the vertical margin"),
("mx", True, ["margin.left", "margin.right"], "the horizontal margin"),
("ml", True, ["margin.left"], "the left margin"),
("mr", True, ["margin.right"], "the right margin"),
]
PADDING_PREFIXES = [
("p", False, ["padding.top", "padding.bottom", "padding.left", "padding.right"], "the padding on all sides"),
("pt", False, ["padding.top"], "the top padding"),
("pb", False, ["padding.bottom"], "the bottom padding"),
("px", False, ["padding.left", "padding.right"], "the horizontal padding"),
("py", False, ["padding.top", "padding.bottom"], "the vertical padding"),
("pl", False, ["padding.left"], "the left padding"),
("pr", False, ["padding.right"], "the right padding"),
]
POSITION_PREFIXES = [
("inset", True, ["inset.top", "inset.right", "inset.bottom", "inset.left"], "the inset on all sides"),
("top", True, ["inset.top"], "the top inset"),
("bottom", True, ["inset.bottom"], "the bottom inset"),
("left", True, ["inset.left"], "the left inset"),
("right", True, ["inset.right"], "the right inset"),
]
# (suffix, (unit, value))
BOX_SUFFIXES = [
("0", ("px", 0.0)),
("0p5", ("rems", 0.125)),
("1", ("rems", 0.25)),
("1p5", ("rems", 0.375)),
("2", ("rems", 0.5)),
("2p5", ("rems", 0.625)),
("3", ("rems", 0.75)),
("3p5", ("rems", 0.875)),
("4", ("rems", 1.0)),
("5", ("rems", 1.25)),
("6", ("rems", 1.5)),
("7", ("rems", 1.75)),
("8", ("rems", 2.0)),
("9", ("rems", 2.25)),
("10", ("rems", 2.5)),
("11", ("rems", 2.75)),
("12", ("rems", 3.0)),
("16", ("rems", 4.0)),
("20", ("rems", 5.0)),
("24", ("rems", 6.0)),
("32", ("rems", 8.0)),
("40", ("rems", 10.0)),
("48", ("rems", 12.0)),
("56", ("rems", 14.0)),
("64", ("rems", 16.0)),
("72", ("rems", 18.0)),
("80", ("rems", 20.0)),
("96", ("rems", 24.0)),
("112", ("rems", 28.0)),
("128", ("rems", 32.0)),
("auto", ("auto", None)),
("px", ("px", 1.0)),
("full", ("relative", 1.0)),
("1_2", ("relative", 0.5)),
("1_3", ("relative", 1.0 / 3.0)),
("2_3", ("relative", 2.0 / 3.0)),
("1_4", ("relative", 0.25)),
("2_4", ("relative", 0.5)),
("3_4", ("relative", 0.75)),
("1_5", ("relative", 0.2)),
("2_5", ("relative", 0.4)),
("3_5", ("relative", 0.6)),
("4_5", ("relative", 0.8)),
("1_6", ("relative", 1.0 / 6.0)),
("5_6", ("relative", 5.0 / 6.0)),
("1_12", ("relative", 1.0 / 12.0)),
]
CORNER_PREFIXES = [
("rounded", ["corner_radii.top_left", "corner_radii.top_right", "corner_radii.bottom_right", "corner_radii.bottom_left"], "all corner radii"),
("rounded_t", ["corner_radii.top_left", "corner_radii.top_right"], "the top corner radii"),
("rounded_b", ["corner_radii.bottom_left", "corner_radii.bottom_right"], "the bottom corner radii"),
("rounded_r", ["corner_radii.top_right", "corner_radii.bottom_right"], "the right corner radii"),
("rounded_l", ["corner_radii.top_left", "corner_radii.bottom_left"], "the left corner radii"),
("rounded_tl", ["corner_radii.top_left"], "the top-left corner radius"),
("rounded_tr", ["corner_radii.top_right"], "the top-right corner radius"),
("rounded_bl", ["corner_radii.bottom_left"], "the bottom-left corner radius"),
("rounded_br", ["corner_radii.bottom_right"], "the bottom-right corner radius"),
]
CORNER_SUFFIXES = [
("none", ("px", 0.0)),
("xs", ("rems", 0.125)),
("sm", ("rems", 0.25)),
("md", ("rems", 0.375)),
("lg", ("rems", 0.5)),
("xl", ("rems", 0.75)),
("2xl", ("rems", 1.0)),
("3xl", ("rems", 1.5)),
("full", ("px", 9999.0)),
]
BORDER_PREFIXES = [
("border", ["border_widths.top", "border_widths.right", "border_widths.bottom", "border_widths.left"], "the border width on all sides"),
("border_t", ["border_widths.top"], "the top border width"),
("border_b", ["border_widths.bottom"], "the bottom border width"),
("border_r", ["border_widths.right"], "the right border width"),
("border_l", ["border_widths.left"], "the left border width"),
("border_x", ["border_widths.left", "border_widths.right"], "the left and right border widths"),
("border_y", ["border_widths.top", "border_widths.bottom"], "the top and bottom border widths"),
]
BORDER_SUFFIXES = [(str(n), ("px", float(n))) for n in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 16, 20, 24, 32]]
# (method, CursorStyle variant)
CURSORS = [
("cursor_default", "Arrow"),
("cursor_pointer", "PointingHand"),
("cursor_text", "IBeam"),
("cursor_move", "ClosedHand"),
("cursor_not_allowed", "OperationNotAllowed"),
("cursor_context_menu", "ContextualMenu"),
("cursor_crosshair", "Crosshair"),
("cursor_vertical_text", "IBeamCursorForVerticalLayout"),
("cursor_alias", "DragLink"),
("cursor_copy", "DragCopy"),
("cursor_no_drop", "OperationNotAllowed"),
("cursor_grab", "OpenHand"),
("cursor_grabbing", "ClosedHand"),
("cursor_ew_resize", "ResizeLeftRight"),
("cursor_ns_resize", "ResizeUpDown"),
("cursor_nesw_resize", "ResizeUpRightDownLeft"),
("cursor_nwse_resize", "ResizeUpLeftDownRight"),
("cursor_col_resize", "ResizeColumn"),
("cursor_row_resize", "ResizeRow"),
("cursor_n_resize", "ResizeUp"),
("cursor_e_resize", "ResizeRight"),
("cursor_s_resize", "ResizeDown"),
("cursor_w_resize", "ResizeLeft"),
]
def fmt_number(value):
text = repr(float(value))
if "e" in text or "E" in text:
return text
return text if "." in text else text + ".0"
def length_expr(spec, target, negate):
"""MoonBit expression for a predefined length, converted to `target`."""
unit, value = spec
if unit == "auto":
assert target == "Length", "auto is only valid for Length fields"
return f"{G}.Length::Auto"
if negate:
value = -value
if value == 0.0:
value = -0.0
number = fmt_number(value)
if unit == "relative":
base = f"{G}.relative({number})"
if target == "Length":
return f"{base}.to_length()"
if target == "DefiniteLength":
return base
raise ValueError("relative lengths are not absolute")
base = f"{G}.{unit}({number})"
return {
"Length": f"{base}.to_length()",
"DefiniteLength": f"{base}.to_definite()",
"AbsoluteLength": f"{base}.to_absolute()",
}[target]
def human(spec, negate):
unit, value = spec
if unit == "auto":
return "`auto`"
value = -value if negate else value
if unit == "relative":
return f"{fmt_number(value * 100)}%"
if unit == "rems":
return f"`rems({fmt_number(value)})` ({fmt_number(value * 16)}px at a 16px rem)"
return f"`px({fmt_number(value)})`"
def group_fields(fields):
"""[('margin', ['top', 'bottom']), ...] preserving order."""
groups = {}
order = []
for f in fields:
container, member = f.split(".")
if container not in groups:
groups[container] = []
order.append(container)
groups[container].append(member)
return [(c, groups[c]) for c in order]
def assignment_body(fields, value_expr):
lines = [" let style = self.style()", f" let value = Some({value_expr})"]
for container, members in group_fields(fields):
updates = ", ".join(f"{m}: value" for m in members)
if len(members) == CONTAINER_ARITY[container]:
lines.append(f" style.{container} = {{ {updates} }}")
else:
lines.append(f" style.{container} = {{ ..style.{container}, {updates} }}")
lines.append(" self")
return "\n".join(lines)
class Methods:
def __init__(self):
self.decls = [] # (name, param_types)
self.impls = [] # source blocks
def add(self, name, params, body, doc):
"""params: list of (name, type) excluding self."""
self.decls.append((name, [t for _, t in params]))
sig = ", ".join(["self : Self"] + [f"{n} : {t}" for n, t in params])
self.impls.append(f"///|\n/// {doc}\nimpl Styled with fn {name}({sig}) -> Self {{\n{body}\n}}\n")
def gen_box_methods(m, prefixes, suffixes):
for prefix, auto_allowed, fields, desc in prefixes:
target = CONTAINER_TYPES[fields[0].split(".")[0]]
if not auto_allowed:
assert target != "Length" or prefix in ("gap", "gap_x", "gap_y")
param_type, conv = PARAM_TYPES[target]
m.add(
prefix,
[("length", "&" + param_type)],
assignment_body(fields, f"length.{conv}()"),
f"Sets {desc}.",
)
for suffix, spec in suffixes:
if suffix != "auto" or auto_allowed:
m.add(
f"{prefix}_{suffix}",
[],
assignment_body(fields, length_expr(spec, target, False)),
f"Sets {desc} to {human(spec, False)}.",
)
if suffix != "auto":
m.add(
f"{prefix}_neg_{suffix}",
[],
assignment_body(fields, length_expr(spec, target, True)),
f"Sets {desc} to {human(spec, True)}.",
)
def gen_value_methods(m, prefixes, suffixes):
for prefix, fields, desc in prefixes:
target = CONTAINER_TYPES[fields[0].split(".")[0]]
param_type, conv = PARAM_TYPES[target]
m.add(
prefix,
[("length", "&" + param_type)],
assignment_body(fields, f"length.{conv}()"),
f"Sets {desc}.",
)
for suffix, spec in suffixes:
m.add(
f"{prefix}_{suffix}",
[],
assignment_body(fields, length_expr(spec, target, False)),
f"Sets {desc} to {human(spec, False)}.",
)
def gen_cursor_methods(m):
for name, variant in CURSORS:
m.add(
name,
[],
f" self.style().mouse_cursor = Some(CursorStyle::{variant})\n self",
f"Shows the `{variant}` cursor while hovering.",
)
def split_params(text):
parts, depth, current = [], 0, ""
for ch in text:
if ch in "[(":
depth += 1
elif ch in "])":
depth -= 1
if ch == "," and depth == 0:
parts.append(current)
current = ""
else:
current += ch
if current.strip():
parts.append(current)
return [p.strip() for p in parts if p.strip()]
def handwritten_decls():
src = open(HANDWRITTEN).read()
decls = []
pattern = re.compile(
r"^impl Styled with (?:fn )?(\w+)\((.*?)\)\s*->\s*Self\s*\{", re.S | re.M
)
for match in pattern.finditer(src):
name = match.group(1)
params = split_params(match.group(2))
if not params or not params[0].startswith("self"):
sys.exit(f"gen_style: {name}: first parameter must be `self : Self`")
types = []
for p in params[1:]:
if ":" not in p:
sys.exit(f"gen_style: {name}: parameter `{p}` needs a type annotation")
types.append(p.split(":", 1)[1].strip())
decls.append((name, types))
if not decls:
sys.exit("gen_style: found no `impl Styled with` blocks in styled.mbt")
return decls
def gen_styled():
m = Methods()
gen_box_methods(m, BOX_PREFIXES, BOX_SUFFIXES)
gen_box_methods(m, MARGIN_PREFIXES, BOX_SUFFIXES)
gen_box_methods(m, PADDING_PREFIXES, BOX_SUFFIXES)
gen_box_methods(m, POSITION_PREFIXES, BOX_SUFFIXES)
gen_value_methods(m, CORNER_PREFIXES, CORNER_SUFFIXES)
gen_value_methods(m, BORDER_PREFIXES, BORDER_SUFFIXES)
gen_cursor_methods(m)
all_decls = handwritten_decls() + m.decls
names = [n for n, _ in all_decls]
duplicates = sorted({n for n in names if names.count(n) > 1})
if duplicates:
sys.exit(f"gen_style: duplicate Styled methods: {duplicates}")
out = [HEADER]
out.append(
"///|\n/// Fluent styling methods (GPUI: `Styled`). Implementors only provide\n"
"/// `style`, the refinement the methods write to; every other method has a\n"
"/// default implementation. Because methods of a trait are not callable with\n"
"/// dot syntax until promoted, implementors also need the `extend` list that\n"
"/// tools/gen_style.py emits (`--extend Type=file`).\n"
)
out.append("pub(open) trait Styled {\n fn style(Self) -> StyleRefinement\n")
for name, types in all_decls:
out.append(f" fn {name}({', '.join(['Self'] + types)}) -> Self = _\n")
out.append("}\n\n")
out.append("\n".join(m.impls))
return "".join(out), names
def gen_extend(type_name, names):
body = ",\n ".join(names)
return (
HEADER
+ f"///|\npub extend {type_name} with Styled::{{\n {body},\n}}\n"
)
def write(path, content):
with open(path, "w") as f:
f.write(content)
print(f"wrote {os.path.relpath(path, ROOT)}")
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument(
"--extend",
action="append",
default=[],
metavar="TYPE=FILE",
help="also emit `pub extend TYPE with Styled::{...}` into FILE (relative to the repo root)",
)
args = parser.parse_args()
write(os.path.join(STYLE_DIR, "style_generated.mbt"), gen_style_structs())
styled, names = gen_styled()
write(os.path.join(STYLE_DIR, "styled_generated.mbt"), styled)
write(
os.path.join(STYLE_DIR, "styled_extend_generated.mbt"),
gen_extend("StyleRefinement", names),
)
for spec in args.extend:
if "=" not in spec:
sys.exit(f"gen_style: --extend expects TYPE=FILE, got {spec!r}")
type_name, path = spec.split("=", 1)
write(os.path.join(ROOT, path), gen_extend(type_name, names))
print(f"{len(names)} Styled methods")
if __name__ == "__main__":
main()