Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ All notable changes to **blenderui** (BUI). The format follows
- Examples: `examples/animation/` (a hero intro, a card grid, magnetic buttons, a marquee with drag and an equalizer).

### Changed
- **Rust: boxes lay out at fractional positions, as in a browser.** A flex item a quarter of 190px is 47.5px wide (it was rounded to 48), and `element_bounds` reports what `getBoundingClientRect` would. Painting snaps each edge of a box's background, border and image to its nearest device pixel, so edges stay crisp and neighbouring boxes still meet; a canvas's own drawing stays anti-aliased, as a browser canvas.
- **Kit: a layout arranges only the nodes that changed.** A node is arranged again when it or a node under it measured again, or when its place changed; the rest keep their places. A frame where one label changes among 3300 nodes: 0.26 ms instead of 0.31 ms. A change of theme, scale or font still arranges every node.
- **Kit: a layout change redraws only what moved.** A layout used to redraw the whole window. Now each widget's
place on screen is compared with where the last frame drew it, and only widgets that moved, resized, appeared or
Expand Down Expand Up @@ -175,6 +176,17 @@ All notable changes to **blenderui** (BUI). The format follows
- **`BUI_PROFILE=each`.** Prints every frame's phase times and their total, not a 60-frame average, so one slow frame (a resize, a first open) shows.

### Fixed
- **CSS (Rust): the cascade, selectors and `rem` follow the specifications.** Found by checking the engine against the specs, with Lean proofs of specificity and cascade order in `proofs/`:
- `!important` declarations in `@layer`s reverse the layer order (an earlier layer beats a later one, and a layered one beats an unlayered one), and UA `!important` beats author `!important`. They were applied in the normal order.
- `! important` (with a space) and `!IMPORTANT` count as important, in stylesheets and in `css!`.
- `:has()` counts as its most specific argument, like `:is()` and `:not()` (it counted as one class).
- `:scope` inside `@scope (root)` is the scoping root (it was the document's root).
- `:empty` sees the element's children: every element matched it, since rules match before the children are built.
- `:has(+ x)` and `:has(~ x)` see the element's following siblings (they never matched).
- `rem` (and `rlh`, `rex`, `rch`, `rcap`, `ric`) uses the root element's font size, not a fixed 16px.
- Out-of-range `rgb()` channels clamp (`rgb(300 -20 0)` is red) instead of being gamut-mapped.
- `:nth-last-child(An+B of S)` counts the following siblings that match `S` (it saw none, since they aren't built when rules match; `S` may name the element's ancestors).
- `light-dark()`, the system colors (`Canvas`, `LinkText` ...) and `@media (prefers-color-scheme)` follow the theme's mode (they were always dark). Light mode uses a browser's light system colors. Windows re-render when the theme changes, with no `notify_all()` needed.
- **Android: the app runs again after Back.** The host's state (`g_quit`, the wake callback, keep-alive, the stop check) starts over on each `BK_android_attach`, so a relaunch in the same process is not a dead window; the activity is `singleTask`, so a second launch brings the running one back instead of attaching a second activity. `BK_android_detach` (new; `android_main` calls it before the glue frees the app) ends wakes from other threads, which used the freed looper. A Lua script that fails after opening its window shows its error (the error window came back NULL and crashed). A second finger joining a one-finger scroll no longer jumps it; `BK_window_timer` returns -1 (not 0) when the window's timers are full, as `BUI_kit.h` says; a failed window allocation returns NULL (the C demo checks it); a frame whose post fails is redrawn. `build.py` aligns the APK with `zipalign 4` (the libraries are deflated: `-P 16` aligned nothing and failed on build-tools 34) and builds a Rust app's crate with `--lib`.
- **WebAssembly: an unstyled canvas keeps its size after a zoom.** At a pixel ratio of 1 its CSS size was not pinned, so after a zoom or a move to a retina screen it grew on every frame; every resize now sizes the backing store and pins it. `build.py --serve` serves `.wasm` and `.js` with their web types on Windows (the override was set on a `functools.partial`, where it did nothing). The wasm workflow runs on changes to the kit, the GPU raster, core and blenderui too, and the smoke test's click check compares against the hovered button, so it can fail.
- **QuickJS (`bui run`, `bui build`, Android `--js`): timers set from promise jobs run.** A `setTimeout` made in a `.then` was missed (a headless app quit with it pending, a windowed one stalled until the next event); timers now run one task at a time with the promise jobs after each, as in HTML's event loop, and the next deadline is read after the last job. A pump that runs out of rounds with work left schedules the next one. `setTimeout(f, Infinity)` (or `NaN`, negative, past 2^31-1 ms) is a 0 ms delay, as in browsers, instead of panicking the runtime.
Expand Down
8 changes: 8 additions & 0 deletions bindings/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ homepage = "https://bui.preetham.top"
authors = ["BUI contributors"]
rust-version = "1.88"

# Each test and example links the whole kit: full debug info made each one's .pdb ~290 MB.
# Line tables keep file:line in backtraces and panics.
[profile.dev]
debug = "line-tables-only"

[profile.dev.package."*"]
debug = false

# Shipped binaries (bindings/node/scripts/build.js: the Node addon and the
# QuickJS runtime): whole-program LTO in one codegen unit. bui-runtime.exe
# measured 7.56 MB with `release`, 7.09 MB with this (Windows, MSVC).
Expand Down
7 changes: 6 additions & 1 deletion bindings/rust/blenderui-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,14 @@ fn expand(input: TokenStream) -> Result<String, String> {
if name.is_empty() {
return Err(format!("css!: missing property name in `{part}`"));
}
// `!important`: `!` and `important` may have whitespace between them and any case (the
// run-time parser, `css::strip_important`, does the same; a proc macro cannot share it)
let mut value = value.trim();
let mut important = false;
if let Some(v) = value.strip_suffix("!important") {
if let Some(v) = value.len().checked_sub(9)
.filter(|&n| value.is_char_boundary(n) && value[n..].eq_ignore_ascii_case("important"))
.and_then(|n| value[..n].trim_end().strip_suffix('!'))
{
value = v.trim_end();
important = true;
}
Expand Down
6 changes: 3 additions & 3 deletions bindings/rust/blenderui/src/anim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1425,7 +1425,7 @@ impl Animations {
let (now, frame) = (self.now, self.frame);
let st = self.els.entry(key).or_default();
st.seen = frame;
let u = Units { font_size: base.font_size, viewport: env.viewport };
let u = base.units(env.viewport);
let mut running = false;

// -- animations: keep the runs whose name stays, start new ones now
Expand Down Expand Up @@ -1608,7 +1608,7 @@ impl Animations {
if !st.fields().all(|f| paint_field(f, leaf)) {
return None;
}
let u = Units { font_size: p.base.font_size, viewport };
let u = p.base.units(viewport);
let (w, h) = (n.bounds.size.width, n.bounds.size.height);
let at = |c: &Computed| (c.translate.0.resolve(&u, w), c.translate.1.resolve(&u, h));
let style = styles.private_mut(n.style);
Expand Down Expand Up @@ -1683,7 +1683,7 @@ impl Animations {
/// Motion's values on top of the CSS animations (`out`: their result).
fn apply_motion(&mut self, key: u64, base: &Computed, env: &Env, mut out: Option<Computed>) -> Option<Computed> {
if env.motion.is_some() || self.motion.has(key) || crate::motion::pending() {
let u = Units { font_size: base.font_size, viewport: env.viewport };
let u = base.units(env.viewport);
let start = out.take();
let from = start.as_ref().unwrap_or(base);
let mut moved = None;
Expand Down
24 changes: 14 additions & 10 deletions bindings/rust/blenderui/src/calc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
//! (`tree.rs` evaluates it against the percentage basis during layout).

use crate::css::Tok;
use crate::geometry::{Units, ROOT_FONT_SIZE};
use crate::geometry::Units;
use crate::style::{key_hasher, KeyMap};
use std::hash::{Hash, Hasher};
use std::sync::{Mutex, OnceLock};
Expand Down Expand Up @@ -121,7 +121,7 @@ impl Calc {
Num(v) | Px(v) => *v,
Pct(p) => p * basis / 100.0,
Em(v) => v * u.font_size,
Rem(v) => v * ROOT_FONT_SIZE,
Rem(v) => v * u.root_font_size,
Vw(v) => v * u.viewport.0 / 100.0,
Vh(v) => v * u.viewport.1 / 100.0,
Vmin(v) => v * u.viewport.0.min(u.viewport.1) / 100.0,
Expand Down Expand Up @@ -300,7 +300,7 @@ impl Resolved {
}

pub fn eval(&self, basis: f32) -> f32 {
let u = Units { font_size: 16.0, viewport: (0.0, 0.0) };
let u = Units::initial(16.0, (0.0, 0.0));
let v = self.0.eval_units(&u, basis);
if v.is_nan() { 0.0 } else { v }
}
Expand Down Expand Up @@ -480,12 +480,16 @@ pub fn leaf(v: f32, unit: &str) -> Option<Calc> {
"px" => Calc::Px(v),
"rem" => Calc::Rem(v),
"em" => Calc::Em(v),
"ex" | "rex" => Calc::Em(v * 0.5),
"ch" | "rch" => Calc::Em(v * 0.55),
"cap" | "rcap" => Calc::Em(v * 0.7),
"ic" | "ric" => Calc::Em(v),
"ex" => Calc::Em(v * 0.5),
"rex" => Calc::Rem(v * 0.5),
"ch" => Calc::Em(v * 0.55),
"rch" => Calc::Rem(v * 0.55),
"cap" => Calc::Em(v * 0.7),
"rcap" => Calc::Rem(v * 0.7),
"ic" => Calc::Em(v),
"ric" => Calc::Rem(v),
"lh" => Calc::Em(v * 1.3),
"rlh" => Calc::Px(v * ROOT_FONT_SIZE * 1.3),
"rlh" => Calc::Rem(v * 1.3),
"vw" | "svw" | "lvw" | "dvw" | "vi" | "svi" | "lvi" | "dvi" | "cqw" | "cqi" => Calc::Vw(v),
"vh" | "svh" | "lvh" | "dvh" | "vb" | "svb" | "lvb" | "dvb" | "cqh" | "cqb" => Calc::Vh(v),
"vmin" | "svmin" | "lvmin" | "dvmin" | "cqmin" => Calc::Vmin(v),
Expand Down Expand Up @@ -519,7 +523,7 @@ mod tests {
let t = tokenize(s);
let Tok::Func(fx) = &t[0] else { panic!("{s}") };
let c = Calc::parse_fn(&fx.name, &fx.args).unwrap_or_else(|| panic!("parse {s}"));
c.eval_units(&Units { font_size: 10.0, viewport: (1000.0, 500.0) }, basis)
c.eval_units(&Units::initial(10.0, (1000.0, 500.0)), basis)
}

#[test]
Expand Down Expand Up @@ -557,7 +561,7 @@ mod tests {
let a = Calc::parse_fn(&fx.name, &fx.args).unwrap();
let b = Calc::parse_fn(&fx.name, &fx.args).unwrap();
assert!(std::ptr::eq(a, b));
let r = a.resolve(&Units { font_size: 20.0, viewport: (0.0, 0.0) });
let r = a.resolve(&Units::initial(20.0, (0.0, 0.0)));
assert_eq!(r.eval(100.0), 80.0);
assert_eq!(r.as_ptr() as usize % 8, 0);
}
Expand Down
49 changes: 27 additions & 22 deletions bindings/rust/blenderui/src/color4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,29 +356,33 @@ fn coords(space: Space, c: Rgba) -> V3 {

// -- parsing ---------------------------------------------------------------------------

/// What `light-dark()` picks: the UI is dark.
pub const DARK: bool = true;
/// Whether the active theme is dark: what `light-dark()`, the system colors and
/// `@media (prefers-color-scheme)` follow.
pub fn dark() -> bool {
crate::theme_name() == "dark"
}

/// A system color (`Canvas`, `LinkText` ...), in the kit's dark theme.
/// A system color (`Canvas`, `LinkText` ...) in the active theme's mode: (dark, light). The dark
/// ones are the kit's dark theme; the light ones a browser's light defaults.
pub fn system(name: &str) -> Option<Rgba> {
use crate::color::rgb;
Some(match name {
"canvas" | "field" | "window" | "background" | "appworkspace" => rgb(0x282828),
let (on_dark, on_light) = match name {
"canvas" | "field" | "window" | "background" | "appworkspace" => (0x282828, 0xffffff),
"canvastext" | "fieldtext" | "windowtext" | "captiontext" | "infotext" | "menutext"
| "buttontext" => rgb(0xe6e6e6),
"linktext" => rgb(0x5c9ce6),
"visitedtext" => rgb(0xb07ce6),
"activetext" => rgb(0xe65c5c),
| "buttontext" => (0xe6e6e6, 0x000000),
"linktext" => (0x5c9ce6, 0x0000ee),
"visitedtext" => (0xb07ce6, 0x551a8b),
"activetext" => (0xe65c5c, 0xee0000),
"buttonface" | "buttonhighlight" | "buttonshadow" | "threedface" | "threedhighlight"
| "threedshadow" | "threeddarkshadow" | "threedlightshadow" | "menu" | "scrollbar" => rgb(0x545454),
"buttonborder" | "activeborder" | "inactiveborder" | "windowframe" => rgb(0x3d3d3d),
"highlight" | "selecteditem" | "accentcolor" | "activecaption" => rgb(0x4772b3),
"highlighttext" | "selecteditemtext" | "accentcolortext" | "inactivecaptiontext" => rgb(0xffffff),
"mark" => rgb(0xe6c84a),
"marktext" => rgb(0x000000),
"graytext" | "inactivecaption" | "infobackground" | "inactiveborder2" => rgb(0x8c8c8c),
| "threedshadow" | "threeddarkshadow" | "threedlightshadow" | "menu" | "scrollbar" => (0x545454, 0xefefef),
"buttonborder" | "activeborder" | "inactiveborder" | "windowframe" => (0x3d3d3d, 0x767676),
"highlight" | "selecteditem" | "accentcolor" | "activecaption" => (0x4772b3, 0x4772b3),
"highlighttext" | "selecteditemtext" | "accentcolortext" | "inactivecaptiontext" => (0xffffff, 0xffffff),
"mark" => (0xe6c84a, 0xffff00),
"marktext" => (0x000000, 0x000000),
"graytext" | "inactivecaption" | "infobackground" | "inactiveborder2" => (0x8c8c8c, 0x6d6d6d),
_ => return None,
})
};
Some(crate::color::rgb(if dark() { on_dark } else { on_light }))
}

/// Channel keywords of a relative color (`from <color>`), in the target space.
Expand Down Expand Up @@ -411,7 +415,7 @@ fn component(toks: &[Tok], pct_ref: f64, hue: bool, ch: Option<&Channels>) -> Op
other => other.clone(),
}).collect()).collect();
let c = crate::calc::Calc::parse_fn(&fx.name, &args)?;
let u = crate::geometry::Units { font_size: 16.0, viewport: (0.0, 0.0) };
let u = crate::geometry::Units::initial(16.0, (0.0, 0.0));
let v = c.eval_units(&u, 100.0) as f64;
// a percentage inside calc resolves against 100: rescale it
if c.has_pct() { v / 100.0 * pct_ref } else { v }
Expand Down Expand Up @@ -440,7 +444,7 @@ pub fn color_fn(fx: &FuncTok, current: Rgba) -> Option<Rgba> {
let name = fx.name.as_ref();
match name {
"light-dark" => {
let pick = if DARK { fx.args.get(1)? } else { fx.args.first()? };
let pick = if dark() { fx.args.get(1)? } else { fx.args.first()? };
return color_toks(pick, current);
}
"color-mix" => return color_mix(fx, current),
Expand Down Expand Up @@ -498,8 +502,9 @@ pub fn color_fn(fx: &FuncTok, current: Rgba) -> Option<Rgba> {
let ch = channels.as_ref();
let comp = |i: usize, pct: f64, hue: bool| component(&parts[i], pct, hue, ch);
let c = match name {
"rgb" | "rgba" => [comp(0, 255.0, false)? / 255.0, comp(1, 255.0, false)? / 255.0,
comp(2, 255.0, false)? / 255.0],
// CSS Color 4 §5.1: out-of-range rgb() channels clamp (no gamut mapping)
"rgb" | "rgba" => [(comp(0, 255.0, false)? / 255.0).clamp(0.0, 1.0), (comp(1, 255.0, false)? / 255.0).clamp(0.0, 1.0),
(comp(2, 255.0, false)? / 255.0).clamp(0.0, 1.0)],
// s / l (w / b) as percentages; bare numbers in modern syntax mean percent too
"hsl" | "hsla" | "hwb" => [comp(0, 0.0, true)?, comp(1, 100.0, false)? / 100.0,
comp(2, 100.0, false)? / 100.0],
Expand Down
23 changes: 16 additions & 7 deletions bindings/rust/blenderui/src/css.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,12 +441,7 @@ impl Decl {

/// Parse `value` for `prop` (the run-time path: `.css()`, stylesheets).
pub fn new(prop: impl AsRef<str>, value: &str) -> Decl {
let mut value = value.trim();
let mut important = false;
if let Some(v) = value.strip_suffix("!important") {
value = v.trim_end();
important = true;
}
let (value, important) = strip_important(value);
let prop = prop.as_ref();
let prop = if prop.bytes().any(|b| b.is_ascii_uppercase()) {
Prop::lookup(&prop.to_ascii_lowercase())
Expand All @@ -463,6 +458,20 @@ impl Decl {
}

/// Parse a declaration block: `color: red; padding: 4px 8px`.
/// A declaration's value without its `!important` (`!` and `important` may have whitespace
/// between them and any case), and whether it had one.
fn strip_important(value: &str) -> (&str, bool) {
let value = value.trim();
let Some(head) = value.len().checked_sub(9).and_then(|n| value.get(..n)) else { return (value, false) };
if !value[head.len()..].eq_ignore_ascii_case("important") {
return (value, false);
}
match head.trim_end().strip_suffix('!') {
Some(v) => (v.trim_end(), true),
None => (value, false),
}
}

pub fn parse_declarations(block: &str) -> Vec<Decl> {
split_top(&strip_comments(block), ';')
.into_iter()
Expand Down Expand Up @@ -490,7 +499,7 @@ pub(crate) fn strip_comments(s: &str) -> String {

pub use crate::selector::{
has_match, Combinator, ContainerQuery, HasEntry, FontFace, Keyframes, MediaEnv, MediaQuery, PropertyRule,
PseudoElement, RelSelector, Rule, Selector, Stylesheet, Subject,
PseudoElement, Query, RelSelector, Rule, Selector, Stylesheet, Subject,
};
pub(crate) use crate::selector::Matches;

Expand Down
11 changes: 10 additions & 1 deletion bindings/rust/blenderui/src/geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,15 +62,24 @@ pub(crate) const ROOT_FONT_SIZE: f32 = 16.0;
#[derive(Clone, Copy, Debug)]
pub struct Units {
pub font_size: f32,
/// The root element's font size (`rem`).
pub root_font_size: f32,
pub viewport: (f32, f32),
}

impl Units {
/// Units outside any element (media queries, tests): the root font size is its initial value.
pub(crate) const fn initial(font_size: f32, viewport: (f32, f32)) -> Units {
Units { font_size, root_font_size: ROOT_FONT_SIZE, viewport }
}
}

impl Length {
/// Absolute pixels, or None for percentages and `auto` (left to layout).
pub(crate) fn to_px(self, u: &Units) -> Option<f32> {
match self {
Length::Px(v) => Some(v),
Length::Rem(v) => Some(v * ROOT_FONT_SIZE),
Length::Rem(v) => Some(v * u.root_font_size),
Length::Em(v) => Some(v * u.font_size),
Length::Vw(v) => Some(v * u.viewport.0 / 100.0),
Length::Vh(v) => Some(v * u.viewport.1 / 100.0),
Expand Down
Loading
Loading