diff --git a/CHANGELOG.md b/CHANGELOG.md index c4eba8db..1ca2cafd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 @@ -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. diff --git a/bindings/rust/Cargo.toml b/bindings/rust/Cargo.toml index 2d351370..1a86953c 100644 --- a/bindings/rust/Cargo.toml +++ b/bindings/rust/Cargo.toml @@ -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). diff --git a/bindings/rust/blenderui-macros/src/lib.rs b/bindings/rust/blenderui-macros/src/lib.rs index 1b955597..199ae561 100644 --- a/bindings/rust/blenderui-macros/src/lib.rs +++ b/bindings/rust/blenderui-macros/src/lib.rs @@ -93,9 +93,14 @@ fn expand(input: TokenStream) -> Result { 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; } diff --git a/bindings/rust/blenderui/src/anim.rs b/bindings/rust/blenderui/src/anim.rs index 7d49cc2f..ed1bc162 100644 --- a/bindings/rust/blenderui/src/anim.rs +++ b/bindings/rust/blenderui/src/anim.rs @@ -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 @@ -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); @@ -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) -> Option { 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; diff --git a/bindings/rust/blenderui/src/calc.rs b/bindings/rust/blenderui/src/calc.rs index d57c6eb3..ce52cbf6 100644 --- a/bindings/rust/blenderui/src/calc.rs +++ b/bindings/rust/blenderui/src/calc.rs @@ -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}; @@ -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, @@ -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 } } @@ -480,12 +480,16 @@ pub fn leaf(v: f32, unit: &str) -> Option { "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), @@ -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] @@ -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); } diff --git a/bindings/rust/blenderui/src/color4.rs b/bindings/rust/blenderui/src/color4.rs index db914450..4f6ec650 100644 --- a/bindings/rust/blenderui/src/color4.rs +++ b/bindings/rust/blenderui/src/color4.rs @@ -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 { - 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 `), in the target space. @@ -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 } @@ -440,7 +444,7 @@ pub fn color_fn(fx: &FuncTok, current: Rgba) -> Option { 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), @@ -498,8 +502,9 @@ pub fn color_fn(fx: &FuncTok, current: Rgba) -> Option { 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], diff --git a/bindings/rust/blenderui/src/css.rs b/bindings/rust/blenderui/src/css.rs index 5267dc7d..08090087 100644 --- a/bindings/rust/blenderui/src/css.rs +++ b/bindings/rust/blenderui/src/css.rs @@ -441,12 +441,7 @@ impl Decl { /// Parse `value` for `prop` (the run-time path: `.css()`, stylesheets). pub fn new(prop: impl AsRef, 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()) @@ -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 { split_top(&strip_comments(block), ';') .into_iter() @@ -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; diff --git a/bindings/rust/blenderui/src/geometry.rs b/bindings/rust/blenderui/src/geometry.rs index 95062879..ca83eb7e 100644 --- a/bindings/rust/blenderui/src/geometry.rs +++ b/bindings/rust/blenderui/src/geometry.rs @@ -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 { 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), diff --git a/bindings/rust/blenderui/src/layout.rs b/bindings/rust/blenderui/src/layout.rs index 45238d54..4da3e9cc 100644 --- a/bindings/rust/blenderui/src/layout.rs +++ b/bindings/rust/blenderui/src/layout.rs @@ -266,6 +266,11 @@ pub(crate) struct ElData { /// refinements or Motion props. Without any (and no `:active` / `:focus` rule in the sheet) a press /// changes nothing on screen by itself. pub reactive: bool, + /// `:empty`: no element or text children (rules match before the children are built). + pub empty: bool, + /// Answers to the author sheet's `Query::LaterMatches` queries: (query, following siblings + /// that match its `S`). + pub later: smallvec::SmallVec<[(u16, u32); 1]>, } const NONE: u32 = u32::MAX; @@ -567,6 +572,32 @@ type Kids = smallvec::SmallVec<[usize; 8]>; type NodeList = smallvec::SmallVec<[NodeId; 8]>; /// The slot index of a layout node (dense: the tree reuses freed slots). +/// The declarations for both passes of `compute`, which apply the normal ones and then the +/// `!important` ones, each in list order. The normal ones go UA, author (rules in cascade order), +/// then the element's own; the important ones reverse the origins and the layers (CSS Cascade 5): +/// author unlayered, author layers from the last to the first, the element's own, then UA. +fn cascade_order<'d>(ua: &[&'d Rule], au: &[&'d Rule], own: &[&'d Decl]) -> smallvec::SmallVec<[&'d Decl; 24]> { + let rules = || ua.iter().chain(au).flat_map(|r| r.decls.iter()); + let mut out: smallvec::SmallVec<[&'d Decl; 24]> = rules().chain(own.iter().copied()).filter(|d| !d.important).collect(); + let important = |d: &&Decl| d.important; + if !rules().chain(own.iter().copied()).any(|d| d.important) { + return out; + } + let mut layered: smallvec::SmallVec<[&'d Rule; 8]> = smallvec::SmallVec::new(); + for r in au { + if r.layer == u16::MAX { + out.extend(r.decls.iter().filter(important)); + } else { + layered.push(r); + } + } + layered.sort_by_key(|r| std::cmp::Reverse(r.layer)); // stable: specificity and order stay + out.extend(layered.iter().flat_map(|r| r.decls.iter()).filter(important)); + out.extend(own.iter().copied().filter(important)); + out.extend(ua.iter().flat_map(|r| r.decls.iter()).filter(important)); + out +} + fn slot(id: NodeId) -> usize { u64::from(id) as usize } @@ -692,11 +723,14 @@ impl Subject for NodeRef<'_> { (t.0 as usize, t.1 as usize) } fn is_empty(&self) -> bool { - self.nodes[self.i].first == NONE + self.el().is_none_or(|e| e.empty) } fn has(&self, id: u16) -> bool { id < 64 && self.el().is_some_and(|e| e.has & (1 << id) != 0) } + fn later_matches(&self, id: u16) -> Option { + self.el()?.later.iter().find(|q| q.0 == id).map(|q| q.1 as usize) + } fn same(&self, o: &Self) -> bool { self.i == o.i } @@ -743,35 +777,60 @@ fn type_counts(els: &[&Div], k: usize) -> (usize, usize) { (before, before + els[k..].iter().filter(|e| e.tag == tag).count()) } -/// Flatten `div`'s element subtree (index 0 = `div` itself, the anchor). -fn flatten<'d>(div: &'d Div, key: Key, out: &mut Vec>) { - out.push(Flat { tag: div.tag, id: None, attrs: &[], parent: NONE, first: NONE, next: NONE, prev: NONE, - pos: (1, 1), tpos: (1, 1), key }); - fn kids<'d>(div: &'d Div, me: u32, key: Key, out: &mut Vec>) { - let els: smallvec::SmallVec<[&'d Div; 16]> = div.children.iter().filter_map(|c| match c { - AnyElement::Element(d) => Some(d), - _ => None, - }).collect(); - let mut prev = NONE; - for (k, d) in els.iter().enumerate() { - let ck = match &d.id { - Some(id) => id_key(id), - None => child_key(key, d.tag, k + 1), - }; - let (before, total) = type_counts(&els, k); - let idx = out.len() as u32; - out.push(Flat { tag: d.tag, id: d.id.as_deref(), attrs: &d.attrs, parent: me, first: NONE, next: NONE, - prev, pos: (k + 1, els.len()), tpos: (before + 1, total), key: ck }); - if prev == NONE { - out[me as usize].first = idx; - } else { - out[prev as usize].next = idx; - } - prev = idx; - kids(d, idx, ck, out); +/// The element children of `div` (and theirs) under flat entry `me`, whose key is `key`. +fn flatten_kids<'d>(div: &'d Div, me: u32, key: Key, out: &mut Vec>) { + let els: smallvec::SmallVec<[&'d Div; 16]> = div.children.iter().filter_map(|c| match c { + AnyElement::Element(d) => Some(d), + AnyElement::Text(_) => None, + }).collect(); + let mut prev = NONE; + for (k, d) in els.iter().enumerate() { + let ck = match &d.id { + Some(id) => id_key(id), + None => child_key(key, d.tag, k + 1), + }; + let (before, total) = type_counts(&els, k); + let idx = out.len() as u32; + out.push(Flat { tag: d.tag, id: d.id.as_deref(), attrs: &d.attrs, parent: me, first: NONE, next: NONE, + prev, pos: (k + 1, els.len()), tpos: (before + 1, total), key: ck }); + if prev == NONE { + out[me as usize].first = idx; + } else { + out[prev as usize].next = idx; } + prev = idx; + flatten_kids(d, idx, ck, out); } - kids(div, 0, key, out); +} + +/// The element siblings after the element at flat entry `me` (`pos` among its siblings): the +/// first `take` of `later`, each with its subtree, chained after `me` under `parent`. Keys are +/// the ones `children` gives them; `built` counts the element and the siblings before it by tag, +/// for their type positions. Returns the first sibling's entry (`NONE` without any). +#[allow(clippy::too_many_arguments)] +fn flatten_later<'d>(later: &'d [AnyElement], take: usize, me: u32, pos: (usize, usize), parent: u32, + parent_key: Key, built: &[(&str, usize)], out: &mut Vec>) -> u32 { + let els: smallvec::SmallVec<[&'d Div; 16]> = later.iter().filter_map(|c| match c { + AnyElement::Element(d) => Some(d), + AnyElement::Text(_) => None, + }).collect(); + let count = |tag: &str| built.iter().find(|b| b.0.eq_ignore_ascii_case(tag)).map_or(0, |b| b.1); + let (first, mut prev) = (out.len() as u32, me); + for (k, d) in els.iter().enumerate().take(take) { + let ck = match &d.id { + Some(id) => id_key(id), + None => child_key(parent_key, d.tag, pos.0 + k + 1), + }; + let (before, total) = type_counts(&els, k); + let idx = out.len() as u32; + let tpos = (count(d.tag) + before + 1, count(d.tag) + total); + out.push(Flat { tag: d.tag, id: d.id.as_deref(), attrs: &d.attrs, parent, first: NONE, next: NONE, + prev, pos: (pos.0 + k + 1, pos.1), tpos, key: ck }); + out[prev as usize].next = idx; + prev = idx; + flatten_kids(d, idx, ck, out); + } + if out.len() as u32 == first { NONE } else { first } } #[derive(Clone)] @@ -865,6 +924,74 @@ fn collect_styles(el: &AnyElement, css: &mut String, title: &mut Option, } impl<'a> Builder<'a> { + /// Element `i` and its built siblings before it, counted by tag (type positions of the + /// siblings after it). + fn built_tags(&self, i: usize) -> smallvec::SmallVec<[(&str, usize); 8]> { + let mut out: smallvec::SmallVec<[(&str, usize); 8]> = smallvec::SmallVec::new(); + let mut cur = Some(self.subject(i)); + while let Some(s) = cur { + let tag = self.els[self.nodes[s.i].el as usize].tag; + match out.iter_mut().find(|t| t.0.eq_ignore_ascii_case(tag)) { + Some(t) => t.1 += 1, + None => out.push((tag, 1)), + } + cur = s.prev_sibling(); + } + out + } + + /// Answers to the author sheet's `Query::LaterMatches` queries (`:nth-last-child(An+B of S)`) + /// for element `i` at `pos`: how many of its following siblings `later` match `S`. They are + /// matched on the declarative elements, under `i`'s built ancestors (`S` may name them); only + /// queries whose `S` the element matches itself are answered. + fn later_matches<'s>(&'s self, i: usize, pos: (usize, usize), later: &'s [AnyElement]) + -> smallvec::SmallVec<[(u16, u32); 1]> { + let mut out = smallvec::SmallVec::new(); + let me = self.subject(i); + let mut queries = self.author.has.iter().enumerate().filter(|(_, q)| { + q.kind == crate::css::Query::LaterMatches && q.rels.iter().any(|r| r.sel.matches(&me)) + }).peekable(); + if queries.peek().is_none() { + return out; + } + // the built ancestors from the root down, then `i` itself + let mut chain: smallvec::SmallVec<[usize; 16]> = smallvec::SmallVec::new(); + let mut n = Some(i); + while let Some(k) = n { + if self.nodes[k].el != NONE { + chain.push(k); + } + n = self.nodes[k].parent; + } + let mut flat: Vec> = Vec::with_capacity(chain.len() + later.len()); + for &k in chain.iter().rev() { + let (node, el) = (&self.nodes[k], &self.els[self.nodes[k].el as usize]); + let idx = flat.len() as u32; + let parent = idx.checked_sub(1).unwrap_or(NONE); + flat.push(Flat { tag: el.tag, id: el.id.as_deref(), attrs: &el.attrs, parent, first: NONE, next: NONE, + prev: NONE, pos: node.pos, tpos: self.subject(k).type_position(), key: node.key }); + if parent != NONE { + flat[parent as usize].first = idx; + } + } + let at = flat.len() as u32 - 1; + let parent = flat[at as usize].parent; + let parent_key = self.nodes[i].parent.map_or(self.nodes[i].key, |p| self.nodes[p].key); + let built = self.built_tags(i); + let first = flatten_later(later, usize::MAX, at, pos, parent, parent_key, &built, &mut flat); + for (id, q) in queries { + let mut count = 0u32; + let mut k = first; + while k != NONE { + let s = DivSubject { flat: &flat, state: self.state, i: k as usize }; + count += u32::from(q.rels.iter().any(|r| r.sel.matches(&s))); + k = flat[k as usize].next; + } + out.push((id as u16, count)); + } + out + } + fn subject(&self, i: usize) -> NodeRef<'_> { NodeRef { nodes: &self.nodes, els: &self.els, state: self.state, containers: self.containers, i } } @@ -997,6 +1124,7 @@ impl<'a> Builder<'a> { self.nodes[i].fp.hash(&mut h); self.nodes[i].styled.hash(&mut h); self.containers.generation.hash(&mut h); + self.author_hash.hash(&mut h); // media results follow the theme's mode self.viewport.0.to_bits().hash(&mut h); self.viewport.1.to_bits().hash(&mut h); h.finish() @@ -1038,6 +1166,8 @@ impl<'a> Builder<'a> { n.tpos.hash(&mut h); if let Some(e) = (n.el != NONE).then(|| &self.els[n.el as usize]) { e.has.hash(&mut h); + e.empty.hash(&mut h); + e.later.hash(&mut h); e.tag.hash(&mut h); e.id.as_deref().hash(&mut h); for (a, v) in &e.attrs { @@ -1057,22 +1187,19 @@ impl<'a> Builder<'a> { fn declared<'d>(&self, i: usize, div: &'d Div, ua: &[&'d Rule], au: &[&'d Rule]) -> smallvec::SmallVec<[&'d Decl; 24]> { let key = self.nodes[i].key; - let mut decls = smallvec::SmallVec::new(); - decls.extend(ua.iter().flat_map(|r| r.decls.iter())); - decls.extend(au.iter().flat_map(|r| r.decls.iter())); - decls.extend(div.decls.iter()); + let mut own: smallvec::SmallVec<[&'d Decl; 16]> = div.decls.iter().collect(); if let Some(st) = &div.states { if self.state.hovered.contains(&key) { - decls.extend(st.hover.iter()); + own.extend(st.hover.iter()); } if self.state.active.contains(&key) { - decls.extend(st.active.iter()); + own.extend(st.active.iter()); } if self.state.focused == Some(key) { - decls.extend(st.focus.iter()); + own.extend(st.focus.iter()); } } - decls + cascade_order(ua, au, &own) } fn compute(&mut self, parent: StyleId, decls: &[&Decl]) -> Computed { @@ -1100,6 +1227,7 @@ impl<'a> Builder<'a> { } else { pvars }; + let root = parent == ROOT_STYLE; let parent = &self.styles[parent]; let mut c = Computed::inherit(parent); c.vars = vars; @@ -1114,7 +1242,6 @@ impl<'a> Builder<'a> { const FONT_SIZE: Prop = Prop::named("font-size"); const FONT: Prop = Prop::named("font"); let font_first = |d: &&Decl| d.prop == FONT_SIZE || d.prop == FONT; - let units = |fs: f32| Units { font_size: fs, viewport: self.viewport }; let run = |c: &mut Computed, u: Units, d: &Decl| { if crate::vars::uses_vars(&d.value) { if let Some(d) = subst(d) { @@ -1127,10 +1254,13 @@ impl<'a> Builder<'a> { for important in [false, true] { // font-size first: em lengths in the other properties depend on it for d in decls.iter().filter(|d| d.important == important && font_first(d)) { - run(&mut c, units(parent.font_size), d); + run(&mut c, parent.units(self.viewport), d); } } - let u = units(c.font_size); + if root { + c.root_font_size = c.font_size; // `rem` everywhere (the root's own font-size used the initial) + } + let u = c.units(self.viewport); for important in [false, true] { for d in decls.iter().filter(|d| d.important == important && !font_first(d)) { run(&mut c, u, d); @@ -1139,10 +1269,6 @@ impl<'a> Builder<'a> { c } - fn units(&self, font_size: f32) -> Units { - Units { font_size, viewport: self.viewport } - } - /// A new box. `link`: append it to its parent's child list (elements and /// text); words, breaks and line boxes only point at their parent. fn push(&mut self, parent: Option, content: Content, owner: Option, style: StyleId, @@ -1210,7 +1336,9 @@ impl<'a> Builder<'a> { } /// Build an element; returns its index (None when not rendered). - fn element(&mut self, mut div: Div, parent: Option, key: Key, pos: (usize, usize)) -> Option { + /// `later`: the siblings after it (for `:has()` with `+` / `~`). + fn element(&mut self, mut div: Div, parent: Option, key: Key, pos: (usize, usize), later: &[AnyElement]) + -> Option { let parent_style = parent.map(|p| self.nodes[p].style).unwrap_or(ROOT_STYLE); let i = self.push(parent, Content::Element, None, parent_style, key, true); self.nodes[i].pos = pos; @@ -1225,26 +1353,42 @@ impl<'a> Builder<'a> { listeners: std::mem::take(&mut div.listeners), has: 0, reactive, + empty: div.children.iter().all(|c| matches!(c, AnyElement::Text(t) if t.is_empty())), + later: smallvec::SmallVec::new(), }); if !self.author.has.is_empty() { // :has() looks at the element's subtree, which isn't built yet: // evaluate it on the declarative children instead let mut bits = 0u64; let mut flat = Vec::new(); + let is_has = |e: &&crate::css::HasEntry| e.kind == crate::css::Query::Has; for (id, entry) in self.author.has.iter().enumerate().take(64) { - if !entry.host_matches(&self.subject(i)) { + if !is_has(&entry) || !entry.host_matches(&self.subject(i)) { continue; } if flat.is_empty() { - flatten(&div, key, &mut flat); + // the following siblings as far as any `:has()` reaches with `+` / `~` + let reach = self.author.has.iter().take(64).filter(is_has) + .map(crate::css::HasEntry::sibling_reach).max().unwrap_or(0); + let parent_key = parent.map_or(key, |p| self.nodes[p].key); + // the anchor (index 0) and its subtree, then the siblings it reaches + flat.push(Flat { tag: div.tag, id: None, attrs: &[], parent: NONE, first: NONE, next: NONE, + prev: NONE, pos, tpos: self.subject(i).type_position(), key }); + flatten_kids(&div, 0, key, &mut flat); + if reach > 0 { + let built = self.built_tags(i); + flatten_later(later, reach, 0, pos, NONE, parent_key, &built, &mut flat); + } } let anchor = DivSubject { flat: &flat, state: self.state, i: 0 }; if crate::css::has_match(&entry.rels, &anchor) { bits |= 1 << id; } } + let counts = self.later_matches(i, pos, later); if let Some(e) = self.els.last_mut() { e.has = bits; + e.later = counts; } } self.nodes[i].fp = self.fingerprint(i); @@ -1285,7 +1429,7 @@ impl<'a> Builder<'a> { spec.html = !self.nodes[i].styled && self.attr(i, "bui-blender").is_none(); spec.bare = spec.html && self.styles[style].border_drawn.iter().all(|d| !d); let own = &self.styles[style]; - let u = self.units(own.font_size); + let u = own.units(self.viewport); spec.radius = own.radius.iter().filter_map(|r| r.to_px(&u)).reduce(f32::max).filter(|r| *r > 0.0); if spec.html && matches!(spec.kind, crate::widgets::WKind::TextArea) { let own = &self.styles[style]; @@ -1437,8 +1581,7 @@ impl<'a> Builder<'a> { let sid = match found { Some(id) => id, None => { - let decls: smallvec::SmallVec<[&Decl; 24]> = - ua.iter().chain(au.iter()).flat_map(|r| r.decls.iter()).collect(); + let decls = cascade_order(&ua, &au, &[]); let mut c = self.compute(parent, &decls); if matches!(self.st(i).display, DisplayKind::Flex | DisplayKind::InlineFlex | DisplayKind::Grid | DisplayKind::InlineGrid) && c.display == DisplayKind::Inline { @@ -1479,7 +1622,8 @@ impl<'a> Builder<'a> { let key = child_key(self.nodes[i].key, tag, 0); let g = self.push(Some(i), Content::Element, None, sid, key, true); self.nodes[g].el = self.els.len() as u32; - self.els.push(ElData { tag, id: None, attrs: Vec::new(), listeners: None, has: 0, reactive: false }); + self.els.push(ElData { tag, id: None, attrs: Vec::new(), listeners: None, has: 0, reactive: false, + empty: text.is_empty(), later: smallvec::SmallVec::new() }); if !text.is_empty() { self.push(Some(g), Content::Text(text.into()), Some(g), sid, child_key(key, "#text", 1), true); } @@ -1521,7 +1665,9 @@ impl<'a> Builder<'a> { } let (mut k, mut n) = (0, 0); let parent_key = self.nodes[i].key; - for child in children.drain(..) { + // taken one at a time: the siblings after each child stay in place for `:has(+ / ~)` + for at in 0..children.len() { + let child = std::mem::replace(&mut children[at], AnyElement::Text(SharedString::Borrowed(""))); n += 1; match child { AnyElement::Element(d) => { @@ -1534,7 +1680,7 @@ impl<'a> Builder<'a> { t.2 += 1; self.next_tpos = (t.2, t.1); } - self.element(d, Some(i), key, (k, count)); + self.element(d, Some(i), key, (k, count), &children[at + 1..]); } // an empty text run renders nothing (`None` as a child) AnyElement::Text(t) if t.is_empty() => {} @@ -1662,7 +1808,7 @@ impl<'a> Builder<'a> { Content::Element => { let inner = self.max_content(c); let st = self.st(c); - let u = self.units(st.font_size); + let u = st.units(self.viewport); let px = |v: LengthPercentage| match v.into_raw() { r if r.tag() == taffy::CompactLength::LENGTH_TAG => r.value(), _ => 0.0, @@ -2183,7 +2329,7 @@ impl<'a> Builder<'a> { let (tab, break_all) = (c.tab_size, c.break_all); let flags = text::flags(c); let line_h = c.line_px(); - let indent = if first { c.text_indent.resolve(&self.units(size), 0.0) } else { 0.0 }; + let indent = if first { c.text_indent.resolve(&c.units(self.viewport), 0.0) } else { 0.0 }; // the processed text, kept in the box let Content::Text(raw) = std::mem::replace(&mut self.nodes[src].content, Content::Anon) else { return }; let mut text = match transform(&raw, tt, ws, tab) { @@ -2454,7 +2600,9 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca next_tpos: (1, 1), author: &author.sheet, ua_styled: &ua_styled, - author_hash: author.hash, + // the theme's mode is part of what the sheet means (`light-dark()`, system colors, + // `prefers-color-scheme`): styles computed in the other mode are not reused + author_hash: author.hash ^ u64::from(crate::color4::dark()), ua_media: ua_stylesheet().media_results(&crate::css::MediaEnv::viewport(viewport)), ua_styled_media: ua_styled.media_results(&crate::css::MediaEnv::viewport(viewport)), au_media: author.sheet.media_results(&crate::css::MediaEnv::viewport(viewport)), @@ -2477,7 +2625,7 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca } }; let s = span(Phase::Build); - let root = match b.element(root_div, None, ROOT_KEY, (1, 1)) { + let root = match b.element(root_div, None, ROOT_KEY, (1, 1), &[]) { Some(r) => r, None => b.push(None, Content::Element, None, ROOT_STYLE, ROOT_KEY, false), }; @@ -2608,7 +2756,7 @@ impl Walk<'_> { let (mut sx, mut sy) = (0.0, 0.0); if let Some(i) = self.box_of.get(slot(id)).filter(|&&b| b != NONE).map(|&b| b as usize) { let st = &self.styles[nodes[i].style]; - let u = Units { font_size: st.font_size, viewport: self.vp }; + let u = st.units(self.vp); // a word carries its owner's style: the owner's translate already moved the line it is in, // unless the owner is an inline element (no box of its own to carry it) let own_translate = !matches!(nodes[i].content, Content::Word { .. }) || nodes[nodes[i].owner].taffy.is_none(); diff --git a/bindings/rust/blenderui/src/motion/element.rs b/bindings/rust/blenderui/src/motion/element.rs index 9069804a..23fadfa6 100644 --- a/bindings/rust/blenderui/src/motion/element.rs +++ b/bindings/rust/blenderui/src/motion/element.rs @@ -671,7 +671,7 @@ impl Elements { } self.dirty[s.node] = true; let st = styles.private_mut(n.style); - let u = Units { font_size: base.font_size, viewport }; + let u = base.units(viewport); let (w, h) = (n.bounds.size.width, n.bounds.size.height); let at = |st: &Computed| (st.translate.0.resolve(&u, w), st.translate.1.resolve(&u, h)); let before = if s.moves { at(st) } else { (0.0, 0.0) }; diff --git a/bindings/rust/blenderui/src/motion/flip.rs b/bindings/rust/blenderui/src/motion/flip.rs index a31803ed..6360dce6 100644 --- a/bindings/rust/blenderui/src/motion/flip.rs +++ b/bindings/rust/blenderui/src/motion/flip.rs @@ -8,7 +8,7 @@ use blenderui_sys as sys; use super::element::{Elements, Slot, start}; use super::spec::Layout; use super::value::{Key, Value}; -use crate::geometry::{Bounds, Units}; +use crate::geometry::Bounds; use crate::layout::{BoxNode, Frame, StyleStore}; use taffy::style::Position; @@ -80,7 +80,7 @@ impl Elements { /// has no parent to follow. fn laid_out(frame: &Frame, n: &BoxNode, styles: &StyleStore, viewport: (f32, f32)) -> Bounds { let st = &styles[n.style]; - let u = Units { font_size: st.font_size, viewport }; + let u = st.units(viewport); let (w, h) = (n.bounds.size.width, n.bounds.size.height); let (mut x, mut y) = (n.bounds.origin.x - st.translate.0.resolve(&u, w), n.bounds.origin.y - st.translate.1.resolve(&u, h)); if let Some(p) = n.parent.filter(|_| st.layout.position != Position::Fixed).and_then(|p| frame.nodes.get(p)) { diff --git a/bindings/rust/blenderui/src/paint.rs b/bindings/rust/blenderui/src/paint.rs index d8feea2a..ed38c9cb 100644 --- a/bindings/rust/blenderui/src/paint.rs +++ b/bindings/rust/blenderui/src/paint.rs @@ -317,6 +317,9 @@ struct Item { clip: Option>, /// Its element has `pointer-events: none`: the pointer goes through it. through: bool, + /// A CSS box's rectangle (background, border, image): its edges snap to device pixels, as + /// browsers paint boxes laid out at fractional positions. + snap: bool, } /// Draws into a canvas display list, in logical pixels. @@ -335,6 +338,8 @@ pub struct Painter { clip: Option>, /// The box being painted has `pointer-events: none`. through: bool, + /// What is being painted is a CSS box (not a canvas's own drawing): see `Item::snap`. + pub(crate) snap: bool, opacity: f32, /// Retained painting (frames where only moving values changed): each /// box's items (start, end; u32::MAX when it painted none), each item's @@ -499,6 +504,7 @@ impl Painter { _ => {} } it.clip = clip_through(it.clip, m, outer); + it.snap = false; // a moved, scaled or turned box: its corners are not a pixel grid's } } @@ -560,7 +566,7 @@ impl Painter { Kind::Oval { outline, width } => Kind::Oval { outline: outline.opacity(self.opacity), width }, k => k, }; - self.items.push(Item { kind, coords, fill, clip: self.clip, through: self.through }); + self.items.push(Item { kind, coords, fill, clip: self.clip, through: self.through, snap: self.snap }); } fn corners(b: Bounds) -> Coords { @@ -831,9 +837,21 @@ impl Painter { } } } + // a CSS box laid out at fractional positions: each edge on its nearest device pixel (so + // neighbours still meet), not blended across two + let snap = it.snap && matches!(it.kind, Kind::Rect { .. } | Kind::Image(_) | Kind::File { .. } | Kind::Video(..)); + if snap { + coords.iter_mut().for_each(|v| *v = v.round()); + } if let Some(c) = it.clip { ci.clip_on = 1; - ci.clip = [c.origin.x * scale, c.origin.y * scale, c.size.width * scale, c.size.height * scale]; + let (x, y) = (c.origin.x * scale, c.origin.y * scale); + let (r, b) = (x + c.size.width * scale, y + c.size.height * scale); + ci.clip = if snap { + [x.round(), y.round(), r.round() - x.round(), b.round() - y.round()] + } else { + [x, y, r - x, b - y] + }; } ci.ncoords = coords.len() as i32; Some(ci) @@ -990,7 +1008,7 @@ fn border_widths(c: &Computed, w: f32) -> [f32; 4] { } fn radius_px(c: &Computed, b: Bounds, vp: (f32, f32)) -> f32 { - let u = Units { font_size: c.font_size, viewport: vp }; + let u = c.units(vp); let m = b.size.width.min(b.size.height); c.radius.iter().map(|r| r.resolve(&u, m)).fold(0.0, f32::max).min(m / 2.0) } @@ -1173,7 +1191,7 @@ fn vector_mats(frame: &Frame, styles: &StyleStore, vp: (f32, f32), out: &mut Mat // parents come before their children let (mut m, mut outer) = n.parent.and_then(|p| Some((*out.m.get(p)?, out.outer[p]))).unwrap_or((IDENTITY, (None, None))); if let Some(e) = effects_of(frame, styles, i) { - let u = Units { font_size: styles[n.style].font_size, viewport: vp }; + let u = styles[n.style].units(vp); out.layered |= !e.backdrop.is_empty() || e.needs_layer(n.bounds, &u); let vector = e.vector(n.bounds, &u); let under = out.under[i]; @@ -1417,7 +1435,7 @@ fn paint_list(cx: &mut LayerCx, list: &[usize], p: &mut Painter, root: Option { @@ -2067,7 +2086,10 @@ fn paint_node(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize, }, Replaced::Video(v) => p.with_clip(inner, |p| p.video(inner, v, c.images.as_ref().map_or( sys::BK_FIT_CONTAIN, |st| st.object_fit.kit_video()))), - Replaced::Painted(f) => p.with_clip(inner, |p| f(inner, p, app)), + Replaced::Painted(f) => { + p.snap = false; // the canvas draws as it says, anti-aliased (as a browser canvas) + p.with_clip(inner, |p| f(inner, p, app)); + } Replaced::Placeholder(tag) => { p.fill(inner, crate::color::rgb(0x282828)); let label = frame.attr(i, "alt").unwrap_or(tag); @@ -2311,7 +2333,7 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba let styled = visible.iter().any(|&k| c.border_style[k] != BorderStyle::Solid); let border_image = c.effects.as_ref().and_then(|e| e.border_image.as_ref()).filter(|bi| bi.source.is_some()); if let Some(bi) = border_image { - paint_border_image(p, bi, b, &bw, &Units { font_size: c.font_size, viewport: vp }); + paint_border_image(p, bi, b, &bw, &c.units(vp)); } else if styled && uniform && r > 0.0 && c.border_style.iter().all(|s| *s == c.border_style[0]) { paint_rounded_styled(p, b, r, bw[0], c.border_color[0], c.border_style[0]); } else if styled { diff --git a/bindings/rust/blenderui/src/selector.rs b/bindings/rust/blenderui/src/selector.rs index e2713958..0a017e64 100644 --- a/bindings/rust/blenderui/src/selector.rs +++ b/bindings/rust/blenderui/src/selector.rs @@ -53,7 +53,9 @@ enum Simple { Attr { name: String, op: AttrOp, val: String, ci: bool }, /// State and structural pseudo-classes without arguments. Pseudo(String), - Nth { a: i32, b: i32, last: bool, of_type: bool, of: Option> }, + /// `later`: for `:nth-last-child(An+B of S)`, the source-tree query (`Query::LaterMatches`) counting + /// the following siblings that match `S`. + Nth { a: i32, b: i32, last: bool, of_type: bool, of: Option>, later: Option }, Not(Box<[Selector]>), Is(Box<[Selector]>), Where(Box<[Selector]>), @@ -61,9 +63,28 @@ enum Simple { Has(u16), Lang(Box<[String]>), Dir(bool), + /// `:scope` (or a bare `&`) inside `@scope`: an element its root selector matches. + ScopeRoot(Box<[Selector]>), Never, } +impl Selector { + /// Inside `@scope (root)`: `:scope` is the scoping root, not the document's. + fn bind_scope(&mut self, root: &[Selector]) { + for (compound, _) in &mut self.parts { + for s in compound { + match s { + Simple::Pseudo(p) if p == "scope" => *s = Simple::ScopeRoot(root.into()), + Simple::Not(l) | Simple::Is(l) | Simple::Where(l) | Simple::Nth { of: Some(l), .. } => { + l.iter_mut().for_each(|sel| sel.bind_scope(root)); + } + _ => {} + } + } + } + } +} + #[derive(Clone, Copy, Debug, PartialEq)] pub enum Combinator { Descendant, @@ -81,15 +102,47 @@ pub struct Selector { pub pseudo: Option, } -/// One `:has()`: its relative selectors and the rest of the compound it -/// sits in (`.card` in `.card:has(img)`). +/// What a source-tree query asks. Rules match while the box tree is being built, before an +/// element's subtree and its following siblings exist, so these are answered on the declarative +/// elements instead. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Query { + /// `:has()`: whether a relative selector holds. + Has, + /// `:nth-last-child(An+B of S)`: how many following siblings match `S` (each `rels` entry + /// holds one selector of `S`). + LaterMatches, +} + +/// One source-tree query: `:has()` (its relative selectors and the rest of the compound it sits +/// in, `.card` in `.card:has(img)`), or the `S` of an `:nth-last-child(An+B of S)`. #[derive(Clone, Debug, PartialEq)] pub struct HasEntry { pub rels: Box<[RelSelector]>, host: Vec, + pub kind: Query, } impl HasEntry { + /// How many following siblings of the anchor this `:has()` can reach: 0 for `> a` / `a b`, + /// one per `+` hop, all of them with a `~`. + pub fn sibling_reach(&self) -> usize { + self.rels.iter().map(|r| { + let hops = std::iter::once(Some(r.comb)).chain(r.sel.parts.iter().map(|p| p.1)); + let mut reach = 0usize; + for c in hops { + match c { + Some(Combinator::Sibling) => return usize::MAX, + Some(Combinator::Adjacent) => reach += 1, + // a descendant / child hop leaves the sibling row + Some(Combinator::Child | Combinator::Descendant) => return reach, + None => {} + } + } + reach + }).max().unwrap_or(0) + } + /// Whether the compound around this `:has()` can match `el` (a cheap /// filter before walking `el`'s subtree). pub fn host_matches(&self, el: &S) -> bool { @@ -139,6 +192,11 @@ pub trait Subject: Sized + Clone { fn has(&self, _id: u16) -> bool { false } + /// The answer to source-tree query number `id` (`Query::LaterMatches`): how many following + /// siblings match its `S`, when they aren't reachable through `next_sibling` yet. + fn later_matches(&self, _id: u16) -> Option { + None + } /// The size of the nearest query container (named `name`, if given). fn container(&self, _name: Option<&str>) -> Option<(f32, f32)> { None @@ -192,25 +250,28 @@ enum Bucket { Universal, } -fn spec_of(compound: &[Simple], spec: &mut (u16, u16, u16)) { +/// Add `compound`'s specificity to `spec`. `:is()`, `:not()`, `:has()` and `of S` count as their +/// most specific argument (Selectors 4); `has` holds the `:has()` arguments. +fn spec_of(compound: &[Simple], has: &[HasEntry], spec: &mut (u16, u16, u16)) { let max_of = |list: &[Selector]| list.iter().map(|s| s.specificity).max().unwrap_or((0, 0, 0)); let add = |spec: &mut (u16, u16, u16), o: (u16, u16, u16)| { - spec.0 += o.0; - spec.1 += o.1; - spec.2 += o.2; + spec.0 = spec.0.saturating_add(o.0); + spec.1 = spec.1.saturating_add(o.1); + spec.2 = spec.2.saturating_add(o.2); }; for s in compound { match s { - Simple::Id(_) => spec.0 += 1, + Simple::Id(_) => add(spec, (1, 0, 0)), Simple::Class(_) | Simple::Attr { .. } | Simple::Pseudo(_) | Simple::Lang(_) | Simple::Dir(_) - | Simple::Has(_) | Simple::Never => spec.1 += 1, + | Simple::ScopeRoot(_) | Simple::Never => add(spec, (0, 1, 0)), + Simple::Has(i) => add(spec, has[*i as usize].rels.iter().map(|r| r.sel.specificity).max().unwrap_or((0, 0, 0))), Simple::Nth { of, .. } => { - spec.1 += 1; + add(spec, (0, 1, 0)); if let Some(of) = of { add(spec, max_of(of)); } } - Simple::Tag(_) => spec.2 += 1, + Simple::Tag(_) => add(spec, (0, 0, 1)), Simple::Not(l) | Simple::Is(l) => add(spec, max_of(l)), Simple::Where(_) | Simple::Universal => {} } @@ -287,10 +348,10 @@ fn parse_complex(s: &str, has: &mut Vec, relative: bool) parts.reverse(); let mut spec = (0u16, 0u16, 0u16); for (compound, _) in &parts { - spec_of(compound, &mut spec); + spec_of(compound, has, &mut spec); } if pseudo.is_some() { - spec.2 += 1; + spec.2 = spec.2.saturating_add(1); } let n = parts.len(); let combs: Vec> = parts.iter().map(|p| p.1).collect(); @@ -454,7 +515,7 @@ fn parse_compound(s: &str, mut i: usize, has: &mut Vec) let (comb, sel) = parse_complex(part, has, true)?; rels.push(RelSelector { comb: comb.unwrap_or(Combinator::Descendant), sel }); } - has.push(HasEntry { rels: rels.into_boxed_slice(), host: Vec::new() }); + has.push(HasEntry { rels: rels.into_boxed_slice(), host: Vec::new(), kind: Query::Has }); Simple::Has((has.len() - 1) as u16) } "nth-child" | "nth-last-child" | "nth-of-type" | "nth-last-of-type" => { @@ -463,8 +524,19 @@ fn parse_compound(s: &str, mut i: usize, has: &mut Vec) None => (arg, None), }; let (a, bb) = parse_nth(expr)?; - Simple::Nth { a, b: bb, last: name.contains("last"), of_type: name.ends_with("of-type"), - of: if name.ends_with("child") { of } else { None } } + let of = if name.ends_with("child") { of } else { None }; + let last = name.contains("last"); + // counting the following siblings that match S: a source-tree query + let later = match &of { + Some(list) if last => { + let rels = list.iter() + .map(|sel| RelSelector { comb: Combinator::Sibling, sel: sel.clone() }).collect(); + has.push(HasEntry { rels, host: Vec::new(), kind: Query::LaterMatches }); + Some((has.len() - 1) as u16) + } + _ => None, + }; + Simple::Nth { a, b: bb, last, of_type: name.ends_with("of-type"), of, later } } "lang" => Simple::Lang(split_top(arg, ',').iter() .map(|l| l.trim().trim_matches(['"', '\'']).to_ascii_lowercase()).collect()), @@ -683,7 +755,7 @@ fn match_simple(s: &Simple, el: &S) -> bool { "defined" => true, other => el.state(other), }, - Simple::Nth { a, b, last, of_type, of } => { + Simple::Nth { a, b, last, of_type, of, later } => { let pos = match (of_type, of) { (true, _) => { let (i, n) = el.type_position(); @@ -693,7 +765,9 @@ fn match_simple(s: &Simple, el: &S) -> bool { if !any_matches(list, el) { return false; } - if *last { + if let Some(n) = later.and_then(|id| el.later_matches(id)) { + n + 1 // answered on the source tree (the siblings aren't built yet) + } else if *last { let mut k = 1; let mut cur = el.next_sibling(); while let Some(s) = cur { @@ -746,6 +820,7 @@ fn match_simple(s: &Simple, el: &S) -> bool { } !*rtl } + Simple::ScopeRoot(root) => any_matches(root, el), Simple::Never => false, } } @@ -810,7 +885,7 @@ pub struct MediaEnv { impl MediaEnv { pub fn viewport(viewport: (f32, f32)) -> MediaEnv { - MediaEnv { width: viewport.0, height: viewport.1, dark: crate::color4::DARK, scale: 1.0 } + MediaEnv { width: viewport.0, height: viewport.1, dark: crate::color4::dark(), scale: 1.0 } } } @@ -884,7 +959,7 @@ fn media_value(s: &str) -> MediaValue { "dpi" => v / 96.0, "dpcm" => v * 2.54 / 96.0, u => crate::calc::leaf(*v, u).map(|c| c.eval_units( - &crate::geometry::Units { font_size: 16.0, viewport: (0.0, 0.0) }, 0.0)).unwrap_or(*v), + &crate::geometry::Units::initial(16.0, (0.0, 0.0)), 0.0)).unwrap_or(*v), }), [t] if t.ident().is_some() => MediaValue::Ident(t.ident().unwrap_or("").to_string()), _ => MediaValue::Ident(s.to_ascii_lowercase()), @@ -1435,7 +1510,10 @@ impl Stylesheet { let layer = self.layer_rank(ctx.layer.as_deref()); let mut has = std::mem::take(&mut self.has); for sel in split_top(selector, ',') { - if let Some((None, selector)) = parse_complex(sel, &mut has, false) { + if let Some((None, mut selector)) = parse_complex(sel, &mut has, false) { + if let Some(s) = ctx.scope { + selector.bind_scope(&self.scopes[s as usize].0); + } let order = self.rules.len(); self.rules.push(Rule { selector, diff --git a/bindings/rust/blenderui/src/style.rs b/bindings/rust/blenderui/src/style.rs index de70541e..c9825adb 100644 --- a/bindings/rust/blenderui/src/style.rs +++ b/bindings/rust/blenderui/src/style.rs @@ -377,6 +377,8 @@ pub struct Computed { pub color: Rgba, pub accent: Option, pub font_size: f32, + /// The root element's font size (`rem`): inherited by every element from the root. + pub root_font_size: f32, pub weight: u16, pub italic: bool, pub underline: bool, @@ -489,6 +491,7 @@ impl Default for Computed { color: crate::color::rgb(0x000000), // initial: CanvasText accent: None, font_size: 13.0, + root_font_size: crate::geometry::ROOT_FONT_SIZE, weight: 400, italic: false, underline: false, @@ -537,6 +540,11 @@ impl Default for Computed { impl Computed { /// A child's starting style: inherited properties from `parent`, the rest initial. + /// What this element's lengths resolve against in `viewport`. + pub(crate) const fn units(&self, viewport: (f32, f32)) -> Units { + Units { font_size: self.font_size, root_font_size: self.root_font_size, viewport } + } + pub fn inherit(parent: &Computed) -> Computed { Computed { visible: parent.visible, @@ -551,6 +559,7 @@ impl Computed { color: parent.color, accent: parent.accent, font_size: parent.font_size, + root_font_size: parent.root_font_size, weight: parent.weight, italic: parent.italic, text_align: parent.text_align, @@ -671,7 +680,7 @@ pub(crate) fn supports_decl(prop: &str, value: &str) -> bool { } let parent = Computed::default(); let mut c = Computed::default(); - apply(&mut c, &parent, Units { font_size: 16.0, viewport: (1000.0, 800.0) }, &d) + apply(&mut c, &parent, Units::initial(16.0, (1000.0, 800.0)), &d) } /// The property index of `name` (run-time lookup for parsed CSS). @@ -3410,7 +3419,7 @@ mod tests { fn computed(css: &str) -> Computed { let parent = Computed::default(); let mut c = Computed::inherit(&parent); - let u = Units { font_size: 13.0, viewport: (800.0, 600.0) }; + let u = Units::initial(13.0, (800.0, 600.0)); for d in parse_declarations(css) { assert!(apply(&mut c, &parent, u, &d), "not applied: {}", d.prop); } diff --git a/bindings/rust/blenderui/src/tree.rs b/bindings/rust/blenderui/src/tree.rs index d23e924d..1da8a63e 100644 --- a/bindings/rust/blenderui/src/tree.rs +++ b/bindings/rust/blenderui/src/tree.rs @@ -1,5 +1,5 @@ //! The layout tree: taffy's algorithms (block with floats, flexbox, grid, -//! out-of-flow positioning, rounding) over our own node storage. +//! out-of-flow positioning) over our own node storage. //! //! taffy's `TaffyTree` resolves every `calc()` to 0; this tree resolves //! them (`crate::calc`), so `width: calc(100% - 2rem)` and friends work. It @@ -9,13 +9,13 @@ use taffy::compute::{ compute_block_layout, compute_cached_layout, compute_flexbox_layout, compute_grid_layout, - compute_hidden_layout, compute_oof_layout, compute_root_layout, round_layout, BlockContext, + compute_hidden_layout, compute_oof_layout, compute_root_layout, BlockContext, }; use taffy::prelude::*; use taffy::tree::{Cache, DetailedLayoutInfo, Layout, LayoutInput, LayoutOutput, RunMode}; use taffy::{ CacheTree, DetailedGridInfo, LayoutBlockContainer, LayoutContainingBlock, LayoutFlexboxContainer, - LayoutGridContainer, LayoutPartialTree, RoundTree, TraversePartialTree, TraverseTree, + LayoutGridContainer, LayoutPartialTree, TraversePartialTree, TraverseTree, }; struct Node { @@ -25,7 +25,6 @@ struct Node { hoisted: Vec, cache: Cache, unrounded: Layout, - layout: Layout, detail: DetailedLayoutInfo, live: bool, } @@ -62,7 +61,6 @@ impl LayoutTree { hoisted: Vec::new(), cache: Cache::new(), unrounded: Layout::new(), - layout: Layout::new(), detail: DetailedLayoutInfo::None, live: true, }; @@ -178,9 +176,10 @@ impl LayoutTree { self.nodes[ix(id)].cache.clear(); } - /// The final (rounded) layout of a node. + /// The layout of a node, in fractional pixels as browsers lay out (paint snaps box edges to + /// device pixels: `Item::snap` in `paint.rs`). pub fn layout(&self, id: NodeId) -> &Layout { - &self.nodes[ix(id)].layout + &self.nodes[ix(id)].unrounded } /// Lay out the tree under `root`; `measure` sizes leaves that carry a context. @@ -190,7 +189,6 @@ impl LayoutTree { { let mut view = View { t: self, measure }; compute_root_layout(&mut view, root, available); - round_layout(&mut view, root); } } @@ -207,7 +205,7 @@ where fn child_layout(&mut self, id: NodeId, inputs: LayoutInput, block: Option<&mut BlockContext<'_>>) -> LayoutOutput { if inputs.run_mode == RunMode::PerformHiddenLayout { - self.t.nodes[ix(id)].layout = Layout::with_order(0); + self.t.nodes[ix(id)].unrounded = Layout::with_order(0); return compute_hidden_layout(self, id); } compute_cached_layout(self, id, inputs, |tree, id, inputs| { @@ -408,37 +406,6 @@ where } } -impl RoundTree for View<'_, C, M> -where - M: FnMut(Size>, Size, &C) -> Size, -{ - #[inline(always)] - fn get_unrounded_layout(&self, id: NodeId) -> Layout { - self.t.nodes[ix(id)].unrounded - } - - #[inline(always)] - fn set_final_layout(&mut self, id: NodeId, layout: &Layout) { - self.t.nodes[ix(id)].layout = *layout; - } - - #[inline(always)] - fn is_out_of_flow(&self, id: NodeId) -> bool { - let s = self.t.style(id); - s.position.is_out_of_flow() && s.display != Display::None - } - - #[inline(always)] - fn hoisted_child_count(&self, id: NodeId) -> usize { - self.t.nodes[ix(id)].hoisted.len() - } - - #[inline(always)] - fn get_hoisted_child_id(&self, id: NodeId, k: usize) -> NodeId { - self.t.nodes[ix(id)].hoisted[k] - } -} - #[cfg(test)] mod tests { use super::{LayoutTree, Node}; diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rs index 77e11f66..97479ede 100644 --- a/bindings/rust/blenderui/src/window.rs +++ b/bindings/rust/blenderui/src/window.rs @@ -395,6 +395,9 @@ pub struct App { real_clock: bool, globals: HashMap>, pub(crate) propagate: bool, + /// The theme generation the windows were last rendered for: a theme change re-renders them + /// (`light-dark()`, system colors, `prefers-color-scheme`, the `styled` sheet follow it). + theme_seen: i32, /// A key listener acted on the key ([`App::prevent_default`]). default_prevented: bool, /// Work sent from other threads ([`UiSender`]). @@ -455,7 +458,8 @@ impl App { crate::motion::start_clock(real_clock); App { windows: Vec::new(), entities: Vec::new(), headless, real_clock, globals: HashMap::new(), propagate: true, default_prevented: false, remote: None, close_hooks: Vec::new(), closed_later: None, - activation_hooks: Vec::new(), notified: 0, shutdown_later: false } + activation_hooks: Vec::new(), notified: 0, shutdown_later: false, + theme_seen: crate::theme_generation() } } /// Create an entity (gpui's `cx.new`). @@ -714,6 +718,11 @@ impl App { /// Re-render dirty windows now (headless) or soon (native: next loop turn). fn flush(&mut self) { self.drain(); + let theme = crate::theme_generation(); + if theme != self.theme_seen { + self.theme_seen = theme; + self.notify_all(); + } // windows whose signals were written (hooks) for id in crate::hooks::take_dirty() { if id == usize::MAX { diff --git a/bindings/rust/blenderui/tests/animation.rs b/bindings/rust/blenderui/tests/suite/animation.rs similarity index 100% rename from bindings/rust/blenderui/tests/animation.rs rename to bindings/rust/blenderui/tests/suite/animation.rs diff --git a/bindings/rust/blenderui/tests/app_root.rs b/bindings/rust/blenderui/tests/suite/app_root.rs similarity index 100% rename from bindings/rust/blenderui/tests/app_root.rs rename to bindings/rust/blenderui/tests/suite/app_root.rs diff --git a/bindings/rust/blenderui/tests/basic_css.rs b/bindings/rust/blenderui/tests/suite/basic_css.rs similarity index 100% rename from bindings/rust/blenderui/tests/basic_css.rs rename to bindings/rust/blenderui/tests/suite/basic_css.rs diff --git a/bindings/rust/blenderui/tests/common/mod.rs b/bindings/rust/blenderui/tests/suite/common.rs similarity index 100% rename from bindings/rust/blenderui/tests/common/mod.rs rename to bindings/rust/blenderui/tests/suite/common.rs diff --git a/bindings/rust/blenderui/tests/css_redraw.rs b/bindings/rust/blenderui/tests/suite/css_redraw.rs similarity index 100% rename from bindings/rust/blenderui/tests/css_redraw.rs rename to bindings/rust/blenderui/tests/suite/css_redraw.rs diff --git a/bindings/rust/blenderui/tests/suite/css_spec.rs b/bindings/rust/blenderui/tests/suite/css_spec.rs new file mode 100644 index 00000000..6ffafb72 --- /dev/null +++ b/bindings/rust/blenderui/tests/suite/css_spec.rs @@ -0,0 +1,213 @@ +//! Cascade, selector and value rules checked against the CSS specifications: each page paints a +//! box red when the rule holds. + +use blenderui::prelude::*; + +struct Page(&'static str, fn() -> Div); + +impl Render for Page { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + (self.1)().child(style().child(self.0)) + } +} + +/// The color (0xRRGGBB) at the middle of the `k`th 10 x 10 box down the page. +fn colors(css: &'static str, body: fn() -> Div, boxes: usize) -> Vec { + let mut out = Vec::new(); + Application::headless().run(|cx| { + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(100.0), px(200.0)), + })), + ..Default::default() + }; + let win = cx.open_window(opts, |_, cx| cx.new(|_| Page(css, body))).unwrap(); + let img = cx.draw(win.id); + let s = img.0 as f32 / 100.0; + out = (0..boxes).map(|k| img.2[((10 * k + 5) as f32 * s) as usize * img.0 + (5.0 * s) as usize]).collect(); + }); + out +} + +const RED: u32 = 0xff0000; + +#[test] +fn important_reverses_layers_and_takes_any_spelling() { + let got = colors( + "html, body { margin: 0; background: #000 } + body > div { width: 10px; height: 10px } + @layer base { #a { background: #f00 !important } } + #a { background: #00f !important } + #b { background: #f00 ! important } + #b { background: #00f } + #c { background: #f00 !IMPORTANT } + #c { background: #00f }", + || body().child(div().id("a")).child(div().id("b")).child(div().id("c")), + 3, + ); + assert_eq!(got, [RED; 3], "a layered !important beats an unlayered one; `! important` and `!IMPORTANT` count"); +} + +#[test] +fn has_counts_its_most_specific_argument() { + // `.p:has(#dc)` is (1, 1, 0): it beats the later `.p.q` (0, 2, 0) + let got = colors( + "html, body { margin: 0; background: #000 } + body > div { width: 10px; height: 10px } + .p:has(#dc) { background: #f00 } + .p.q { background: #00f }", + || body().child(div().class("p q").child(div().id("dc"))), + 1, + ); + assert_eq!(got, [RED]); +} + +#[test] +fn scope_is_the_scoping_root() { + let got = colors( + "html, body { margin: 0; background: #000 } + body > div { width: 10px; height: 10px } + @scope (#s) { :scope { background: #f00 } }", + || body().child(div().id("s")), + 1, + ); + assert_eq!(got, [RED]); +} + +#[test] +fn empty_sees_the_children() { + let got = colors( + "html, body { margin: 0; background: #000 } + body > div { width: 10px; height: 10px; color: #f00 } + div { background: #f00 } + div:empty { background: #00f } + #e:empty { background: #f00 }", + || body().child(div().child("x")).child(div().child(span())).child(div().id("e")), + 3, + ); + assert_eq!(got, [RED; 3], "text and element children are not empty; no children is"); +} + +#[test] +fn has_reaches_following_siblings() { + let got = colors( + "html, body { margin: 0; background: #000 } + body > div { width: 10px; height: 10px } + #b:has(+ .y) { background: #f00 } + #c:has(~ .z) { background: #f00 } + #d { background: #f00 } + #d:has(+ .nope) { background: #00f }", + || body().child(div().id("b")).child(div().class("y")) + .child(div().id("c")).child(div()).child(div().class("z")) + .child(div().id("d")).child(div()), + 8, + ); + assert_eq!((got[0], got[2], got[5]), (RED, RED, RED)); +} + +#[test] +fn rgb_channels_clamp() { + let got = colors( + "html, body { margin: 0; background: #000 } + body > div { width: 10px; height: 10px } + div { background: rgb(300 -20 0) }", + || body().child(div()), + 1, + ); + assert_eq!(got, [RED]); +} + +#[test] +fn rem_is_the_root_font_size() { + Application::headless().run(|cx| { + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(200.0), px(100.0)), + })), + ..Default::default() + }; + let win = cx.open_window(opts, |_, cx| cx.new(|_| Page( + "html { font-size: 10px } html, body { margin: 0 } + div { height: 4px } + #a { width: calc(2rem + 6px) } + #b { font-size: 20px; width: calc(1em + 1rem) } + #c { width: 1rlh }", + || body().child(div().id("a")).child(div().id("b")).child(div().id("c")), + ))).unwrap(); + cx.draw(win.id); + let mut w = |id: &str| cx.element_bounds(win.id, id).unwrap().size.width; + assert_eq!((w("a"), w("b"), w("c")), (26.0, 30.0, 13.0)); + }); +} + +/// The Rust parser's specificity against the Lean model's: `#eval vectors` in +/// `proofs/Bui/Specificity.lean` prints these (the model's theorems cover every rule they use). +#[test] +fn specificity_matches_the_lean_model() { + let cases: [(&str, (u16, u16, u16)); 13] = [ + ("div", (0, 0, 1)), + ("p#a.b", (1, 1, 1)), + ("ul li.x :hover", (0, 2, 2)), + (".p:has(#d)", (1, 1, 0)), + (":has(.x, #y.z)", (1, 1, 0)), + (":is(p, #q)", (1, 0, 0)), + (":not(.a, .b.c)", (0, 2, 0)), + (":where(#w).k", (0, 1, 0)), + (":nth-child(2n+1)", (0, 1, 0)), + (":nth-child(2n+1 of .x, #y)", (1, 1, 0)), + ("p::before", (0, 0, 2)), + ("*[data-x]", (0, 1, 0)), + (":is(:has(#deep))", (1, 0, 0)), + ]; + for (sel, want) in cases { + let got = blenderui::css::Selector::parse(sel).unwrap_or_else(|| panic!("{sel} parses")).specificity; + assert_eq!(got, want, "{sel}"); + } +} + +#[test] +fn nth_last_child_of_counts_the_following_siblings() { + let got = colors( + "html, body { margin: 0; background: #000 } + body > div { width: 10px; height: 10px; background: #00f } + #a:nth-last-child(4 of .x) { background: #f00 } + #b:nth-last-child(3 of .x) { background: #f00 } + #c:nth-last-child(1 of body > .x) { background: #f00 }", + || body().child(div().id("a").class("x")).child(div().id("b").class("x")) + .child(div().class("x")).child(div()).child(div().id("c").class("x")), + 5, + ); + // #a and #b count the .x after them (not the plain div); #c through a combinator naming its parent + assert_eq!((got[0], got[1], got[4]), (RED, RED, RED)); +} + +/// Boxes lay out at fractional positions, as in a browser (`getBoundingClientRect` gives 47.5), +/// and paint with each edge on its nearest device pixel: no half-blended column at 47.5. +#[test] +fn fractional_layout_with_snapped_edges() { + Application::headless().run(|cx| { + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(200.0), px(20.0)), + })), + ..Default::default() + }; + let win = cx.open_window(opts, |_, cx| cx.new(|_| Page( + "html, body { margin: 0; background: #000 } + #row { display: flex; height: 10px; gap: 10px } + #g1 { flex: 1; background: #f00 } #g2 { flex: 3; background: #00f }", + || body().child(div().id("row").child(div().id("g1")).child(div().id("g2"))), + ))).unwrap(); + let img = cx.draw(win.id); + let w = |cx: &mut App, id: &str| cx.element_bounds(win.id, id).unwrap(); + assert_eq!(w(cx, "g1").size.width, 47.5); + assert_eq!((w(cx, "g2").origin.x, w(cx, "g2").size.width), (57.5, 142.5)); + let s = img.0 / 200; + let at = |x: usize| img.2[5 * s * img.0 + x * s]; + assert_eq!((at(47), at(48), at(57), at(58)), (RED, 0x000000, 0x000000, 0x0000ff), + "edges at 47.5 and 57.5 round to device pixels 48 and 58"); + }); +} diff --git a/bindings/rust/blenderui/tests/damage_drag.rs b/bindings/rust/blenderui/tests/suite/damage_drag.rs similarity index 100% rename from bindings/rust/blenderui/tests/damage_drag.rs rename to bindings/rust/blenderui/tests/suite/damage_drag.rs diff --git a/bindings/rust/blenderui/tests/effects.rs b/bindings/rust/blenderui/tests/suite/effects.rs similarity index 100% rename from bindings/rust/blenderui/tests/effects.rs rename to bindings/rust/blenderui/tests/suite/effects.rs diff --git a/bindings/rust/blenderui/tests/features.rs b/bindings/rust/blenderui/tests/suite/features.rs similarity index 100% rename from bindings/rust/blenderui/tests/features.rs rename to bindings/rust/blenderui/tests/suite/features.rs diff --git a/bindings/rust/blenderui/tests/font_fallback.rs b/bindings/rust/blenderui/tests/suite/font_fallback.rs similarity index 100% rename from bindings/rust/blenderui/tests/font_fallback.rs rename to bindings/rust/blenderui/tests/suite/font_fallback.rs diff --git a/bindings/rust/blenderui/tests/gpu_turn.rs b/bindings/rust/blenderui/tests/suite/gpu_turn.rs similarity index 99% rename from bindings/rust/blenderui/tests/gpu_turn.rs rename to bindings/rust/blenderui/tests/suite/gpu_turn.rs index 421a9ca0..fd306893 100644 --- a/bindings/rust/blenderui/tests/gpu_turn.rs +++ b/bindings/rust/blenderui/tests/suite/gpu_turn.rs @@ -3,7 +3,7 @@ //! Needs a GPU (Direct3D 11 / OpenGL 3.3); without one the test has nothing //! to check and passes. -mod common; +use crate::common; use blenderui::effects::{transform, turn_box, turn_texture, Argb, Pixels, TURN_SHADER}; use blenderui::{GpuTarget, Image, ShaderEffect}; diff --git a/bindings/rust/blenderui/tests/headless.rs b/bindings/rust/blenderui/tests/suite/headless.rs similarity index 100% rename from bindings/rust/blenderui/tests/headless.rs rename to bindings/rust/blenderui/tests/suite/headless.rs diff --git a/bindings/rust/blenderui/tests/hooks.rs b/bindings/rust/blenderui/tests/suite/hooks.rs similarity index 100% rename from bindings/rust/blenderui/tests/hooks.rs rename to bindings/rust/blenderui/tests/suite/hooks.rs diff --git a/bindings/rust/blenderui/tests/images.rs b/bindings/rust/blenderui/tests/suite/images.rs similarity index 100% rename from bindings/rust/blenderui/tests/images.rs rename to bindings/rust/blenderui/tests/suite/images.rs diff --git a/bindings/rust/blenderui/tests/listener_bounds.rs b/bindings/rust/blenderui/tests/suite/listener_bounds.rs similarity index 100% rename from bindings/rust/blenderui/tests/listener_bounds.rs rename to bindings/rust/blenderui/tests/suite/listener_bounds.rs diff --git a/bindings/rust/blenderui/tests/suite/main.rs b/bindings/rust/blenderui/tests/suite/main.rs new file mode 100644 index 00000000..e8777f97 --- /dev/null +++ b/bindings/rust/blenderui/tests/suite/main.rs @@ -0,0 +1,62 @@ +//! The integration tests in one binary: each test file was its own executable, every one linking +//! the whole kit. Files that change or measure process-wide state (the theme, the UI scale, a +//! counting allocator) stay separate. + +mod common; +#[cfg(feature = "a11y")] +mod animation; +mod app_root; +mod basic_css; +mod css_redraw; +mod css_spec; +mod damage_drag; +mod effects; +mod features; +mod font_fallback; +mod gpu_turn; +mod headless; +mod hooks; +mod images; +mod listener_bounds; +mod modern_css; +mod motion; +mod motion_builders; +mod motion_clip_move; +mod motion_derived; +mod motion_drag; +mod motion_hover_under; +mod motion_inview_scroll; +mod motion_layout; +mod motion_layout_parent; +mod motion_loop; +mod motion_presence; +mod motion_redraw; +mod motion_redraw_work; +mod motion_scroll; +mod motion_selector; +mod motion_stale; +mod motion_widgets; +mod option_child; +mod option_props; +mod pangui_layout; +mod parity; +mod perf_effects; +mod render_target; +mod rsx; +mod screen; +mod scroll_into_view; +mod scroll_replace; +mod selection; +mod sound; +mod struct_props; +mod table; +mod text_overflow; +mod text_translate; +mod textarea_grow; +mod titlebar; +mod vector_transforms; +mod vlist; +mod vlist_custom; +mod widget_clip; +mod widget_layers; +mod widget_through; diff --git a/bindings/rust/blenderui/tests/modern_css.rs b/bindings/rust/blenderui/tests/suite/modern_css.rs similarity index 99% rename from bindings/rust/blenderui/tests/modern_css.rs rename to bindings/rust/blenderui/tests/suite/modern_css.rs index fe8cbaa5..e2efd91a 100644 --- a/bindings/rust/blenderui/tests/modern_css.rs +++ b/bindings/rust/blenderui/tests/suite/modern_css.rs @@ -280,7 +280,7 @@ fn tailwind_classes() { assert_eq!(rect(cx, w, "b1").2, 40.0); assert_eq!(rect(cx, w, "b2").0, 16.0 + 40.0 + 16.0, "gap-4"); assert_eq!(rect(cx, w, "b2").3, 48.0, "md: applies at 800px"); - assert_eq!(rect(cx, w, "c1").2, 157.0, "col-span-2 of 3 (gap-x-2 = 8px), rounded"); + assert!((rect(cx, w, "c1").2 - 472.0 / 3.0).abs() < 1e-3, "col-span-2 of 3 (gap-x-2 = 8px): fractional, as in a browser"); assert_eq!(rect(cx, w, "g").3, 8.0); assert_eq!(rect(cx, w, "d").3, 28.0, "data-[state=open]:"); assert_eq!(rect(cx, w, "e").3, 12.0, "hidden md:block"); diff --git a/bindings/rust/blenderui/tests/motion.rs b/bindings/rust/blenderui/tests/suite/motion.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion.rs rename to bindings/rust/blenderui/tests/suite/motion.rs diff --git a/bindings/rust/blenderui/tests/motion_builders.rs b/bindings/rust/blenderui/tests/suite/motion_builders.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_builders.rs rename to bindings/rust/blenderui/tests/suite/motion_builders.rs diff --git a/bindings/rust/blenderui/tests/motion_clip_move.rs b/bindings/rust/blenderui/tests/suite/motion_clip_move.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_clip_move.rs rename to bindings/rust/blenderui/tests/suite/motion_clip_move.rs diff --git a/bindings/rust/blenderui/tests/motion_derived.rs b/bindings/rust/blenderui/tests/suite/motion_derived.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_derived.rs rename to bindings/rust/blenderui/tests/suite/motion_derived.rs diff --git a/bindings/rust/blenderui/tests/motion_drag.rs b/bindings/rust/blenderui/tests/suite/motion_drag.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_drag.rs rename to bindings/rust/blenderui/tests/suite/motion_drag.rs diff --git a/bindings/rust/blenderui/tests/motion_hover_under.rs b/bindings/rust/blenderui/tests/suite/motion_hover_under.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_hover_under.rs rename to bindings/rust/blenderui/tests/suite/motion_hover_under.rs diff --git a/bindings/rust/blenderui/tests/motion_inview_scroll.rs b/bindings/rust/blenderui/tests/suite/motion_inview_scroll.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_inview_scroll.rs rename to bindings/rust/blenderui/tests/suite/motion_inview_scroll.rs diff --git a/bindings/rust/blenderui/tests/motion_layout.rs b/bindings/rust/blenderui/tests/suite/motion_layout.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_layout.rs rename to bindings/rust/blenderui/tests/suite/motion_layout.rs diff --git a/bindings/rust/blenderui/tests/motion_layout_parent.rs b/bindings/rust/blenderui/tests/suite/motion_layout_parent.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_layout_parent.rs rename to bindings/rust/blenderui/tests/suite/motion_layout_parent.rs diff --git a/bindings/rust/blenderui/tests/motion_loop.rs b/bindings/rust/blenderui/tests/suite/motion_loop.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_loop.rs rename to bindings/rust/blenderui/tests/suite/motion_loop.rs diff --git a/bindings/rust/blenderui/tests/motion_presence.rs b/bindings/rust/blenderui/tests/suite/motion_presence.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_presence.rs rename to bindings/rust/blenderui/tests/suite/motion_presence.rs diff --git a/bindings/rust/blenderui/tests/motion_redraw.rs b/bindings/rust/blenderui/tests/suite/motion_redraw.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_redraw.rs rename to bindings/rust/blenderui/tests/suite/motion_redraw.rs diff --git a/bindings/rust/blenderui/tests/motion_redraw_work.rs b/bindings/rust/blenderui/tests/suite/motion_redraw_work.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_redraw_work.rs rename to bindings/rust/blenderui/tests/suite/motion_redraw_work.rs diff --git a/bindings/rust/blenderui/tests/motion_scroll.rs b/bindings/rust/blenderui/tests/suite/motion_scroll.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_scroll.rs rename to bindings/rust/blenderui/tests/suite/motion_scroll.rs diff --git a/bindings/rust/blenderui/tests/motion_selector.rs b/bindings/rust/blenderui/tests/suite/motion_selector.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_selector.rs rename to bindings/rust/blenderui/tests/suite/motion_selector.rs diff --git a/bindings/rust/blenderui/tests/motion_stale.rs b/bindings/rust/blenderui/tests/suite/motion_stale.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_stale.rs rename to bindings/rust/blenderui/tests/suite/motion_stale.rs diff --git a/bindings/rust/blenderui/tests/motion_widgets.rs b/bindings/rust/blenderui/tests/suite/motion_widgets.rs similarity index 100% rename from bindings/rust/blenderui/tests/motion_widgets.rs rename to bindings/rust/blenderui/tests/suite/motion_widgets.rs diff --git a/bindings/rust/blenderui/tests/option_child.rs b/bindings/rust/blenderui/tests/suite/option_child.rs similarity index 100% rename from bindings/rust/blenderui/tests/option_child.rs rename to bindings/rust/blenderui/tests/suite/option_child.rs diff --git a/bindings/rust/blenderui/tests/option_props.rs b/bindings/rust/blenderui/tests/suite/option_props.rs similarity index 100% rename from bindings/rust/blenderui/tests/option_props.rs rename to bindings/rust/blenderui/tests/suite/option_props.rs diff --git a/bindings/rust/blenderui/tests/pangui_layout.rs b/bindings/rust/blenderui/tests/suite/pangui_layout.rs similarity index 99% rename from bindings/rust/blenderui/tests/pangui_layout.rs rename to bindings/rust/blenderui/tests/suite/pangui_layout.rs index 9138adaf..440fea87 100644 --- a/bindings/rust/blenderui/tests/pangui_layout.rs +++ b/bindings/rust/blenderui/tests/suite/pangui_layout.rs @@ -3,7 +3,7 @@ //! margin and gap, with `calc()`, `min()`, `max()` and `clamp()` as the custom //! math. Every test checks exact boxes against numbers worked out by hand (or by //! a small independent formula). `scene_timings` prints the layout time per node -//! for the same scenes: `cargo test --release --test pangui_layout -- --ignored --nocapture`. +//! for the same scenes: `cargo test --release --test suite pangui_layout:: -- --ignored --nocapture`. use blenderui::prelude::*; use std::time::Instant; diff --git a/bindings/rust/blenderui/tests/parity.rs b/bindings/rust/blenderui/tests/suite/parity.rs similarity index 98% rename from bindings/rust/blenderui/tests/parity.rs rename to bindings/rust/blenderui/tests/suite/parity.rs index 9e5af26b..873fe638 100644 --- a/bindings/rust/blenderui/tests/parity.rs +++ b/bindings/rust/blenderui/tests/suite/parity.rs @@ -1,5 +1,5 @@ //! Coverage of HTML elements and CSS properties (the numbers in the README). -//! `cargo test --test parity -- --nocapture` prints the report. +//! `cargo test --test suite parity:: -- --nocapture` prints the report. use blenderui::html::{tag_kind, TagKind, HTML_ELEMENT_COUNT, TAGS}; use blenderui::style::{implemented_properties, is_implemented, is_supported, ACCEPTED}; diff --git a/bindings/rust/blenderui/tests/perf_effects.rs b/bindings/rust/blenderui/tests/suite/perf_effects.rs similarity index 98% rename from bindings/rust/blenderui/tests/perf_effects.rs rename to bindings/rust/blenderui/tests/suite/perf_effects.rs index a935115d..ddab0ebc 100644 --- a/bindings/rust/blenderui/tests/perf_effects.rs +++ b/bindings/rust/blenderui/tests/suite/perf_effects.rs @@ -2,7 +2,7 @@ //! long song's lyrics (300 lines of text): CSS transitions, animated scale on //! text, blur (still, moving, animated, a wide backdrop). Headless, so drawn //! by the software rasterizer. Run in release: -//! `cargo test --release --test perf_effects -- --ignored --nocapture --test-threads=1` +//! `cargo test --release --test suite perf_effects:: -- --ignored --nocapture --test-threads=1` use std::fmt::Write as _; use std::time::{Duration, Instant}; diff --git a/bindings/rust/blenderui/tests/render_target.rs b/bindings/rust/blenderui/tests/suite/render_target.rs similarity index 99% rename from bindings/rust/blenderui/tests/render_target.rs rename to bindings/rust/blenderui/tests/suite/render_target.rs index 5607e861..e12ff850 100644 --- a/bindings/rust/blenderui/tests/render_target.rs +++ b/bindings/rust/blenderui/tests/suite/render_target.rs @@ -1,7 +1,7 @@ //! Render targets: effects that draw into textures, with feedback. Needs a GPU device (Direct3D 11 or //! OpenGL 3.3); without one each test says so and passes. -mod common; +use crate::common; use blenderui::{GpuTarget, RenderTarget, ShaderEffect, TargetFormat}; use common::gpu_lock; diff --git a/bindings/rust/blenderui/tests/rsx.rs b/bindings/rust/blenderui/tests/suite/rsx.rs similarity index 100% rename from bindings/rust/blenderui/tests/rsx.rs rename to bindings/rust/blenderui/tests/suite/rsx.rs diff --git a/bindings/rust/blenderui/tests/screen.rs b/bindings/rust/blenderui/tests/suite/screen.rs similarity index 100% rename from bindings/rust/blenderui/tests/screen.rs rename to bindings/rust/blenderui/tests/suite/screen.rs diff --git a/bindings/rust/blenderui/tests/scroll_into_view.rs b/bindings/rust/blenderui/tests/suite/scroll_into_view.rs similarity index 100% rename from bindings/rust/blenderui/tests/scroll_into_view.rs rename to bindings/rust/blenderui/tests/suite/scroll_into_view.rs diff --git a/bindings/rust/blenderui/tests/scroll_replace.rs b/bindings/rust/blenderui/tests/suite/scroll_replace.rs similarity index 100% rename from bindings/rust/blenderui/tests/scroll_replace.rs rename to bindings/rust/blenderui/tests/suite/scroll_replace.rs diff --git a/bindings/rust/blenderui/tests/selection.rs b/bindings/rust/blenderui/tests/suite/selection.rs similarity index 100% rename from bindings/rust/blenderui/tests/selection.rs rename to bindings/rust/blenderui/tests/suite/selection.rs diff --git a/bindings/rust/blenderui/tests/sound.rs b/bindings/rust/blenderui/tests/suite/sound.rs similarity index 100% rename from bindings/rust/blenderui/tests/sound.rs rename to bindings/rust/blenderui/tests/suite/sound.rs diff --git a/bindings/rust/blenderui/tests/struct_props.rs b/bindings/rust/blenderui/tests/suite/struct_props.rs similarity index 100% rename from bindings/rust/blenderui/tests/struct_props.rs rename to bindings/rust/blenderui/tests/suite/struct_props.rs diff --git a/bindings/rust/blenderui/tests/table.rs b/bindings/rust/blenderui/tests/suite/table.rs similarity index 100% rename from bindings/rust/blenderui/tests/table.rs rename to bindings/rust/blenderui/tests/suite/table.rs diff --git a/bindings/rust/blenderui/tests/text_overflow.rs b/bindings/rust/blenderui/tests/suite/text_overflow.rs similarity index 100% rename from bindings/rust/blenderui/tests/text_overflow.rs rename to bindings/rust/blenderui/tests/suite/text_overflow.rs diff --git a/bindings/rust/blenderui/tests/text_translate.rs b/bindings/rust/blenderui/tests/suite/text_translate.rs similarity index 100% rename from bindings/rust/blenderui/tests/text_translate.rs rename to bindings/rust/blenderui/tests/suite/text_translate.rs diff --git a/bindings/rust/blenderui/tests/textarea_grow.rs b/bindings/rust/blenderui/tests/suite/textarea_grow.rs similarity index 100% rename from bindings/rust/blenderui/tests/textarea_grow.rs rename to bindings/rust/blenderui/tests/suite/textarea_grow.rs diff --git a/bindings/rust/blenderui/tests/titlebar.rs b/bindings/rust/blenderui/tests/suite/titlebar.rs similarity index 100% rename from bindings/rust/blenderui/tests/titlebar.rs rename to bindings/rust/blenderui/tests/suite/titlebar.rs diff --git a/bindings/rust/blenderui/tests/vector_transforms.rs b/bindings/rust/blenderui/tests/suite/vector_transforms.rs similarity index 100% rename from bindings/rust/blenderui/tests/vector_transforms.rs rename to bindings/rust/blenderui/tests/suite/vector_transforms.rs diff --git a/bindings/rust/blenderui/tests/vlist.rs b/bindings/rust/blenderui/tests/suite/vlist.rs similarity index 100% rename from bindings/rust/blenderui/tests/vlist.rs rename to bindings/rust/blenderui/tests/suite/vlist.rs diff --git a/bindings/rust/blenderui/tests/vlist_custom.rs b/bindings/rust/blenderui/tests/suite/vlist_custom.rs similarity index 100% rename from bindings/rust/blenderui/tests/vlist_custom.rs rename to bindings/rust/blenderui/tests/suite/vlist_custom.rs diff --git a/bindings/rust/blenderui/tests/widget_clip.rs b/bindings/rust/blenderui/tests/suite/widget_clip.rs similarity index 100% rename from bindings/rust/blenderui/tests/widget_clip.rs rename to bindings/rust/blenderui/tests/suite/widget_clip.rs diff --git a/bindings/rust/blenderui/tests/widget_layers.rs b/bindings/rust/blenderui/tests/suite/widget_layers.rs similarity index 100% rename from bindings/rust/blenderui/tests/widget_layers.rs rename to bindings/rust/blenderui/tests/suite/widget_layers.rs diff --git a/bindings/rust/blenderui/tests/widget_through.rs b/bindings/rust/blenderui/tests/suite/widget_through.rs similarity index 100% rename from bindings/rust/blenderui/tests/widget_through.rs rename to bindings/rust/blenderui/tests/suite/widget_through.rs diff --git a/bindings/rust/blenderui/tests/theme.rs b/bindings/rust/blenderui/tests/theme.rs index e747b45b..f8218d29 100644 --- a/bindings/rust/blenderui/tests/theme.rs +++ b/bindings/rust/blenderui/tests/theme.rs @@ -3,6 +3,12 @@ use blenderui::prelude::*; +/// Boxes at y = 70, 80, 90 (x < 10) that follow the theme's mode. +const LIGHT_DARK: &str = "#ld { background: light-dark(#00ff00, #ff0000) } + #sys { background: Canvas } + #mq { background: #ff0000 } + @media (prefers-color-scheme: light) { #mq { background: #00ff00 } }"; + struct Page; impl Render for Page { @@ -11,6 +17,10 @@ impl Render for Page { .m_0() .child(div().id("themed").styled().h(px(40.0)).child(pre().id("pre").child("x"))) .child(div().id("plain").h(px(20.0))) + .child(style().child(LIGHT_DARK)) + .child(div().id("ld").w(px(10.0)).h(px(10.0))) + .child(div().id("sys").w(px(10.0)).h(px(10.0))) + .child(div().id("mq").w(px(10.0)).h(px(10.0))) } } @@ -18,7 +28,7 @@ fn draw(cx: &mut App) -> (usize, usize, Vec) { let opts = WindowOptions { window_bounds: Some(WindowBounds::Windowed(Bounds { origin: point(px(0.0), px(0.0)), - size: size(px(200.0), px(80.0)), + size: size(px(200.0), px(100.0)), })), ..Default::default() }; @@ -50,16 +60,36 @@ fn dark_and_light_themes() { let dark = draw(cx); assert_eq!(at(&dark, 190.0, 38.0), 0x303030, "styled: Blender's dark background"); assert_eq!(at(&dark, 190.0, 70.0), 0xffffff, "plain HTML stays white"); + assert_eq!((at(&dark, 5.0, 75.0), at(&dark, 5.0, 85.0), at(&dark, 5.0, 95.0)), (0xff0000, 0x282828, 0xff0000), + "dark: light-dark() takes its dark color, Canvas is dark, prefers-color-scheme is dark"); }); Application::headless().theme("light").run(|cx| { assert_eq!(blenderui::theme_name(), "light"); let light = draw(cx); assert_eq!(at(&light, 190.0, 38.0), 0xb3b3b3, "styled: Blender_Light.xml's background"); assert_eq!(at(&light, 190.0, 70.0), 0xffffff, "plain HTML stays white"); + assert_eq!((at(&light, 5.0, 75.0), at(&light, 5.0, 85.0), at(&light, 5.0, 95.0)), (0x00ff00, 0xffffff, 0x00ff00), + "light: the light color, a light Canvas, prefers-color-scheme: light"); }); assert!(blenderui::set_theme("dark")); Application::headless().run(|cx| { let again = draw(cx); assert_eq!(at(&again, 190.0, 38.0), 0x303030); }); + // switching while a window is open: its cached styles follow the new mode + Application::headless().run(|cx| { + let opts = WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds { + origin: point(px(0.0), px(0.0)), + size: size(px(200.0), px(100.0)), + })), + ..Default::default() + }; + let win = cx.open_window(opts, |_, cx| cx.new(|_| Page)).unwrap(); + assert_eq!(at(&cx.draw(win.id), 5.0, 75.0), 0xff0000); + assert!(blenderui::set_theme("light")); + assert_eq!(at(&cx.draw(win.id), 5.0, 75.0), 0x00ff00, "restyled in the new mode"); + assert!(blenderui::set_theme("dark")); + assert_eq!(at(&cx.draw(win.id), 5.0, 75.0), 0xff0000); + }); } diff --git a/docs/effects-performance.md b/docs/effects-performance.md index 6ec0ddef..bcc469d6 100644 --- a/docs/effects-performance.md +++ b/docs/effects-performance.md @@ -13,8 +13,8 @@ per frame. ## What it costs now -`cargo test --release --test perf_effects -- --ignored --nocapture --test-threads=1` -(`bindings/rust/blenderui/tests/perf_effects.rs`): a 1280×800 headless window, +`cargo test --release --test suite perf_effects:: -- --ignored --nocapture --test-threads=1` +(`bindings/rust/blenderui/tests/suite/perf_effects.rs`): a 1280×800 headless window, 300 rows of text, 60 frames of 16 ms each. | Scene | First frame | BUI per frame (mean / worst) | diff --git a/docs/rust.md b/docs/rust.md index 1379146c..97d07b99 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -471,7 +471,7 @@ autoscroll. On the `Window` (listeners get it): `selected_text() -> Option`, `select_all()`, `clear_selection()`, `on_selection_change(|text, window, app| ..)` (fires for the user's changes) and `read_clipboard()` / `write_clipboard(text)`. -`examples/selectable.rs` is a page of paragraphs; `tests/selection.rs` drives it +`examples/selectable.rs` is a page of paragraphs; `tests/suite/selection.rs` drives it headlessly with `simulate_drag`, `simulate_click` and `simulate_key_with`. ## Screens, areas and regions @@ -589,7 +589,7 @@ let chat = cx.new(|cx| ListState::new(ChatList::from_messages(synth::messages(0, // elsewhere: chat.update(cx, |s, _| s.push(message)); // follows while at the bottom ``` -For items that are not messages, build a `List` from your own `ItemSource`, `Measurer` and `ItemPainter` and show it with `variable_list(&state)`. A `Record` carries an `id`, `time` and `sender` values and `flags` bits (`FLAG_PLACEHOLDER` is the engine's, `FLAG_USER << n` is free), `text`, an image and opaque `data` bytes your look decodes (stored in the page's buffer, no allocation per item); `ItemPainter::hit` returns an item-local part id for a press, delivered by `VariableList::on_item_hit(|item, part, list| ..)` next to `on_item_click`; `on_item_hover(|item, list| ..)` reports the item under the pointer (`None` off it) and only repaints, and `on_copy(|state| ..)` returns the text Ctrl+C copies; `Measurer::estimator` has a default. Everything a look needs (`PaintSink`, `Palette`, `Rect`, `Rgba`, `Lines`, `Record`, ...) is re-exported from `blenderui::vlist`. Items are painted, not elements: no buttons or text fields inside an item. `examples/vlist_cards.rs` is a non-chat feed of task cards and `tests/vlist_custom.rs` runs a custom look headlessly. `bindings/rust/blenderui-vlist-gpui` is the same list for real gpui (outside the main workspace); its benchmark against gpui's `list` and gpui-component's `virtual_list` is in `bench/`. Measured numbers and the method are on the website page "Variable-height lists". Not built yet: selecting text across messages, a background measuring thread, damage regions, JavaScript and Python wrappers. +For items that are not messages, build a `List` from your own `ItemSource`, `Measurer` and `ItemPainter` and show it with `variable_list(&state)`. A `Record` carries an `id`, `time` and `sender` values and `flags` bits (`FLAG_PLACEHOLDER` is the engine's, `FLAG_USER << n` is free), `text`, an image and opaque `data` bytes your look decodes (stored in the page's buffer, no allocation per item); `ItemPainter::hit` returns an item-local part id for a press, delivered by `VariableList::on_item_hit(|item, part, list| ..)` next to `on_item_click`; `on_item_hover(|item, list| ..)` reports the item under the pointer (`None` off it) and only repaints, and `on_copy(|state| ..)` returns the text Ctrl+C copies; `Measurer::estimator` has a default. Everything a look needs (`PaintSink`, `Palette`, `Rect`, `Rgba`, `Lines`, `Record`, ...) is re-exported from `blenderui::vlist`. Items are painted, not elements: no buttons or text fields inside an item. `examples/vlist_cards.rs` is a non-chat feed of task cards and `tests/suite/vlist_custom.rs` runs a custom look headlessly. `bindings/rust/blenderui-vlist-gpui` is the same list for real gpui (outside the main workspace); its benchmark against gpui's `list` and gpui-component's `virtual_list` is in `bench/`. Measured numbers and the method are on the website page "Variable-height lists". Not built yet: selecting text across messages, a background measuring thread, damage regions, JavaScript and Python wrappers. `blenderui::shadcn` also has `VirtualList` (`count` and an `item` closure that writes each item's text, so ten million rows cost a screenful) and `ChatList`, with TanStack Virtual's names: `estimate_size`, `overscan`, `get_item_key`, `on_range_change`, and `scroll_to_index` / `scroll_to_offset` / `measure_element` on the `ListHandle` that `use_virtual_list()` returns. They sit on `ListState` and `ItemSource` (the new `CountSource` and `RowStyle` in `blenderui-vlist`), so the file-backed source works under them. See the website page "Virtual list API" and `examples/site_shadcn_list.rs`. @@ -615,7 +615,7 @@ The kit has global state, so one `Application` runs at a time per process ## Coverage -From `cargo test --test parity -- --nocapture`: +From `cargo test --test suite parity:: -- --nocapture`: | Area | Coverage | | ------------------------------------- | -------------------------------------------------------------------------------- | @@ -629,7 +629,7 @@ From `cargo test --test parity -- --nocapture`: Beyond properties, the engine supports: - **Values:** every CSS math function (`calc`, `min`, `max`, `clamp`, `round`, `mod`, `rem`, trigonometry, `pow`, `hypot` ...) with mixed units, every length unit, and `var()` / `env()`. -- **Colors:** CSS Color 4/5: `oklch`, `lab`, `color()`, `color-mix()`, relative colors and `light-dark()`. +- **Colors:** CSS Color 4/5: `oklch`, `lab`, `color()`, `color-mix()`, relative colors and `light-dark()` (which, like the system colors and `prefers-color-scheme`, follows the theme's mode: `set_theme("light")` re-renders the windows). - **Selectors:** Selectors Level 4 (`:has()`, `:is()`, `:where()`, `:nth-child(of S)` ...), nesting, and `::before` / `::after` with `content`. - **At-rules:** `@media` (Media Queries 4 ranges), `@supports`, `@layer` and `@scope`. diff --git a/proofs/.gitignore b/proofs/.gitignore new file mode 100644 index 00000000..01f8cdb6 --- /dev/null +++ b/proofs/.gitignore @@ -0,0 +1 @@ +.lake/ diff --git a/proofs/Bui.lean b/proofs/Bui.lean new file mode 100644 index 00000000..3fbfcd1d --- /dev/null +++ b/proofs/Bui.lean @@ -0,0 +1,2 @@ +import Bui.Specificity +import Bui.Cascade diff --git a/proofs/Bui/Cascade.lean b/proofs/Bui/Cascade.lean new file mode 100644 index 00000000..5d90866c --- /dev/null +++ b/proofs/Bui/Cascade.lean @@ -0,0 +1,162 @@ +import Bui.Specificity + +/-! +# Cascade order + +`cascade_order` in `bindings/rust/blenderui/src/layout.rs` lists an element's declarations for +the two passes of `compute`, which apply the normal ones, then the `!important` ones, each in list +order, so a later declaration overrides an earlier one. This file proves the order it produces is +CSS Cascade 5's (§6.1): for any two declarations of the same importance, the one listed later is +the one the specification says wins. + +What the Rust code emits, as a sort key (rules arrive sorted by `(layer, specificity, order)`, +unlayered ranking above every layer): + +* normal: UA rules, then author rules (by layer, unlayered last), then the element's own; +* important: author rules (unlayered, then the layers from the last to the first), then the + element's own, then UA rules. + +The precedence below is the specification's, step by step: origin and importance, then +element-attached (the style attribute; BUI's own declarations on an element), then layers, then +specificity, then order of appearance. +-/ + + +namespace Bui + +inductive Origin where + | ua + | author +deriving DecidableEq + +/-- One declaration that applies to an element. -/ +structure Decl where + origin : Origin + /-- Element-attached (the style attribute; BUI's own declarations on the element). -/ + own : Bool + /-- Cascade layer: `none` for unlayered, else its rank (earlier layers rank lower). -/ + layer : Option Nat + spec : Spec + /-- Order of appearance. -/ + order : Nat + important : Bool + +/-- What can occur: element-attached and UA declarations are unlayered, and only author +declarations are element-attached. Layer ranks stay below `bound` (the Rust code ranks unlayered +rules at `u16::MAX`, above every layer). -/ +def Decl.wf (bound : Nat) (d : Decl) : Prop := + (d.own → d.origin = .author ∧ d.layer = none) ∧ + (d.origin = .ua → d.layer = none) ∧ + (∀ l, d.layer = some l → l < bound) + +/-- Lexicographic `<` on equal-length keys. -/ +def lexLt : List Nat → List Nat → Prop + | [], [] => False + | x :: xs, y :: ys => x < y ∨ (x = y ∧ lexLt xs ys) + | _, _ => False + +/-! ## The Rust order -/ + +/-- Where the Rust code lists a normal declaration. -/ +def rustNormal (bound : Nat) (d : Decl) : List Nat := + [ match d.origin, d.own with + | .ua, _ => 0 + | .author, false => 1 + | .author, true => 2 + , match d.layer with + | none => bound + | some l => l + , d.spec.a, d.spec.b, d.spec.c, d.order ] + +/-- Where the Rust code lists an important declaration. -/ +def rustImportant (bound : Nat) (d : Decl) : List Nat := + [ match d.origin, d.own with + | .author, false => 0 + | .author, true => 1 + | .ua, _ => 2 + , match d.layer with + | none => 0 + | some l => bound - l + , d.spec.a, d.spec.b, d.spec.c, d.order ] + +/-! ## The specification's precedence -/ + +/-- Whether `y` wins over `x` by specificity then order of appearance. -/ +def laterBySpecOrder (x y : Decl) : Prop := + x.spec.a < y.spec.a ∨ (x.spec.a = y.spec.a ∧ (x.spec.b < y.spec.b ∨ (x.spec.b = y.spec.b ∧ + (x.spec.c < y.spec.c ∨ (x.spec.c = y.spec.c ∧ x.order < y.order))))) + +/-- CSS Cascade 5 §6.1: `y` wins over `x`, both normal. -/ +def winsNormal (x y : Decl) : Prop := + -- origin: author over user agent + (x.origin = .ua ∧ y.origin = .author) ∨ + (x.origin = y.origin ∧ ( + -- element-attached over rules + (x.own = false ∧ y.own = true) ∨ + (x.own = y.own ∧ ( + -- layers: unlayered over layered, later layers over earlier + (x.layer.isSome ∧ y.layer = none) ∨ + (∃ lx ly, x.layer = some lx ∧ y.layer = some ly ∧ lx < ly) ∨ + (x.layer = y.layer ∧ laterBySpecOrder x y))))) + +/-- CSS Cascade 5 §6.1: `y` wins over `x`, both `!important`. -/ +def winsImportant (x y : Decl) : Prop := + -- origin: important user agent over important author + (x.origin = .author ∧ y.origin = .ua) ∨ + (x.origin = y.origin ∧ ( + -- element-attached over rules + (x.own = false ∧ y.own = true) ∨ + (x.own = y.own ∧ ( + -- layers reverse: layered over unlayered, earlier layers over later + (x.layer = none ∧ y.layer.isSome) ∨ + (∃ lx ly, x.layer = some lx ∧ y.layer = some ly ∧ ly < lx) ∨ + (x.layer = y.layer ∧ laterBySpecOrder x y))))) + +/-! ## They agree -/ + +/-- Normal declarations: the Rust code lists `y` after `x` exactly when `y` wins. -/ +theorem normal_order_is_the_cascade (bound : Nat) (x y : Decl) (hx : x.wf bound) (hy : y.wf bound) : + lexLt (rustNormal bound x) (rustNormal bound y) ↔ winsNormal x y := by + obtain ⟨xo, xs, xl, xsp, xord, _⟩ := x + obtain ⟨yo, ys, yl, ysp, yord, _⟩ := y + obtain ⟨xa, xb, xc⟩ := xsp + obtain ⟨ya, yb, yc⟩ := ysp + obtain ⟨hx1, hx2, hx3⟩ := hx + obtain ⟨hy1, hy2, hy3⟩ := hy + simp only at hx1 hx2 hx3 hy1 hy2 hy3 + cases xo <;> cases yo <;> cases xs <;> cases ys <;> cases xl <;> cases yl <;> + simp_all [rustNormal, winsNormal, laterBySpecOrder, lexLt] <;> + first + | omega + | (rename_i lx ly; have := hx3 lx rfl; have := hy3 ly rfl; omega) + | (rename_i l; have := hx3 l rfl; omega) + | (rename_i l; have := hy3 l rfl; omega) + +/-- Important declarations: the Rust code lists `y` after `x` exactly when `y` wins. -/ +theorem important_order_is_the_cascade (bound : Nat) (x y : Decl) (hx : x.wf bound) (hy : y.wf bound) : + lexLt (rustImportant bound x) (rustImportant bound y) ↔ winsImportant x y := by + obtain ⟨xo, xs, xl, xsp, xord, _⟩ := x + obtain ⟨yo, ys, yl, ysp, yord, _⟩ := y + obtain ⟨xa, xb, xc⟩ := xsp + obtain ⟨ya, yb, yc⟩ := ysp + obtain ⟨hx1, hx2, hx3⟩ := hx + obtain ⟨hy1, hy2, hy3⟩ := hy + simp only at hx1 hx2 hx3 hy1 hy2 hy3 + cases xo <;> cases yo <;> cases xs <;> cases ys <;> cases xl <;> cases yl <;> + simp_all [rustImportant, winsImportant, laterBySpecOrder, lexLt] <;> + first + | omega + | (rename_i lx ly; have := hx3 lx rfl; have := hy3 ly rfl; omega) + | (rename_i l; have := hx3 l rfl; omega) + | (rename_i l; have := hy3 l rfl; omega) + +/-- The order before the fix listed important declarations like normal ones (layers in order, +unlayered last), so an unlayered `!important` beat a layered one: the specification says the +layered one wins. -/ +theorem old_important_order_was_wrong : + let layered : Decl := ⟨.author, false, some 0, ⟨1, 0, 0⟩, 0, true⟩ + let unlayered : Decl := ⟨.author, false, none, ⟨1, 0, 0⟩, 1, true⟩ + lexLt (rustNormal 1 layered) (rustNormal 1 unlayered) ∧ winsImportant unlayered layered := by + simp [rustNormal, lexLt, winsImportant] + +end Bui diff --git a/proofs/Bui/Specificity.lean b/proofs/Bui/Specificity.lean new file mode 100644 index 00000000..94f8efe0 --- /dev/null +++ b/proofs/Bui/Specificity.lean @@ -0,0 +1,216 @@ +/-! +# Selector specificity + +A model of `spec_of` in `bindings/rust/blenderui/src/selector.rs`, after Selectors 4 §17: +an id counts (1, 0, 0); a class, attribute or pseudo-class (0, 1, 0); a type or pseudo-element +(0, 0, 1); `:where()` nothing; `:is()`, `:not()` and `:has()` their most specific argument; +`:nth-child(An+B of S)` a pseudo-class plus its most specific argument. + +The theorems pin down the properties the cascade relies on: the order is total, `:where()` adds +nothing, `:has()` counts like `:is()` (the Rust code counted it as one class until this was +checked), a function counts at least as much as any of its arguments, and adding a simple selector +never lowers a selector's specificity. `vectors` prints test cases for +`bindings/rust/blenderui/tests/suite/css_spec.rs`, which checks the Rust parser agrees. +-/ + +namespace Bui + +/-- Specificity (a, b, c), compared lexicographically. -/ +structure Spec where + a : Nat + b : Nat + c : Nat +deriving DecidableEq, Repr + +namespace Spec + +def zero : Spec := ⟨0, 0, 0⟩ + +def add (x y : Spec) : Spec := ⟨x.a + y.a, x.b + y.b, x.c + y.c⟩ + +/-- Lexicographic `≤`. -/ +def le (x y : Spec) : Prop := + x.a < y.a ∨ (x.a = y.a ∧ (x.b < y.b ∨ (x.b = y.b ∧ x.c ≤ y.c))) + +instance (x y : Spec) : Decidable (le x y) := by unfold le; exact inferInstance + +def max (x y : Spec) : Spec := if le x y then y else x + +theorem le_refl (x : Spec) : le x x := by + unfold le; omega + +theorem le_trans {x y z : Spec} : le x y → le y z → le x z := by + unfold le; omega + +theorem le_total (x y : Spec) : le x y ∨ le y x := by + unfold le; omega + +theorem le_antisymm {x y : Spec} : le x y → le y x → x = y := by + rcases x with ⟨a, b, c⟩; rcases y with ⟨a', b', c'⟩ + unfold le; simp only [mk.injEq]; omega + +theorem le_max_left (x y : Spec) : le x (max x y) := by + unfold max; split + · assumption + · exact le_refl x + +theorem le_max_right (x y : Spec) : le y (max x y) := by + unfold max; split + · exact le_refl y + · rcases le_total x y with h | h + · contradiction + · exact h + +/-- Adding anything never lowers a specificity. -/ +theorem le_add_left (x y : Spec) : le y (add x y) := by + unfold le add; simp only; omega + +end Spec + +mutual + /-- A simple selector. Arguments of functional pseudo-classes are selector lists. -/ + inductive Simple where + | universal + | tag (name : String) + | id (name : String) + | cls (name : String) + | attr (name : String) + | pseudoClass (name : String) + | is (args : List Sel) + | not (args : List Sel) + | where_ (args : List Sel) + | has (args : List Sel) + | nth (of : Option (List Sel)) + + /-- A complex selector: compounds (descendant combinators between them), and whether it ends + in a pseudo-element. -/ + inductive Sel where + | mk (compounds : List (List Simple)) (pseudoElement : Bool) +end + +mutual + def Simple.spec : Simple → Spec + | .universal => Spec.zero + | .tag _ => ⟨0, 0, 1⟩ + | .id _ => ⟨1, 0, 0⟩ + | .cls _ | .attr _ | .pseudoClass _ => ⟨0, 1, 0⟩ + | .is l | .not l | .has l => maxSpec l + | .where_ _ => Spec.zero + | .nth none => ⟨0, 1, 0⟩ + | .nth (some l) => Spec.add ⟨0, 1, 0⟩ (maxSpec l) + + /-- The most specific selector of a list (`(0, 0, 0)` for none). -/ + def maxSpec : List Sel → Spec + | [] => Spec.zero + | s :: rest => Spec.max (Sel.spec s) (maxSpec rest) + + def compoundSpec : List Simple → Spec + | [] => Spec.zero + | s :: rest => Spec.add (Simple.spec s) (compoundSpec rest) + + def compoundsSpec : List (List Simple) → Spec + | [] => Spec.zero + | c :: rest => Spec.add (compoundSpec c) (compoundsSpec rest) + + def Sel.spec : Sel → Spec + | .mk cs pe => Spec.add (compoundsSpec cs) (if pe then ⟨0, 0, 1⟩ else Spec.zero) +end + +/-- `:where()` adds nothing. -/ +theorem where_adds_nothing (l : List Sel) : (Simple.where_ l).spec = Spec.zero := by + simp [Simple.spec] + +/-- `:has()` counts exactly like `:is()` over the same arguments. -/ +theorem has_counts_like_is (l : List Sel) : (Simple.has l).spec = (Simple.is l).spec := by + simp [Simple.spec] + +/-- `:not()` counts exactly like `:is()` over the same arguments. -/ +theorem not_counts_like_is (l : List Sel) : (Simple.not l).spec = (Simple.is l).spec := by + simp [Simple.spec] + +/-- The list maximum is at least each member's specificity. -/ +theorem maxSpec_ge {s : Sel} : ∀ {l : List Sel}, s ∈ l → Spec.le s.spec (maxSpec l) + | _ :: rest, .head _ => by simp only [maxSpec]; exact Spec.le_max_left _ _ + | t :: rest, .tail _ h => by + simp only [maxSpec] + exact Spec.le_trans (maxSpec_ge h) (Spec.le_max_right _ _) + +/-- `:is()` (and so `:not()` / `:has()`) counts at least as much as any argument. -/ +theorem is_ge_argument {s : Sel} {l : List Sel} (h : s ∈ l) : Spec.le s.spec (Simple.is l).spec := by + simp only [Simple.spec]; exact maxSpec_ge h + +/-- Adding a simple selector to a compound never lowers its specificity. -/ +theorem compound_monotone (s : Simple) (c : List Simple) : + Spec.le (compoundSpec c) (compoundSpec (s :: c)) := by + simp only [compoundSpec]; exact Spec.le_add_left _ _ + +/-- Adding a compound to a selector never lowers its specificity. -/ +theorem compounds_monotone (c : List Simple) (cs : List (List Simple)) : + Spec.le (compoundsSpec cs) (compoundsSpec (c :: cs)) := by + simp only [compoundsSpec]; exact Spec.le_add_left _ _ + +/-! ## Test vectors + +Selectors written in CSS with the specificity the model gives; `#eval vectors` prints them as +Rust tuples for `css_spec.rs`. -/ + +mutual + def Simple.css : Simple → String + | .universal => "*" + | .tag n => n + | .id n => "#" ++ n + | .cls n => "." ++ n + | .attr n => "[" ++ n ++ "]" + | .pseudoClass n => ":" ++ n + | .is l => ":is(" ++ listCss l ++ ")" + | .not l => ":not(" ++ listCss l ++ ")" + | .where_ l => ":where(" ++ listCss l ++ ")" + | .has l => ":has(" ++ listCss l ++ ")" + | .nth none => ":nth-child(2n+1)" + | .nth (some l) => ":nth-child(2n+1 of " ++ listCss l ++ ")" + + def listCss : List Sel → String + | [] => "" + | [s] => Sel.css s + | s :: rest => Sel.css s ++ ", " ++ listCss rest + + def compoundCss : List Simple → String + | [] => "" + | s :: rest => Simple.css s ++ compoundCss rest + + def compoundsCss : List (List Simple) → String + | [] => "" + | [c] => compoundCss c + | c :: rest => compoundCss c ++ " " ++ compoundsCss rest + + def Sel.css : Sel → String + | .mk cs pe => compoundsCss cs ++ (if pe then "::before" else "") +end + +open Simple in +/-- Selectors that exercise every rule of the model. -/ +def cases : List Sel := + let one (c : List Simple) := Sel.mk [c] false + [ one [tag "div"] + , one [tag "p", id "a", cls "b"] + , Sel.mk [[tag "ul"], [tag "li", cls "x"], [pseudoClass "hover"]] false + , one [cls "p", has [one [id "d"]]] + , one [has [one [cls "x"], one [id "y", cls "z"]]] + , one [is [one [tag "p"], one [id "q"]]] + , one [not [one [cls "a"], one [cls "b", cls "c"]]] + , one [where_ [one [id "w"]], cls "k"] + , one [nth none] + , one [nth (some [one [cls "x"], one [id "y"]])] + , Sel.mk [[tag "p"]] true + , one [universal, attr "data-x"] + , one [is [one [has [one [id "deep"]]]]] + ] + +def vectors : String := + String.intercalate "\n" (cases.map fun s => + let p := s.spec + s!"(\"{s.css}\", ({p.a}, {p.b}, {p.c})),") + +#eval IO.println vectors + +end Bui diff --git a/proofs/README.md b/proofs/README.md new file mode 100644 index 00000000..631df777 --- /dev/null +++ b/proofs/README.md @@ -0,0 +1,13 @@ +# Proofs + +Lean 4 models of parts of the Rust CSS engine (`bindings/rust/blenderui`), with proofs of the +properties the engine relies on. They cover the models, not the Rust code itself: the tests in +`bindings/rust/blenderui/tests/suite/css_spec.rs` check the code agrees with them. + +| File | What it proves | +| --- | --- | +| `Bui/Specificity.lean` | Selector specificity (`spec_of` in `selector.rs`): a total order; `:where()` adds nothing; `:is()`, `:not()` and `:has()` count as their most specific argument; adding a simple selector never lowers it. `#eval vectors` prints the test cases `css_spec.rs` checks against the parser. | +| `Bui/Cascade.lean` | The order `cascade_order` in `layout.rs` lists declarations in is CSS Cascade 5's, for normal and `!important` declarations (origins, element-attached, layers, specificity, order); and the order before the fix was not. | + +Build with `lake build` in this folder (Lean 4.36, no dependencies). `#print axioms` on each +theorem lists only Lean's standard axioms. diff --git a/proofs/lake-manifest.json b/proofs/lake-manifest.json new file mode 100644 index 00000000..79a5252d --- /dev/null +++ b/proofs/lake-manifest.json @@ -0,0 +1,6 @@ +{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": [], + "name": "«bui-proofs»", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/proofs/lakefile.toml b/proofs/lakefile.toml new file mode 100644 index 00000000..5c0d9e97 --- /dev/null +++ b/proofs/lakefile.toml @@ -0,0 +1,5 @@ +name = "bui-proofs" +defaultTargets = ["Bui"] + +[[lean_lib]] +name = "Bui" diff --git a/proofs/lean-toolchain b/proofs/lean-toolchain new file mode 100644 index 00000000..00f84835 --- /dev/null +++ b/proofs/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.36.0 diff --git a/website/src/content/docs/concepts/screens.mdx b/website/src/content/docs/concepts/screens.mdx index 0d31b4b9..44451494 100644 --- a/website/src/content/docs/concepts/screens.mdx +++ b/website/src/content/docs/concepts/screens.mdx @@ -3,7 +3,7 @@ title: Screens, areas and regions description: Blender's resizable, splittable, dockable editor layout in every language. Drag the edges between areas, drag a corner to split, join or dock, maximize with Ctrl+Space; regions (headers, toolbars, sidebars) resize, hide and flip; panels reorder and pin. Ported from Blender's editors/screen. section: Concepts order: 68 -sources: ["kit/intern/screen/screen_intern.h", "kit/intern/screen/screen_geometry.c", "kit/intern/screen/screen_edit.c", "kit/intern/screen/area.c", "kit/intern/screen/screen_ops.c", "kit/intern/screen/screen_draw.c", "kit/intern/screen/screen_layout.c", "kit/intern/screen/screen_node.c", "kit/include/BUI_kit.h", "bindings/python/bui/components/screen.py", "bindings/python/bui/qtcontainers.py", "bindings/python/bui/tksyntax/_widgets.py", "bindings/lua/src/bui_node.c", "bindings/d/source/bui/node.d", "tests/screen_test.c", "bindings/python/tests/test_screen.py", "bindings/lua/tests/test_screen.lua", "bindings/rust/blenderui/src/screen.rs", "bindings/rust/blenderui/tests/screen.rs", "bindings/node/screen.js", "bindings/react/index.js"] +sources: ["kit/intern/screen/screen_intern.h", "kit/intern/screen/screen_geometry.c", "kit/intern/screen/screen_edit.c", "kit/intern/screen/area.c", "kit/intern/screen/screen_ops.c", "kit/intern/screen/screen_draw.c", "kit/intern/screen/screen_layout.c", "kit/intern/screen/screen_node.c", "kit/include/BUI_kit.h", "bindings/python/bui/components/screen.py", "bindings/python/bui/qtcontainers.py", "bindings/python/bui/tksyntax/_widgets.py", "bindings/lua/src/bui_node.c", "bindings/d/source/bui/node.d", "tests/screen_test.c", "bindings/python/tests/test_screen.py", "bindings/lua/tests/test_screen.lua", "bindings/rust/blenderui/src/screen.rs", "bindings/rust/blenderui/tests/suite/screen.rs", "bindings/node/screen.js", "bindings/react/index.js"] --- Blender's window is a **screen** of **areas**, each showing one editor, and each area is made of **regions**: a header, a toolbar, a sidebar, the main view. BUI has the same thing, ported from Blender's `editors/screen` (`screen_geometry.cc`, `screen_edit.cc`, `area.cc`, `screen_ops.cc`, `screen_draw.cc`), so it behaves like Blender in every language. diff --git a/website/src/content/docs/reference/binary-size.mdx b/website/src/content/docs/reference/binary-size.mdx index bb20d8c3..8931f20a 100644 --- a/website/src/content/docs/reference/binary-size.mdx +++ b/website/src/content/docs/reference/binary-size.mdx @@ -4,7 +4,7 @@ description: Pay only for what you use. One feature table turns BUI's optional p section: Reference order: 22 languages: ["c", "rust", "javascript", "python"] -sources: ["features.json", "features.cmake", "kit/CMakeLists.txt", "gpu/CMakeLists.txt", "bindings/rust/blenderui-sys/build.rs", "bindings/rust/blenderui-sys/Cargo.toml", "bindings/rust/blenderui/Cargo.toml", "bindings/rust/blenderui/tests/features.rs", "bindings/node/features.js", "bindings/node/cli.js", "bindings/node/scripts/build.js", "bindings/node/bench/size/hello.jsx"] +sources: ["features.json", "features.cmake", "kit/CMakeLists.txt", "gpu/CMakeLists.txt", "bindings/rust/blenderui-sys/build.rs", "bindings/rust/blenderui-sys/Cargo.toml", "bindings/rust/blenderui/Cargo.toml", "bindings/rust/blenderui/tests/suite/features.rs", "bindings/node/features.js", "bindings/node/cli.js", "bindings/node/scripts/build.js", "bindings/node/bench/size/hello.jsx"] --- A feature should cost binary size only if you use it. BUI's optional parts are one table, [`features.json`](https://github.com/ppmpreetham/BUI/blob/main/features.json), and three tools read it: diff --git a/website/src/content/docs/reference/coverage.mdx b/website/src/content/docs/reference/coverage.mdx index 8aa59ddf..b6f9211b 100644 --- a/website/src/content/docs/reference/coverage.mdx +++ b/website/src/content/docs/reference/coverage.mdx @@ -56,7 +56,7 @@ The plan is to measure against PySide6 itself, run the same programs on real Qt ## HTML and CSS (Rust and JavaScript) -Counted by `cargo test --test parity -- --nocapture` in `bindings/rust`. +Counted by `cargo test --test suite parity:: -- --nocapture` in `bindings/rust`. | Area | Coverage | | --- | --- | diff --git a/website/src/content/docs/rust/css-and-tailwind.mdx b/website/src/content/docs/rust/css-and-tailwind.mdx index 1b192d25..04992c98 100644 --- a/website/src/content/docs/rust/css-and-tailwind.mdx +++ b/website/src/content/docs/rust/css-and-tailwind.mdx @@ -4,7 +4,7 @@ description: Style Rust UIs with typed methods, compile-checked CSS, stylesheets section: Rust order: 40 languages: ["rust"] -sources: ["docs/rust.md", "bindings/rust/blenderui/src/style.rs", "bindings/rust/blenderui/src/styled.rs", "bindings/rust/blenderui/src/color.rs", "bindings/rust/blenderui/src/lib.rs", "bindings/rust/blenderui-macros/src/lib.rs", "bindings/rust/blenderui-macros/src/rsx.rs", "bindings/rust/blenderui-tailwind/src/lib.rs", "bindings/rust/blenderui/tests/modern_css.rs", "bindings/rust/blenderui/tests/rsx.rs", "bindings/rust/blenderui/tests/parity.rs", "CHANGELOG.md"] +sources: ["docs/rust.md", "bindings/rust/blenderui/src/style.rs", "bindings/rust/blenderui/src/styled.rs", "bindings/rust/blenderui/src/color.rs", "bindings/rust/blenderui/src/lib.rs", "bindings/rust/blenderui-macros/src/lib.rs", "bindings/rust/blenderui-macros/src/rsx.rs", "bindings/rust/blenderui-tailwind/src/lib.rs", "bindings/rust/blenderui/tests/suite/modern_css.rs", "bindings/rust/blenderui/tests/suite/rsx.rs", "bindings/rust/blenderui/tests/suite/parity.rs", "CHANGELOG.md"] --- Whatever way you like to style, it works here. Chain typed methods, write a CSS block, drop in a `