Author SHA1 Message Date
nandiandClaude Opus 5.5 6d8389a97c ci: run moon fmt, check and test on pull requests
CI / moon fmt, check, test (pull_request) Successful in 17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:11:46 -08:00
nandi ae3fd7da55 M1: style — Style/StyleRefinement, generated Styled API, font, card example (#2) 2026-11-24 21:53:38 +00:00
27 changed files with 45697 additions and 30 deletions

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
+37
View File
@@ -13,6 +13,43 @@ roadmap.
| `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:
+56 -28
View File
@@ -130,7 +130,8 @@ stays isolated.
| `geometry` | `geometry.rs`, `ContentMask` (window.rs) | pure | **done** |
| `color` | `color.rs`, `colors.rs` | pure | **done** (`colors.rs` theme defaults pending) |
| `scene` | `scene.rs`, `bounds_tree.rs`, `AtlasTile` (platform.rs) | pure | **done** (see deviations) |
| `style` | `style.rs`, `styled.rs`, Refineable | pure | next |
| `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 |
@@ -146,6 +147,7 @@ stays isolated.
| `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
@@ -331,7 +333,7 @@ gantt
- **M0 (this PR).** `geometry`, `color`, and `scene`: units, rects, colors,
primitives, the bounds tree, layers, batching, and replay.
- **M1: style.**
- **M1: style (done).**
- `Style`, `TextStyle`, `Fill`, `BoxShadow`, and the enums (`Display`,
`Position`, `Overflow`, flex and alignment enums, `Visibility`,
`CursorStyle`, `WhiteSpace`, and so on).
@@ -423,30 +425,56 @@ gantt
---
## 7. Open design questions
### 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.
1. **Entity liveness without `Drop`.** Should entities be released explicitly
(`release()`, or ownership through windows and views)? The alternative is
for strong handles to be ordinary GC references and drop GPUI's release
semantics (`on_release`, dropped-entity cleanup), which is simpler but
diverges. *Recommendation: explicit release for entities that have release
listeners or are observed, with views released when their window closes.*
2. **Text shaping on the web.** Shape with `moon_cosmic`, which is pure,
deterministic, the same on every backend, matches upstream `gpui_web`, and
needs bundled fonts. Or use browser Canvas `measureText`/`fillText`, which
gives system fonts and is quick to build, but has no glyph-level shaping
output and cannot be tested headless. *Recommendation: `moon_cosmic`, with
Canvas text only as an emoji/CJK fallback, as upstream does.*
3. **Layout engine.** Vendor and fix `moon_taffy` 0.5 (which needs toolchain
fixes, and whose API differs from taffy 0.15), or port taffy 0.15's
algorithms directly. *Recommendation: vendor `moon_taffy` now and upstream
the fixes.*
4. **First renderer.** Canvas2D on js (fastest to pixels), WebGPU on js
(closest to GPUI, reusing the WGSL shaders), or a pure software rasterizer
(golden-image tests on every backend). *Recommendation: Canvas2D first,
WebGPU second.*
5. **API surface naming.** Keep GPUI names verbatim where possible (`div()`,
`px()`, `rems()`, `.flex().p_2().bg(...)`), so Rust GPUI code ports
mechanically? *Recommendation: yes.*
6. **Module name.** `experiments/gpui` for now; publishing to mooncakes would
need an owner namespace.
## 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`.
+21 -1
View File
@@ -19,7 +19,7 @@ pub(all) struct Rgba {
///|
/// A color as hue, saturation, lightness and alpha, all in `0.0..=1.0`.
#derive(Eq, Compare, Default, Debug)
#derive(Eq, Compare, Hash, Default, Debug)
pub(all) struct Hsla {
h : Double
s : Double
@@ -515,3 +515,23 @@ pub fn Background::is_transparent(self : Background) -> Bool {
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()
}
+6 -1
View File
@@ -77,7 +77,7 @@ pub(all) enum ColorSpace {
pub impl Default for ColorSpace
pub impl Show for ColorSpace
#derive(Compare, Default, Eq, @debug.Debug)
#derive(Compare, Default, Eq, Hash, @debug.Debug)
pub(all) struct Hsla {
h : Double
s : Double
@@ -93,6 +93,7 @@ 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)
@@ -117,8 +118,12 @@ 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
+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
}
+89
View File
@@ -356,3 +356,92 @@ test "edges and corners" {
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),
})
}
+84
View File
@@ -49,6 +49,9 @@ 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
@@ -144,10 +147,21 @@ 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)
@@ -157,6 +171,8 @@ 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
@@ -194,6 +210,7 @@ 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]
@@ -202,6 +219,36 @@ 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)
@@ -209,6 +256,7 @@ pub(all) enum Length {
}
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
@@ -238,6 +286,9 @@ 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
@@ -262,6 +313,7 @@ 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]
@@ -271,6 +323,14 @@ 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)
@@ -286,6 +346,9 @@ 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
@@ -328,6 +391,7 @@ 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]
@@ -337,6 +401,14 @@ 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
@@ -346,6 +418,18 @@ pub trait Half {
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
}
+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(_)
}
+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()