Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI
feat: components & css
Preetham Pemmasaniee2074933aa2
diff --git a/README.md b/README.mdindex 8500d02..3931829 100644--- a/README.md+++ b/README.md@@ -312,7 +312,7 @@ error: rsx!: `bg-sky-50O` is not a Tailwind utility; did you mean `bg-sky-500` o| Windows | A native Win32 window in C: DPI-aware, vsync-paced animation, clipboard, cursors, window-manager features || tkinter syntax | **Complete**: every public tkinter and ttk name (7,846 of 7,846) || Components | 45 Blender components, including the color ramp and curve editors |-| Rust | HTML (113/113 elements), Flexbox 12/12, Grid 23/23, CSS 2.1 88/90, math functions, `var()`, CSS Color 4/5, Selectors 4, `@layer`/`@media`/`@supports`/`@scope`/`@container`/`@font-face`/`@property`, background images, `object-fit`, Tailwind v4, `rsx!`, `#[component]` with optional props and `key`, hooks, headless testing |+| Rust | HTML (113/113 elements), Flexbox 12/12, Grid 23/23, CSS 2.1 90/90, math functions, `var()`, CSS Color 4/5, Selectors 4, `@layer`/`@media`/`@supports`/`@scope`/`@container`/`@font-face`/`@property`, `@keyframes` animations and transitions, background images, `object-fit`, Tailwind v4, `rsx!`, `#[component]` with optional props and `key`, hooks, headless testing || Rendering | Software raster (parallel, damage-tracked), GPU renderer (Direct3D 11), portable text engine || JavaScript / React | `@blender-ui/native`: a DOM-like API over napi-rs, with its own UI thread, only changes crossing the boundary, vsync-paced `requestAnimationFrame` and signals. `@blender-ui/react`: a React 19.3 renderer whose hooks (`useState`, `useMemo`, `useEffect` ...) hold signals that update nodes without re-renders. Both on Node.js and Bun, with headless testing. `bui build` makes standalone executables: about 5 MB with the embedded QuickJS runtime, or Bun's with `--bun` ([guide](docs/javascript.md)) || Packaging | [`blenderui` on PyPI](https://pypi.org/project/blenderui/), with a CI workflow for wheels on all platforms; [`@blender-ui/react`](https://www.npmjs.com/package/@blender-ui/react) and [`@blender-ui/native`](https://www.npmjs.com/package/@blender-ui/native) on npm |@@ -322,7 +322,7 @@ error: rsx!: `bg-sky-50O` is not a Tailwind utility; did you mean `bg-sky-500` o| Area | What's missing || ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ || Qt syntax (~25%) | Model/view classes, docks, toolbars, splitters, Qt stylesheets ([details](docs/qt.md#coverage)) |-| CSS (223 of 745 W3C properties render, 161 more parse) | Rendering effects: `rotate`/`skew` transforms, `filter`/`backdrop-filter`, blend modes, `clip-path`, masks, `border-image`. Also animations and transitions. Most of the remaining W3C list is drafts, speech, print and SVG ([breakdown](docs/rust.md#coverage)) |+| CSS (261 of 745 W3C properties render, 129 more parse) | 3D transforms, OpenType font features, multi-column layout. Most of the remaining W3C list is drafts, speech, print and SVG ([breakdown](docs/rust.md#coverage)) || Text | No text wrapping around floats; no right-to-left shaping || Rust components | No async resources (`use_resource`); no generic components || JavaScript / React on Linux / macOS | Prebuilt for Windows x64 only (elsewhere: build from source, headless); events reach JavaScript after BUI handled them (no native `preventDefault`), and `event.target` is the deepest _listening_ element |diff --git a/bindings/node/index.js b/bindings/node/index.jsindex 52021e8..2cbc826 100644--- a/bindings/node/index.js+++ b/bindings/node/index.js@@ -356,6 +356,15 @@ class Window {}createElement (tag) {+ // Blender's widgets: capitalized tags are always Blender widgets; their+ // lowercase HTML counterparts look like a browser's (Blender's inside `styled`)+ const blender = BLENDER_COMPONENTS[tag]+ if (blender) {+ const el = this.createElement(blender[0])+ if (blender[1]) el.setAttribute('type', blender[1])+ el.setAttribute('bui-blender', '')+ return el+ }const id = this._next++const el = new Element(this, id, tag)this._nodes.set(id, el)@@ -550,4 +559,19 @@ class App {}}-module.exports = { App, Window, Element, TextNode, Node, BuiEvent, styleText, BUTTONS, native, ...signals }+/** Capitalized Blender widgets for `createElement`: [HTML tag, input type]. */+const BLENDER_COMPONENTS = {+ Button: ['button'],+ Checkbox: ['input', 'checkbox'],+ Radio: ['input', 'radio'],+ NumberField: ['input', 'number'],+ NumberSlider: ['input', 'range'],+ TextField: ['input', 'text'],+ TextArea: ['textarea'],+ ColorSwatch: ['input', 'color'],+ Dropdown: ['select'],+ ProgressBar: ['progress'],+}++module.exports = {+ BLENDER_COMPONENTS, App, Window, Element, TextNode, Node, BuiEvent, styleText, BUTTONS, native, ...signals }diff --git a/bindings/react/index.d.ts b/bindings/react/index.d.tsindex ae6eaff..5096eab 100644--- a/bindings/react/index.d.ts+++ b/bindings/react/index.d.ts@@ -93,3 +93,18 @@ declare module 'react' {buiSignal: ReadSignal<unknown>}}++/** Blender's widgets as components: always drawn and handled like Blender.+ * Their lowercase HTML counterparts look like a browser's form controls+ * (and like Blender inside an element with the `styled` attribute). */+type BlenderProps = Record<string, unknown> & { children?: ReactNode }+export function Button (props: BlenderProps): ReactNode+export function Checkbox (props: BlenderProps): ReactNode+export function Radio (props: BlenderProps): ReactNode+export function NumberField (props: BlenderProps): ReactNode+export function NumberSlider (props: BlenderProps): ReactNode+export function TextField (props: BlenderProps): ReactNode+export function TextArea (props: BlenderProps): ReactNode+export function ColorSwatch (props: BlenderProps): ReactNode+export function Dropdown (props: BlenderProps): ReactNode+export function ProgressBar (props: BlenderProps): ReactNodediff --git a/bindings/react/index.js b/bindings/react/index.jsindex 0ddee67..216ae16 100644--- a/bindings/react/index.js+++ b/bindings/react/index.js@@ -339,7 +339,18 @@ function act (fn) {const reactHooks = {}for (const k of Object.keys(React)) if (/^use([A-Z]|$)/.test(k)) reactHooks[k] = React[k]+// Blender's widgets as components: `<NumberSlider min={0} max={10} />`,+// `<Button onClick={..}>Apply</Button>`. Always Blender widgets; their+// lowercase HTML counterparts look like a browser's (Blender's inside `styled`).+const blenderComponents = {}+for (const name of Object.keys(native.BLENDER_COMPONENTS)) {+ const C = (props) => React.createElement(name, props)+ Object.defineProperty(C, 'name', { value: name })+ blenderComponents[name] = C+}+module.exports = {+ ...blenderComponents,...reactHooks,...hooks,render,diff --git a/bindings/rust/blenderui-macros/src/rsx.rs b/bindings/rust/blenderui-macros/src/rsx.rsindex 0a2f28c..9f94d49 100644--- a/bindings/rust/blenderui-macros/src/rsx.rs+++ b/bindings/rust/blenderui-macros/src/rsx.rs@@ -204,10 +204,15 @@ impl P<'_> {return Ok(fragment(kids));}let tag = self.name()?;- let component = tag.chars().next().is_some_and(|c| c.is_ascii_uppercase())- || !tag.contains('-') && !tag.contains(':') && !HTML_TAGS.contains(&tag.as_str());+ // Blender's widget components (`<Button>`, `<NumberSlider>` ...) are+ // elements: their attributes work like on any HTML element+ let blender = BLENDER_COMPONENTS.contains(&tag.as_str());+ let component = !blender && (tag.chars().next().is_some_and(|c| c.is_ascii_uppercase())+ || !tag.contains('-') && !tag.contains(':') && !HTML_TAGS.contains(&tag.as_str()));let mut base = if component {TokenStream::new()+ } else if blender {+ ts(&format!("::blenderui::components::{tag}::__builder()"))} else if tag.contains('-') || tag.contains(':') {ts(&format!("::blenderui::element::Div::new({tag:?})"))} else {@@ -467,6 +472,12 @@ const HTML_TAGS: &[&str] = &["track", "area", "br", "wbr",];+/// Blender's widgets (`blenderui::components`): capitalized, used like elements.+const BLENDER_COMPONENTS: &[&str] = &[+ "Button", "Checkbox", "Radio", "NumberField", "NumberSlider", "TextField", "TextArea", "ColorSwatch",+ "Dropdown", "ProgressBar",+];+/// HTML boolean attributes: bare, they stay attributes even where a/// Tailwind utility has the same name (`hidden`).const BOOLEAN_ATTRS: &[&str] = &[diff --git a/bindings/rust/blenderui-sys/src/lib.rs b/bindings/rust/blenderui-sys/src/lib.rsindex d3fd5fc..ecdbad4 100644--- a/bindings/rust/blenderui-sys/src/lib.rs+++ b/bindings/rust/blenderui-sys/src/lib.rs@@ -186,6 +186,10 @@ unsafe extern "C" {pub fn BK_canvas_set_item(canvas: *mut BKNode, item: *const BKCanvasItem);pub fn BK_canvas_add_item(canvas: *mut BKNode, item: *const BKCanvasItem);pub fn BK_canvas_put_item(canvas: *mut BKNode, index: c_int, item: *const BKCanvasItem);+ /// Offscreen: `items` (device pixels) drawn into a `w` x `h` straight-alpha+ /// RGBA8 buffer whose top left is at (`x0`, `y0`). 1 on success.+ pub fn BK_canvas_rasterize(items: *const BKCanvasItem, n: c_int, x0: f32, y0: f32, w: c_int, h: c_int,+ rgba: *mut u8) -> c_int;pub fn BK_canvas_truncate(canvas: *mut BKNode, count: c_int);pub fn BK_canvas_delete(canvas: *mut BKNode, id: c_int);pub fn BK_canvas_count(canvas: *mut BKNode) -> c_int;diff --git a/bindings/rust/blenderui/examples/forms.rs b/bindings/rust/blenderui/examples/forms.rsnew file mode 100644index 0000000..ddbb5af--- /dev/null+++ b/bindings/rust/blenderui/examples/forms.rs@@ -0,0 +1,64 @@+//! Form controls three ways: plain HTML (browser look), inside `styled`+//! (Blender look), and the capitalized Blender components.+//! `cargo run --example forms` (`--screenshot out.png` renders it headless).++use blenderui::prelude::*;++struct Forms;++fn controls() -> Div {+ div().flex().flex_col().gap_2().p_3()+ .child(div().flex().gap_2().items_center()+ .child(button().child("Button"))+ .child(input().value("Text field"))+ .child(input().input_type("number").value("42")))+ .child(div().flex().gap_2().items_center()+ .child(label().child(input().input_type("checkbox").checked(true)).child(" Checkbox"))+ .child(label().child(input().input_type("radio").checked(true)).child(" Radio"))+ .child(input().input_type("range").min(0.0).max(10.0).value("6")))+ .child(div().flex().gap_2().items_center()+ .child(select().child(optgroup().attr("label", "Mesh").child(option().child("Cube")).child(option().child("Sphere"))))+ .child(progress().attr("value", "0.6"))+ .child(meter().attr("value", "0.3"))+ .child(input().input_type("color").value("#4772b3")))+ .child(textarea().child("A textarea"))+}++impl Render for Forms {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ body().m_0().flex().flex_col()+ .child(h3().child("Plain HTML (browser look)").p_3().m_0())+ .child(controls())+ .child(div().styled().child(h3().child("Inside styled (Blender look)").p_3().m_0()).child(controls()))+ .child(div().child(h3().child("Blender components").p_3().m_0())+ .child(div().flex().gap_2().p_3().items_center()+ .child(Button().child("Button"))+ .child(TextField().value("Text"))+ .child(NumberSlider().min(0.0).max(10.0).value("6"))+ .child(Checkbox().checked(true))))+ }+}++fn main() {+ let shot = std::env::args().skip_while(|a| a != "--screenshot").nth(1);+ let app = if shot.is_some() { Application::headless() } else { Application::new() };+ app.run(move |cx| {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds {+ origin: point(px(0.0), px(0.0)),+ size: size(px(620.0), px(620.0)),+ })),+ ..Default::default()+ };+ let win = cx.open_window(opts, |_, cx| cx.new(|_| Forms)).unwrap();+ if let Some(path) = &shot {+ let (w, h, px) = cx.draw(win.id);+ let rgba: Vec<u8> = px.iter().flat_map(|p| [(p >> 16) as u8, (p >> 8) as u8, *p as u8, 255]).collect();+ let file = std::fs::File::create(path).expect("create png");+ let mut enc = png::Encoder::new(std::io::BufWriter::new(file), w as u32, h as u32);+ enc.set_color(png::ColorType::Rgba);+ enc.set_depth(png::BitDepth::Eight);+ enc.write_header().expect("png").write_image_data(&rgba).expect("png");+ }+ });+}diff --git a/bindings/rust/blenderui/src/anim.rs b/bindings/rust/blenderui/src/anim.rsnew file mode 100644index 0000000..6452631--- /dev/null+++ b/bindings/rust/blenderui/src/anim.rs@@ -0,0 +1,1564 @@+//! CSS animations (`@keyframes`, `animation-*`) and transitions+//! (`transition-*`).+//!+//! The cascade (`layout.rs`) computes and shares styles as usual; for an+//! element with animations or transitions, [`Animations::apply`] then+//! builds a private copy of its style with the animated values on top (an+//! override layer that is never put in the shared style cache). State lives+//! here per element key: when each animation started, running transitions,+//! and the element's previous style (to notice changes worth a transition).+//!+//! Values interpolate per [`Field`] (a longhand slot of [`Computed`]):+//! lengths and percentages, colors (premultiplied sRGB), numbers, shadows,+//! `translate` / `scale`, `visibility`; anything else flips at 50%.+//!+//! Composition order: cascade, then transitions, then animations (later+//! ones in `animation-name` win); fields set by `!important` declarations+//! keep their cascaded value against animations.++use taffy::prelude::*;+use taffy::style::CompactLength;++use crate::color::Rgba;+use crate::css::{Decl, Prop, Tok};+use crate::geometry::{Length, Units};+use crate::effects::{Filter as FilterFn, TransformFn};+use crate::style::{BorderStyle, Computed, Ctx, FnvMap, Gradient, ImageStyle, LineHeight, Shadow};++// ==========================================================================+// Timing functions++/// An easing function.+#[derive(Clone, Debug, PartialEq)]+pub enum Timing {+ Linear,+ /// `cubic-bezier(x1, y1, x2, y2)` (also `ease`, `ease-in` ...).+ Bezier(f32, f32, f32, f32),+ /// `steps(n, position)`.+ Steps(u32, StepPos),+ /// `linear(...)`: (input, output) points, inputs ascending.+ Points(Box<[(f32, f32)]>),+}++/// The jump position of `steps()`.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum StepPos {+ Start,+ End,+ None,+ Both,+}++pub const EASE: Timing = Timing::Bezier(0.25, 0.1, 0.25, 1.0);++impl Timing {+ /// Parse one easing function token.+ pub fn parse(t: &Tok) -> Option<Timing> {+ Some(match t {+ Tok::Ident(s) => match s.as_ref() {+ "linear" => Timing::Linear,+ "ease" => EASE,+ "ease-in" => Timing::Bezier(0.42, 0.0, 1.0, 1.0),+ "ease-out" => Timing::Bezier(0.0, 0.0, 0.58, 1.0),+ "ease-in-out" => Timing::Bezier(0.42, 0.0, 0.58, 1.0),+ "step-start" => Timing::Steps(1, StepPos::Start),+ "step-end" => Timing::Steps(1, StepPos::End),+ _ => return None,+ },+ Tok::Func(fx) => {+ let num = |a: &Vec<Tok>| match a.as_slice() {+ [Tok::Num(v)] => Some(*v),+ _ => None,+ };+ match fx.name.as_ref() {+ "cubic-bezier" if fx.args.len() == 4 => {+ let v: Option<Vec<f32>> = fx.args.iter().map(num).collect();+ let v = v?;+ if !(0.0..=1.0).contains(&v[0]) || !(0.0..=1.0).contains(&v[2]) {+ return None;+ }+ Timing::Bezier(v[0], v[1], v[2], v[3])+ }+ "steps" => {+ let n = num(fx.args.first()?)?;+ let pos = match fx.args.get(1).map(|a| a.as_slice()) {+ None => StepPos::End,+ Some([Tok::Ident(p)]) => match p.as_ref() {+ "jump-start" | "start" => StepPos::Start,+ "jump-end" | "end" => StepPos::End,+ "jump-none" => StepPos::None,+ "jump-both" => StepPos::Both,+ _ => return None,+ },+ _ => return None,+ };+ let min = if pos == StepPos::None { 2.0 } else { 1.0 };+ if n < min || n.fract() != 0.0 {+ return None;+ }+ Timing::Steps(n as u32, pos)+ }+ "linear" => linear_points(&fx.args)?,+ _ => return None,+ }+ }+ _ => return None,+ })+ }++ /// The eased progress for input `x`. `before`: the animation is in its+ /// before phase (matters for `steps()` at a jump).+ pub fn apply(&self, x: f32, before: bool) -> f32 {+ match self {+ Timing::Linear => x,+ Timing::Bezier(x1, y1, x2, y2) => bezier(*x1, *y1, *x2, *y2, x),+ Timing::Steps(n, pos) => {+ let n = *n as f32;+ let mut step = (x * n).floor();+ if matches!(pos, StepPos::Start | StepPos::Both) {+ step += 1.0;+ }+ if before && (x * n).fract() == 0.0 {+ step -= 1.0;+ }+ let jumps = match pos {+ StepPos::Start | StepPos::End => n,+ StepPos::None => n - 1.0,+ StepPos::Both => n + 1.0,+ };+ if x >= 0.0 && step < 0.0 {+ step = 0.0;+ }+ if x <= 1.0 && step > jumps {+ step = jumps;+ }+ step / jumps+ }+ Timing::Points(p) => {+ if p.is_empty() {+ return x;+ }+ // the segment holding x (extrapolating past the ends)+ let k = p.iter().rposition(|&(i, _)| i <= x).unwrap_or(0).min(p.len().saturating_sub(2));+ if p.len() == 1 {+ return p[0].1;+ }+ let ((i0, o0), (i1, o1)) = (p[k], p[k + 1]);+ if i1 == i0 {+ o1+ } else {+ o0 + (o1 - o0) * (x - i0) / (i1 - i0)+ }+ }+ }+ }+}++/// `linear(0, 0.25 75%, 1)`: outputs with optional input percentages.+fn linear_points(args: &[Vec<Tok>]) -> Option<Timing> {+ let mut pts: Vec<(Option<f32>, f32)> = Vec::new();+ for a in args {+ let out = match a.first()? {+ Tok::Num(v) => *v,+ _ => return None,+ };+ let ins: Vec<f32> = a[1..].iter().map(|t| match t {+ Tok::Pct(p) => Some(p / 100.0),+ _ => None,+ }).collect::<Option<_>>()?;+ if ins.is_empty() {+ pts.push((None, out));+ }+ for i in ins.into_iter().take(2) {+ pts.push((Some(i), out));+ }+ }+ if pts.len() < 2 {+ return None;+ }+ let n = pts.len();+ if pts[0].0.is_none() {+ pts[0].0 = Some(0.0);+ }+ if pts[n - 1].0.is_none() {+ pts[n - 1].0 = Some(1.0);+ }+ // inputs never go backwards; runs without one are spread evenly+ let mut last = 0.0f32;+ for p in pts.iter_mut() {+ if let Some(i) = &mut p.0 {+ *i = i.max(last);+ last = *i;+ }+ }+ let mut k = 0;+ while k < n {+ if pts[k].0.is_some() {+ k += 1;+ continue;+ }+ let start = k - 1;+ let end = (k..n).find(|&j| pts[j].0.is_some()).unwrap_or(n - 1);+ let (a, b) = (pts[start].0.unwrap_or(0.0), pts[end].0.unwrap_or(1.0));+ for j in k..end {+ pts[j].0 = Some(a + (b - a) * (j - start) as f32 / (end - start) as f32);+ }+ k = end;+ }+ Some(Timing::Points(pts.into_iter().map(|(i, o)| (i.unwrap_or(0.0), o)).collect()))+}++/// Solve a CSS cubic Bézier for y at x (Newton, then bisection).+fn bezier(x1: f32, y1: f32, x2: f32, y2: f32, x: f32) -> f32 {+ let (x1, y1, x2, y2, x) = (x1 as f64, y1 as f64, x2 as f64, y2 as f64, x as f64);+ // outside 0..1 the curve extends along its end tangents+ if x <= 0.0 {+ let slope = if x1 > 0.0 { y1 / x1 } else if y1 == 0.0 && x2 > 0.0 { y2 / x2 } else { 0.0 };+ return (slope * x) as f32;+ }+ if x >= 1.0 {+ let slope = if x2 < 1.0 { (y2 - 1.0) / (x2 - 1.0) } else if y2 == 1.0 && x1 < 1.0 { (y1 - 1.0) / (x1 - 1.0) } else { 0.0 };+ return (1.0 + slope * (x - 1.0)) as f32;+ }+ let (cx, cy) = (3.0 * x1, 3.0 * y1);+ let (bx, by) = (3.0 * (x2 - x1) - cx, 3.0 * (y2 - y1) - cy);+ let (ax, ay) = (1.0 - cx - bx, 1.0 - cy - by);+ let sx = |t: f64| ((ax * t + bx) * t + cx) * t;+ let sy = |t: f64| ((ay * t + by) * t + cy) * t;+ let dx = |t: f64| (3.0 * ax * t + 2.0 * bx) * t + cx;+ let mut t = x;+ for _ in 0..8 {+ let e = sx(t) - x;+ if e.abs() < 1e-7 {+ return sy(t) as f32;+ }+ let d = dx(t);+ if d.abs() < 1e-6 {+ break;+ }+ t -= e / d;+ }+ let (mut lo, mut hi) = (0.0, 1.0);+ t = x;+ for _ in 0..60 {+ let v = sx(t);+ if (v - x).abs() < 1e-7 {+ break;+ }+ if v < x {+ lo = t;+ } else {+ hi = t;+ }+ t = (lo + hi) / 2.0;+ }+ sy(t) as f32+}++// ==========================================================================+// The animation-* / transition-* properties++#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum Direction {+ #[default]+ Normal,+ Reverse,+ Alternate,+ AlternateReverse,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum Fill {+ #[default]+ None,+ Forwards,+ Backwards,+ Both,+}++/// The `animation-*` and `transition-*` longhands of one element (lists:+/// value `i` of a shorter list is `list[i % len]`). Not inherited.+#[derive(Clone, Debug, PartialEq, Default)]+pub struct AnimSpec {+ pub names: Vec<Box<str>>,+ pub durations: Vec<f32>,+ pub timings: Vec<Timing>,+ pub delays: Vec<f32>,+ /// `f32::INFINITY` for `infinite`.+ pub iterations: Vec<f32>,+ pub directions: Vec<Direction>,+ pub fills: Vec<Fill>,+ /// true = paused.+ pub paused: Vec<bool>,+ /// `transition-property` (`all`, `none` or a property name).+ pub t_props: Vec<Box<str>>,+ pub t_durations: Vec<f32>,+ pub t_timings: Vec<Timing>,+ pub t_delays: Vec<f32>,+ /// `transition-behavior: allow-discrete`.+ pub t_discrete: Vec<bool>,+}++fn nth<T: Clone>(list: &[T], i: usize, default: T) -> T {+ if list.is_empty() { default } else { list[i % list.len()].clone() }+}++impl AnimSpec {+ fn has_animations(&self) -> bool {+ self.names.iter().any(|n| &**n != "none")+ }++ fn has_transitions(&self) -> bool {+ (0..self.t_props.len().max(1)).any(|i| {+ nth(&self.t_durations, i, 0.0).max(0.0) + nth(&self.t_delays, i, 0.0) > 0.0+ && &*nth(&self.t_props, i, "all".into()) != "none"+ })+ }++ /// Duration, delay, easing and allow-discrete of the transition for+ /// `field` (None: not transitioned).+ fn transition_for(&self, field: Field) -> Option<(f32, f32, Timing, bool)> {+ let n = self.t_props.len().max(1);+ // the last matching entry wins+ (0..n).rev().find(|&i| {+ let p = nth(&self.t_props, i, "all".into());+ match &*p {+ "all" => ALL_FIELDS.contains(&field),+ "none" => false,+ name => fields_of(Prop::lookup(name)).contains(&field),+ }+ }).map(|i| (nth(&self.t_durations, i, 0.0).max(0.0), nth(&self.t_delays, i, 0.0),+ nth(&self.t_timings, i, EASE), nth(&self.t_discrete, i, false)))+ }++ /// The fields that may transition.+ fn watched(&self) -> Vec<Field> {+ let mut out = Vec::new();+ for i in 0..self.t_props.len().max(1) {+ let p = nth(&self.t_props, i, "all".into());+ match &*p {+ "all" => out.extend_from_slice(ALL_FIELDS),+ "none" => {}+ name => out.extend(fields_of(Prop::lookup(name)).iter().copied()),+ }+ }+ out.sort_unstable_by_key(|f| field_rank(*f));+ out.dedup();+ out+ }+}++fn spec<'c>(c: &'c mut Ctx) -> &'c mut AnimSpec {+ c.c.anim.get_or_insert_with(Default::default)+}++fn items(v: &[Tok]) -> impl Iterator<Item = &[Tok]> {+ v.split(|t| matches!(t, Tok::Comma))+}++fn time(t: &Tok) -> Option<f32> {+ match t {+ Tok::Dim(v, u) if u == "s" => Some(*v),+ Tok::Dim(v, u) if u == "ms" => Some(*v / 1000.0),+ Tok::Num(v) if *v == 0.0 => Some(0.0),+ _ => None,+ }+}++fn list<T>(v: &[Tok], one: impl Fn(&[Tok]) -> Option<T>) -> Option<Vec<T>> {+ items(v).map(one).collect()+}++fn single<T>(f: impl Fn(&Tok) -> Option<T>) -> impl Fn(&[Tok]) -> Option<T> {+ move |item| match item {+ [t] => f(t),+ _ => None,+ }+}++fn direction(s: &str) -> Option<Direction> {+ Some(match s {+ "normal" => Direction::Normal,+ "reverse" => Direction::Reverse,+ "alternate" => Direction::Alternate,+ "alternate-reverse" => Direction::AlternateReverse,+ _ => return None,+ })+}++fn fill(s: &str) -> Option<Fill> {+ Some(match s {+ "none" => Fill::None,+ "forwards" => Fill::Forwards,+ "backwards" => Fill::Backwards,+ "both" => Fill::Both,+ _ => return None,+ })+}++fn iteration(t: &Tok) -> Option<f32> {+ match t {+ Tok::Num(v) if *v >= 0.0 => Some(*v),+ Tok::Ident(s) if s == "infinite" => Some(f32::INFINITY),+ _ => None,+ }+}++fn name(t: &Tok) -> Option<Box<str>> {+ match t {+ Tok::Ident(s) => Some(s.as_ref().into()),+ Tok::Str(s) => Some(s.as_ref().into()),+ _ => None,+ }+}++pub(crate) fn h_animation(c: &mut Ctx, v: &[Tok]) -> bool {+ let s = spec(c);+ // the shorthand resets every animation longhand, keeps the transition ones+ let mut out = AnimSpec {+ t_props: std::mem::take(&mut s.t_props),+ t_durations: std::mem::take(&mut s.t_durations),+ t_timings: std::mem::take(&mut s.t_timings),+ t_delays: std::mem::take(&mut s.t_delays),+ t_discrete: std::mem::take(&mut s.t_discrete),+ ..Default::default()+ };+ for item in items(v) {+ let (mut dur, mut delay, mut timing, mut iter, mut dir, mut fl, mut paused, mut nm) =+ (None, None, None, None, None, None, None, None);+ for t in item {+ if let Some(x) = time(t) {+ if dur.is_none() {+ dur = Some(x);+ } else if delay.is_none() {+ delay = Some(x);+ } else {+ return false;+ }+ } else if let Some(x) = Timing::parse(t).filter(|_| timing.is_none()) {+ timing = Some(x);+ } else if let Some(x) = iteration(t).filter(|_| iter.is_none()) {+ iter = Some(x);+ } else if let Some(x) = t.ident().and_then(direction).filter(|_| dir.is_none()) {+ dir = Some(x);+ } else if let Some(x) = t.ident().filter(|s| *s != "none").and_then(fill).filter(|_| fl.is_none()) {+ fl = Some(x);+ } else if let Some(x) = t.ident().and_then(|s| match s {+ "running" => Some(false),+ "paused" => Some(true),+ _ => None,+ }).filter(|_| paused.is_none()) {+ paused = Some(x);+ } else if let Some(x) = name(t).filter(|_| nm.is_none()) {+ nm = Some(x);+ } else {+ return false;+ }+ }+ out.names.push(nm.unwrap_or_else(|| "none".into()));+ out.durations.push(dur.unwrap_or(0.0).max(0.0));+ out.delays.push(delay.unwrap_or(0.0));+ out.timings.push(timing.unwrap_or(EASE));+ out.iterations.push(iter.unwrap_or(1.0));+ out.directions.push(dir.unwrap_or_default());+ out.fills.push(fl.unwrap_or_default());+ out.paused.push(paused.unwrap_or(false));+ }+ *spec(c) = out;+ true+}++pub(crate) fn h_transition(c: &mut Ctx, v: &[Tok]) -> bool {+ let (mut props, mut durs, mut timings, mut delays, mut discrete) = (vec![], vec![], vec![], vec![], vec![]);+ for item in items(v) {+ let (mut prop, mut dur, mut delay, mut timing, mut disc) = (None, None, None, None, None);+ for t in item {+ if let Some(x) = time(t) {+ if dur.is_none() {+ dur = Some(x);+ } else if delay.is_none() {+ delay = Some(x);+ } else {+ return false;+ }+ } else if let Some(x) = Timing::parse(t).filter(|_| timing.is_none()) {+ timing = Some(x);+ } else if let Some(x) = t.ident().and_then(|s| match s {+ "allow-discrete" => Some(true),+ "normal" => Some(false),+ _ => None,+ }).filter(|_| disc.is_none()) {+ disc = Some(x);+ } else if let Some(x) = t.ident().filter(|_| prop.is_none()) {+ prop = Some(Box::<str>::from(x));+ } else {+ return false;+ }+ }+ props.push(prop.unwrap_or_else(|| "all".into()));+ durs.push(dur.unwrap_or(0.0).max(0.0));+ delays.push(delay.unwrap_or(0.0));+ timings.push(timing.unwrap_or(EASE));+ discrete.push(disc.unwrap_or(false));+ }+ let s = spec(c);+ (s.t_props, s.t_durations, s.t_timings, s.t_delays, s.t_discrete) = (props, durs, timings, delays, discrete);+ true+}++macro_rules! longhand {+ ($fn:ident, $field:ident, $parse:expr) => {+ pub(crate) fn $fn(c: &mut Ctx, v: &[Tok]) -> bool {+ match list(v, $parse) {+ Some(l) => {+ spec(c).$field = l;+ true+ }+ None => false,+ }+ }+ };+}++longhand!(h_animation_name, names, single(name));+longhand!(h_animation_duration, durations, single(|t| time(t).filter(|v| *v >= 0.0)));+longhand!(h_animation_timing, timings, single(Timing::parse));+longhand!(h_animation_delay, delays, single(time));+longhand!(h_animation_iterations, iterations, single(iteration));+longhand!(h_animation_direction, directions, single(|t: &Tok| t.ident().and_then(direction)));+longhand!(h_animation_fill, fills, single(|t: &Tok| t.ident().and_then(fill)));+longhand!(h_animation_play_state, paused, single(|t: &Tok| match t.ident() {+ Some("running") => Some(false),+ Some("paused") => Some(true),+ _ => None,+}));+longhand!(h_transition_property, t_props, single(|t: &Tok| t.ident().map(Box::<str>::from)));+longhand!(h_transition_duration, t_durations, single(|t| time(t).filter(|v| *v >= 0.0)));+longhand!(h_transition_timing, t_timings, single(Timing::parse));+longhand!(h_transition_delay, t_delays, single(time));+longhand!(h_transition_behavior, t_discrete, single(|t: &Tok| match t.ident() {+ Some("allow-discrete") => Some(true),+ Some("normal") => Some(false),+ _ => None,+}));++// ==========================================================================+// Fields: what interpolates, and how++/// One animatable slot of [`Computed`] (a longhand, or a few that only+/// make sense together).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub(crate) enum Field {+ Width,+ Height,+ MinWidth,+ MinHeight,+ MaxWidth,+ MaxHeight,+ FlexBasis,+ FlexGrow,+ FlexShrink,+ Order,+ Margin(u8),+ Padding(u8),+ Inset(u8),+ RowGap,+ ColumnGap,+ BorderWidth(u8),+ BorderColor(u8),+ /// `border-*-style` (with whether the side is drawn): discrete.+ BorderStyle(u8),+ Radius(u8),+ FontSize,+ FontWeight,+ LetterSpacing,+ WordSpacing,+ LineHeight,+ TextIndent,+ OutlineWidth,+ OutlineColor,+ OutlineOffset,+ OutlineStyle,+ Background,+ /// Gradient and image placement: discrete.+ BackgroundImage,+ Color,+ DecorationColor,+ Accent,+ Opacity,+ Visibility,+ ZIndex,+ /// `transform` / `translate`: translations stay a layout offset;+ /// `Transform` is the rest of the function list (rotate, skew, scale,+ /// matrix), interpolated function by function.+ Translate,+ Transform,+ /// The individual `rotate` and `scale` properties.+ Rotate,+ Scale,+ /// `filter` / `backdrop-filter` lists, function by function.+ Filter,+ Backdrop,+ BoxShadow,+ TextShadow,+ /// Any other property: applied as declared, flipping at 50%.+ Other(Prop),+}++/// What `transition-property: all` covers.+const ALL_FIELDS: &[Field] = &{+ use Field::*;+ [Width, Height, MinWidth, MinHeight, MaxWidth, MaxHeight, FlexBasis, FlexGrow, FlexShrink, Order,+ Margin(0), Margin(1), Margin(2), Margin(3), Padding(0), Padding(1), Padding(2), Padding(3),+ Inset(0), Inset(1), Inset(2), Inset(3), RowGap, ColumnGap,+ BorderWidth(0), BorderWidth(1), BorderWidth(2), BorderWidth(3),+ BorderColor(0), BorderColor(1), BorderColor(2), BorderColor(3),+ BorderStyle(0), BorderStyle(1), BorderStyle(2), BorderStyle(3),+ Radius(0), Radius(1), Radius(2), Radius(3),+ FontSize, FontWeight, LetterSpacing, WordSpacing, LineHeight, TextIndent,+ OutlineWidth, OutlineColor, OutlineOffset, OutlineStyle, Background, BackgroundImage, Color,+ DecorationColor, Accent, Opacity, Visibility, ZIndex, Translate, Transform, Rotate, Scale, Filter, Backdrop,+ BoxShadow, TextShadow]+};++fn field_rank(f: Field) -> usize {+ match f {+ Field::Other(p) => 1000 + p.0 as usize,+ f => ALL_FIELDS.iter().position(|x| *x == f).unwrap_or(999),+ }+}++/// The fields a property sets (an `Other` for properties without one).+pub(crate) fn fields_of(p: Prop) -> &'static [Field] {+ use Field::*;+ macro_rules! sides {+ ($f:ident) => {+ &[$f(0), $f(1), $f(2), $f(3)]+ };+ }+ match p.name() {+ "width" => &[Width],+ "height" => &[Height],+ "min-width" => &[MinWidth],+ "min-height" => &[MinHeight],+ "max-width" => &[MaxWidth],+ "max-height" => &[MaxHeight],+ "flex-basis" => &[FlexBasis],+ "flex-grow" => &[FlexGrow],+ "flex-shrink" => &[FlexShrink],+ "flex" => &[FlexGrow, FlexShrink, FlexBasis],+ "order" => &[Order],+ "margin" => sides!(Margin),+ "margin-top" => &[Margin(0)],+ "margin-right" => &[Margin(1)],+ "margin-bottom" => &[Margin(2)],+ "margin-left" => &[Margin(3)],+ "padding" => sides!(Padding),+ "padding-top" => &[Padding(0)],+ "padding-right" => &[Padding(1)],+ "padding-bottom" => &[Padding(2)],+ "padding-left" => &[Padding(3)],+ "inset" => sides!(Inset),+ "top" => &[Inset(0)],+ "right" => &[Inset(1)],+ "bottom" => &[Inset(2)],+ "left" => &[Inset(3)],+ "gap" | "grid-gap" => &[RowGap, ColumnGap],+ "row-gap" | "grid-row-gap" => &[RowGap],+ "column-gap" | "grid-column-gap" => &[ColumnGap],+ "border-width" => sides!(BorderWidth),+ "border-top-width" => &[BorderWidth(0)],+ "border-right-width" => &[BorderWidth(1)],+ "border-bottom-width" => &[BorderWidth(2)],+ "border-left-width" => &[BorderWidth(3)],+ "border-color" => sides!(BorderColor),+ "border-top-color" => &[BorderColor(0)],+ "border-right-color" => &[BorderColor(1)],+ "border-bottom-color" => &[BorderColor(2)],+ "border-left-color" => &[BorderColor(3)],+ "border-style" => sides!(BorderStyle),+ "border-top-style" => &[BorderStyle(0)],+ "border-right-style" => &[BorderStyle(1)],+ "border-bottom-style" => &[BorderStyle(2)],+ "border-left-style" => &[BorderStyle(3)],+ "border" => &[BorderWidth(0), BorderWidth(1), BorderWidth(2), BorderWidth(3),+ BorderColor(0), BorderColor(1), BorderColor(2), BorderColor(3),+ BorderStyle(0), BorderStyle(1), BorderStyle(2), BorderStyle(3)],+ "border-top" => &[BorderWidth(0), BorderColor(0), BorderStyle(0)],+ "border-right" => &[BorderWidth(1), BorderColor(1), BorderStyle(1)],+ "border-bottom" => &[BorderWidth(2), BorderColor(2), BorderStyle(2)],+ "border-left" => &[BorderWidth(3), BorderColor(3), BorderStyle(3)],+ "border-radius" => sides!(Radius),+ "border-top-left-radius" => &[Radius(0)],+ "border-top-right-radius" => &[Radius(1)],+ "border-bottom-right-radius" => &[Radius(2)],+ "border-bottom-left-radius" => &[Radius(3)],+ "font-size" => &[FontSize],+ "font-weight" => &[FontWeight],+ "letter-spacing" => &[LetterSpacing],+ "word-spacing" => &[WordSpacing],+ "line-height" => &[LineHeight],+ "text-indent" => &[TextIndent],+ "outline" => &[OutlineWidth, OutlineColor, OutlineStyle],+ "outline-width" => &[OutlineWidth],+ "outline-color" => &[OutlineColor],+ "outline-offset" => &[OutlineOffset],+ "outline-style" => &[OutlineStyle],+ "background-color" => &[Background],+ "background" => &[Background, BackgroundImage],+ "color" => &[Color],+ "text-decoration-color" => &[DecorationColor],+ "accent-color" => &[Accent],+ "opacity" => &[Opacity],+ "visibility" => &[Visibility],+ "z-index" => &[ZIndex],+ "transform" => &[Translate, Transform],+ "translate" => &[Translate],+ "rotate" => &[Rotate],+ "scale" => &[Scale],+ "filter" => &[Filter],+ "backdrop-filter" | "-webkit-backdrop-filter" => &[Backdrop],+ "box-shadow" => &[BoxShadow],+ "text-shadow" => &[TextShadow],+ _ => &[],+ }+}++/// A field's value.+#[derive(Clone, Debug, PartialEq)]+enum Val {+ Dim(Dimension),+ Lpa(LengthPercentageAuto),+ Lp(LengthPercentage),+ Num(f32),+ Int(i32),+ Color(Rgba),+ OptColor(Option<Rgba>),+ Len(Length),+ Len2(Length, Length),+ Shadows(Vec<Shadow>),+ TextShadow(Option<Shadow>),+ Visible(bool),+ Z(Option<i32>),+ Lh(LineHeight),+ Border(BorderStyle, bool),+ Outline(BorderStyle),+ Bg(Option<Gradient>, Option<Box<ImageStyle>>),+ Pair(f32, f32),+ Fns(Vec<TransformFn>),+ Filters(Vec<FilterFn>),+}++fn side<T: Copy>(r: &taffy::geometry::Rect<T>, s: u8) -> T {+ match s {+ 0 => r.top,+ 1 => r.right,+ 2 => r.bottom,+ _ => r.left,+ }+}++fn side_mut<T>(r: &mut taffy::geometry::Rect<T>, s: u8) -> &mut T {+ match s {+ 0 => &mut r.top,+ 1 => &mut r.right,+ 2 => &mut r.bottom,+ _ => &mut r.left,+ }+}++fn get(f: Field, c: &Computed) -> Option<Val> {+ use Field::*;+ let l = &c.layout;+ Some(match f {+ Width => Val::Dim(l.size.width),+ Height => Val::Dim(l.size.height),+ MinWidth => Val::Lpa(l.min_size.width),+ MinHeight => Val::Lpa(l.min_size.height),+ MaxWidth => Val::Lpa(l.max_size.width),+ MaxHeight => Val::Lpa(l.max_size.height),+ FlexBasis => Val::Dim(l.flex_basis),+ FlexGrow => Val::Num(l.flex_grow),+ FlexShrink => Val::Num(l.flex_shrink),+ Order => Val::Int(c.order),+ Margin(s) => Val::Lpa(side(&l.margin, s)),+ Padding(s) => Val::Lp(side(&l.padding, s)),+ Inset(s) => Val::Lpa(side(&l.inset, s)),+ RowGap => Val::Lp(l.gap.height),+ ColumnGap => Val::Lp(l.gap.width),+ BorderWidth(s) => Val::Lp(side(&l.border, s)),+ BorderColor(s) => Val::Color(c.border_color[s as usize]),+ BorderStyle(s) => Val::Border(c.border_style[s as usize], c.border_drawn[s as usize]),+ Radius(s) => Val::Len(c.radius[s as usize]),+ FontSize => Val::Num(c.font_size),+ FontWeight => Val::Int(c.weight as i32),+ LetterSpacing => Val::Num(c.letter_spacing),+ WordSpacing => Val::Num(c.word_spacing),+ LineHeight => Val::Lh(c.line_height),+ TextIndent => Val::Len(c.text_indent),+ OutlineWidth => Val::Num(c.outline.0),+ OutlineColor => Val::Color(c.outline.1),+ OutlineOffset => Val::Num(c.outline.2),+ OutlineStyle => Val::Outline(c.outline_style),+ Background => Val::Color(c.background),+ BackgroundImage => Val::Bg(c.gradient.clone(), c.images.clone()),+ Color => Val::Color(c.color),+ DecorationColor => Val::OptColor(c.decoration_color),+ Accent => Val::OptColor(c.accent),+ Opacity => Val::Num(c.opacity),+ Visibility => Val::Visible(c.visible),+ ZIndex => Val::Z(c.z_index),+ Translate => Val::Len2(c.translate.0, c.translate.1),+ Transform => Val::Fns(c.effects.as_ref().map(|e| e.transform.clone()).unwrap_or_default()),+ Rotate => Val::Num(c.effects.as_ref().map_or(0.0, |e| e.rotate)),+ Scale => {+ let (x, y) = c.effects.as_ref().and_then(|e| e.scale2).unwrap_or((1.0, 1.0));+ Val::Pair(x, y)+ }+ Filter => Val::Filters(c.effects.as_ref().map(|e| e.filter.clone()).unwrap_or_default()),+ Backdrop => Val::Filters(c.effects.as_ref().map(|e| e.backdrop.clone()).unwrap_or_default()),+ BoxShadow => Val::Shadows(c.shadows.clone()),+ TextShadow => Val::TextShadow(c.text_shadow),+ Other(_) => return None,+ })+}++fn set(f: Field, c: &mut Computed, v: Val) {+ use Field::*;+ let l = &mut c.layout;+ match (f, v) {+ (Width, Val::Dim(d)) => l.size.width = d,+ (Height, Val::Dim(d)) => l.size.height = d,+ (MinWidth, Val::Lpa(d)) => l.min_size.width = d,+ (MinHeight, Val::Lpa(d)) => l.min_size.height = d,+ (MaxWidth, Val::Lpa(d)) => l.max_size.width = d,+ (MaxHeight, Val::Lpa(d)) => l.max_size.height = d,+ (FlexBasis, Val::Dim(d)) => l.flex_basis = d,+ (FlexGrow, Val::Num(n)) => l.flex_grow = n.max(0.0),+ (FlexShrink, Val::Num(n)) => l.flex_shrink = n.max(0.0),+ (Order, Val::Int(n)) => c.order = n,+ (Margin(s), Val::Lpa(d)) => *side_mut(&mut l.margin, s) = d,+ (Padding(s), Val::Lp(d)) => *side_mut(&mut l.padding, s) = d,+ (Inset(s), Val::Lpa(d)) => *side_mut(&mut l.inset, s) = d,+ (RowGap, Val::Lp(d)) => l.gap.height = d,+ (ColumnGap, Val::Lp(d)) => l.gap.width = d,+ (BorderWidth(s), Val::Lp(d)) => *side_mut(&mut l.border, s) = d,+ (BorderColor(s), Val::Color(x)) => c.border_color[s as usize] = x,+ (BorderStyle(s), Val::Border(st, drawn)) => {+ c.border_style[s as usize] = st;+ c.border_drawn[s as usize] = drawn;+ }+ (Radius(s), Val::Len(x)) => c.radius[s as usize] = x,+ (FontSize, Val::Num(n)) => c.font_size = n.max(0.0),+ (FontWeight, Val::Int(n)) => c.weight = n.clamp(1, 1000) as u16,+ (LetterSpacing, Val::Num(n)) => c.letter_spacing = n,+ (WordSpacing, Val::Num(n)) => c.word_spacing = n,+ (LineHeight, Val::Lh(x)) => c.line_height = x,+ (TextIndent, Val::Len(x)) => c.text_indent = x,+ (OutlineWidth, Val::Num(n)) => c.outline.0 = n.max(0.0),+ (OutlineColor, Val::Color(x)) => c.outline.1 = x,+ (OutlineOffset, Val::Num(n)) => c.outline.2 = n,+ (OutlineStyle, Val::Outline(x)) => c.outline_style = x,+ (Background, Val::Color(x)) => c.background = x,+ (BackgroundImage, Val::Bg(g, i)) => {+ c.gradient = g;+ c.images = i;+ }+ (Color, Val::Color(x)) => c.color = x,+ (DecorationColor, Val::OptColor(x)) => c.decoration_color = x,+ (Accent, Val::OptColor(x)) => c.accent = x,+ (Opacity, Val::Num(n)) => c.opacity = n.clamp(0.0, 1.0),+ (Visibility, Val::Visible(x)) => c.visible = x,+ (ZIndex, Val::Z(x)) => c.z_index = x,+ (Translate, Val::Len2(x, y)) => c.translate = (x, y),+ (Transform, Val::Fns(x)) => {+ if !x.is_empty() || c.effects.is_some() {+ c.effects_mut().transform = x;+ }+ }+ (Rotate, Val::Num(n)) => {+ if n != 0.0 || c.effects.is_some() {+ c.effects_mut().rotate = n;+ }+ }+ (Scale, Val::Pair(x, y)) => {+ if (x, y) != (1.0, 1.0) || c.effects.is_some() {+ c.effects_mut().scale2 = ((x, y) != (1.0, 1.0)).then_some((x, y));+ }+ }+ (Filter, Val::Filters(x)) => {+ if !x.is_empty() || c.effects.is_some() {+ c.effects_mut().filter = x;+ }+ }+ (Backdrop, Val::Filters(x)) => {+ if !x.is_empty() || c.effects.is_some() {+ c.effects_mut().backdrop = x;+ }+ }+ (BoxShadow, Val::Shadows(x)) => c.shadows = x,+ (TextShadow, Val::TextShadow(x)) => c.text_shadow = x,+ _ => {}+ }+}++fn mix(a: f32, b: f32, t: f32) -> f32 {+ a + (b - a) * t+}++/// Colors mix in premultiplied sRGB, as browsers do.+fn mix_color(a: Rgba, b: Rgba, t: f32) -> Rgba {+ let alpha = mix(a.a, b.a, t).clamp(0.0, 1.0);+ if alpha <= 0.0 {+ return Rgba::TRANSPARENT;+ }+ let ch = |x: f32, y: f32| (mix(x * a.a, y * b.a, t) / alpha).clamp(0.0, 1.0);+ Rgba { r: ch(a.r, b.r), g: ch(a.g, b.g), b: ch(a.b, b.b), a: alpha }+}++/// Two compact lengths (`Dimension`, `LengthPercentage(Auto)`): both pixels+/// or both percentages mix; anything else (auto, keywords, calc) doesn't.+fn mix_compact(a: CompactLength, b: CompactLength, t: f32) -> Option<(bool, f32)> {+ let (ta, tb) = (a.tag(), b.tag());+ if ta == CompactLength::LENGTH_TAG && tb == CompactLength::LENGTH_TAG {+ Some((false, mix(a.value(), b.value(), t)))+ } else if ta == CompactLength::PERCENT_TAG && tb == CompactLength::PERCENT_TAG {+ Some((true, mix(a.value(), b.value(), t)))+ } else {+ None+ }+}++fn mix_length(a: Length, b: Length, t: f32, u: &Units) -> Option<Length> {+ match (a, b) {+ (Length::Percent(x), Length::Percent(y)) => Some(Length::Percent(mix(x, y, t))),+ _ => Some(Length::Px(mix(a.to_px(u)?, b.to_px(u)?, t))),+ }+}++fn mix_shadow(a: &Shadow, b: &Shadow, t: f32) -> Option<Shadow> {+ (a.inset == b.inset).then(|| Shadow {+ x: mix(a.x, b.x, t),+ y: mix(a.y, b.y, t),+ blur: mix(a.blur, b.blur, t).max(0.0),+ spread: mix(a.spread, b.spread, t),+ color: mix_color(a.color, b.color, t),+ inset: a.inset,+ })+}++/// The identity function of the same kind (CSS: `none` interpolates+/// against a list of identities).+fn identity_fn(f: &TransformFn) -> TransformFn {+ match f {+ TransformFn::Translate(..) => TransformFn::Translate(Length::Px(0.0), Length::Px(0.0)),+ TransformFn::Scale(..) => TransformFn::Scale(1.0, 1.0),+ TransformFn::Rotate(_) => TransformFn::Rotate(0.0),+ TransformFn::Skew(..) => TransformFn::Skew(0.0, 0.0),+ TransformFn::Matrix(_) => TransformFn::Matrix(crate::effects::IDENTITY),+ }+}++/// Transform lists, function by function (the shorter padded with+/// identities); None when the kinds differ (the value then flips at 50%).+fn mix_transforms(a: &[TransformFn], b: &[TransformFn], t: f32, u: &Units) -> Option<Vec<TransformFn>> {+ let n = a.len().max(b.len());+ let mut out = Vec::with_capacity(n);+ for i in 0..n {+ let (x, y) = match (a.get(i), b.get(i)) {+ (Some(x), Some(y)) => (x.clone(), y.clone()),+ (Some(x), None) => (x.clone(), identity_fn(x)),+ (None, Some(y)) => (identity_fn(y), y.clone()),+ (None, None) => break,+ };+ out.push(match (x, y) {+ (TransformFn::Translate(x0, y0), TransformFn::Translate(x1, y1)) => {+ TransformFn::Translate(mix_length(x0, x1, t, u)?, mix_length(y0, y1, t, u)?)+ }+ (TransformFn::Scale(x0, y0), TransformFn::Scale(x1, y1)) => TransformFn::Scale(mix(x0, x1, t), mix(y0, y1, t)),+ (TransformFn::Rotate(a0), TransformFn::Rotate(a1)) => TransformFn::Rotate(mix(a0, a1, t)),+ (TransformFn::Skew(x0, y0), TransformFn::Skew(x1, y1)) => TransformFn::Skew(mix(x0, x1, t), mix(y0, y1, t)),+ (TransformFn::Matrix(m0), TransformFn::Matrix(m1)) => {+ TransformFn::Matrix(std::array::from_fn(|k| mix(m0[k], m1[k], t)))+ }+ _ => return None,+ });+ }+ Some(out)+}++fn identity_filter(f: &FilterFn) -> FilterFn {+ match f {+ FilterFn::Blur(_) => FilterFn::Blur(0.0),+ FilterFn::Brightness(_) => FilterFn::Brightness(1.0),+ FilterFn::Contrast(_) => FilterFn::Contrast(1.0),+ FilterFn::Grayscale(_) => FilterFn::Grayscale(0.0),+ FilterFn::HueRotate(_) => FilterFn::HueRotate(0.0),+ FilterFn::Invert(_) => FilterFn::Invert(0.0),+ FilterFn::Opacity(_) => FilterFn::Opacity(1.0),+ FilterFn::Saturate(_) => FilterFn::Saturate(1.0),+ FilterFn::Sepia(_) => FilterFn::Sepia(0.0),+ FilterFn::DropShadow { color, .. } => FilterFn::DropShadow { x: 0.0, y: 0.0, blur: 0.0, color: color.alpha(0.0) },+ }+}++/// Filter lists, function by function (Filter Effects 1, "Interpolation of+/// filters"); None when the kinds differ.+fn mix_filters(a: &[FilterFn], b: &[FilterFn], t: f32) -> Option<Vec<FilterFn>> {+ use FilterFn as F;+ let n = a.len().max(b.len());+ let mut out = Vec::with_capacity(n);+ for i in 0..n {+ let (x, y) = match (a.get(i), b.get(i)) {+ (Some(x), Some(y)) => (x.clone(), y.clone()),+ (Some(x), None) => (x.clone(), identity_filter(x)),+ (None, Some(y)) => (identity_filter(y), y.clone()),+ (None, None) => break,+ };+ out.push(match (x, y) {+ (F::Blur(p), F::Blur(q)) => F::Blur(mix(p, q, t)),+ (F::Brightness(p), F::Brightness(q)) => F::Brightness(mix(p, q, t)),+ (F::Contrast(p), F::Contrast(q)) => F::Contrast(mix(p, q, t)),+ (F::Grayscale(p), F::Grayscale(q)) => F::Grayscale(mix(p, q, t)),+ (F::HueRotate(p), F::HueRotate(q)) => F::HueRotate(mix(p, q, t)),+ (F::Invert(p), F::Invert(q)) => F::Invert(mix(p, q, t)),+ (F::Opacity(p), F::Opacity(q)) => F::Opacity(mix(p, q, t)),+ (F::Saturate(p), F::Saturate(q)) => F::Saturate(mix(p, q, t)),+ (F::Sepia(p), F::Sepia(q)) => F::Sepia(mix(p, q, t)),+ (F::DropShadow { x: x0, y: y0, blur: b0, color: c0 }, F::DropShadow { x: x1, y: y1, blur: b1, color: c1 }) => {+ F::DropShadow { x: mix(x0, x1, t), y: mix(y0, y1, t), blur: mix(b0, b1, t), color: mix_color(c0, c1, t) }+ }+ _ => return None,+ });+ }+ Some(out)+}++const NO_SHADOW: Shadow = Shadow { x: 0.0, y: 0.0, blur: 0.0, spread: 0.0, color: Rgba::TRANSPARENT, inset: false };++/// Interpolate; None when the values don't interpolate (discrete).+fn lerp(a: &Val, b: &Val, t: f32, u: &Units) -> Option<Val> {+ Some(match (a, b) {+ (Val::Dim(x), Val::Dim(y)) => match mix_compact(x.into_raw(), y.into_raw(), t)? {+ (false, v) => Val::Dim(Dimension::length(v)),+ (true, v) => Val::Dim(Dimension::percent(v)),+ },+ (Val::Lpa(x), Val::Lpa(y)) => match mix_compact(x.into_raw(), y.into_raw(), t)? {+ (false, v) => Val::Lpa(LengthPercentageAuto::length(v)),+ (true, v) => Val::Lpa(LengthPercentageAuto::percent(v)),+ },+ (Val::Lp(x), Val::Lp(y)) => match mix_compact(x.into_raw(), y.into_raw(), t)? {+ (false, v) => Val::Lp(LengthPercentage::length(v)),+ (true, v) => Val::Lp(LengthPercentage::percent(v)),+ },+ (Val::Num(x), Val::Num(y)) => Val::Num(mix(*x, *y, t)),+ (Val::Int(x), Val::Int(y)) => Val::Int(mix(*x as f32, *y as f32, t).round() as i32),+ (Val::Color(x), Val::Color(y)) => Val::Color(mix_color(*x, *y, t)),+ (Val::OptColor(Some(x)), Val::OptColor(Some(y))) => Val::OptColor(Some(mix_color(*x, *y, t))),+ (Val::Len(x), Val::Len(y)) => Val::Len(mix_length(*x, *y, t, u)?),+ (Val::Len2(x0, y0), Val::Len2(x1, y1)) => Val::Len2(mix_length(*x0, *x1, t, u)?, mix_length(*y0, *y1, t, u)?),+ (Val::Shadows(x), Val::Shadows(y)) => {+ // the shorter list is padded with transparent zero shadows+ let n = x.len().max(y.len());+ let pad = |l: &Vec<Shadow>, o: &Vec<Shadow>, i: usize| {+ l.get(i).copied().unwrap_or(Shadow { inset: o[i].inset, ..NO_SHADOW })+ };+ Val::Shadows((0..n).map(|i| mix_shadow(&pad(x, y, i), &pad(y, x, i), t)).collect::<Option<_>>()?)+ }+ (Val::TextShadow(x), Val::TextShadow(y)) => {+ let (p, q) = (x.unwrap_or(NO_SHADOW), y.unwrap_or(NO_SHADOW));+ if x.is_none() && y.is_none() {+ Val::TextShadow(None)+ } else {+ Val::TextShadow(mix_shadow(&p, &q, t))+ }+ }+ (Val::Visible(x), Val::Visible(y)) => Val::Visible(if t <= 0.0 {+ *x+ } else if t >= 1.0 {+ *y+ } else {+ *x || *y+ }),+ (Val::Z(Some(x)), Val::Z(Some(y))) => Val::Z(Some(mix(*x as f32, *y as f32, t).round() as i32)),+ (Val::Pair(a0, a1), Val::Pair(b0, b1)) => Val::Pair(mix(*a0, *b0, t), mix(*a1, *b1, t)),+ (Val::Fns(x), Val::Fns(y)) => Val::Fns(mix_transforms(x, y, t, u)?),+ (Val::Filters(x), Val::Filters(y)) => Val::Filters(mix_filters(x, y, t)?),+ (Val::Lh(x), Val::Lh(y)) => Val::Lh(match (x, y) {+ (LineHeight::Factor(p), LineHeight::Factor(q)) => LineHeight::Factor(mix(*p, *q, t)),+ (LineHeight::Px(p), LineHeight::Px(q)) => LineHeight::Px(mix(*p, *q, t)),+ _ => return None,+ }),+ _ => return None,+ })+}++/// Interpolate, or flip at 50% when the values don't interpolate.+fn blend(a: &Val, b: &Val, t: f32, u: &Units) -> Val {+ lerp(a, b, t, u).unwrap_or_else(|| if t < 0.5 { a.clone() } else { b.clone() })+}++// ==========================================================================+// Clock++/// A window's animation clock in seconds: real time for native windows,+/// virtual (advanced only by [`Clock::advance`]) for headless ones so tests+/// are deterministic.+pub(crate) struct Clock {+ origin: Option<std::time::Instant>,+ offset: f64,+}++impl Clock {+ pub(crate) fn new(real: bool) -> Clock {+ Clock { origin: real.then(std::time::Instant::now), offset: 0.0 }+ }++ pub(crate) fn now(&self) -> f64 {+ self.origin.map_or(0.0, |o| o.elapsed().as_secs_f64()) + self.offset+ }++ pub(crate) fn advance(&mut self, d: std::time::Duration) {+ self.offset += d.as_secs_f64();+ }+}++// ==========================================================================+// Per-element state++/// One animation of an element (an `animation-name` entry).+struct Run {+ name: Box<str>,+ /// Clock time the animation started.+ start: f64,+ /// While paused: the local time it stopped at.+ held: Option<f64>,+}++/// A running transition of one field.+struct Transition {+ field: Field,+ from: Val,+ to: Val,+ start: f64,+ delay: f32,+ duration: f32,+ timing: Timing,+ /// For reversing a transition midway (css-transitions "reversing-adjusted+ /// start value" and "reversing shortening factor").+ reversing_start: Val,+ shortening: f32,+}++impl Transition {+ /// Eased progress at `now` (may sit outside 0..1 for overshooting easings).+ fn progress(&self, now: f64) -> f32 {+ let local = (now - self.start) as f32 - self.delay;+ if local < 0.0 {+ return 0.0;+ }+ if self.duration <= 0.0 {+ return 1.0;+ }+ self.timing.apply((local / self.duration).min(1.0), false)+ }++ fn done(&self, now: f64) -> bool {+ (now - self.start) as f32 >= self.delay + self.duration+ }++ fn value(&self, now: f64, u: &Units) -> Val {+ blend(&self.from, &self.to, self.progress(now), u)+ }+}++#[derive(Default)]+struct ElState {+ seen: u64,+ runs: Vec<Run>,+ transitions: Vec<Transition>,+ /// The element's cascaded style last frame (when it has transitions).+ prev: Option<Box<Computed>>,+}++/// What [`Animations::apply`] needs from the cascade.+pub(crate) struct Env<'a> {+ pub parent: &'a Computed,+ pub viewport: (f32, f32),+ /// The element's custom properties (`var()` in keyframes).+ pub vars: &'a [(Prop, Box<[Tok]>)],+ pub sheet: &'a crate::css::Stylesheet,+ /// The sheet's media query results this frame.+ pub media: &'a [bool],+ /// Properties set by `!important` declarations on the element.+ pub important: &'a [Prop],+}++/// Animation and transition state of a window's elements, by element key.+#[derive(Default)]+pub(crate) struct Animations {+ now: f64,+ frame: u64,+ els: FnvMap<u64, ElState>,+ /// Something is moving: render another frame.+ running: bool,+}++impl Animations {+ /// Before a layout: the time this frame shows.+ pub(crate) fn begin(&mut self, now: f64) {+ self.now = now;+ self.frame += 1;+ self.running = false;+ }++ /// After a layout: forget elements that are gone (or lost their+ /// animations). True when another frame is needed.+ pub(crate) fn end(&mut self) -> bool {+ let frame = self.frame;+ self.els.retain(|_, e| e.seen == frame);+ self.running+ }++ /// Whether anything is animating (as of the last layout).+ pub(crate) fn running(&self) -> bool {+ self.running+ }++ /// Whether any element has animation state (time passing may matter).+ pub(crate) fn any(&self) -> bool {+ !self.els.is_empty()+ }++ /// Whether element `key` with cascaded style `base` needs [`apply`](Self::apply).+ pub(crate) fn wants(&self, key: u64, base: &Computed) -> bool {+ base.anim.is_some() || (!self.els.is_empty() && self.els.contains_key(&key))+ }++ /// The animated style of element `key` whose cascaded style is `base`+ /// (None: the cascaded style as is).+ pub(crate) fn apply(&mut self, key: u64, base: &Computed, env: &Env) -> Option<Computed> {+ let spec = base.anim.as_deref().filter(|s| s.has_animations() || s.has_transitions());+ if spec.is_none() && !self.els.get(&key).is_some_and(|e| !e.transitions.is_empty()) {+ self.els.remove(&key);+ return None;+ }+ 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 mut running = false;++ // -- animations: keep the runs whose name stays, start new ones now+ let names: &[Box<str>] = spec.map(|s| &s.names[..]).unwrap_or(&[]);+ let mut old = std::mem::take(&mut st.runs);+ for n in names {+ let run = match old.iter().position(|r| r.name == *n) {+ Some(k) => old.remove(k),+ None => Run { name: n.clone(), start: now, held: None },+ };+ st.runs.push(run);+ }++ // -- transitions: start one for each watched field that changed+ let mut watched = Vec::new();+ if let Some(s) = spec.filter(|s| s.has_transitions()) {+ watched = s.watched();+ if let Some(prev) = &st.prev {+ for &f in &watched {+ let (Some(before), Some(after)) = (get(f, prev), get(f, base)) else { continue };+ if before == after {+ continue;+ }+ let running_t = st.transitions.iter().position(|t| t.field == f);+ if running_t.is_some_and(|k| st.transitions[k].to == after) {+ continue;+ }+ let current = match running_t {+ Some(k) => st.transitions[k].value(now, &u),+ None => before,+ };+ let old_t = running_t.map(|k| st.transitions.remove(k));+ let Some((mut dur, mut delay, timing, discrete)) = s.transition_for(f) else { continue };+ if dur + delay <= 0.0 || current == after+ || (!discrete && f != Field::Visibility && lerp(¤t, &after, 0.5, &u).is_none()) {+ continue;+ }+ let (mut reversing_start, mut shortening) = (current.clone(), 1.0);+ if let Some(o) = old_t.filter(|o| o.reversing_start == after) {+ // going back to where it came from: take as long as it has run+ let p = o.progress(now).clamp(0.0, 1.0);+ shortening = (p * o.shortening + (1.0 - o.shortening)).clamp(0.0, 1.0);+ dur *= shortening;+ if delay < 0.0 {+ delay *= shortening;+ }+ reversing_start = o.to.clone();+ }+ st.transitions.push(Transition { field: f, from: current, to: after, start: now, delay,+ duration: dur, timing, reversing_start, shortening });+ }+ }+ // remember the style the next frame compares against+ let stale = match &st.prev {+ Some(p) => ALL_FIELDS.iter().any(|&f| get(f, p) != get(f, base)),+ None => true,+ };+ if stale {+ st.prev = Some(Box::new(base.clone()));+ }+ } else {+ st.prev = None;+ }+ // a property no longer transitioned stops at once+ st.transitions.retain(|t| watched.contains(&t.field) && !t.done(now));++ let mut out: Option<Computed> = None;+ for t in &st.transitions {+ running = true;+ set(t.field, out.get_or_insert_with(|| base.clone()), t.value(now, &u));+ }++ // -- animations on top+ if let Some(s) = spec {+ let important: Vec<Field> = env.important.iter().flat_map(|p| fields_of(*p).iter().copied()).collect();+ for (i, run) in st.runs.iter_mut().enumerate() {+ if &*run.name == "none" {+ continue;+ }+ let paused = nth(&s.paused, i, false);+ match (paused, run.held) {+ (true, None) => run.held = Some(now - run.start),+ (false, Some(h)) => {+ run.start = now - h;+ run.held = None;+ }+ _ => {}+ }+ let local = run.held.unwrap_or(now - run.start) as f32;+ let Some(kf) = keyframes(env.sheet, env.media, &run.name) else { continue };+ let anim = Anim {+ duration: nth(&s.durations, i, 0.0),+ delay: nth(&s.delays, i, 0.0),+ iterations: nth(&s.iterations, i, 1.0),+ direction: nth(&s.directions, i, Direction::Normal),+ fill: nth(&s.fills, i, Fill::None),+ };+ let (progress, active) = anim.progress(local);+ if active && !paused {+ running = true;+ }+ let Some((p, before)) = progress else { continue };+ let timing = nth(&s.timings, i, EASE);+ let c = out.get_or_insert_with(|| base.clone());+ sample(kf, p, before, &timing, base, c, env, &important, &u);+ }+ }+ if st.runs.is_empty() && st.transitions.is_empty() && st.prev.is_none() {+ self.els.remove(&key);+ }+ self.running |= running;+ out+ }+}++/// The `@keyframes` rule called `name` (the last one whose media match).+fn keyframes<'s>(sheet: &'s crate::css::Stylesheet, media: &[bool], name: &str) -> Option<&'s crate::css::Keyframes> {+ sheet.keyframes.iter().rev()+ .find(|k| k.name == name && k.media.iter().all(|&m| media.get(m as usize).copied().unwrap_or(true)))+}++/// One animation's timing (css-animations / web-animations timing model).+struct Anim {+ duration: f32,+ delay: f32,+ iterations: f32,+ direction: Direction,+ fill: Fill,+}++impl Anim {+ /// At local time `t`: the directed progress through the current+ /// iteration and whether in the before phase (None: no effect), and+ /// whether the animation is still to finish (before or active phase).+ fn progress(&self, t: f32) -> (Option<(f32, bool)>, bool) {+ let active_dur = if self.iterations.is_infinite() {+ f32::INFINITY+ } else {+ self.duration * self.iterations+ };+ let end = (self.delay + active_dur).max(0.0);+ let before_end = self.delay.min(end).max(0.0);+ let active_end = (self.delay + active_dur).min(end).max(0.0);+ let (phase_before, phase_after) = (t < before_end, t >= active_end);+ let active_time = if phase_before {+ if !matches!(self.fill, Fill::Backwards | Fill::Both) {+ return (None, true);+ }+ (t - self.delay).max(0.0)+ } else if phase_after {+ if !matches!(self.fill, Fill::Forwards | Fill::Both) {+ return (None, false);+ }+ (t - self.delay).min(active_dur).max(0.0)+ } else {+ t - self.delay+ };+ let overall = if self.duration == 0.0 {+ if phase_before { 0.0 } else { self.iterations }+ } else {+ active_time / self.duration+ };+ let mut simple = if overall.is_infinite() { 0.0 } else { overall.fract() };+ if simple == 0.0 && !phase_before && active_time == active_dur && self.iterations != 0.0 {+ simple = 1.0;+ }+ let iteration = if phase_after && self.iterations.is_infinite() {+ f32::INFINITY+ } else if simple == 1.0 {+ overall.floor() - 1.0+ } else {+ overall.floor()+ };+ let even = iteration.is_infinite() || (iteration as i64) % 2 == 0;+ let forward = match self.direction {+ Direction::Normal => true,+ Direction::Reverse => false,+ Direction::Alternate => even,+ Direction::AlternateReverse => !even,+ };+ let p = if forward { simple } else { 1.0 - simple };+ (Some((p, phase_before)), !phase_after)+ }+}++/// Apply keyframes `kf` at iteration progress `p` onto `out`.+#[allow(clippy::too_many_arguments)]+fn sample(kf: &crate::css::Keyframes, p: f32, before: bool, timing: &Timing, base: &Computed, out: &mut Computed,+ env: &Env, important: &[Field], u: &Units) {+ const TIMING: Prop = Prop::named("animation-timing-function");+ // per field: (offset, declaration, the keyframe's own easing), by offset+ let mut tracks: Vec<(Field, Vec<(f32, &Decl, Option<Timing>)>)> = Vec::new();+ for (offsets, decls) in &kf.frames {+ let own = decls.iter().rev().find(|d| d.prop == TIMING).and_then(|d| d.value.first().and_then(Timing::parse));+ for &o in offsets {+ if !(0.0..=1.0).contains(&o) {+ continue;+ }+ for d in decls.iter().filter(|d| !d.important && d.prop != TIMING && d.prop != Prop::UNKNOWN+ && !d.prop.name().starts_with("animation")) {+ let fs = fields_of(d.prop);+ let other = [Field::Other(d.prop)];+ for &f in if fs.is_empty() { &other[..] } else { fs } {+ let k = match tracks.iter().position(|t| t.0 == f) {+ Some(k) => k,+ None => {+ tracks.push((f, Vec::new()));+ tracks.len() - 1+ }+ };+ let list = &mut tracks[k].1;+ // a later block with the same offset wins+ list.retain(|e| e.0 != o);+ list.push((o, d, own.clone()));+ }+ }+ }+ }+ let mut applied: Vec<(*const Decl, Computed)> = Vec::new();+ let with = |d: &Decl, applied: &mut Vec<(*const Decl, Computed)>| -> usize {+ if let Some(k) = applied.iter().position(|e| std::ptr::eq(e.0, d)) {+ return k;+ }+ let mut c = base.clone();+ apply_decl(&mut c, d, env, u);+ applied.push((d as *const Decl, c));+ applied.len() - 1+ };+ // discrete declarations first: interpolated fields are set over them+ tracks.sort_by_key(|t| !matches!(t.0, Field::Other(_)));+ for (f, mut list) in tracks {+ if important.contains(&f) || matches!(f, Field::Other(p) if env.important.contains(&p)) {+ continue;+ }+ list.sort_by(|a, b| a.0.total_cmp(&b.0));+ // implicit 0% / 100% keyframes hold the underlying value+ type Key<'d> = (f32, Option<&'d Decl>, Option<Timing>);+ let mut keys: Vec<Key> = list.into_iter().map(|(o, d, t)| (o, Some(d), t)).collect();+ if keys.first().is_none_or(|k| k.0 > 0.0) {+ keys.insert(0, (0.0, None, None));+ }+ if keys.last().is_none_or(|k| k.0 < 1.0) {+ keys.push((1.0, None, None));+ }+ let k = keys.iter().rposition(|e| e.0 <= p).unwrap_or(0).min(keys.len() - 2);+ let (a, b) = (&keys[k], &keys[k + 1]);+ let local = if b.0 > a.0 { (p - a.0) / (b.0 - a.0) } else { 1.0 };+ let eased = a.2.as_ref().unwrap_or(timing).apply(local, before);+ match f {+ Field::Other(_) => {+ // discrete: the nearer keyframe's declaration as is+ if let Some(d) = if eased < 0.5 { a.1 } else { b.1 } {+ apply_decl(out, d, env, u);+ }+ }+ _ => {+ let val = |e: &Key, applied: &mut Vec<(*const Decl, Computed)>| match e.1 {+ Some(d) => {+ let k = with(d, applied);+ get(f, &applied[k].1)+ }+ None => get(f, base),+ };+ let (Some(va), Some(vb)) = (val(a, &mut applied), val(b, &mut applied)) else { continue };+ set(f, out, blend(&va, &vb, eased, u));+ }+ }+ }+}++/// Apply one keyframe declaration (with `var()` substituted).+fn apply_decl(c: &mut Computed, d: &Decl, env: &Env, u: &Units) {+ if crate::vars::uses_vars(&d.value) {+ if let Some(v) = crate::vars::substitute(&d.value, env.vars) {+ let d = Decl { prop: d.prop, value: crate::css::Value::Owned(v.into_boxed_slice()), important: false };+ crate::style::apply(c, env.parent, *u, &d);+ }+ } else {+ crate::style::apply(c, env.parent, *u, d);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn easing_functions() {+ let ease = EASE;+ assert!((ease.apply(0.5, false) - 0.8024).abs() < 1e-3);+ assert_eq!(Timing::Linear.apply(0.3, false), 0.3);+ let s = Timing::Steps(4, StepPos::End);+ assert_eq!(s.apply(0.3, false), 0.25);+ assert_eq!(s.apply(1.0, false), 1.0);+ let s = Timing::Steps(4, StepPos::Start);+ assert_eq!(s.apply(0.3, false), 0.5);+ let s = Timing::Steps(3, StepPos::None);+ assert_eq!(s.apply(0.5, false), 0.5);+ let s = Timing::Steps(1, StepPos::Both);+ assert_eq!(s.apply(0.2, false), 0.5);+ let l = linear_points(&crate::css::tokenize("linear(0, 0.25 75%, 1)").iter().map(|t| match t {+ Tok::Func(f) => f.args.clone(),+ _ => vec![],+ }).next().unwrap()).unwrap();+ assert!((l.apply(0.75, false) - 0.25).abs() < 1e-6);+ assert!((l.apply(0.375, false) - 0.125).abs() < 1e-6);+ }++ #[test]+ fn premultiplied_colors() {+ let red = Rgba { r: 1.0, g: 0.0, b: 0.0, a: 1.0 };+ let c = mix_color(red, Rgba::TRANSPARENT, 0.5);+ assert_eq!((c.r, c.a), (1.0, 0.5), "no darkening through transparent black");+ }+}diff --git a/bindings/rust/blenderui/src/components.rs b/bindings/rust/blenderui/src/components.rsnew file mode 100644index 0000000..1dec2de--- /dev/null+++ b/bindings/rust/blenderui/src/components.rs@@ -0,0 +1,76 @@+//! Blender's widgets as components: capitalized, always drawn and handled+//! like Blender, whether or not they sit inside a `styled` subtree. Their+//! lowercase HTML counterparts (`button()`, `input()` ...) look like a+//! browser's form controls instead (and like Blender inside `styled`).+//!+//! ```ignore+//! rsx! {+//! <NumberSlider min={0.0} max={10.0} value="2.5" onChange={|e: &ChangeEvent| println!("{:?}", e.number)} />+//! <Button onClick={|| println!("apply")}>"Apply"</Button>+//! <Dropdown><option>"Cube"</option><option>"Sphere"</option></Dropdown>+//! }+//! // gpui syntax: the same components are functions+//! div().child(Checkbox().checked(true)).child(Button().child("Apply"))+//! ```+//!+//! Each component is the element it stands for, so every element method is+//! a prop (`min`, `max`, `step`, `value`, `checked`, `placeholder`,+//! `disabled`, `on_change`, `on_click`, styling ...).++use crate::element::Div;+use crate::html;++/// Marks an element as a Blender widget (see the module docs).+pub const BLENDER_ATTR: &str = "bui-blender";++macro_rules! blender_component {+ ($($(#[$m:meta])* $name:ident => $make:expr;)*) => {$(+ $(#[$m])*+ pub struct $name {+ _private: (),+ }++ impl $name {+ #[doc(hidden)]+ pub fn __builder() -> Div {+ $make.attr(BLENDER_ATTR, "")+ }+ }++ $(#[$m])*+ #[allow(non_snake_case)]+ pub fn $name() -> Div {+ $name::__builder()+ }+ )*};+}++blender_component! {+ /// Blender's push button (`<Button>"Apply"</Button>`).+ Button => html::button();+ /// Blender's checkbox.+ Checkbox => html::input().input_type("checkbox");+ /// Blender's radio button (grouped by `name`).+ Radio => html::input().input_type("radio");+ /// Blender's number field: drag to scrub, click to step, double-click to type.+ NumberField => html::input().input_type("number");+ /// Blender's number slider: the field fills with the value.+ NumberSlider => html::input().input_type("range");+ /// Blender's single-line text field.+ TextField => html::input().input_type("text");+ /// Blender's multi-line text editor.+ TextArea => html::textarea();+ /// Blender's color swatch (opens Blender's color picker).+ ColorSwatch => html::input().input_type("color");+ /// Blender's dropdown menu; options are `option()` children.+ Dropdown => html::select();+ /// Blender's progress bar (`value`, `max`).+ ProgressBar => html::progress();+}++impl crate::hooks::Complete for Div {+ type Props = Div;+ fn finish(self) -> Div {+ self+ }+}diff --git a/bindings/rust/blenderui/src/effects.rs b/bindings/rust/blenderui/src/effects.rsnew file mode 100644index 0000000..66ae799--- /dev/null+++ b/bindings/rust/blenderui/src/effects.rs@@ -0,0 +1,625 @@+//! CSS effects that work on an element's pixels: `filter`,+//! `backdrop-filter`, `mix-blend-mode`, `clip-path`, `mask`, and transforms+//! beyond `translate` (`rotate`, `skew`, `scale`, `matrix`).+//!+//! The element's subtree is painted into its own display list, rasterized+//! offscreen with the canvas' own item code (`BK_canvas_rasterize`), then+//! filtered, clipped, masked, transformed and composited here, and drawn back+//! as one image item. That works the same under the CPU and GPU renderers;+//! results are cached by content, so a page that doesn't change costs+//! nothing.+//!+//! The formulas are the W3C ones (Filter Effects 1, Compositing and Blending+//! 1), which is what browsers implement. Blur is a three-pass box blur, the+//! Gaussian approximation browsers use. Resampling is bilinear over+//! premultiplied pixels, like Blender's `IMB_transform`.++use crate::color::Rgba;+use crate::geometry::{Length, Units};+use crate::style::{BoxEdge, Gradient, Pos};++// ==========================================================================+// Style values++/// One `filter` / `backdrop-filter` function. Amounts are fractions+/// (`50%` = 0.5); `hue-rotate` in degrees; lengths in px.+#[derive(Clone, Debug, PartialEq)]+pub enum Filter {+ Blur(f32),+ Brightness(f32),+ Contrast(f32),+ Grayscale(f32),+ HueRotate(f32),+ Invert(f32),+ Opacity(f32),+ Saturate(f32),+ Sepia(f32),+ DropShadow { x: f32, y: f32, blur: f32, color: Rgba },+}++/// `mix-blend-mode` (and `background-blend-mode`).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum Blend {+ #[default]+ Normal,+ Multiply,+ Screen,+ Overlay,+ Darken,+ Lighten,+ ColorDodge,+ ColorBurn,+ HardLight,+ SoftLight,+ Difference,+ Exclusion,+ Hue,+ Saturation,+ Color,+ Luminosity,+ PlusLighter,+}++impl Blend {+ pub fn parse(s: &str) -> Option<Blend> {+ Some(match s {+ "normal" => Blend::Normal,+ "multiply" => Blend::Multiply,+ "screen" => Blend::Screen,+ "overlay" => Blend::Overlay,+ "darken" => Blend::Darken,+ "lighten" => Blend::Lighten,+ "color-dodge" => Blend::ColorDodge,+ "color-burn" => Blend::ColorBurn,+ "hard-light" => Blend::HardLight,+ "soft-light" => Blend::SoftLight,+ "difference" => Blend::Difference,+ "exclusion" => Blend::Exclusion,+ "hue" => Blend::Hue,+ "saturation" => Blend::Saturation,+ "color" => Blend::Color,+ "luminosity" => Blend::Luminosity,+ "plus-lighter" => Blend::PlusLighter,+ _ => return None,+ })+ }+}++/// One `transform` function.+#[derive(Clone, Debug, PartialEq)]+pub enum TransformFn {+ Translate(Length, Length),+ Scale(f32, f32),+ /// radians+ Rotate(f32),+ /// radians+ Skew(f32, f32),+ Matrix([f32; 6]),+}++/// A `clip-path` shape radius: a length, or `closest-side` / `farthest-side`.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum ShapeRadius {+ Len(Length),+ Closest,+ Farthest,+}++/// A `clip-path` basic shape, in its reference box.+#[derive(Clone, Debug, PartialEq)]+pub enum ClipShape {+ /// top, right, bottom, left insets and a corner radius+ Inset([Length; 4], Length),+ Circle(ShapeRadius, [Pos; 2]),+ Ellipse(ShapeRadius, ShapeRadius, [Pos; 2]),+ Polygon(Vec<(Length, Length)>),+ /// just the reference box (`clip-path: padding-box`)+ Box,+}++/// A mask or border-image source: a gradient or a PNG file.+#[derive(Clone, Debug, PartialEq)]+pub enum ImageSource {+ Gradient(Gradient),+ Url(std::sync::Arc<str>),+}++/// `mask` / `mask-image` and its placement.+#[derive(Clone, Debug, PartialEq)]+pub struct Mask {+ pub image: Option<ImageSource>,+ /// `mask-mode: luminance` (else alpha)+ pub luminance: bool,+ pub size: crate::style::BgSize,+ pub position: [Pos; 2],+ pub repeat: (bool, bool),+}++impl Default for Mask {+ fn default() -> Mask {+ Mask { image: None, luminance: false, size: crate::style::BgSize::Auto, position: [Pos::START; 2],+ repeat: (true, true) }+ }+}++/// A `border-image-slice` / `-width` / `-outset` component.+#[derive(Clone, Copy, Debug, PartialEq)]+pub enum Side {+ /// a plain number: image pixels (slice) or multiples of the border width+ Num(f32),+ Len(Length),+ Auto,+}++/// `border-image-repeat` along one axis.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum Tile {+ #[default]+ Stretch,+ Repeat,+ Round,+ Space,+}++/// `border-image` and its longhands.+#[derive(Clone, Debug, PartialEq)]+pub struct BorderImage {+ pub source: Option<ImageSource>,+ pub slice: [Side; 4],+ pub fill: bool,+ pub width: [Side; 4],+ pub outset: [Side; 4],+ pub repeat: (Tile, Tile),+}++impl Default for BorderImage {+ fn default() -> BorderImage {+ BorderImage { source: None, slice: [Side::Len(Length::Percent(100.0)); 4], fill: false,+ width: [Side::Num(1.0); 4], outset: [Side::Num(0.0); 4], repeat: (Tile::Stretch, Tile::Stretch) }+ }+}++/// The effects of one element (boxed in `Computed`: most elements have none).+#[derive(Clone, Debug, PartialEq, Default)]+pub struct Effects {+ pub filter: Vec<Filter>,+ pub backdrop: Vec<Filter>,+ pub blend: Blend,+ pub isolate: bool,+ pub clip_path: Option<(ClipShape, BoxEdge)>,+ pub mask: Option<Mask>,+ /// `transform` functions that need pixels (anything but translate)+ pub transform: Vec<TransformFn>,+ /// the individual `rotate` property, radians+ pub rotate: f32,+ /// the individual `scale` property when it isn't uniform+ pub scale2: Option<(f32, f32)>,+ /// `transform-origin` (default: the centre)+ pub origin: Option<[Pos; 2]>,+ pub border_image: Option<BorderImage>,+}++impl Effects {+ /// Whether the element must be painted into its own layer.+ pub fn needs_layer(&self) -> bool {+ !self.filter.is_empty() || self.blend != Blend::Normal || self.clip_path.is_some()+ || self.mask.as_ref().is_some_and(|m| m.image.is_some()) || !self.transform.is_empty()+ || self.rotate != 0.0 || self.scale2.is_some()+ }+}++// ==========================================================================+// Affine transforms: [a, b, c, d, e, f] maps (x, y) to (a x + c y + e, b x + d y + f)++pub type Affine = [f32; 6];++pub const IDENTITY: Affine = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];++/// `m * n`: n applied first.+pub fn mul(m: &Affine, n: &Affine) -> Affine {+ [+ m[0] * n[0] + m[2] * n[1],+ m[1] * n[0] + m[3] * n[1],+ m[0] * n[2] + m[2] * n[3],+ m[1] * n[2] + m[3] * n[3],+ m[0] * n[4] + m[2] * n[5] + m[4],+ m[1] * n[4] + m[3] * n[5] + m[5],+ ]+}++pub fn apply(m: &Affine, x: f32, y: f32) -> (f32, f32) {+ (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5])+}++pub fn invert(m: &Affine) -> Option<Affine> {+ let det = m[0] * m[3] - m[1] * m[2];+ if det.abs() < 1e-9 {+ return None;+ }+ let (a, b, c, d) = (m[3] / det, -m[1] / det, -m[2] / det, m[0] / det);+ Some([a, b, c, d, -(a * m[4] + c * m[5]), -(b * m[4] + d * m[5])])+}++/// The matrix of a function list for a box of size `w` x `h` (percentages+/// of translate resolve against it), before the origin is applied.+pub fn matrix_of(fns: &[TransformFn], w: f32, h: f32, u: &Units) -> Affine {+ let mut m = IDENTITY;+ for f in fns {+ let n = match *f {+ TransformFn::Translate(x, y) => [1.0, 0.0, 0.0, 1.0, x.resolve(u, w), y.resolve(u, h)],+ TransformFn::Scale(x, y) => [x, 0.0, 0.0, y, 0.0, 0.0],+ TransformFn::Rotate(a) => [a.cos(), a.sin(), -a.sin(), a.cos(), 0.0, 0.0],+ TransformFn::Skew(ax, ay) => [1.0, ay.tan(), ax.tan(), 1.0, 0.0, 0.0],+ TransformFn::Matrix(v) => v,+ };+ m = mul(&m, &n);+ }+ m+}++// ==========================================================================+// Pixels: premultiplied linear-in-sRGB f32 RGBA, row-major++pub struct Pixels {+ pub w: usize,+ pub h: usize,+ pub px: Vec<[f32; 4]>,+}++impl Pixels {+ pub fn new(w: usize, h: usize) -> Pixels {+ Pixels { w, h, px: vec![[0.0; 4]; w * h] }+ }++ /// From straight-alpha RGBA8.+ pub fn from_rgba8(w: usize, h: usize, rgba: &[u8]) -> Pixels {+ let px = rgba.chunks_exact(4).map(|c| {+ let a = c[3] as f32 / 255.0;+ [c[0] as f32 / 255.0 * a, c[1] as f32 / 255.0 * a, c[2] as f32 / 255.0 * a, a]+ }).collect();+ Pixels { w, h, px }+ }++ /// To straight-alpha RGBA8.+ pub fn to_rgba8(&self) -> Vec<u8> {+ let mut out = Vec::with_capacity(self.px.len() * 4);+ for p in &self.px {+ let a = p[3].clamp(0.0, 1.0);+ let un = |v: f32| if a > 0.0 { (v / a).clamp(0.0, 1.0) } else { 0.0 };+ out.extend([(un(p[0]) * 255.0).round() as u8, (un(p[1]) * 255.0).round() as u8,+ (un(p[2]) * 255.0).round() as u8, (a * 255.0).round() as u8]);+ }+ out+ }++ fn get(&self, x: isize, y: isize) -> [f32; 4] {+ if x < 0 || y < 0 || x >= self.w as isize || y >= self.h as isize {+ [0.0; 4]+ } else {+ self.px[y as usize * self.w + x as usize]+ }+ }++ /// Bilinear sample at a pixel-space position (pixel centres at +0.5).+ pub fn sample(&self, x: f32, y: f32) -> [f32; 4] {+ let (fx, fy) = (x - 0.5, y - 0.5);+ let (x0, y0) = (fx.floor(), fy.floor());+ let (tx, ty) = (fx - x0, fy - y0);+ let (x0, y0) = (x0 as isize, y0 as isize);+ let (a, b, c, d) = (self.get(x0, y0), self.get(x0 + 1, y0), self.get(x0, y0 + 1), self.get(x0 + 1, y0 + 1));+ let mut o = [0.0; 4];+ for k in 0..4 {+ let top = a[k] + (b[k] - a[k]) * tx;+ let bot = c[k] + (d[k] - c[k]) * tx;+ o[k] = top + (bot - top) * ty;+ }+ o+ }+}++// -- filters ---------------------------------------------------------------------++/// Box sizes for three box blurs approximating a Gaussian of `sigma`.+fn boxes(sigma: f32) -> [usize; 3] {+ let n = 3.0;+ let w_ideal = (12.0 * sigma * sigma / n + 1.0).sqrt();+ let mut wl = w_ideal.floor() as i32;+ if wl % 2 == 0 {+ wl -= 1;+ }+ let wu = wl + 2;+ let m_ideal = (12.0 * sigma * sigma - n * (wl * wl) as f32 - 4.0 * n * wl as f32 - 3.0 * n)+ / (-4.0 * wl as f32 - 4.0);+ let m = m_ideal.round() as i32;+ let mut out = [0usize; 3];+ for (i, o) in out.iter_mut().enumerate() {+ *o = (if (i as i32) < m { wl } else { wu }).max(1) as usize;+ }+ out+}++fn box_pass(src: &[[f32; 4]], dst: &mut [[f32; 4]], w: usize, h: usize, r: usize, horizontal: bool) {+ let (len, lines) = if horizontal { (w, h) } else { (h, w) };+ let idx = |line: usize, i: usize| if horizontal { line * w + i } else { i * w + line };+ let norm = 1.0 / (2 * r + 1) as f32;+ for line in 0..lines {+ let mut acc = [0.0f32; 4];+ // window over [i - r, i + r], transparent outside+ for i in 0..=r.min(len.saturating_sub(1)) {+ let p = src[idx(line, i)];+ for k in 0..4 {+ acc[k] += p[k];+ }+ }+ for i in 0..len {+ let o = &mut dst[idx(line, i)];+ for k in 0..4 {+ o[k] = acc[k] * norm;+ }+ if i + r + 1 < len {+ let p = src[idx(line, i + r + 1)];+ for k in 0..4 {+ acc[k] += p[k];+ }+ }+ if i >= r {+ let p = src[idx(line, i - r)];+ for k in 0..4 {+ acc[k] -= p[k];+ }+ }+ }+ }+}++/// Gaussian blur with standard deviation `sigma` (device pixels).+pub fn blur(p: &mut Pixels, sigma: f32) {+ if sigma < 0.3 || p.w == 0 || p.h == 0 {+ return;+ }+ let mut tmp = vec![[0.0f32; 4]; p.px.len()];+ for b in boxes(sigma) {+ let r = (b - 1) / 2;+ box_pass(&p.px, &mut tmp, p.w, p.h, r, true);+ box_pass(&tmp, &mut p.px, p.w, p.h, r, false);+ }+}++/// A 4x5 colour matrix (rows r, g, b, a; columns r g b a offset) over+/// unpremultiplied colour, as Filter Effects' feColorMatrix.+fn color_matrix(p: &mut Pixels, m: &[[f32; 5]; 4]) {+ for px in &mut p.px {+ let a = px[3];+ if a <= 0.0 {+ continue;+ }+ let c = [px[0] / a, px[1] / a, px[2] / a, a];+ let mut o = [0.0f32; 4];+ for (r, row) in m.iter().enumerate() {+ o[r] = (row[0] * c[0] + row[1] * c[1] + row[2] * c[2] + row[3] * c[3] + row[4]).clamp(0.0, 1.0);+ }+ *px = [o[0] * o[3], o[1] * o[3], o[2] * o[3], o[3]];+ }+}++fn diag(r: f32, g: f32, b: f32, a: f32, off: f32) -> [[f32; 5]; 4] {+ [[r, 0.0, 0.0, 0.0, off], [0.0, g, 0.0, 0.0, off], [0.0, 0.0, b, 0.0, off], [0.0, 0.0, 0.0, a, 0.0]]+}++fn rgb3(m: [[f32; 3]; 3]) -> [[f32; 5]; 4] {+ [[m[0][0], m[0][1], m[0][2], 0.0, 0.0], [m[1][0], m[1][1], m[1][2], 0.0, 0.0],+ [m[2][0], m[2][1], m[2][2], 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0]]+}++/// Apply one filter function; `scale` = device pixels per CSS px.+pub fn apply_filter(p: &mut Pixels, f: &Filter, scale: f32) {+ match *f {+ Filter::Blur(r) => blur(p, r * scale),+ Filter::Brightness(b) => color_matrix(p, &diag(b, b, b, 1.0, 0.0)),+ Filter::Contrast(c) => color_matrix(p, &diag(c, c, c, 1.0, 0.5 - 0.5 * c)),+ Filter::Opacity(o) => p.px.iter_mut().for_each(|px| px.iter_mut().for_each(|v| *v *= o.clamp(0.0, 1.0))),+ Filter::Invert(a) => {+ let a = a.clamp(0.0, 1.0);+ color_matrix(p, &diag(1.0 - 2.0 * a, 1.0 - 2.0 * a, 1.0 - 2.0 * a, 1.0, a))+ }+ Filter::Grayscale(a) => {+ let s = 1.0 - a.clamp(0.0, 1.0);+ color_matrix(p, &rgb3([+ [0.2126 + 0.7874 * s, 0.7152 - 0.7152 * s, 0.0722 - 0.0722 * s],+ [0.2126 - 0.2126 * s, 0.7152 + 0.2848 * s, 0.0722 - 0.0722 * s],+ [0.2126 - 0.2126 * s, 0.7152 - 0.7152 * s, 0.0722 + 0.9278 * s],+ ]))+ }+ Filter::Sepia(a) => {+ let s = 1.0 - a.clamp(0.0, 1.0);+ color_matrix(p, &rgb3([+ [0.393 + 0.607 * s, 0.769 - 0.769 * s, 0.189 - 0.189 * s],+ [0.349 - 0.349 * s, 0.686 + 0.314 * s, 0.168 - 0.168 * s],+ [0.272 - 0.272 * s, 0.534 - 0.534 * s, 0.131 + 0.869 * s],+ ]))+ }+ Filter::Saturate(s) => color_matrix(p, &rgb3([+ [0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s],+ [0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s],+ [0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s],+ ])),+ Filter::HueRotate(deg) => {+ let (c, s) = (deg.to_radians().cos(), deg.to_radians().sin());+ color_matrix(p, &rgb3([+ [0.213 + c * 0.787 - s * 0.213, 0.715 - c * 0.715 - s * 0.715, 0.072 - c * 0.072 + s * 0.928],+ [0.213 - c * 0.213 + s * 0.143, 0.715 + c * 0.285 + s * 0.140, 0.072 - c * 0.072 - s * 0.283],+ [0.213 - c * 0.213 - s * 0.787, 0.715 - c * 0.715 + s * 0.715, 0.072 + c * 0.928 + s * 0.072],+ ]))+ }+ Filter::DropShadow { x, y, blur: b, color } => {+ // the source's alpha, coloured, blurred and offset, under the source+ let (dx, dy) = ((x * scale).round() as isize, (y * scale).round() as isize);+ let mut sh = Pixels::new(p.w, p.h);+ for yy in 0..p.h as isize {+ for xx in 0..p.w as isize {+ let a = p.get(xx - dx, yy - dy)[3] * color.a;+ sh.px[yy as usize * p.w + xx as usize] = [color.r * a, color.g * a, color.b * a, a];+ }+ }+ blur(&mut sh, b * scale / 2.0);+ for (s, d) in p.px.iter_mut().zip(&sh.px) {+ let ia = 1.0 - s[3];+ for k in 0..4 {+ s[k] += d[k] * ia;+ }+ }+ }+ }+}++/// How far a filter list can spread pixels past the element (CSS px).+pub fn filter_outset(filters: &[Filter]) -> f32 {+ let mut o = 0.0f32;+ for f in filters {+ o += match *f {+ Filter::Blur(r) => 3.0 * r,+ Filter::DropShadow { x, y, blur, .. } => x.abs().max(y.abs()) + 1.5 * blur,+ _ => 0.0,+ };+ }+ o.ceil()+}++// -- compositing (W3C Compositing and Blending 1) ------------------------------------++fn lum(c: [f32; 3]) -> f32 {+ 0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]+}++fn clip_color(c: [f32; 3]) -> [f32; 3] {+ let l = lum(c);+ let n = c[0].min(c[1]).min(c[2]);+ let x = c[0].max(c[1]).max(c[2]);+ let mut o = c;+ if n < 0.0 {+ o = o.map(|v| l + (v - l) * l / (l - n).max(1e-6));+ }+ if x > 1.0 {+ o = o.map(|v| l + (v - l) * (1.0 - l) / (x - l).max(1e-6));+ }+ o+}++fn set_lum(c: [f32; 3], l: f32) -> [f32; 3] {+ let d = l - lum(c);+ clip_color([c[0] + d, c[1] + d, c[2] + d])+}++fn sat(c: [f32; 3]) -> f32 {+ c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2])+}++fn set_sat(c: [f32; 3], s: f32) -> [f32; 3] {+ let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2]));+ if mx - mn <= 1e-6 {+ return [0.0; 3];+ }+ c.map(|v| (v - mn) * s / (mx - mn))+}++fn separable(mode: Blend, cb: f32, cs: f32) -> f32 {+ match mode {+ Blend::Multiply => cb * cs,+ Blend::Screen => cb + cs - cb * cs,+ Blend::Overlay => separable(Blend::HardLight, cs, cb),+ Blend::Darken => cb.min(cs),+ Blend::Lighten => cb.max(cs),+ Blend::ColorDodge => {+ if cb <= 0.0 { 0.0 } else if cs >= 1.0 { 1.0 } else { (cb / (1.0 - cs)).min(1.0) }+ }+ Blend::ColorBurn => {+ if cb >= 1.0 { 1.0 } else if cs <= 0.0 { 0.0 } else { 1.0 - ((1.0 - cb) / cs).min(1.0) }+ }+ Blend::HardLight => {+ if cs <= 0.5 { cb * 2.0 * cs } else { separable(Blend::Screen, cb, 2.0 * cs - 1.0) }+ }+ Blend::SoftLight => {+ if cs <= 0.5 {+ cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb)+ } else {+ let d = if cb <= 0.25 { ((16.0 * cb - 12.0) * cb + 4.0) * cb } else { cb.sqrt() };+ cb + (2.0 * cs - 1.0) * (d - cb)+ }+ }+ Blend::Difference => (cb - cs).abs(),+ Blend::Exclusion => cb + cs - 2.0 * cb * cs,+ _ => cs,+ }+}++/// B(Cb, Cs) for unpremultiplied colours.+fn blend_fn(mode: Blend, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {+ match mode {+ Blend::Hue => set_lum(set_sat(cs, sat(cb)), lum(cb)),+ Blend::Saturation => set_lum(set_sat(cb, sat(cs)), lum(cb)),+ Blend::Color => set_lum(cs, lum(cb)),+ Blend::Luminosity => set_lum(cb, lum(cs)),+ _ => [separable(mode, cb[0], cs[0]), separable(mode, cb[1], cs[1]), separable(mode, cb[2], cs[2])],+ }+}++/// Composite `src` over `backdrop` (same size, premultiplied) with `mode`.+pub fn composite(backdrop: &Pixels, src: &Pixels, mode: Blend) -> Pixels {+ let mut out = Pixels::new(src.w, src.h);+ for ((o, b), s) in out.px.iter_mut().zip(&backdrop.px).zip(&src.px) {+ let (ab, as_) = (b[3], s[3]);+ if mode == Blend::PlusLighter {+ *o = [(b[0] + s[0]).min(1.0), (b[1] + s[1]).min(1.0), (b[2] + s[2]).min(1.0), (ab + as_).min(1.0)];+ continue;+ }+ let un = |p: &[f32; 4], a: f32| if a > 0.0 { [p[0] / a, p[1] / a, p[2] / a] } else { [0.0; 3] };+ let (cb, cs) = (un(b, ab), un(s, as_));+ let mixed = blend_fn(mode, cb, cs);+ for k in 0..3 {+ // co = cs (1 - ab) + cb (1 - as) + as ab B(Cb, Cs), premultiplied+ o[k] = s[k] * (1.0 - ab) + b[k] * (1.0 - as_) + as_ * ab * mixed[k];+ }+ o[3] = as_ + ab * (1.0 - as_);+ }+ out+}++/// Multiply every pixel by the coverage in `mask` (alpha, or luminance).+pub fn apply_mask(p: &mut Pixels, mask: &Pixels, luminance: bool) {+ for (d, m) in p.px.iter_mut().zip(&mask.px) {+ let f = if luminance {+ // premultiplied luminance = luminance x alpha+ 0.2126 * m[0] + 0.7152 * m[1] + 0.0722 * m[2]+ } else {+ m[3]+ };+ for v in d.iter_mut() {+ *v *= f;+ }+ }+}++/// Resample `src` (whose top-left is at `origin` in device pixels) through+/// the affine `m` (device pixels). Returns the result and its top-left.+pub fn transform(src: &Pixels, origin: (f32, f32), m: &Affine) -> Option<(Pixels, (f32, f32))> {+ let inv = invert(m)?;+ let (x0, y0) = origin;+ let (x1, y1) = (x0 + src.w as f32, y0 + src.h as f32);+ let pts = [apply(m, x0, y0), apply(m, x1, y0), apply(m, x0, y1), apply(m, x1, y1)];+ let minx = pts.iter().map(|p| p.0).fold(f32::INFINITY, f32::min).floor();+ let miny = pts.iter().map(|p| p.1).fold(f32::INFINITY, f32::min).floor();+ let maxx = pts.iter().map(|p| p.0).fold(f32::NEG_INFINITY, f32::max).ceil();+ let maxy = pts.iter().map(|p| p.1).fold(f32::NEG_INFINITY, f32::max).ceil();+ let (w, h) = ((maxx - minx) as usize, (maxy - miny) as usize);+ if w == 0 || h == 0 || w > 8192 || h > 8192 {+ return None;+ }+ let mut out = Pixels::new(w, h);+ for y in 0..h {+ for x in 0..w {+ let (sx, sy) = apply(&inv, minx + x as f32 + 0.5, miny + y as f32 + 0.5);+ out.px[y * w + x] = src.sample(sx - x0, sy - y0);+ }+ }+ Some((out, (minx, miny)))+}diff --git a/bindings/rust/blenderui/src/html.rs b/bindings/rust/blenderui/src/html.rsindex df40d3d..83544c4 100644--- a/bindings/rust/blenderui/src/html.rs+++ b/bindings/rust/blenderui/src/html.rs@@ -71,7 +71,7 @@ pub fn custom(tag: &'static str) -> Div {/// (`div().styled()`, `<div styled>`) and everything inside it get Blender's/// dark theme instead. Form widgets are Blender widgets either way.pub const UA_CSS: &str = r#"-html { display: block; background-color: #ffffff; color: #000000; font-size: 16px; }+html { display: block; background-color: #ffffff; color: #000000; font-size: 16px; font-family: serif; }body { display: block; margin: 8px; }address, article, aside, blockquote, dd, details, dialog, div, dl, dt, fieldset, figcaption,figure, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, hr, legend, main, menu, nav, ol,@@ -133,7 +133,7 @@ output { display: inline; }/// background, text colour and 13px UI font size.pub const UA_STYLED_CSS: &str = r#"html { display: block; }-[styled] { background-color: #303030; color: #e6e6e6; font-size: 13px; }+[styled] { background-color: #303030; color: #e6e6e6; font-size: 13px; font-family: system-ui; }body { display: block; margin: 8px; }address, article, aside, blockquote, dd, details, dialog, div, dl, dt, fieldset, figcaption,figure, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, hr, legend, main, menu, nav, ol,diff --git a/bindings/rust/blenderui/src/layout.rs b/bindings/rust/blenderui/src/layout.rsindex 5444a4c..aa39294 100644--- a/bindings/rust/blenderui/src/layout.rs+++ b/bindings/rust/blenderui/src/layout.rs@@ -335,9 +335,14 @@ pub(crate) struct LayoutCaches {recon: Recon,/// Measured text leaves: key -> box index, this frame.text_box: FnvMap<Key, usize>,+ /// Content widths of blocks with `overflow-wrap: anywhere` from the last+ /// layout: their long words are split to fit before layout.+ wrap_widths: FnvMap<Key, f32>,tw: TwJit,/// `@container`: query containers' content sizes from the last layout.containers: Containers,+ /// CSS animations and transitions by element key.+ pub(crate) anim: crate::anim::Animations,}impl LayoutCaches {@@ -345,7 +350,23 @@ impl LayoutCaches {/// window must render again (an `@container` query may match differently).pub(crate) fn after_layout(&mut self, frame: &Frame) -> bool {let queried = self.author.sheet.has_container_queries();- self.containers.update(frame, &self.styles, queried)+ let mut again = self.containers.update(frame, &self.styles, queried);+ // overflow-wrap: blocks whose width changed lay out their words again+ for n in &frame.nodes {+ let c = &self.styles[n.style];+ if c.wrap_anywhere && n.taffy.is_some() && !c.display.is_inline_level()+ && matches!(n.content, Content::Element) {+ let w = crate::paint::content_box(c, n.bounds).size.width;+ if self.wrap_widths.get(&n.key).is_none_or(|old| (old - w).abs() > 0.5) {+ self.wrap_widths.insert(n.key, w);+ again = true;+ }+ }+ }+ if self.wrap_widths.len() > 4096 {+ self.wrap_widths.clear();+ }+ again}}@@ -416,8 +437,10 @@ impl Default for LayoutCaches {matched: MatchCache::default(),recon: Recon::default(),text_box: FnvMap::default(),+ wrap_widths: FnvMap::default(),tw: TwJit::default(),containers: Containers::default(),+ anim: Default::default(),}}}@@ -450,6 +473,18 @@ struct Builder<'a> {/// CSS counters in scope: name, value, and the box whose subtree the/// instance is scoped to (dropped when that box is finished).counters: Vec<(Box<str>, i32, usize)>,+ /// Column widths of each table (by box), computed before its cells.+ table_cols: FnvMap<usize, TableCols>,+ wrap_widths: &'a FnvMap<Key, f32>,+ anim: &'a mut crate::anim::Animations,+}++/// A table's columns: widths in px, and whether the table sizes to them.+struct TableCols {+ widths: Vec<f32>,+ /// the table's width is auto: it shrinks to its columns+ fit: bool,+ fixed: bool,}/// Child box indices / layout nodes being assembled: on the stack for the usual few.@@ -825,6 +860,33 @@ impl<'a> Builder<'a> {id}+ /// CSS animations and transitions of element `i` (`anim.rs`): a private+ /// copy of its shared style `style` with the animated values on top.+ /// Never cached, so the shared styles stay what the cascade made them.+ fn animate(&mut self, i: usize, div: &Div, parent: StyleId, style: StyleId) -> StyleId {+ let key = self.nodes[i].key;+ if !self.anim.wants(key, &self.styles[style]) {+ return style;+ }+ let important: smallvec::SmallVec<[Prop; 8]> = {+ let (ua, au) = self.matched_rules(i);+ self.declared(i, div, &ua, &au).iter().filter(|d| d.important).map(|d| d.prop).collect()+ };+ let base = &self.styles[style];+ let env = crate::anim::Env {+ parent: &self.styles[parent],+ viewport: self.viewport,+ vars: self.styles.vars.get(base.vars),+ sheet: self.author,+ media: &self.au_media,+ important: &important,+ };+ match self.anim.apply(key, base, &env) {+ Some(c) => self.styles.add(c),+ None => style,+ }+ }+/// The UA and author rules matching element `i`: from the memo when an/// element with the same fingerprint was matched before.fn matched_rules(&mut self, i: usize) -> (crate::css::Matches<'static>, crate::css::Matches<'a>) {@@ -1103,6 +1165,7 @@ impl<'a> Builder<'a> {self.pop();return None;}+ let style = self.animate(i, &div, parent_style, style);self.nodes[i].style = style;self.counter_ops(style, parent.unwrap_or(usize::MAX));// attributes moved into ElData: widgets read them back through the arena@@ -1111,7 +1174,10 @@ impl<'a> Builder<'a> {TagKind::Widget => {let spec = WidgetSpec::from_element(&div, self.els.last().map(|e| &e.attrs[..]).unwrap_or(&[]),key, self.state);- if let Some(spec) = spec {+ if let Some(mut spec) = spec {+ // browser-look controls in plain HTML; Blender widgets inside+ // `styled` and for the Blender components (`bui-blender`)+ spec.html = !self.nodes[i].styled && self.attr(i, "bui-blender").is_none();self.nodes[i].content = Content::Widget(spec);} else {self.children(i, div.children);@@ -1373,15 +1439,183 @@ impl<'a> Builder<'a> {_ if c.layout.display == Display::FlowRoot => Display::FlowRoot,_ => Display::Block,};+ if c.display == DisplayKind::Table {+ if let Some(tc) = self.table_cols.get(&i).filter(|t| t.fit && !t.widths.is_empty()) {+ // auto width: the table shrinks to its columns (up to its container)+ let sp = if c.border_collapse { 0.0 } else { c.border_spacing.0 };+ let w: f32 = tc.widths.iter().sum::<f32>() + sp * (tc.widths.len() + 1) as f32;+ let pad = |v: LengthPercentage| match v.into_raw() {+ r if r.tag() == taffy::CompactLength::LENGTH_TAG => r.value(),+ _ => 0.0,+ };+ let extra = pad(s.padding.left) + pad(s.padding.right) + pad(s.border.left) + pad(s.border.right);+ s.size.width = Dimension::length((w + extra).ceil());+ if s.max_size.width == LengthPercentageAuto::auto() {+ s.max_size.width = LengthPercentageAuto::percent(1.0);+ }+ }+ }if c.display == DisplayKind::TableCell && s.size.width == Dimension::auto() {- let span = self.attr(i, "colspan").and_then(|v| v.parse::<f32>().ok()).unwrap_or(1.0);- s.flex_grow = span;- s.flex_shrink = 1.0;- s.flex_basis = Dimension::percent(0.0);+ let span = self.attr(i, "colspan").and_then(|v| v.parse::<usize>().ok()).unwrap_or(1).max(1);+ match self.cell_columns(i, span) {+ // every cell of a column gets the column's width: rows line up+ Some((w, fit, fixed)) if w > 0.0 || fixed => {+ s.flex_basis = Dimension::length(w);+ s.flex_grow = if fit && !fixed { 0.0 } else { w.max(1.0) };+ s.flex_shrink = w.max(1.0);+ if fixed {+ s.min_size.width = LengthPercentageAuto::length(0.0); // fixed tables don't widen for content+ }+ }+ _ => {+ s.flex_grow = span as f32;+ s.flex_shrink = 1.0;+ s.flex_basis = Dimension::percent(0.0);+ }+ }}s}+ /// The rows of table `t` (in row groups or directly inside).+ fn table_rows(&self, t: usize) -> Vec<usize> {+ let mut rows = Vec::new();+ for k in kids(&self.nodes, t) {+ if !matches!(self.nodes[k].content, Content::Element) {+ continue;+ }+ match self.st(k).display {+ DisplayKind::TableRow => rows.push(k),+ DisplayKind::TableRowGroup => rows.extend(kids(&self.nodes, k)+ .filter(|&r| matches!(self.nodes[r].content, Content::Element)+ && self.st(r).display == DisplayKind::TableRow)),+ _ => {}+ }+ }+ rows+ }++ fn row_cells(&self, r: usize) -> Vec<usize> {+ kids(&self.nodes, r).filter(|&c| matches!(self.nodes[c].content, Content::Element | Content::Widget(_))+ && self.st(c).display == DisplayKind::TableCell).collect()+ }++ /// The single-line width of everything in box `k` (its text, in its fonts).+ fn max_content(&mut self, k: usize) -> f32 {+ let mut w = 0.0f32;+ let list: Vec<usize> = kids(&self.nodes, k).collect();+ for c in list {+ match &self.nodes[c].content {+ Content::Text(t) => {+ let st = &self.styles[self.nodes[c].style];+ let (size, flags) = (st.font_size, text::flags(st));+ let t = t.split_whitespace().collect::<Vec<_>>().join(" ");+ w += self.text.width(&t, size, flags) + st.letter_spacing * t.chars().count() as f32;+ }+ Content::Element => {+ let inner = self.max_content(c);+ let st = self.st(c);+ let u = self.units(st.font_size);+ let px = |v: LengthPercentage| match v.into_raw() {+ r if r.tag() == taffy::CompactLength::LENGTH_TAG => r.value(),+ _ => 0.0,+ };+ let edges = px(st.layout.padding.left) + px(st.layout.padding.right)+ + px(st.layout.border.left) + px(st.layout.border.right);+ let explicit = match st.layout.size.width.into_raw() {+ r if r.tag() == taffy::CompactLength::LENGTH_TAG => Some(r.value()),+ _ => None,+ };+ let _ = u;+ let own = explicit.unwrap_or(inner + edges);+ // blocks stack; inline content continues the line+ if st.display.is_inline_level() || st.display == DisplayKind::Inline {+ w += own;+ } else {+ w = w.max(own);+ }+ }+ _ => {}+ }+ }+ w+ }++ /// Column widths of table `t`: the widest single-line content of each+ /// column (auto layout), or the first row's cell widths (fixed).+ fn table_columns(&mut self, t: usize) {+ let fixed = self.st(t).table_fixed;+ let fit = self.st(t).layout.size.width == Dimension::auto();+ let mut widths: Vec<f32> = Vec::new();+ let rows = self.table_rows(t);+ for (ri, r) in rows.iter().enumerate() {+ if fixed && ri > 0 {+ break;+ }+ let mut col = 0usize;+ for c in self.row_cells(*r) {+ let span = self.attr(c, "colspan").and_then(|v| v.parse::<usize>().ok()).unwrap_or(1).max(1);+ let st = self.st(c);+ let px = |v: LengthPercentage| match v.into_raw() {+ r if r.tag() == taffy::CompactLength::LENGTH_TAG => r.value(),+ _ => 0.0,+ };+ let edges = px(st.layout.padding.left) + px(st.layout.padding.right)+ + px(st.layout.border.left) + px(st.layout.border.right);+ let explicit = match st.layout.size.width.into_raw() {+ r if r.tag() == taffy::CompactLength::LENGTH_TAG => Some(r.value()),+ _ => None,+ };+ let w = if fixed { explicit.unwrap_or(0.0) } else { explicit.unwrap_or(0.0).max(self.max_content(c) + edges) };+ if widths.len() < col + span {+ widths.resize(col + span, 0.0);+ }+ if span == 1 {+ widths[col] = widths[col].max(w.ceil());+ }+ col += span;+ }+ }+ if fixed {+ // unspecified columns share what the specified ones leave+ let given: f32 = widths.iter().sum();+ let free = widths.iter().filter(|w| **w == 0.0).count();+ if free > 0 {+ let total = match self.st(t).layout.size.width.into_raw() {+ r if r.tag() == taffy::CompactLength::LENGTH_TAG => r.value(),+ _ => self.viewport.0,+ };+ let each = ((total - given) / free as f32).max(0.0);+ widths.iter_mut().filter(|w| **w == 0.0).for_each(|w| *w = each);+ }+ }+ self.table_cols.insert(t, TableCols { widths, fit, fixed });+ }++ /// The width (px) of the columns cell `c` spans, and its table's mode.+ fn cell_columns(&self, c: usize, span: usize) -> Option<(f32, bool, bool)> {+ let row = self.nodes[c].parent?;+ let mut t = self.nodes[row].parent?;+ if self.st(t).display == DisplayKind::TableRowGroup {+ t = self.nodes[t].parent?;+ }+ let tc = self.table_cols.get(&t)?;+ let mut col = 0usize;+ for k in self.row_cells(row) {+ if k == c {+ break;+ }+ col += self.attr(k, "colspan").and_then(|v| v.parse::<usize>().ok()).unwrap_or(1).max(1);+ }+ let end = (col + span).min(tc.widths.len());+ if col >= end {+ return None;+ }+ let sp = self.st(t).border_spacing.0;+ let w = tc.widths[col..end].iter().sum::<f32>() + sp * (end - col - 1) as f32;+ Some((w, tc.fit, tc.fixed))+ }+/// Make line-container style: a wrapping flex row aligned per text-align.fn line_style(c: &Computed, mut s: Style) -> Style {s.display = Display::Flex;@@ -1450,10 +1684,14 @@ impl<'a> Builder<'a> {/// Replace the text of box `k` by its whitespace-processed, transformed form.fn transform_text(&mut self, k: usize, c: StyleId) {let (tt, ws, tab) = (self.styles[c].text_transform, self.styles[c].white_space, self.styles[c].tab_size);+ let (rtl, ovr) = (self.styles[c].layout.direction == taffy::style::Direction::Rtl, self.styles[c].bidi_override);if let Content::Text(t) = &self.nodes[k].content {- if let std::borrow::Cow::Owned(s) = transform(t, tt, ws, tab) {- self.nodes[k].content = Content::Text(s);- }+ let t = match transform(t, tt, ws, tab) {+ std::borrow::Cow::Owned(s) => s,+ std::borrow::Cow::Borrowed(s) => s.to_owned(),+ };+ let t = text::bidi_visual(&t, rtl, ovr).unwrap_or(t);+ self.nodes[k].content = Content::Text(t);}}@@ -1483,6 +1721,9 @@ impl<'a> Builder<'a> {}fn layout_node_inner(&mut self, i: usize) -> NodeId {+ if self.st(i).display == DisplayKind::Table {+ self.table_columns(i);+ }let mut base = self.base_style(i);if i == 0 {// the root fills the viewport@@ -1717,6 +1958,11 @@ impl<'a> Builder<'a> {std::borrow::Cow::Borrowed(_) => raw,std::borrow::Cow::Owned(s) => s,};+ // bidirectional text: laid out in visual order+ let (rtl, ovr) = (c.layout.direction == taffy::style::Direction::Rtl, c.bidi_override);+ if let Some(v) = text::bidi_visual(&text, rtl, ovr) {+ text = v;+ }if ws == WhiteSpace::NoWrap {text = collapse(&text);}@@ -1759,6 +2005,41 @@ impl<'a> Builder<'a> {}}}+ // overflow-wrap: a word wider than its block (as laid out last+ // frame) is cut where it has to be+ let anywhere = self.styles[sid].wrap_anywhere && !break_all+ && ws != WhiteSpace::NoWrap && ws != WhiteSpace::Pre;+ if anywhere {+ let mut blk = owner;+ while self.st(blk).display.is_inline_level() || self.st(blk).display == DisplayKind::Inline {+ match self.nodes[blk].parent {+ Some(p) => blk = p,+ None => break,+ }+ }+ let max = self.wrap_widths.get(&self.nodes[blk].key).copied().unwrap_or(self.viewport.0).max(1.0);+ let mut out: smallvec::SmallVec<[(usize, usize, bool, bool); 16]> = smallvec::SmallVec::new();+ for &(a, b, trailing, brk) in &pieces {+ let piece = &text[a..b];+ if self.text.width(piece, size, flags) <= max {+ out.push((a, b, trailing, brk));+ continue;+ }+ let mut start = a;+ let mut acc = String::new();+ for (o, ch) in piece.char_indices() {+ acc.push(ch);+ if self.text.width(&acc, size, flags) > max && acc.chars().count() > 1 {+ out.push((start, a + o, false, false));+ start = a + o;+ acc.clear();+ acc.push(ch);+ }+ }+ out.push((start, b, trailing, brk));+ }+ pieces = out;+ }if break_all && ws != WhiteSpace::NoWrap && ws != WhiteSpace::Pre {let mut chars: smallvec::SmallVec<[(usize, usize, bool, bool); 16]> = smallvec::SmallVec::new();for &(a, b, trailing, brk) in &pieces {@@ -1912,7 +2193,8 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, cacaches.matched.map.clear();caches.matched.author = caches.author.hash;}- let LayoutCaches { styles, text, images, author, taffy, box_of, acc, matched, recon, text_box, containers, .. } = caches;+ let LayoutCaches { styles, text, images, author, taffy, box_of, acc, matched, recon, text_box, containers,+ wrap_widths, anim, .. } = caches;let mut b = Builder {nodes,els,@@ -1924,6 +2206,7 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, carecon,text_box,containers,+ wrap_widths,changed: false,next_tpos: (1, 1),author: &author.sheet,@@ -1936,6 +2219,8 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, catitle,widgets,counters: Vec::new(),+ table_cols: FnvMap::default(),+ anim,};// the document: <html><body> unless the app built them itselflet root_div = match root {@@ -2219,6 +2504,12 @@ impl Frame {el_attr(&self.nodes, &self.els, i, name)}+ /// Element children of box `i`.+ pub(crate) fn children_of(&self, i: usize) -> impl Iterator<Item = usize> + '_ {+ kids(&self.nodes, i).filter(|&k| matches!(self.nodes[k].content, Content::Element | Content::Widget(_)+ | Content::Replaced(_)))+ }+/// Box `i` has no content (only collapsible whitespace): `empty-cells`.pub(crate) fn is_empty(&self, i: usize) -> bool {kids(&self.nodes, i).all(|k| match &self.nodes[k].content {diff --git a/bindings/rust/blenderui/src/lib.rs b/bindings/rust/blenderui/src/lib.rsindex 5fb0b98..b872eb5 100644--- a/bindings/rust/blenderui/src/lib.rs+++ b/bindings/rust/blenderui/src/lib.rs@@ -94,7 +94,10 @@ pub use blenderui_macros::rsx as view;/// `Option<T>` fields and `children`, and names missing required ones.pub use blenderui_macros::Props;+pub mod anim;pub mod calc;+pub mod components;+pub mod effects;pub mod color;mod color4;pub mod css;@@ -177,6 +180,9 @@ pub mod prelude {};pub use blenderui_macros::{component, Props};pub use crate::color::*;+ pub use crate::components::{+ Button, Checkbox, ColorSwatch, Dropdown, NumberField, NumberSlider, ProgressBar, Radio, TextArea, TextField,+ };pub use crate::element::*;pub use crate::events::*;pub use crate::geometry::{point, px, relative, rems, size, Bounds, Length, Pixels, Point, Rems, Size};diff --git a/bindings/rust/blenderui/src/paint.rs b/bindings/rust/blenderui/src/paint.rsindex 4f31cc4..fc1aac1 100644--- a/bindings/rust/blenderui/src/paint.rs+++ b/bindings/rust/blenderui/src/paint.rs@@ -7,7 +7,7 @@ use std::sync::Arc;use taffy::prelude::*;use crate::color::Rgba;-use crate::geometry::{rect, Bounds, Units};+use crate::geometry::{rect, Bounds, Length, Units};use crate::layout::{BoxNode, Content, Frame, Replaced, StyleStore};use crate::style::{BorderStyle, BoxEdge, Computed, DecoStyle, DisplayKind, TextAlign, WhiteSpace};use crate::text::{self, TextCache};@@ -248,82 +248,79 @@ impl Painter {self.clip = saved;}- /// Replace the canvas display list with these items, scaled to device pixels.- pub(crate) fn flush(&self, canvas: *mut sys::BKNode, scale: f32) {- let mut heap: Vec<f32> = Vec::new();- let mut count: i32 = 0;- for it in &self.items {- let src = it.coords.as_slice();- let mut inline = [0.0f32; 4];- let coords: &mut [f32] = if src.len() <= 4 {- for (d, s) in inline.iter_mut().zip(src) {- *d = s * scale;- }- &mut inline[..src.len()]- } else {- heap.clear();- heap.extend(src.iter().map(|v| v * scale));- &mut heap[..]- };- let mut ncoords = coords.len();- let mut ci = sys::BKCanvasItem { fill: it.fill.to_array(), ..Default::default() };- let mut _keep_px = None;- match &it.kind {- Kind::Rect { radius, outline, width } => {- ci.type_ = if *radius > 0.0 { sys::BK_ITEM_ROUNDRECT } else { sys::BK_ITEM_RECT };- ci.radius = radius * scale;- if *width > 0.0 {- ci.outline = outline.to_array();- ci.width = (width * scale).max(1.0);- }- }- Kind::Oval { outline, width } => {- ci.type_ = sys::BK_ITEM_OVAL;- if *width > 0.0 {- ci.outline = outline.to_array();- ci.width = (width * scale).max(1.0);- }- }- Kind::Line { width } => {- ci.type_ = sys::BK_ITEM_LINE;+ /// The kit item for `it`, scaled to device pixels; its coordinates go+ /// into `coords` (point `ci.coords` at them once filled) and image+ /// pixels into `keep`. None: nothing to draw.+ fn build_item(&self, it: &Item, scale: f32, coords: &mut Vec<f32>, keep: &mut Option<Vec<u8>>)+ -> Option<sys::BKCanvasItem> {+ coords.clear();+ coords.extend(it.coords.as_slice().iter().map(|v| v * scale));+ let mut ci = sys::BKCanvasItem { fill: it.fill.to_array(), ..Default::default() };+ match &it.kind {+ Kind::Rect { radius, outline, width } => {+ ci.type_ = if *radius > 0.0 { sys::BK_ITEM_ROUNDRECT } else { sys::BK_ITEM_RECT };+ ci.radius = radius * scale;+ if *width > 0.0 {+ ci.outline = outline.to_array();ci.width = (width * scale).max(1.0);}- Kind::Polygon => ci.type_ = sys::BK_ITEM_POLYGON,- Kind::Arc { start, extent } => {- ci.type_ = sys::BK_ITEM_ARC;- ci.start = *start;- ci.extent = *extent;- }- Kind::Text { start, size, flags } => {- ci.type_ = sys::BK_ITEM_TEXT;- ci.size = size * scale;- (ci.family, ci.text_flags) = crate::text::family(*flags);- ci.anchor = sys::BK_ANCHOR_N | sys::BK_ANCHOR_W;- ci.text = self.text[*start as usize..].as_ptr().cast();- }- Kind::Image(img) => {- let w = (coords[2] - coords[0]).round().max(1.0) as u32;- let h = (coords[3] - coords[1]).round().max(1.0) as u32;- if img.width == 0 || img.height == 0 {- continue;- }- let px = img.resized(w, h);- ci.type_ = sys::BK_ITEM_IMAGE;- ci.anchor = sys::BK_ANCHOR_N | sys::BK_ANCHOR_W;- ci.rgba = px.as_ptr();- ci.iw = w as i32;- ci.ih = h as i32;- ncoords = 2;- _keep_px = Some(px);+ }+ Kind::Oval { outline, width } => {+ ci.type_ = sys::BK_ITEM_OVAL;+ if *width > 0.0 {+ ci.outline = outline.to_array();+ ci.width = (width * scale).max(1.0);}}- 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];+ Kind::Line { width } => {+ ci.type_ = sys::BK_ITEM_LINE;+ ci.width = (width * scale).max(1.0);}+ Kind::Polygon => ci.type_ = sys::BK_ITEM_POLYGON,+ Kind::Arc { start, extent } => {+ ci.type_ = sys::BK_ITEM_ARC;+ ci.start = *start;+ ci.extent = *extent;+ }+ Kind::Text { start, size, flags } => {+ ci.type_ = sys::BK_ITEM_TEXT;+ ci.size = size * scale;+ (ci.family, ci.text_flags) = crate::text::family(*flags);+ ci.anchor = sys::BK_ANCHOR_N | sys::BK_ANCHOR_W;+ ci.text = self.text[*start as usize..].as_ptr().cast();+ }+ Kind::Image(img) => {+ let w = (coords[2] - coords[0]).round().max(1.0) as u32;+ let h = (coords[3] - coords[1]).round().max(1.0) as u32;+ if img.width == 0 || img.height == 0 {+ return None;+ }+ let px = img.resized(w, h);+ ci.type_ = sys::BK_ITEM_IMAGE;+ ci.anchor = sys::BK_ANCHOR_N | sys::BK_ANCHOR_W;+ ci.rgba = px.as_ptr();+ ci.iw = w as i32;+ ci.ih = h as i32;+ coords.truncate(2);+ *keep = Some(px);+ }+ }+ 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];+ }+ ci.ncoords = coords.len() as i32;+ Some(ci)+ }++ /// Replace the canvas display list with these items, scaled to device pixels.+ pub(crate) fn flush(&self, canvas: *mut sys::BKNode, scale: f32) {+ let mut coords: Vec<f32> = Vec::new();+ let mut count: i32 = 0;+ for it in &self.items {+ let mut keep = None;+ let Some(mut ci) = self.build_item(it, scale, &mut coords, &mut keep) else { continue };ci.coords = coords.as_ptr();- ci.ncoords = ncoords as i32;// SAFETY: every pointer in `ci` outlives the call; the kit copies// them into the slot's existing buffers.unsafe { sys::BK_canvas_put_item(canvas, count, &ci) };@@ -332,6 +329,66 @@ impl Painter {// SAFETY: `canvas` is a live kit canvas node owned by the window.unsafe { sys::BK_canvas_truncate(canvas, count) };}++ /// Draw the items offscreen into a `w` x `h` device-pixel region whose+ /// top left is (`x0`, `y0`) (CSS effects).+ pub(crate) fn rasterize(&self, scale: f32, x0: f32, y0: f32, w: usize, h: usize)+ -> Option<crate::effects::Pixels> {+ if w == 0 || h == 0 || w > 8192 || h > 8192 {+ return None;+ }+ let mut coords: Vec<Vec<f32>> = Vec::with_capacity(self.items.len());+ let mut keep: Vec<Option<Vec<u8>>> = Vec::with_capacity(self.items.len());+ let mut items: Vec<sys::BKCanvasItem> = Vec::with_capacity(self.items.len());+ for it in &self.items {+ let (mut c, mut k) = (Vec::new(), None);+ if let Some(ci) = self.build_item(it, scale, &mut c, &mut k) {+ items.push(ci);+ coords.push(c);+ keep.push(k);+ }+ }+ for (ci, c) in items.iter_mut().zip(&coords) {+ ci.coords = c.as_ptr();+ }+ let mut rgba = vec![0u8; w * h * 4];+ // SAFETY: `items` point into `coords`, `keep` and `self.text`, all alive here.+ let ok = unsafe {+ sys::BK_canvas_rasterize(items.as_ptr(), items.len() as i32, x0, y0, w as i32, h as i32,+ rgba.as_mut_ptr())+ };+ drop(keep);+ (ok != 0).then(|| crate::effects::Pixels::from_rgba8(w, h, &rgba))+ }++ /// A hash of everything drawn (layer caching).+ fn content_hash(&self, h: &mut impl std::hash::Hasher) {+ use std::hash::Hash;+ for it in &self.items {+ for v in it.coords.as_slice() {+ v.to_bits().hash(h);+ }+ it.fill.to_array().map(f32::to_bits).hash(h);+ match &it.kind {+ Kind::Rect { radius, outline, width } => {+ (0u8, radius.to_bits(), outline.to_array().map(f32::to_bits), width.to_bits()).hash(h)+ }+ Kind::Oval { outline, width } => (1u8, outline.to_array().map(f32::to_bits), width.to_bits()).hash(h),+ Kind::Line { width } => (2u8, width.to_bits()).hash(h),+ Kind::Polygon => 3u8.hash(h),+ Kind::Arc { start, extent } => (4u8, start.to_bits(), extent.to_bits()).hash(h),+ Kind::Text { start, size, flags } => {+ let t = &self.text[*start as usize..];+ let end = t.iter().position(|&b| b == 0).unwrap_or(t.len());+ (5u8, &t[..end], size.to_bits(), flags).hash(h)+ }+ Kind::Image(img) => (6u8, Arc::as_ptr(img) as usize).hash(h),+ }+ if let Some(c) = it.clip {+ (c.origin.x.to_bits(), c.origin.y.to_bits(), c.size.width.to_bits(), c.size.height.to_bits()).hash(h);+ }+ }+ }}// ==========================================================================@@ -359,24 +416,370 @@ fn radius_px(c: &Computed, b: Bounds<f32>, vp: (f32, f32)) -> f32 {c.radius.iter().map(|r| r.resolve(&u, m)).fold(0.0, f32::max).min(m / 2.0)}-/// Paint every box of `frame`, in stacking order.+/// Paint every box of `frame`, in stacking order. `scale`: device pixels+/// per logical pixel (for elements whose effects work on pixels).pub(crate) fn paint_frame(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, p: &mut Painter,- vp: (f32, f32)) {+ vp: (f32, f32), scale: f32) {let mut order: Vec<usize> = (0..frame.nodes.len()).collect();if frame.nodes.iter().any(|n| styles[n.style].z_index.is_some()) {order.sort_by_key(|&i| frame.z_of(i, styles)); // stable: tree order within a level}- for i in order {- let n = &frame.nodes[i];+ let has_effects = frame.nodes.iter().any(|n| styles[n.style].effects.is_some());+ if !has_effects {+ for i in order {+ let n = &frame.nodes[i];+ if !n.visible || n.opacity <= 0.0 {+ continue;+ }+ p.opacity = n.opacity;+ p.clip = n.clip;+ paint_node(frame, styles, tc, i, p, vp);+ }+ } else {+ let mut cx = LayerCx { frame, styles, tc, vp, scale, done: vec![false; frame.nodes.len()] };+ paint_list(&mut cx, &order, p, None, 1.0);+ LAYERS.with(|l| l.borrow_mut().end_frame());+ }+ p.opacity = 1.0;+ p.clip = None;+}++struct LayerCx<'a> {+ frame: &'a Frame,+ styles: &'a StyleStore,+ tc: &'a mut TextCache,+ vp: (f32, f32),+ scale: f32,+ done: Vec<bool>,+}++/// Rendered layers by content hash, kept while they're used (frames that+/// don't change reuse them: no rasterizing, no filtering).+#[derive(Default)]+struct LayerCache {+ map: HashMap<u64, (Arc<Image>, Bounds<f32>, bool)>,+}++impl LayerCache {+ fn get(&mut self, k: u64) -> Option<(Arc<Image>, Bounds<f32>)> {+ self.map.get_mut(&k).map(|e| {+ e.2 = true;+ (e.0.clone(), e.1)+ })+ }+ fn put(&mut self, k: u64, img: Arc<Image>, b: Bounds<f32>) {+ self.map.insert(k, (img, b, true));+ }+ fn end_frame(&mut self) {+ self.map.retain(|_, e| std::mem::replace(&mut e.2, false));+ }+}++thread_local! {+ static LAYERS: std::cell::RefCell<LayerCache> = std::cell::RefCell::new(LayerCache::default());+}++fn is_inside(frame: &Frame, mut k: usize, root: usize) -> bool {+ loop {+ if k == root {+ return true;+ }+ match frame.nodes[k].parent {+ Some(p) => k = p,+ None => return false,+ }+ }+}++/// Paint `list` (in stacking order) into `p`; elements whose effects need+/// pixels are painted with their subtree into a layer. `root`: the layer+/// being painted (its own effects were applied by the caller); `base`: its+/// opacity (descendants paint relative to it: the layer takes it as a group).+fn paint_list(cx: &mut LayerCx, list: &[usize], p: &mut Painter, root: Option<usize>, base: f32) {+ for (idx, &i) in list.iter().enumerate() {+ if cx.done[i] {+ continue;+ }+ let n = &cx.frame.nodes[i];if !n.visible || n.opacity <= 0.0 {continue;}- p.opacity = n.opacity;+ let fx = cx.styles[n.style].effects.as_deref();+ if fx.is_some_and(|e| !e.backdrop.is_empty()) && Some(i) != root {+ paint_backdrop(cx, i, p);+ }+ if fx.is_some_and(|e| e.needs_layer()) && Some(i) != root {+ let sub: Vec<usize> = list[idx..].iter().copied()+ .filter(|&k| !cx.done[k] && is_inside(cx.frame, k, i)).collect();+ // the layer's own pass paints these; mark them after+ paint_layer(cx, i, &sub, p, base);+ for &k in &sub {+ cx.done[k] = true;+ }+ continue;+ }+ cx.done[i] = true;+ p.opacity = (n.opacity / base.max(1e-6)).min(1.0);+ p.clip = n.clip;+ let (frame, styles, vp) = (cx.frame, cx.styles, cx.vp);+ paint_node(frame, styles, cx.tc, i, p, vp);+ }+}++/// The logical-pixel area a layer's content can cover: its boxes, their+/// outlines and shadows, and how far its filters spread.+fn layer_area(cx: &LayerCx, list: &[usize], fx: &crate::effects::Effects) -> Bounds<f32> {+ let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);+ for &k in list {+ let n = &cx.frame.nodes[k];+ let c = &cx.styles[n.style];+ let mut grow = c.outline.0 + c.outline.2.max(0.0);+ for sh in c.shadows.iter().filter(|s| !s.inset) {+ grow = grow.max(sh.x.abs().max(sh.y.abs()) + sh.blur + sh.spread.max(0.0));+ }+ if let Some(bi) = c.effects.as_ref().and_then(|e| e.border_image.as_ref()) {+ for o in bi.outset {+ if let crate::effects::Side::Len(Length::Px(v)) = o {+ grow = grow.max(v);+ }+ }+ }+ let b = n.bounds;+ x0 = x0.min(b.origin.x - grow);+ y0 = y0.min(b.origin.y - grow);+ x1 = x1.max(b.origin.x + b.size.width + grow);+ y1 = y1.max(b.origin.y + b.size.height + grow);+ }+ let g = crate::effects::filter_outset(&fx.filter);+ rect(x0 - g, y0 - g, (x1 - x0 + 2.0 * g).max(0.0), (y1 - y0 + 2.0 * g).max(0.0))+}++/// Device-pixel rectangle covering `b`: (x0, y0, w, h).+fn device_rect(b: Bounds<f32>, scale: f32) -> (f32, f32, usize, usize) {+ let x0 = (b.origin.x * scale).floor();+ let y0 = (b.origin.y * scale).floor();+ let x1 = ((b.origin.x + b.size.width) * scale).ceil();+ let y1 = ((b.origin.y + b.size.height) * scale).ceil();+ (x0, y0, (x1 - x0).max(0.0) as usize, (y1 - y0).max(0.0) as usize)+}++/// Paint element `root` and its subtree `list` through its effects.+fn paint_layer(cx: &mut LayerCx, root: usize, list: &[usize], p: &mut Painter, base: f32) {+ use crate::effects as fx;+ use std::hash::{Hash, Hasher};+ let n = &cx.frame.nodes[root];+ let c = &cx.styles[n.style];+ let Some(e) = c.effects.as_deref().cloned() else { return };+ let rel_opacity = (n.opacity / base.max(1e-6)).min(1.0);+ // the content, painted at full opacity relative to the root+ let mut sub = Painter::new();+ paint_list(cx, list, &mut sub, Some(root), n.opacity);+ let n = &cx.frame.nodes[root];+ let c = &cx.styles[n.style];+ let screen = rect(-cx.vp.0, -cx.vp.1, cx.vp.0 * 3.0, cx.vp.1 * 3.0);+ let area = layer_area(cx, list, &e).intersect(&screen);+ let (x0, y0, w, h) = device_rect(area, cx.scale);+ if w == 0 || h == 0 {+ return;+ }+ let b = n.bounds;+ let u = Units { font_size: c.font_size, viewport: cx.vp };+ // the transform, in device pixels about transform-origin+ let mut m = fx::IDENTITY;+ if e.rotate != 0.0 {+ m = fx::mul(&m, &[e.rotate.cos(), e.rotate.sin(), -e.rotate.sin(), e.rotate.cos(), 0.0, 0.0]);+ }+ if let Some((sx, sy)) = e.scale2 {+ m = fx::mul(&m, &[sx, 0.0, 0.0, sy, 0.0, 0.0]);+ }+ if !e.transform.is_empty() {+ m = fx::mul(&m, &fx::matrix_of(&e.transform, b.size.width, b.size.height, &u));+ }+ let transformed = m != fx::IDENTITY;+ let origin = e.origin.unwrap_or([crate::style::Pos::CENTER; 2]);+ let (ox, oy) = ((b.origin.x + origin[0].at(b.size.width)) * cx.scale,+ (b.origin.y + origin[1].at(b.size.height)) * cx.scale);+ let m_dev = {+ let lin = [m[0], m[1], m[2], m[3], m[4] * cx.scale, m[5] * cx.scale];+ fx::mul(&fx::mul(&[1.0, 0.0, 0.0, 1.0, ox, oy], &lin), &[1.0, 0.0, 0.0, 1.0, -ox, -oy])+ };+ let key = {+ let mut hh = Fnv64::default();+ sub.content_hash(&mut hh);+ format!("{e:?}").hash(&mut hh);+ (x0.to_bits(), y0.to_bits(), w, h, cx.scale.to_bits(), rel_opacity.to_bits(),+ b.origin.x.to_bits(), b.origin.y.to_bits(), b.size.width.to_bits(), b.size.height.to_bits()).hash(&mut hh);+ hh.finish()+ };+ let blend = e.blend;+ let emit = |p: &mut Painter, img: Arc<Image>, at: Bounds<f32>| {+ p.opacity = 1.0;p.clip = n.clip;- paint_node(frame, styles, tc, i, p, vp);+ p.image(at, &img);+ };+ if blend == fx::Blend::Normal {+ if let Some((img, at)) = LAYERS.with(|l| l.borrow_mut().get(key)) {+ emit(p, img, at);+ return;+ }+ }+ let Some(mut px) = sub.rasterize(cx.scale, x0, y0, w, h) else { return };+ for f in &e.filter {+ fx::apply_filter(&mut px, f, cx.scale);+ }+ if let Some((shape, edge)) = &e.clip_path {+ let mut mp = Painter::new();+ clip_shape(&mut mp, shape, *edge, c, b, &u);+ if let Some(mask) = mp.rasterize(cx.scale, x0, y0, w, h) {+ fx::apply_mask(&mut px, &mask, false);+ }+ }+ if let Some(mask) = e.mask.as_ref().filter(|m| m.image.is_some()) {+ let mut mp = Painter::new();+ paint_source(&mut mp, mask.image.as_ref().unwrap(), b, Some(mask), cx.vp);+ if let Some(mk) = mp.rasterize(cx.scale, x0, y0, w, h) {+ fx::apply_mask(&mut px, &mk, mask.luminance);+ }+ }+ if rel_opacity < 1.0 {+ px.px.iter_mut().for_each(|q| q.iter_mut().for_each(|v| *v *= rel_opacity));+ }+ let (mut px, (mut tx, mut ty)) = (px, (x0, y0));+ if transformed {+ match fx::transform(&px, (x0, y0), &m_dev) {+ Some((out, at)) => {+ px = out;+ (tx, ty) = at;+ }+ None => return, // a degenerate matrix draws nothing+ }+ }+ if blend != fx::Blend::Normal {+ if let Some(back) = p.rasterize(cx.scale, tx, ty, px.w, px.h) {+ px = fx::composite(&back, &px, blend);+ }+ }+ let img = Arc::new(Image { width: px.w as u32, height: px.h as u32, rgba: px.to_rgba8() });+ let at = rect(tx / cx.scale, ty / cx.scale, px.w as f32 / cx.scale, px.h as f32 / cx.scale);+ if blend == fx::Blend::Normal {+ LAYERS.with(|l| l.borrow_mut().put(key, img.clone(), at));}+ emit(p, img, at);+}++/// `backdrop-filter`: what's already painted under the element's border+/// box, filtered and clipped to its rounded box.+fn paint_backdrop(cx: &mut LayerCx, i: usize, p: &mut Painter) {+ use crate::effects as fx;+ let n = &cx.frame.nodes[i];+ let c = &cx.styles[n.style];+ let Some(e) = c.effects.as_deref() else { return };+ let b = n.bounds;+ let g = fx::filter_outset(&e.backdrop);+ let grown = rect(b.origin.x - g, b.origin.y - g, b.size.width + 2.0 * g, b.size.height + 2.0 * g);+ let (x0, y0, w, h) = device_rect(grown, cx.scale);+ let Some(mut px) = p.rasterize(cx.scale, x0, y0, w, h) else { return };+ for f in &e.backdrop {+ fx::apply_filter(&mut px, f, cx.scale);+ }+ let mut mp = Painter::new();+ mp.quad(b, radius_px(c, b, cx.vp), Rgba { r: 1.0, g: 1.0, b: 1.0, a: 1.0 }, Rgba::TRANSPARENT, 0.0);+ if let Some(mask) = mp.rasterize(cx.scale, x0, y0, w, h) {+ fx::apply_mask(&mut px, &mask, false);+ }+ let img = Arc::new(Image { width: w as u32, height: h as u32, rgba: px.to_rgba8() });p.opacity = 1.0;- p.clip = None;+ p.clip = n.clip;+ p.image(rect(x0 / cx.scale, y0 / cx.scale, w as f32 / cx.scale, h as f32 / cx.scale), &img);+}++/// The coverage of a `clip-path` shape, painted white.+fn clip_shape(p: &mut Painter, shape: &crate::effects::ClipShape, edge: crate::style::BoxEdge, c: &Computed,+ b: Bounds<f32>, u: &Units) {+ use crate::effects::{ClipShape as S, ShapeRadius as R};+ let white = Rgba { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };+ let bw = border_widths(c, b.size.width);+ let rb = match edge {+ crate::style::BoxEdge::Border => b,+ crate::style::BoxEdge::Padding => rect(b.origin.x + bw[3], b.origin.y + bw[0],+ (b.size.width - bw[1] - bw[3]).max(0.0),+ (b.size.height - bw[0] - bw[2]).max(0.0)),+ crate::style::BoxEdge::Content => content_box(c, b),+ };+ let (x, y, w, h) = (rb.origin.x, rb.origin.y, rb.size.width, rb.size.height);+ let radius = |r: &R, cx: f32, cy: f32, horizontal: Option<bool>| -> f32 {+ let (dx, dy) = (cx.min(w - cx), cy.min(h - cy));+ let (fx_, fy) = (cx.max(w - cx), cy.max(h - cy));+ match (r, horizontal) {+ (R::Len(l), Some(true)) => l.resolve(u, w),+ (R::Len(l), Some(false)) => l.resolve(u, h),+ // circle: percentages of the box's normalised diagonal+ (R::Len(l), None) => l.resolve(u, (w * w + h * h).sqrt() / std::f32::consts::SQRT_2),+ (R::Closest, Some(true)) => dx,+ (R::Closest, Some(false)) => dy,+ (R::Closest, None) => dx.min(dy),+ (R::Farthest, Some(true)) => fx_,+ (R::Farthest, Some(false)) => fy,+ (R::Farthest, None) => fx_.max(fy),+ }+ };+ match shape {+ S::Box => p.fill(rb, white),+ S::Inset(s, r) => {+ let (t, rr, bb, l) = (s[0].resolve(u, h), s[1].resolve(u, w), s[2].resolve(u, h), s[3].resolve(u, w));+ let ib = rect(x + l, y + t, (w - l - rr).max(0.0), (h - t - bb).max(0.0));+ p.quad(ib, r.resolve(u, ib.size.width.min(ib.size.height)), white, Rgba::TRANSPARENT, 0.0);+ }+ S::Circle(r, at) => {+ let (cx_, cy) = (at[0].at(w), at[1].at(h));+ let rad = radius(r, cx_, cy, None);+ p.oval(rect(x + cx_ - rad, y + cy - rad, 2.0 * rad, 2.0 * rad), white, Rgba::TRANSPARENT, 0.0);+ }+ S::Ellipse(rx, ry, at) => {+ let (cx_, cy) = (at[0].at(w), at[1].at(h));+ let (a, bb) = (radius(rx, cx_, cy, Some(true)), radius(ry, cx_, cy, Some(false)));+ p.oval(rect(x + cx_ - a, y + cy - bb, 2.0 * a, 2.0 * bb), white, Rgba::TRANSPARENT, 0.0);+ }+ S::Polygon(pts) => {+ let pts: Vec<(f32, f32)> = pts.iter().map(|(px_, py)| (x + px_.resolve(u, w), y + py.resolve(u, h))).collect();+ p.polygon(&pts, white);+ }+ }+}++/// A mask or border-image source painted over `area` (sized, positioned and+/// tiled like a background when `mask` gives the placement).+fn paint_source(p: &mut Painter, src: &crate::effects::ImageSource, area: Bounds<f32>,+ mask: Option<&crate::effects::Mask>, _vp: (f32, f32)) {+ match src {+ crate::effects::ImageSource::Gradient(g) => p.with_clip(area, |p| paint_gradient(p, g, area)),+ crate::effects::ImageSource::Url(u) => {+ let mut st = crate::style::ImageStyle { bg_url: Some(u.clone()), ..Default::default() };+ if let Some(m) = mask {+ st.bg_size = m.size;+ st.bg_position = m.position;+ st.bg_repeat = m.repeat;+ }+ paint_background_image(p, &st, area, area);+ }+ }+}++/// FNV-1a for layer keys.+#[derive(Default)]+struct Fnv64(u64);++impl std::hash::Hasher for Fnv64 {+ fn finish(&self) -> u64 {+ self.0+ }+ fn write(&mut self, bytes: &[u8]) {+ let mut h = if self.0 == 0 { 0xcbf29ce484222325 } else { self.0 };+ for b in bytes {+ h = (h ^ *b as u64).wrapping_mul(0x100000001b3);+ }+ self.0 = h;+ }}/// A background that repaints exactly the pixels already under it: an opaque@@ -633,7 +1036,12 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_balet uniform = visible.len() == 4 && bw.iter().all(|w| *w == bw[0])&& c.border_color.iter().all(|x| *x == c.border_color[0]);let styled = visible.iter().any(|&k| c.border_style[k] != BorderStyle::Solid);- if styled {+ 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 });+ } 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 {let styles: [BorderStyle; 4] = std::array::from_fn(|k| c.border_style[k]);let widths: [f32; 4] = std::array::from_fn(|k| if visible.contains(&k) { bw[k] } else { 0.0 });paint_edges(p, b, widths, c.border_color, styles);@@ -665,6 +1073,275 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba}}+/// Blender's rounded-box corner tessellation (`cornervec`,+/// interface_widgets.cc): 9 points from the start of a quarter circle to its+/// end, as fractions of the radius.+const CORNERVEC: [[f32; 2]; 9] = [+ [0.0, 0.0], [0.195, 0.02], [0.383, 0.067], [0.55, 0.169], [0.707, 0.293], [0.831, 0.45], [0.924, 0.617],+ [0.98, 0.805], [1.0, 1.0],+];++/// A closed rounded rectangle outline as points (clockwise from the top+/// edge's start), with each point's outward normal direction: 0 top,+/// 1 right, 2 bottom, 3 left (corners split at their middle).+fn rounded_path(b: Bounds<f32>, r: f32) -> Vec<(f32, f32, usize)> {+ let (x0, y0, x1, y1) = (b.origin.x, b.origin.y, b.origin.x + b.size.width, b.origin.y + b.size.height);+ let r = r.min(b.size.width / 2.0).min(b.size.height / 2.0).max(0.0);+ let mut pts = Vec::with_capacity(40);+ // top-right, bottom-right, bottom-left, top-left corners, like Blender's round_box edges+ for (k, v) in CORNERVEC.iter().enumerate() {+ pts.push((x1 - r + v[0] * r, y0 + r - (1.0 - v[1]) * r, if k < 5 { 0 } else { 1 }));+ }+ for (k, v) in CORNERVEC.iter().enumerate() {+ pts.push((x1 - r + (1.0 - v[1]) * r, y1 - r + v[0] * r, if k < 5 { 1 } else { 2 }));+ }+ for (k, v) in CORNERVEC.iter().enumerate() {+ pts.push((x0 + r - v[0] * r, y1 - r + (1.0 - v[1]) * r, if k < 5 { 2 } else { 3 }));+ }+ for (k, v) in CORNERVEC.iter().enumerate() {+ pts.push((x0 + r - (1.0 - v[1]) * r, y0 + r - v[0] * r, if k < 5 { 3 } else { 0 }));+ }+ pts+}++/// Non-solid uniform borders on a rounded box: dashes and dots follow the+/// curve, `double` is two rounded lines, and groove / ridge / inset / outset+/// shade each side's part of the path.+fn paint_rounded_styled(p: &mut Painter, b: Bounds<f32>, r: f32, w: f32, col: Rgba, style: BorderStyle) {+ let inset = |d: f32| rect(b.origin.x + d, b.origin.y + d, (b.size.width - 2.0 * d).max(0.0),+ (b.size.height - 2.0 * d).max(0.0));+ match style {+ BorderStyle::Double if w >= 3.0 => {+ let t = w / 3.0;+ p.quad(inset(t / 2.0), (r - t / 2.0).max(0.0), Rgba::TRANSPARENT, col, t);+ p.quad(inset(w - t / 2.0), (r - w + t / 2.0).max(0.0), Rgba::TRANSPARENT, col, t);+ }+ BorderStyle::Dashed | BorderStyle::Dotted => {+ let mut path = rounded_path(inset(w / 2.0), (r - w / 2.0).max(0.0));+ path.push(path[0]);+ let total: f32 = path.windows(2).map(|q| ((q[1].0 - q[0].0).powi(2) + (q[1].1 - q[0].1).powi(2)).sqrt()).sum();+ let dotted = style == BorderStyle::Dotted;+ let (on, gap) = if dotted { (w, w) } else { (w * 3.0, w * 3.0) };+ let n = ((total / (on + gap)).floor()).max(1.0);+ let period = total / n; // an even number of segments around the box+ let on = on.min(period);+ // walk the path, emitting [start, start + on) of every period+ let point_at = |d: f32| -> (f32, f32) {+ let mut acc = 0.0;+ for q in path.windows(2) {+ let len = ((q[1].0 - q[0].0).powi(2) + (q[1].1 - q[0].1).powi(2)).sqrt();+ if acc + len >= d && len > 0.0 {+ let t = (d - acc) / len;+ return (q[0].0 + (q[1].0 - q[0].0) * t, q[0].1 + (q[1].1 - q[0].1) * t);+ }+ acc += len;+ }+ (path[0].0, path[0].1)+ };+ for k in 0..n as usize {+ let start = k as f32 * period;+ if dotted {+ let (cx, cy) = point_at(start + on / 2.0);+ p.oval(rect(cx - w / 2.0, cy - w / 2.0, w, w), col, Rgba::TRANSPARENT, 0.0);+ } else {+ let steps = 6;+ let pts: Vec<(f32, f32)> = (0..=steps).map(|j| point_at(start + on * j as f32 / steps as f32)).collect();+ p.line(&pts, col, w);+ }+ }+ }+ _ => {+ // shaded styles: the path in two halves of the width, coloured per side+ let dark = shade(col, 0.5);+ let side_col = |side: usize, outer: bool| -> Rgba {+ let lit = side == 0 || side == 3;+ match style {+ BorderStyle::Inset => if lit { dark } else { col },+ BorderStyle::Outset => if lit { col } else { dark },+ BorderStyle::Groove => if lit == outer { dark } else { col },+ BorderStyle::Ridge => if lit == outer { col } else { dark },+ _ => col,+ }+ };+ let halves: &[(f32, bool)] = if matches!(style, BorderStyle::Groove | BorderStyle::Ridge) {+ &[(w / 4.0, true), (w * 3.0 / 4.0, false)]+ } else {+ &[(w / 2.0, true)]+ };+ let lw = if halves.len() == 2 { w / 2.0 } else { w };+ for &(d, outer) in halves {+ let mut path = rounded_path(inset(d), (r - d).max(0.0));+ path.push(path[0]);+ for q in path.windows(2) {+ p.line(&[(q[0].0, q[0].1), (q[1].0, q[1].1)], side_col(q[0].2, outer), lw);+ }+ }+ }+ }+}++/// Border-image source pixels, cached per source and size.+fn border_image_source(src: &crate::effects::ImageSource, w: f32, h: f32) -> Option<Arc<Image>> {+ match src {+ crate::effects::ImageSource::Url(u) => background_file(u),+ crate::effects::ImageSource::Gradient(g) => {+ thread_local! {+ static GRADIENTS: std::cell::RefCell<HashMap<String, Arc<Image>>> =+ std::cell::RefCell::new(HashMap::new());+ }+ let (iw, ih) = (w.ceil().max(1.0) as usize, h.ceil().max(1.0) as usize);+ let key = format!("{g:?}{iw}x{ih}");+ if let Some(i) = GRADIENTS.with(|m| m.borrow().get(&key).cloned()) {+ return Some(i);+ }+ let mut gp = Painter::new();+ let area = rect(0.0, 0.0, iw as f32, ih as f32);+ gp.with_clip(area, |gp| paint_gradient(gp, g, area));+ let px = gp.rasterize(1.0, 0.0, 0.0, iw, ih)?;+ let img = Arc::new(Image { width: iw as u32, height: ih as u32, rgba: px.to_rgba8() });+ GRADIENTS.with(|m| {+ let mut m = m.borrow_mut();+ if m.len() > 64 {+ m.clear();+ }+ m.insert(key, img.clone());+ });+ Some(img)+ }+ }+}++/// A sub-rectangle of an image (whole pixels), cached.+fn crop(img: &Arc<Image>, x: u32, y: u32, w: u32, h: u32) -> Option<Arc<Image>> {+ if w == 0 || h == 0 || x + w > img.width || y + h > img.height {+ return None;+ }+ thread_local! {+ static CROPS: std::cell::RefCell<HashMap<(usize, [u32; 4]), Arc<Image>>> =+ std::cell::RefCell::new(HashMap::new());+ }+ let key = (Arc::as_ptr(img) as usize, [x, y, w, h]);+ if let Some(c) = CROPS.with(|m| m.borrow().get(&key).cloned()) {+ return Some(c);+ }+ let mut rgba = Vec::with_capacity((w * h * 4) as usize);+ for row in y..y + h {+ let s = ((row * img.width + x) * 4) as usize;+ rgba.extend_from_slice(&img.rgba[s..s + (w * 4) as usize]);+ }+ let c = Arc::new(Image { width: w, height: h, rgba });+ CROPS.with(|m| {+ let mut m = m.borrow_mut();+ if m.len() > 512 {+ m.clear();+ }+ m.insert(key, c.clone());+ });+ Some(c)+}++/// `border-image`: the source cut into nine parts by `slice`; corners go in+/// the corners of the border-image area, edges are stretched or tiled along+/// the sides, and the middle is drawn with `fill`.+fn paint_border_image(p: &mut Painter, bi: &crate::effects::BorderImage, b: Bounds<f32>, bw: &[f32; 4], u: &Units) {+ use crate::effects::{Side, Tile};+ let resolve = |v: Side, k: usize, basis: f32| -> f32 {+ match v {+ Side::Num(n) => n * bw[k],+ Side::Len(l) => l.resolve(u, basis),+ Side::Auto => bw[k],+ }+ };+ let out: [f32; 4] = std::array::from_fn(|k| resolve(bi.outset[k], k, 0.0));+ let area = rect(b.origin.x - out[3], b.origin.y - out[0], b.size.width + out[1] + out[3],+ b.size.height + out[0] + out[2]);+ let Some(src) = bi.source.as_ref().and_then(|s| border_image_source(s, area.size.width, area.size.height)) else {+ return;+ };+ let (iw, ih) = (src.width as f32, src.height as f32);+ // slices in image pixels (numbers are pixels; percentages of the image)+ let sl: [f32; 4] = std::array::from_fn(|k| {+ let basis = if k % 2 == 0 { ih } else { iw };+ match bi.slice[k] {+ Side::Num(n) => n,+ Side::Len(Length::Percent(pc)) => basis * pc / 100.0,+ Side::Len(l) => l.resolve(u, basis),+ Side::Auto => 0.0,+ }.clamp(0.0, basis)+ });+ // widths in CSS px (numbers: multiples of the border width; auto: the slice)+ let mut wd: [f32; 4] = std::array::from_fn(|k| match bi.width[k] {+ Side::Auto => sl[k],+ v => resolve(v, k, if k % 2 == 0 { area.size.height } else { area.size.width }),+ });+ // scale down when opposite widths overlap+ let f = (area.size.width / (wd[1] + wd[3]).max(1e-6)).min(area.size.height / (wd[0] + wd[2]).max(1e-6)).min(1.0);+ wd.iter_mut().for_each(|v| *v *= f);+ let (ax, ay, aw, ah) = (area.origin.x, area.origin.y, area.size.width, area.size.height);+ let (sx, sy) = ([0.0, sl[3], iw - sl[1], iw], [0.0, sl[0], ih - sl[2], ih]);+ let (dx, dy) = ([ax, ax + wd[3], ax + aw - wd[1], ax + aw], [ay, ay + wd[0], ay + ah - wd[2], ay + ah]);+ for j in 0..3 {+ for i in 0..3 {+ if i == 1 && j == 1 && !bi.fill {+ continue;+ }+ let (cx, cy) = (sx[i].round() as u32, sy[j].round() as u32);+ let (cw, ch) = ((sx[i + 1] - sx[i]).round() as u32, (sy[j + 1] - sy[j]).round() as u32);+ let dest = rect(dx[i], dy[j], dx[i + 1] - dx[i], dy[j + 1] - dy[j]);+ if dest.size.width <= 0.0 || dest.size.height <= 0.0 {+ continue;+ }+ let Some(part) = crop(&src, cx, cy, cw, ch) else { continue };+ // edges tile along their length; corners always stretch+ let tile_x = if j != 1 || i == 1 { if i == 1 { bi.repeat.0 } else { Tile::Stretch } } else { Tile::Stretch };+ let tile_y = if i != 1 || j == 1 { if j == 1 { bi.repeat.1 } else { Tile::Stretch } } else { Tile::Stretch };+ // the tile's size: scaled to the edge's thickness+ let (mut tw, mut th) = (dest.size.width, dest.size.height);+ if tile_x != Tile::Stretch && i == 1 {+ tw = cw as f32 * (dest.size.height / ch.max(1) as f32);+ }+ if tile_y != Tile::Stretch && j == 1 {+ th = ch as f32 * (dest.size.width / cw.max(1) as f32);+ }+ let fit = |len: f32, t: f32, mode: Tile| -> (f32, usize, f32) {+ if mode == Tile::Stretch || t <= 0.0 {+ return (len, 1, 0.0);+ }+ match mode {+ Tile::Round => {+ let n = (len / t).round().max(1.0);+ (len / n, n as usize, 0.0)+ }+ Tile::Space => {+ let n = (len / t).floor();+ if n < 1.0 { (t, 0, 0.0) } else { (t, n as usize, (len - n * t) / (n + 1.0)) }+ }+ _ => {+ // repeat: centred, partial tiles at both ends+ let n = (len / t).ceil() as usize + 1;+ (t, n, 0.0)+ }+ }+ };+ let (tw2, nx, gx) = fit(dest.size.width, tw, if i == 1 { tile_x } else { Tile::Stretch });+ let (th2, ny, gy) = fit(dest.size.height, th, if j == 1 { tile_y } else { Tile::Stretch });+ let start = |len: f32, t: f32, n: usize, g: f32, mode: Tile| -> f32 {+ if mode == Tile::Repeat { (len - n as f32 * t) / 2.0 } else { g }+ };+ let x0 = dest.origin.x + start(dest.size.width, tw2, nx, gx, if i == 1 { tile_x } else { Tile::Stretch });+ let y0 = dest.origin.y + start(dest.size.height, th2, ny, gy, if j == 1 { tile_y } else { Tile::Stretch });+ p.with_clip(dest, |p| {+ for yy in 0..ny {+ for xx in 0..nx {+ let at = rect(x0 + xx as f32 * (tw2 + gx), y0 + yy as f32 * (th2 + gy), tw2, th2);+ p.image(at, &part);+ }+ }+ });+ }+ }+}+/// The border, padding or content box of `b`.fn edge_box(c: &Computed, b: Bounds<f32>, edge: BoxEdge, bw: &[f32; 4]) -> Bounds<f32> {match edge {diff --git a/bindings/rust/blenderui/src/selector.rs b/bindings/rust/blenderui/src/selector.rsindex 34aff27..a0a5d7c 100644--- a/bindings/rust/blenderui/src/selector.rs+++ b/bindings/rust/blenderui/src/selector.rs@@ -1154,6 +1154,8 @@ pub struct FontFace {pub struct Keyframes {pub name: String,pub frames: Vec<(Vec<f32>, Vec<Decl>)>,+ /// The enclosing `@media` queries (indices into the sheet's media results).+ pub(crate) media: smallvec::SmallVec<[u16; 2]>,}/// `@property`: a registered custom property.@@ -1382,7 +1384,8 @@ impl Stylesheet {frames.push((offs, parse_declarations(&rest[open + 1..close.min(rest.len())])));rest = &rest[(close + 1).min(rest.len())..];}- self.keyframes.push(Keyframes { name: q.trim().trim_matches(['"', '\'']).to_string(), frames });+ self.keyframes.push(Keyframes { name: q.trim().trim_matches(['"', '\'']).to_string(), frames,+ media: ctx.media.clone() });}"property" => {let decls = raw_decls(body);diff --git a/bindings/rust/blenderui/src/style.rs b/bindings/rust/blenderui/src/style.rsindex f227ff2..87d4f7f 100644--- a/bindings/rust/blenderui/src/style.rs+++ b/bindings/rust/blenderui/src/style.rs@@ -322,6 +322,9 @@ pub struct Computed {pub clip_rect: Option<[Option<Length>; 4]>,/// `counter-*` operations (None: none).pub counters: Option<Box<CounterOps>>,+ /// Filters, blending, clip-path, masks, transforms beyond translate and+ /// border-image (None: none).+ pub effects: Option<Box<crate::effects::Effects>>,pub opacity: f32,pub z_index: Option<i32>,pub translate: (Length, Length),@@ -356,6 +359,16 @@ pub struct Computed {pub border_spacing: (f32, f32),pub border_collapse: bool,pub caption_bottom: bool,+ /// `table-layout: fixed` (not inherited).+ pub table_fixed: bool,+ /// `unicode-bidi: bidi-override | isolate-override`: characters are laid+ /// out in `direction` order, ignoring their own directionality.+ pub bidi_override: bool,+ /// `scroll-snap-type`: axes (1 = x, 2 = y) and strictness.+ pub snap_axes: u8,+ pub snap_mandatory: bool,+ /// `scroll-snap-align` per axis (x, y): 0 none, 1 start, 2 center, 3 end.+ pub snap_align: (u8, u8),pub marker_inside: bool,/// `quotes`: None = the default curly quotes.pub quotes: Option<(String, String)>,@@ -380,6 +393,8 @@ pub struct Computed {pub vars: u32,/// `content` (for `::before` / `::after`): None = `normal` / `none`.pub content: Option<Box<[ContentPart]>>,+ /// `animation-*` / `transition-*` (None: none). Not inherited.+ pub anim: Option<Box<crate::anim::AnimSpec>>,}/// One piece of generated content.@@ -418,6 +433,7 @@ impl Default for Computed {bg_origin: BoxEdge::Padding,clip_rect: None,counters: None,+ effects: None,opacity: 1.0,z_index: None,translate: (Length::Px(0.0), Length::Px(0.0)),@@ -449,6 +465,11 @@ impl Default for Computed {border_spacing: (0.0, 0.0),border_collapse: false,caption_bottom: false,+ table_fixed: false,+ bidi_override: false,+ snap_axes: 0,+ snap_mandatory: false,+ snap_align: (0, 0),marker_inside: false,quotes: None,text_shadow: None,@@ -463,6 +484,7 @@ impl Default for Computed {tab_size: 8,vars: 0,content: None,+ anim: None,}}}@@ -515,6 +537,10 @@ impl Computed {}}+ pub(crate) fn effects_mut(&mut self) -> &mut crate::effects::Effects {+ self.effects.get_or_insert_with(Default::default)+ }+fn images_mut(&mut self) -> &mut ImageStyle {self.images.get_or_insert_with(Default::default)}@@ -607,19 +633,14 @@ pub(crate) fn prop_index(name: &str) -> Prop {/// Standard properties that parse and are accepted but have no effect in this/// renderer (floats, bidi, generated content, background images, animation ...).pub const ACCEPTED: &[&str] = &[- "clip-path", "unicode-bidi", "writing-mode", "table-layout",- "filter", "backdrop-filter", "mix-blend-mode", "isolation",- "transition", "transition-property", "transition-duration", "transition-timing-function",- "transition-delay", "animation", "animation-name", "animation-duration", "animation-delay",- "animation-iteration-count", "animation-direction", "animation-fill-mode",- "animation-timing-function", "animation-play-state", "will-change",- "user-select", "resize", "appearance", "caret-color", "scroll-behavior", "scroll-snap-type",- "scroll-snap-align", "overscroll-behavior", "touch-action", "hyphens",+ "writing-mode", "will-change",+ "user-select", "resize", "appearance", "caret-color", "scroll-behavior",+ "overscroll-behavior", "touch-action", "hyphens","font-feature-settings", "font-kerning","font-stretch", "text-rendering", "-webkit-font-smoothing", "-moz-osx-font-smoothing","orphans", "widows", "page-break-before", "page-break-after", "page-break-inside","break-before", "break-after", "break-inside", "columns", "column-count", "column-width",- "column-rule", "rotate", "transform-origin", "perspective", "backface-visibility",+ "column-rule", "perspective", "backface-visibility","box-decoration-break", "image-rendering", "shape-outside","text-justify", "line-break","all",@@ -647,14 +668,14 @@ pub const ACCEPTED: &[&str] = &[// sizing / containment / rendering hints"contain-intrinsic-size", "contain-intrinsic-width", "contain-intrinsic-height","contain-intrinsic-block-size", "contain-intrinsic-inline-size", "content-visibility",- "field-sizing", "interpolate-size", "transition-behavior", "color-scheme", "forced-color-adjust",+ "field-sizing", "interpolate-size", "color-scheme", "forced-color-adjust","print-color-adjust", "color-adjust", "image-orientation", "image-resolution","transform-box", "transform-style", "perspective-origin", "zoom", "caret", "caret-shape","background-blend-mode", "column-span", "column-fill", "column-rule-color", "column-rule-style","column-rule-width",// masking- "mask", "mask-image", "mask-mode", "mask-repeat", "mask-position", "mask-clip", "mask-origin",- "mask-size", "mask-composite", "mask-type", "mask-border", "mask-border-source",+ "mask-clip", "mask-origin",+ "mask-composite", "mask-type", "mask-border", "mask-border-source","mask-border-slice", "mask-border-width", "mask-border-outset", "mask-border-repeat","mask-border-mode",];@@ -1224,7 +1245,7 @@ fn grid_line(v: &[Tok]) -> Option<Line<GridPlacement<Ident>>> {// -- backgrounds, shadows, fonts ------------------------------------------------------------fn gradient(ctx: &Ctx, t: &Tok) -> Option<Gradient> {+pub(crate) fn gradient(ctx: &Ctx, t: &Tok) -> Option<Gradient> {let Tok::Func(fx) = t else { return None };let (f, args) = (&fx.name, &fx.args);let radial = f.contains("radial");@@ -1474,6 +1495,204 @@ fn list_style(s: &str) -> Option<ListStyle> {})}+/// An angle in radians (`45deg`, `0.5turn`, `1rad`, `100grad`, a bare 0).+fn angle(t: &Tok) -> Option<f32> {+ match t {+ Tok::Num(n) if *n == 0.0 => Some(0.0),+ Tok::Dim(v, u) => Some(match u.as_ref() {+ "deg" => v.to_radians(),+ "rad" => *v,+ "turn" => v * std::f32::consts::TAU,+ "grad" => v * std::f32::consts::PI / 200.0,+ _ => return None,+ }),+ _ => None,+ }+}++fn add_len(a: Length, b: Length) -> Length {+ match (a, b) {+ (Length::Px(x), Length::Px(y)) => Length::Px(x + y),+ (Length::Px(x), o) | (o, Length::Px(x)) if x == 0.0 => o,+ (_, o) => o,+ }+}++/// A `transform` function list.+fn transform_list(c: &Ctx, v: &[Tok]) -> Option<Vec<crate::effects::TransformFn>> {+ use crate::effects::TransformFn as T;+ let mut out = Vec::new();+ for t in v {+ let Tok::Func(fx) = t else { return None };+ let args: Vec<&Tok> = fx.args.iter().flatten().filter(|t| !matches!(t, Tok::Comma)).collect();+ let num = |i: usize| args.get(i).and_then(|t| number(t));+ let len = |i: usize| args.get(i).and_then(|t| length(t));+ let ang = |i: usize| args.get(i).and_then(|t| angle(t));+ let _ = c;+ out.push(match fx.name.as_ref() {+ "translate" | "translate3d" => T::Translate(len(0)?, len(1).unwrap_or(Length::Px(0.0))),+ "translatex" => T::Translate(len(0)?, Length::Px(0.0)),+ "translatey" => T::Translate(Length::Px(0.0), len(0)?),+ "translatez" => continue,+ "scale" | "scale3d" => {+ let x = num(0).or_else(|| match args.first() { Some(Tok::Pct(p)) => Some(p / 100.0), _ => None })?;+ T::Scale(x, num(1).unwrap_or(x))+ }+ "scalex" => T::Scale(num(0)?, 1.0),+ "scaley" => T::Scale(1.0, num(0)?),+ "scalez" => continue,+ "rotate" | "rotatez" => T::Rotate(ang(0)?),+ "skew" => T::Skew(ang(0)?, ang(1).unwrap_or(0.0)),+ "skewx" => T::Skew(ang(0)?, 0.0),+ "skewy" => T::Skew(0.0, ang(0)?),+ "matrix" => {+ let m: Option<Vec<f32>> = (0..6).map(num).collect();+ let m = m?;+ T::Matrix([m[0], m[1], m[2], m[3], m[4], m[5]])+ }+ // 3D functions without a 2D meaning: no effect on the 2D plane+ "perspective" | "rotatex" | "rotatey" | "rotate3d" | "matrix3d" => continue,+ _ => return None,+ });+ }+ Some(out)+}++/// A `filter` / `backdrop-filter` value.+fn filter_list(c: &Ctx, v: &[Tok]) -> Option<Vec<crate::effects::Filter>> {+ use crate::effects::Filter as F;+ if kw(v) == Some("none") {+ return Some(Vec::new());+ }+ let mut out = Vec::new();+ for t in v {+ let Tok::Func(fx) = t else { return None };+ let args: Vec<&Tok> = fx.args.iter().flatten().filter(|t| !matches!(t, Tok::Comma)).collect();+ // amounts: numbers or percentages, default 1+ let amount = |d: f32| match args.first() {+ None => Some(d),+ Some(Tok::Num(n)) => Some(*n),+ Some(Tok::Pct(p)) => Some(p / 100.0),+ _ => None,+ };+ out.push(match fx.name.as_ref() {+ "blur" => F::Blur(args.first().map_or(Some(0.0), |t| length(t).map(|l| px(c, l)))?),+ "brightness" => F::Brightness(amount(1.0)?),+ "contrast" => F::Contrast(amount(1.0)?),+ "grayscale" => F::Grayscale(amount(1.0)?),+ "invert" => F::Invert(amount(1.0)?),+ "opacity" => F::Opacity(amount(1.0)?),+ "saturate" => F::Saturate(amount(1.0)?),+ "sepia" => F::Sepia(amount(1.0)?),+ "hue-rotate" => F::HueRotate(args.first().map_or(Some(0.0), |t| angle(t))?.to_degrees()),+ "drop-shadow" => {+ let lens: Vec<f32> = args.iter().filter_map(|t| match t {+ Tok::Dim(..) | Tok::Num(_) | Tok::Calc(_) => length(t).map(|l| px(c, l)),+ _ => None,+ }).collect();+ let color = args.iter().find_map(|t| match t {+ Tok::Dim(..) | Tok::Num(_) => None,+ t => color(t, c.c.color),+ }).unwrap_or(c.c.color);+ match lens.as_slice() {+ [x, y] => F::DropShadow { x: *x, y: *y, blur: 0.0, color },+ [x, y, b, ..] => F::DropShadow { x: *x, y: *y, blur: *b, color },+ _ => return None,+ }+ }+ _ => return None, // url(#svg-filter): not supported+ });+ }+ Some(out)+}++/// A `clip-path` basic shape.+fn clip_shape(c: &Ctx, t: &Tok) -> Option<crate::effects::ClipShape> {+ use crate::effects::{ClipShape as S, ShapeRadius as R};+ let Tok::Func(fx) = t else { return None };+ let flat: Vec<Tok> = fx.args.iter().flatten().cloned().collect();+ // split at `at` (circle / ellipse) and `round` (inset)+ let split = |word: &str| -> (Vec<Tok>, Vec<Tok>) {+ match flat.iter().position(|t| t.ident() == Some(word)) {+ Some(k) => (flat[..k].to_vec(), flat[k + 1..].to_vec()),+ None => (flat.clone(), Vec::new()),+ }+ };+ let radius = |t: &Tok| match t.ident() {+ Some("closest-side") => Some(R::Closest),+ Some("farthest-side") => Some(R::Farthest),+ _ => length(t).map(R::Len),+ };+ let center = |rest: &[Tok]| if rest.is_empty() { Some([Pos::CENTER; 2]) } else { position(c, rest) };+ Some(match fx.name.as_ref() {+ "inset" => {+ let (sides, round) = split("round");+ let l: Option<Vec<Length>> = sides.iter().map(length).collect();+ let s = four(&l?)?;+ let r = round.first().and_then(length).unwrap_or(Length::Px(0.0));+ S::Inset(s, r)+ }+ "circle" => {+ let (r, at) = split("at");+ S::Circle(r.first().map_or(Some(R::Closest), radius)?, center(&at)?)+ }+ "ellipse" => {+ let (r, at) = split("at");+ let rx = r.first().map_or(Some(R::Closest), radius)?;+ let ry = r.get(1).map_or(Some(R::Closest), radius)?;+ S::Ellipse(rx, ry, center(&at)?)+ }+ "polygon" => {+ let mut pts = Vec::new();+ for group in &fx.args {+ let ls: Vec<Length> = group.iter().filter_map(length).collect();+ if let [x, y] = ls.as_slice() {+ pts.push((*x, *y));+ }+ }+ if pts.len() < 3 {+ return None;+ }+ S::Polygon(pts)+ }+ _ => return None,+ })+}++/// A mask / border-image source: a gradient or `url()` (PNG).+fn image_source(c: &Ctx, t: &Tok) -> Option<crate::effects::ImageSource> {+ if let Tok::Func(fx) = t {+ if fx.name == "url" {+ if let Some(Tok::Str(u)) = fx.args.first().and_then(|a| a.first()) {+ return Some(crate::effects::ImageSource::Url(u.as_ref().into()));+ }+ return None;+ }+ }+ gradient(c, t).map(crate::effects::ImageSource::Gradient)+}++fn four_sides<T: Copy>(v: &[T]) -> Option<[T; 4]> {+ Some(match v {+ [a] => [*a; 4],+ [a, b] => [*a, *b, *a, *b],+ [a, b, c] => [*a, *b, *c, *b],+ [a, b, c, d] => [*a, *b, *c, *d],+ _ => return None,+ })+}++/// `border-image-width` / `-outset`: numbers (border widths), lengths, `auto`.+fn side_values(v: &[Tok]) -> Option<[crate::effects::Side; 4]> {+ use crate::effects::Side;+ let vals: Option<Vec<Side>> = v.iter().map(|t| match t {+ Tok::Ident(k) if k.as_ref() == "auto" => Some(Side::Auto),+ Tok::Num(n) => Some(Side::Num(*n)),+ t => length(t).map(Side::Len),+ }).collect();+ four_sides(&vals?)+}+fn deco_style(s: &str) -> Option<DecoStyle> {Some(match s {"solid" => DecoStyle::Solid,@@ -2178,42 +2397,272 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{}),h("box-shadow", |c, v| shadows(c, v).map(|s| c.c.shadows = s).is_some()),h("transform", |c, v| {- let mut ok = true;+ if kw(v) == Some("none") {+ c.c.translate = (Length::Px(0.0), Length::Px(0.0));+ c.c.scale = 1.0;+ if let Some(e) = c.c.effects.as_mut() {+ e.transform.clear();+ }+ return true;+ }+ let Some(fns) = transform_list(c, v) else { return false };+ use crate::effects::TransformFn as T;+ // translations alone stay a layout offset; anything else is drawn+ // through the element's layer+ if fns.iter().all(|f| matches!(f, T::Translate(..))) {+ let mut t = (Length::Px(0.0), Length::Px(0.0));+ for f in &fns {+ if let T::Translate(x, y) = f {+ t = (add_len(t.0, *x), add_len(t.1, *y));+ }+ }+ c.c.translate = t;+ if let Some(e) = c.c.effects.as_mut() {+ e.transform.clear();+ }+ } else {+ c.c.translate = (Length::Px(0.0), Length::Px(0.0));+ c.c.effects_mut().transform = fns;+ }+ true+ }),+ h("scale", |c, v| {+ let nums: Vec<f32> = v.iter().filter_map(|t| match t {+ Tok::Num(n) => Some(*n),+ Tok::Pct(p) => Some(*p / 100.0),+ _ => None,+ }).collect();+ let (x, y) = match (kw(v), nums.as_slice()) {+ (Some("none"), _) => (1.0, 1.0),+ (_, [s]) => (*s, *s),+ (_, [x, y, ..]) => (*x, *y),+ _ => return false,+ };+ c.c.scale = 1.0;+ c.c.effects_mut().scale2 = ((x, y) != (1.0, 1.0)).then_some((x, y));+ true+ }),+ h("rotate", |c, v| match (kw(v), v.last().and_then(angle)) {+ (Some("none"), _) => {+ c.c.effects_mut().rotate = 0.0;+ true+ }+ (_, Some(a)) => {+ c.c.effects_mut().rotate = a;+ true+ }+ _ => false,+ }),+ h("transform-origin", |c, v| {+ let xy: Vec<Tok> = v.iter().take(2).cloned().collect();+ position(c, &xy).map(|p| c.c.effects_mut().origin = Some(p)).is_some()+ }),+ // -- filters, blending, clipping, masking -------------------------------------+ h("filter", |c, v| filter_list(c, v).map(|f| c.c.effects_mut().filter = f).is_some()),+ h("backdrop-filter", |c, v| filter_list(c, v).map(|f| c.c.effects_mut().backdrop = f).is_some()),+ h("-webkit-backdrop-filter", |c, v| delegate(c, "backdrop-filter", v)),+ h("mix-blend-mode", |c, v| kw(v).and_then(crate::effects::Blend::parse)+ .map(|b| c.c.effects_mut().blend = b).is_some()),+ h("isolation", |c, v| match kw(v) {+ Some(k @ ("auto" | "isolate")) => {+ c.c.effects_mut().isolate = k == "isolate";+ true+ }+ _ => false,+ }),+ h("clip-path", |c, v| {+ if kw(v) == Some("none") {+ c.c.effects_mut().clip_path = None;+ return true;+ }+ let mut shape = None;+ let mut edge = BoxEdge::Border;for t in v {match t {- Tok::Func(fx) => {- let (f, args) = (&fx.name, &fx.args);- let arg = |i: usize| args.get(i).and_then(|a| a.first()).and_then(length);- match f.as_ref() {- "translate" => {- c.c.translate = (arg(0).unwrap_or_default(), arg(1).unwrap_or(Length::Px(0.0)))- }- "translatex" => c.c.translate.0 = arg(0).unwrap_or_default(),- "translatey" => c.c.translate.1 = arg(0).unwrap_or_default(),- "scale" => {- c.c.scale = args.first().and_then(|a| a.first()).and_then(number).unwrap_or(1.0)- }- _ => ok = false, // rotate/skew/matrix: not drawn- }- }- Tok::Ident(s) if s == "none" => {- c.c.translate = (Length::Px(0.0), Length::Px(0.0));- c.c.scale = 1.0;- }- _ => ok = false,+ Tok::Ident(k) => match BoxEdge::parse(k) {+ Some(e) => edge = e,+ None if matches!(k.as_ref(), "margin-box" | "fill-box" | "stroke-box" | "view-box") => {}+ None => return false,+ },+ Tok::Func(_) => match clip_shape(c, t) {+ Some(sh) => shape = Some(sh),+ None => return false,+ },+ _ => return false,+ }+ }+ c.c.effects_mut().clip_path = Some((shape.unwrap_or(crate::effects::ClipShape::Box), edge));+ true+ }),+ h("-webkit-clip-path", |c, v| delegate(c, "clip-path", v)),+ h("mask-image", |c, v| {+ let first = v.split(|t| matches!(t, Tok::Comma)).next().unwrap_or(&[]);+ let src = match first {+ [Tok::Ident(k)] if k.as_ref() == "none" => None,+ [t] => match image_source(c, t) {+ Some(src) => Some(src),+ None => return false,+ },+ _ => return false,+ };+ c.c.effects_mut().mask.get_or_insert_with(Default::default).image = src;+ true+ }),+ h("mask-mode", |c, v| match kw(v) {+ Some(k @ ("alpha" | "luminance" | "match-source")) => {+ c.c.effects_mut().mask.get_or_insert_with(Default::default).luminance = k == "luminance";+ true+ }+ _ => false,+ }),+ h("mask-size", |c, v| {+ // reuse background-size's parser on a scratch style+ let mut tmp = Computed::default();+ let parent = Computed::default();+ let mut cx = Ctx { c: &mut tmp, parent: &parent, u: c.u };+ if !delegate(&mut cx, "background-size", v) {+ return false;+ }+ let size = tmp.images.map(|i| i.bg_size).unwrap_or_default();+ c.c.effects_mut().mask.get_or_insert_with(Default::default).size = size;+ true+ }),+ h("mask-position", |c, v| {+ let first = v.split(|t| matches!(t, Tok::Comma)).next().unwrap_or(&[]);+ position(c, first).map(|p| c.c.effects_mut().mask.get_or_insert_with(Default::default).position = p)+ .is_some()+ }),+ h("mask-repeat", |c, v| {+ let words: Vec<&str> = v.iter().take_while(|t| !matches!(t, Tok::Comma)).filter_map(Tok::ident).collect();+ let rep = |w: &str| matches!(w, "repeat" | "space" | "round");+ let r = match words.as_slice() {+ ["repeat-x"] => (true, false),+ ["repeat-y"] => (false, true),+ [a] => (rep(a), rep(a)),+ [a, b] => (rep(a), rep(b)),+ _ => return false,+ };+ c.c.effects_mut().mask.get_or_insert_with(Default::default).repeat = r;+ true+ }),+ h("mask", |c, v| {+ if kw(v) == Some("none") {+ c.c.effects_mut().mask = None;+ return true;+ }+ let layer = v.split(|t| matches!(t, Tok::Comma)).next().unwrap_or(&[]);+ let mut ok = false;+ for t in layer {+ if let Ok(src) = image_source(c, t).ok_or(()) {+ c.c.effects_mut().mask.get_or_insert_with(Default::default).image = Some(src);+ ok = true;+ }+ }+ if let Some(k) = layer.iter().position(|t| matches!(t, Tok::Slash)) {+ let size: Vec<Tok> = layer[k + 1..].iter().take_while(|t| length(t).is_some()+ || matches!(t.ident(), Some("auto" | "cover" | "contain"))).cloned().take(2).collect();+ delegate(c, "mask-size", &size);+ }+ let pos: Vec<Tok> = layer.iter().take_while(|t| !matches!(t, Tok::Slash))+ .filter(|t| length(t).is_some() && !matches!(t, Tok::Num(_))+ || matches!(t.ident(), Some("left" | "right" | "top" | "bottom" | "center")))+ .cloned().collect();+ if !pos.is_empty() {+ delegate(c, "mask-position", &pos);+ }+ let reps: Vec<Tok> = layer.iter().filter(|t| matches!(t.ident(),+ Some("repeat" | "no-repeat" | "repeat-x" | "repeat-y" | "space" | "round"))).cloned().collect();+ if !reps.is_empty() {+ delegate(c, "mask-repeat", &reps);+ }+ for k in layer.iter().filter_map(Tok::ident) {+ if matches!(k, "alpha" | "luminance") {+ c.c.effects_mut().mask.get_or_insert_with(Default::default).luminance = k == "luminance";}}ok}),- h("scale", |c, v| {- c.c.scale = match (kw(v), v.first()) {- (Some("none"), _) => 1.0,- (_, Some(Tok::Num(n))) => *n,- (_, Some(Tok::Pct(p))) => *p / 100.0,+ h("-webkit-mask", |c, v| delegate(c, "mask", v)),+ h("-webkit-mask-image", |c, v| delegate(c, "mask-image", v)),+ h("-webkit-mask-size", |c, v| delegate(c, "mask-size", v)),+ h("-webkit-mask-position", |c, v| delegate(c, "mask-position", v)),+ h("-webkit-mask-repeat", |c, v| delegate(c, "mask-repeat", v)),+ // -- border-image ---------------------------------------------------------------+ h("border-image-source", |c, v| match v {+ [Tok::Ident(k)] if k.as_ref() == "none" => {+ c.c.effects_mut().border_image.get_or_insert_with(Default::default).source = None;+ true+ }+ [t] => image_source(c, t).map(|s| c.c.effects_mut().border_image.get_or_insert_with(Default::default)+ .source = Some(s)).is_some(),+ _ => false,+ }),+ h("border-image-slice", |c, v| {+ let fill = v.iter().any(|t| t.ident() == Some("fill"));+ let vals: Option<Vec<crate::effects::Side>> = v.iter().filter(|t| t.ident() != Some("fill"))+ .map(|t| match t {+ Tok::Num(n) => Some(crate::effects::Side::Num(*n)),+ Tok::Pct(p) => Some(crate::effects::Side::Len(Length::Percent(*p))),+ _ => None,+ }).collect();+ let Some(sides) = vals.as_deref().and_then(four_sides) else { return false };+ let b = c.c.effects_mut().border_image.get_or_insert_with(Default::default);+ b.slice = sides;+ b.fill = fill;+ true+ }),+ h("border-image-width", |c, v| side_values(v).map(|s| c.c.effects_mut().border_image+ .get_or_insert_with(Default::default).width = s).is_some()),+ h("border-image-outset", |c, v| side_values(v).map(|s| c.c.effects_mut().border_image+ .get_or_insert_with(Default::default).outset = s).is_some()),+ h("border-image-repeat", |c, v| {+ let tile = |w: &str| Some(match w {+ "stretch" => crate::effects::Tile::Stretch,+ "repeat" => crate::effects::Tile::Repeat,+ "round" => crate::effects::Tile::Round,+ "space" => crate::effects::Tile::Space,+ _ => return None,+ });+ let words: Option<Vec<crate::effects::Tile>> = v.iter().map(|t| t.ident().and_then(tile)).collect();+ let r = match words.as_deref() {+ Some([a]) => (*a, *a),+ Some([a, b]) => (*a, *b),_ => return false,};+ c.c.effects_mut().border_image.get_or_insert_with(Default::default).repeat = r;true}),+ h("border-image", |c, v| {+ if kw(v) == Some("none") {+ c.c.effects_mut().border_image = None;+ return true;+ }+ // <source> || <slice> [/ <width> [/ <outset>]] || <repeat>+ let mut ok = false;+ let mut rest: Vec<Tok> = Vec::new();+ for t in v {+ if matches!(t, Tok::Func(_)) && image_source(c, t).is_some() {+ ok |= delegate(c, "border-image-source", std::slice::from_ref(t));+ } else if matches!(t.ident(), Some("stretch" | "repeat" | "round" | "space")) {+ let reps: Vec<Tok> = v.iter().filter(|t| matches!(t.ident(),+ Some("stretch" | "repeat" | "round" | "space"))).cloned().collect();+ delegate(c, "border-image-repeat", &reps);+ } else {+ rest.push(t.clone());+ }+ }+ let parts: Vec<&[Tok]> = rest.split(|t| matches!(t, Tok::Slash)).collect();+ if let Some(slice) = parts.first().filter(|p| !p.is_empty()) {+ ok &= delegate(c, "border-image-slice", slice);+ }+ if let Some(w) = parts.get(1).filter(|p| !p.is_empty()) {+ delegate(c, "border-image-width", w);+ }+ if let Some(o) = parts.get(2).filter(|p| !p.is_empty()) {+ delegate(c, "border-image-outset", o);+ }+ ok+ }),h("translate", |c, v| {let l = lengths(v).unwrap_or_default();c.c.translate = (*l.first().unwrap_or(&Length::Px(0.0)), *l.get(1).unwrap_or(&Length::Px(0.0)));@@ -2490,6 +2939,57 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{}true}),+ h("scroll-snap-type", |c, v| {+ let words: Vec<&str> = v.iter().filter_map(Tok::ident).collect();+ if words == ["none"] {+ c.c.snap_axes = 0;+ return true;+ }+ let axes = match words.first() {+ Some(&"x" | &"inline") => 1,+ Some(&"y" | &"block") => 2,+ Some(&"both") => 3,+ _ => return false,+ };+ c.c.snap_axes = axes;+ c.c.snap_mandatory = words.get(1) == Some(&"mandatory");+ true+ }),+ h("scroll-snap-align", |c, v| {+ let one = |w: &str| Some(match w {+ "none" => 0,+ "start" => 1,+ "center" => 2,+ "end" => 3,+ _ => return None,+ });+ let words: Option<Vec<u8>> = v.iter().map(|t| t.ident().and_then(one)).collect();+ // one value: both axes; two: block (y) then inline (x)+ c.c.snap_align = match words.as_deref() {+ Some([a]) => (*a, *a),+ Some([y, x]) => (*x, *y),+ _ => return false,+ };+ true+ }),+ h("unicode-bidi", |c, v| match kw(v) {+ Some("normal" | "embed" | "isolate" | "plaintext") => {+ c.c.bidi_override = false;+ true+ }+ Some("bidi-override" | "isolate-override") => {+ c.c.bidi_override = true;+ true+ }+ _ => false,+ }),+ h("table-layout", |c, v| match kw(v) {+ Some(k @ ("auto" | "fixed")) => {+ c.c.table_fixed = k == "fixed";+ true+ }+ _ => false,+ }),h("border-collapse", |c, v| match kw(v) {Some(k @ ("collapse" | "separate")) => {c.c.border_collapse = k == "collapse";@@ -2680,6 +3180,22 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{}_ => v.first().and_then(|t| color(t, c.c.color)).map(|col| c.c.accent = Some(col)).is_some(),}),+ // -- animations and transitions (run by anim.rs) -----------------------------------+ h("animation", crate::anim::h_animation),+ h("animation-name", crate::anim::h_animation_name),+ h("animation-duration", crate::anim::h_animation_duration),+ h("animation-timing-function", crate::anim::h_animation_timing),+ h("animation-delay", crate::anim::h_animation_delay),+ h("animation-iteration-count", crate::anim::h_animation_iterations),+ h("animation-direction", crate::anim::h_animation_direction),+ h("animation-fill-mode", crate::anim::h_animation_fill),+ h("animation-play-state", crate::anim::h_animation_play_state),+ h("transition", crate::anim::h_transition),+ h("transition-property", crate::anim::h_transition_property),+ h("transition-duration", crate::anim::h_transition_duration),+ h("transition-timing-function", crate::anim::h_transition_timing),+ h("transition-delay", crate::anim::h_transition_delay),+ h("transition-behavior", crate::anim::h_transition_behavior),]};diff --git a/bindings/rust/blenderui/src/text.rs b/bindings/rust/blenderui/src/text.rsindex 64e70f6..ee1364f 100644--- a/bindings/rust/blenderui/src/text.rs+++ b/bindings/rust/blenderui/src/text.rs@@ -189,3 +189,148 @@ impl TextCache {chars[..lo].iter().collect::<String>() + "\u{2026}"}}++// ==========================================================================+// Bidirectional text: a compact Unicode Bidirectional Algorithm (UAX #9)++#[derive(Clone, Copy, PartialEq, Eq)]+enum Class {+ L,+ R,+ /// European / Arabic digits+ N,+ /// whitespace and punctuation+ Neutral,+}++fn class(c: char) -> Class {+ let u = c as u32;+ if matches!(u, 0x0590..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFF | 0x10800..=0x10FFF | 0x1E800..=0x1EFFF) {+ Class::R+ } else if c.is_ascii_digit() || matches!(u, 0x0660..=0x0669 | 0x06F0..=0x06F9) {+ Class::N+ } else if c.is_alphabetic() {+ Class::L+ } else {+ Class::Neutral+ }+}++/// `s` in visual (left-to-right display) order. `rtl`: the paragraph's+/// direction; `override_`: `unicode-bidi: bidi-override` (every character+/// takes the paragraph's direction). Returns None when nothing moves (pure+/// left-to-right text, the common case).+pub(crate) fn bidi_visual(s: &str, rtl: bool, override_: bool) -> Option<String> {+ if override_ {+ return rtl.then(|| s.chars().rev().collect());+ }+ let chars: Vec<char> = s.chars().collect();+ let classes: Vec<Class> = chars.iter().map(|&c| class(c)).collect();+ if !rtl && !classes.contains(&Class::R) {+ return None;+ }+ let base: u8 = rtl as u8;+ // resolved levels: R odd, L even (W/I rules simplified: digits take the+ // level above the base, so they stay left-to-right inside RTL text)+ let mut levels: Vec<u8> = classes.iter().map(|c| match (c, base) {+ (Class::R, _) => 1,+ (Class::L, 0) => 0,+ (Class::L, _) => 2,+ (Class::N, 0) => 0,+ (Class::N, _) => 2,+ (Class::Neutral, _) => u8::MAX,+ }).collect();+ // digits right after RTL text in an LTR paragraph sit inside it+ if base == 0 {+ let mut prev_r = false;+ for k in 0..levels.len() {+ match classes[k] {+ Class::R => prev_r = true,+ Class::L => prev_r = false,+ Class::N if prev_r => levels[k] = 2,+ _ => {}+ }+ }+ }+ // neutrals (N1/N2): between two strong runs of the same direction they+ // take it; otherwise the paragraph's level+ let dir = |l: u8| l % 2;+ let n = levels.len();+ let mut k = 0;+ while k < n {+ if levels[k] != u8::MAX {+ k += 1;+ continue;+ }+ let start = k;+ while k < n && levels[k] == u8::MAX {+ k += 1;+ }+ let before = if start == 0 { base } else { levels[start - 1] };+ let after = if k == n { base } else { levels[k] };+ let l = match (dir(before), dir(after)) {+ (1, 1) => 1,+ (0, 0) => if base == 0 { 0 } else { 2 },+ _ => base,+ };+ for lv in &mut levels[start..k] {+ *lv = l;+ }+ }+ // trailing whitespace goes back to the paragraph level (L1)+ for k in (0..n).rev() {+ if chars[k].is_whitespace() {+ levels[k] = base;+ } else {+ break;+ }+ }+ // L2: from the highest level down to the lowest odd one, reverse every+ // run at that level or above+ let max = levels.iter().copied().max().unwrap_or(0);+ let min_odd = levels.iter().copied().filter(|l| l % 2 == 1).min().unwrap_or(1);+ let mut order: Vec<usize> = (0..n).collect();+ let mut lvl = max;+ while lvl >= min_odd && lvl > 0 {+ let mut k = 0;+ while k < n {+ if levels[order[k]] >= lvl {+ let start = k;+ while k < n && levels[order[k]] >= lvl {+ k += 1;+ }+ order[start..k].reverse();+ } else {+ k += 1;+ }+ }+ lvl -= 1;+ }+ // mirrored brackets in RTL runs+ let mirror = |c: char| match c {+ '(' => ')', ')' => '(', '[' => ']', ']' => '[', '{' => '}', '}' => '{', '<' => '>', '>' => '<',+ c => c,+ };+ let out: String = order.iter().map(|&k| if levels[k] % 2 == 1 { mirror(chars[k]) } else { chars[k] }).collect();+ (out != s).then_some(out)+}++#[cfg(test)]+mod bidi_tests {+ use super::bidi_visual;++ #[test]+ fn reorders_rtl_runs() {+ // Hebrew inside English: the Hebrew run is reversed, the rest stays+ assert_eq!(bidi_visual("abc \u{05d0}\u{05d1}\u{05d2} def", false, false).as_deref(),+ Some("abc \u{05d2}\u{05d1}\u{05d0} def"));+ // pure LTR: untouched+ assert_eq!(bidi_visual("hello world", false, false), None);+ // RTL paragraph: English words keep their order inside, runs swap+ assert_eq!(bidi_visual("abc \u{05d0}\u{05d1}", true, false).as_deref(), Some("\u{05d1}\u{05d0} abc"));+ // numbers stay left-to-right inside RTL text+ assert_eq!(bidi_visual("\u{05d0} 123", true, false).as_deref(), Some("123 \u{05d0}"));+ // override+ assert_eq!(bidi_visual("abc", true, true).as_deref(), Some("cba"));+ }+}diff --git a/bindings/rust/blenderui/src/widgets.rs b/bindings/rust/blenderui/src/widgets.rsindex 89a94a1..ae613f8 100644--- a/bindings/rust/blenderui/src/widgets.rs+++ b/bindings/rust/blenderui/src/widgets.rs@@ -25,6 +25,7 @@ pub(crate) enum WKind {Select,TextArea,Progress,+ Meter,}impl WKind {@@ -40,6 +41,7 @@ impl WKind {WKind::Select => c"dropdown",WKind::TextArea => c"textarea",WKind::Progress => c"progress",+ WKind::Meter => c"meter",}}@@ -49,7 +51,7 @@ impl WKind {WKind::Text { .. } | WKind::Number | WKind::Slider => (150.0, 20.0),WKind::Select => (120.0, 20.0),WKind::TextArea => (240.0, 64.0),- WKind::Progress => (160.0, 20.0),+ WKind::Progress | WKind::Meter => (160.0, 20.0),WKind::Color => (40.0, 20.0),WKind::Checkbox | WKind::Radio => (20.0, 20.0),WKind::Button => (20.0, 20.0),@@ -72,6 +74,54 @@ pub(crate) struct WidgetSpec {pub placeholder: String,pub disabled: bool,pub name: Option<String>,+ /// Drawn like a browser's form control (plain HTML outside `styled`);+ /// false: a Blender widget (inside `styled`, or a Blender component).+ pub html: bool,+ /// `<optgroup>` labels: (index of the option they come before, label).+ pub groups: Vec<(usize, String)>,+ /// `<meter>`'s low, high and optimum.+ pub meter: [Option<f64>; 3],+}++impl WidgetSpec {+ /// The kit's item list: options, with group labels (marked `\x01`) in+ /// the browser look.+ fn kit_items(&self) -> Vec<String> {+ if !self.html || self.groups.is_empty() {+ return self.items.clone();+ }+ let mut out = Vec::with_capacity(self.items.len() + self.groups.len());+ let mut g = self.groups.iter().peekable();+ for (k, it) in self.items.iter().enumerate() {+ while let Some((at, label)) = g.next_if(|(at, _)| *at <= k) {+ let _ = at;+ out.push(format!("\u{1}{label}"));+ }+ out.push(it.clone());+ }+ out.extend(g.map(|(_, l)| format!("\u{1}{l}")));+ out+ }++ /// Option index to the kit's item index, and back.+ fn to_kit(&self, option: f64) -> f64 {+ if !self.html {+ return option;+ }+ option + self.groups.iter().filter(|(at, _)| (*at as f64) <= option).count() as f64+ }+ fn from_kit(&self, item: f64) -> f64 {+ if !self.html {+ return item;+ }+ let mut labels = 0.0;+ for (at, _) in &self.groups {+ if (*at as f64) + labels <= item {+ labels += 1.0;+ }+ }+ item - labels+ }}fn text_of(children: &[AnyElement]) -> Option<String> {@@ -104,6 +154,9 @@ impl WidgetSpec {placeholder: attr(attrs, "placeholder").unwrap_or("").to_owned(),disabled: attr(attrs, "disabled").is_some(),name: attr(attrs, "name").map(str::to_owned),+ html: false,+ groups: Vec::new(),+ meter: [None; 3],}}@@ -176,19 +229,22 @@ impl WidgetSpec {s = WidgetSpec::new(WKind::Select, attrs);let mut selected = None;let want = attr(attrs, "value");- fn options<'a>(c: &'a [AnyElement], out: &mut Vec<&'a Div>) {+ fn options<'a>(c: &'a [AnyElement], out: &mut Vec<&'a Div>, groups: &mut Vec<(usize, String)>) {for e in c {if let AnyElement::Element(d) = e {match d.tag {"option" => out.push(d),- "optgroup" => options(&d.children, out),+ "optgroup" => {+ groups.push((out.len(), d.get_attr("label").unwrap_or("").to_owned()));+ options(&d.children, out, groups)+ }_ => {}}}}}let mut opts = Vec::new();- options(&d.children, &mut opts);+ options(&d.children, &mut opts, &mut s.groups);for (k, o) in opts.iter().enumerate() {let label = text_of(&o.children).unwrap_or_default();let value = o.get_attr("value").map(str::to_owned).unwrap_or_else(|| label.clone());@@ -207,12 +263,22 @@ impl WidgetSpec {_ => None,}).collect()));}- "progress" | "meter" => {+ "progress" => {s = WidgetSpec::new(WKind::Progress, attrs);- let min = if d.tag == "meter" { num("min").unwrap_or(0.0) } else { 0.0 };let max = num("max").unwrap_or(1.0);- let v = num("value").unwrap_or(0.0);- s.value = Some(((v - min) / (max - min).max(1e-9)).clamp(0.0, 1.0));+ // no value: indeterminate (a negative factor)+ s.value = Some(match num("value") {+ Some(v) => (v / max.max(1e-9)).clamp(0.0, 1.0),+ None => -1.0,+ });+ s.label = text_of(&d.children).unwrap_or_default();+ }+ "meter" => {+ s = WidgetSpec::new(WKind::Meter, attrs);+ s.min = num("min").unwrap_or(0.0);+ s.max = num("max").unwrap_or(1.0);+ s.value = Some(num("value").unwrap_or(0.0).clamp(s.min, s.max));+ s.meter = [num("low"), num("high"), num("optimum")];s.label = text_of(&d.children).unwrap_or_default();}_ => return None,@@ -279,7 +345,8 @@ impl Widgets {let mut nat = [0i32; 2];// SAFETY: valid node, two-int out array.unsafe { sys::BK_node_natural(entry.node, nat.as_mut_ptr()) };- let (mw, mh) = spec.kind.min_size();+ // browser-look controls keep the browser's sizes+ let (mw, mh) = if spec.html { (0.0, 0.0) } else { spec.kind.min_size() };((nat[0] as f32 / scale).max(mw), (nat[1] as f32 / scale).max(mh))}@@ -328,11 +395,11 @@ impl Widgets {checked: num != 0.0,number: num,},- WKind::Select => ChangeEvent {- value: w.spec.items.get(num as usize).cloned().unwrap_or_default(),- checked: false,- number: num,- },+ WKind::Select => {+ let num = w.spec.from_kit(num);+ ChangeEvent { value: w.spec.items.get(num as usize).cloned().unwrap_or_default(), checked: false,+ number: num }+ }WKind::Color => {let mut c = [0f32; 4];sys::BK_get_color(n, c"value".as_ptr(), c.as_mut_ptr());@@ -379,6 +446,9 @@ fn sync(n: *mut sys::BKNode, old: Option<&WidgetSpec>, spec: &WidgetSpec) {unsafe {let set_num = |k: &CStr, v: f64| { sys::BK_set_num(n, k.as_ptr(), v); };let set_str = |k: &CStr, v: &str| { let c = cstr(v); sys::BK_set_str(n, k.as_ptr(), c.as_ptr()); };+ if old.is_none_or(|o| o.html != spec.html) {+ set_num(c"html", spec.html as i32 as f64);+ }if old.is_none_or(|o| o.disabled != spec.disabled) {set_num(c"enabled", (!spec.disabled) as i32 as f64);}@@ -396,6 +466,15 @@ fn sync(n: *mut sys::BKNode, old: Option<&WidgetSpec>, spec: &WidgetSpec) {set_num(c"mask", 1.0);}}+ if spec.kind == WKind::Meter && old.is_none_or(|o| (o.min, o.max, o.meter) != (spec.min, spec.max, spec.meter)) {+ set_num(c"min", spec.min);+ set_num(c"max", spec.max);+ for (k, v) in [c"low", c"high", c"optimum"].iter().zip(spec.meter) {+ if let Some(v) = v {+ set_num(k, v);+ }+ }+ }if old.is_none_or(|o| (o.min, o.max, o.step) != (spec.min, spec.max, spec.step))&& matches!(spec.kind, WKind::Number | WKind::Slider){@@ -410,18 +489,27 @@ fn sync(n: *mut sys::BKNode, old: Option<&WidgetSpec>, spec: &WidgetSpec) {set_num(c"precision", 0.0);}}- if old.is_none_or(|o| o.items != spec.items) && spec.kind == WKind::Select {- let cs: Vec<CString> = spec.items.iter().map(|s| cstr(s)).collect();+ if old.is_none_or(|o| (&o.items, &o.groups, o.html) != (&spec.items, &spec.groups, spec.html))+ && spec.kind == WKind::Select {+ let items = spec.kit_items();+ let cs: Vec<CString> = items.iter().map(|s| cstr(s)).collect();let ptrs: Vec<*const std::ffi::c_char> = cs.iter().map(|c| c.as_ptr()).collect();sys::BK_set_strs(n, c"items".as_ptr(), ptrs.as_ptr(), ptrs.len() as i32);}if old.is_none_or(|o| o.text != spec.text) {if let Some(t) = &spec.text {- set_str(c"text", t);+ // the textarea takes its whole text as "value"+ set_str(if spec.kind == WKind::TextArea { c"value" } else { c"text" }, t);}}- if old.is_none_or(|o| o.value != spec.value) {+ if old.is_none_or(|o| (o.value, o.html) != (spec.value, spec.html)) {if let Some(v) = spec.value {+ let v = match spec.kind {+ WKind::Select => spec.to_kit(v),+ // indeterminate progress exists in the browser look only+ WKind::Progress if !spec.html => v.max(0.0),+ _ => v,+ };set_num(if spec.kind == WKind::Progress { c"factor" } else { c"value" }, v);}}diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rsindex 0ef0df9..d814c62 100644--- a/bindings/rust/blenderui/src/window.rs+++ b/bindings/rust/blenderui/src/window.rs@@ -613,6 +613,19 @@ impl App {(pw as usize, ph as usize, px)}+ /// Move every window's CSS animation clock forward by `d`. Headless+ /// windows' clocks stand still otherwise, so tests step animations and+ /// transitions deterministically; native windows add `d` to real time.+ pub fn advance_clock(&mut self, d: std::time::Duration) {+ for w in self.windows.iter_mut().flatten() {+ w.clock.advance(d);+ if w.caches.anim.any() {+ w.dirty = true;+ }+ }+ self.flush();+ }+/// Bounds (logical pixels) of the element with `.id(id)`.pub fn element_bounds(&mut self, window: WindowId, id: &str) -> Option<Bounds<f32>> {self.flush();@@ -782,6 +795,8 @@ pub struct Window {dirty: bool,timer_pending: bool,animation_frame: bool,+ /// CSS animation time (virtual in headless windows).+ clock: crate::anim::Clock,vsync: bool,closed: bool,title: String,@@ -836,6 +851,7 @@ impl Window {dirty: true,timer_pending: false,animation_frame: false,+ clock: crate::anim::Clock::new(!headless),vsync: true,closed: false,title: title.to_owned(),@@ -896,6 +912,18 @@ impl Window {self.vsync = on;}+ /// Whether CSS animations or transitions were running at the last+ /// render (the window keeps requesting frames while they are).+ pub fn is_animating(&self) -> bool {+ self.caches.anim.running()+ }++ /// Whether the window will render again (something changed or is+ /// animating). False for an idle window.+ pub fn needs_render(&self) -> bool {+ self.dirty+ }+/// Frames presented to the native window so far.pub fn presented_frames(&self) -> u64 {self.native.map_or(0, |n| unsafe { sys::BK_window_frames(n) } as u64)@@ -992,15 +1020,19 @@ impl Window {let (canvas, scale) = (self.canvas, self.scale);let widgets = &mut self.widgets;let recycle = self.frame.take().unwrap_or_default();+ self.caches.anim.begin(self.clock.now());let frame = layout(root, vp, &self.state, &mut self.caches, recycle,&mut |key, spec| widgets.ensure(canvas, key, spec, scale));+ // CSS animations / transitions still moving: render again next frame+ // (nothing running: no frames, so an idle window costs no CPU)+ let animating = self.caches.anim.end();// `@container`: sizes changed under a query: render once morelet container_changed = self.caches.after_layout(&frame);let p = &mut self.painter;p.reset();{let _s = span(Phase::Paint);- paint_frame(&frame, &self.caches.styles, &mut self.caches.text, p, vp);+ paint_frame(&frame, &self.caches.styles, &mut self.caches.text, p, vp, self.scale);}{let _s = span(Phase::Flush);@@ -1034,6 +1066,9 @@ impl Window {if container_changed {self.dirty = true;}+ if animating {+ self.request_animation_frame();+ }}// -- events ------------------------------------------------------------------------------@@ -1263,6 +1298,7 @@ impl Window {} else {(sx, (sy + dy).clamp(0.0, ry))};+ let (nx, ny) = snap(f, &self.caches.styles, i, (sx, sy), (nx, ny));if (nx, ny) != (sx, sy) {self.state.scroll.insert(*key, (nx, ny));self.dirty = true;@@ -1314,3 +1350,75 @@ impl Window {/// Marker so `Window` is not `Send` (it holds raw kit pointers).#[allow(dead_code)]struct NotSend(PhantomData<*const ()>);++/// `scroll-snap-type`: the scroll position `to` (moving from `from`) of+/// container `i` moved to its children's snap positions: the next one in+/// the direction of travel (`mandatory`), or the nearest when it's within a+/// third of the view (`proximity`).+fn snap(f: &crate::layout::Frame, styles: &crate::layout::StyleStore, i: usize, from: (f32, f32), to: (f32, f32))+ -> (f32, f32) {+ let n = &f.nodes[i];+ let c = &styles[n.style];+ if c.snap_axes == 0 {+ return to;+ }+ let (rx, ry) = n.scroll_range;+ let view = n.bounds;+ let mut out = to;+ for axis in 0..2 {+ if c.snap_axes & (1 << axis) == 0 {+ continue;+ }+ let (cur, target, range, view_len) = if axis == 0 {+ (from.0, to.0, rx, view.size.width)+ } else {+ (from.1, to.1, ry, view.size.height)+ };+ if target == cur {+ continue;+ }+ // snap positions of the children, in scroll coordinates+ let mut points: Vec<f32> = Vec::new();+ for k in f.children_of(i) {+ let kc = &styles[f.nodes[k].style];+ let align = if axis == 0 { kc.snap_align.0 } else { kc.snap_align.1 };+ if align == 0 {+ continue;+ }+ let b = f.nodes[k].bounds;+ let (start, len, vstart) = if axis == 0 {+ (b.origin.x + cur, b.size.width, view.origin.x)+ } else {+ (b.origin.y + cur, b.size.height, view.origin.y)+ };+ let rel = start - vstart;+ let p = match align {+ 1 => rel,+ 2 => rel + len / 2.0 - view_len / 2.0,+ _ => rel + len - view_len,+ };+ points.push(p.clamp(0.0, range));+ }+ if points.is_empty() {+ continue;+ }+ let forward = target > cur;+ let pick = if c.snap_mandatory {+ if forward {+ points.iter().copied().filter(|p| *p > cur + 0.5).fold(f32::INFINITY, f32::min)+ } else {+ points.iter().copied().filter(|p| *p < cur - 0.5).fold(f32::NEG_INFINITY, f32::max)+ }+ } else {+ let near = points.iter().copied().min_by(|a, b| (a - target).abs().total_cmp(&(b - target).abs()));+ near.filter(|p| (p - target).abs() <= view_len / 3.0).unwrap_or(target)+ };+ let v = if pick.is_finite() { pick } else { target };+ if axis == 0 {+ out.0 = v;+ } else {+ out.1 = v;+ }+ }+ out+}diff --git a/bindings/rust/blenderui/tests/animation.rs b/bindings/rust/blenderui/tests/animation.rsnew file mode 100644index 0000000..93477cb--- /dev/null+++ b/bindings/rust/blenderui/tests/animation.rs@@ -0,0 +1,317 @@+//! CSS animations and transitions. Headless windows run on a virtual clock+//! that only `App::advance_clock` moves, so every sample is deterministic.++use std::time::Duration;++use blenderui::prelude::*;++fn open<V: Render>(cx: &mut App, w: f32, h: f32, v: V) -> WindowHandle<V> {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds {+ origin: point(px(0.0), px(0.0)),+ size: size(px(w), px(h)),+ })),+ ..Default::default()+ };+ cx.open_window(opts, |_, cx| cx.new(|_| v)).unwrap()+}++struct Page {+ css: &'static str,+}++impl Render for Page {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ body()+ .child(div().id("a"))+ .child(div().id("b"))+ .child(div().id("c"))+ .child(style().child(self.css))+ }+}++fn page(cx: &mut App, css: &'static str) -> WindowId {+ let win = open(cx, 400.0, 300.0, Page { css });+ cx.draw(win.id);+ win.id+}++fn width(cx: &mut App, win: WindowId, id: &str) -> f32 {+ cx.element_bounds(win, id).unwrap_or_else(|| panic!("no element {id}")).size.width+}++fn ms(cx: &mut App, n: u64) {+ cx.advance_clock(Duration::from_millis(n));+}++fn near(a: f32, b: f32) -> bool {+ (a - b).abs() <= 1.0+}++/// The window is idle: not animating and nothing scheduled.+fn idle(cx: &mut App, win: WindowId) -> bool {+ cx.draw(win);+ let w = cx.window(win).unwrap();+ !w.is_animating() && !w.needs_render()+}+++#[test]+fn keyframes_width_from_50_to() {+ Application::headless().run(|cx| {+ let w = page(cx, "body { margin: 0 } div { height: 10px; width: 30px }+ @keyframes grow { 0% { width: 0 } 50% { width: 100px } 100% { width: 50px } }+ #a { animation: grow 2s linear }");+ assert_eq!(width(cx, w, "a"), 0.0, "0%");+ assert!(cx.window(w).unwrap().is_animating());+ ms(cx, 500);+ assert_eq!(width(cx, w, "a"), 50.0, "25%: halfway to the 50% keyframe");+ ms(cx, 500);+ assert_eq!(width(cx, w, "a"), 100.0, "50%");+ ms(cx, 500);+ assert_eq!(width(cx, w, "a"), 75.0, "75%");+ ms(cx, 600);+ assert_eq!(width(cx, w, "a"), 30.0, "finished, no fill: the cascaded value");+ assert!(idle(cx, w), "no frames once finished");+ assert_eq!(width(cx, w, "b"), 30.0, "other elements untouched");+ });+}++#[test]+fn from_to_selector_lists_and_later_blocks() {+ Application::headless().run(|cx| {+ let w = page(cx, "body { margin: 0 } div { height: 10px; width: 30px }+ @keyframes k { from, to { width: 100px } to { width: 200px } }+ @keyframes k2 { from { width: 1px } }+ @keyframes k2 { to { width: 300px } }+ @media (max-width: 10px) { @keyframes k2 { to { width: 5px } } }+ #a { animation: k 1s linear }+ #b { animation: k2 1s linear }");+ ms(cx, 500);+ assert_eq!(width(cx, w, "a"), 150.0, "`to` given twice: the later block wins");+ assert_eq!(width(cx, w, "b"), 165.0, "the last matching @keyframes wins, from the underlying 30px");+ });+}++#[test]+fn iterations_and_alternate() {+ Application::headless().run(|cx| {+ let w = page(cx, "body { margin: 0 } div { height: 10px; width: 30px }+ @keyframes k { from { width: 0 } to { width: 100px } }+ #a { animation: k 1s linear 2 alternate forwards }+ #b { animation: k 1s linear infinite reverse }");+ ms(cx, 250);+ assert_eq!(width(cx, w, "a"), 25.0);+ assert_eq!(width(cx, w, "b"), 75.0, "reverse");+ ms(cx, 1000);+ assert_eq!(width(cx, w, "a"), 75.0, "second iteration runs backwards");+ assert_eq!(width(cx, w, "b"), 75.0);+ ms(cx, 2000);+ assert_eq!(width(cx, w, "a"), 0.0, "forwards fill holds the end of the last (reversed) iteration");+ assert!(cx.window(w).unwrap().is_animating(), "infinite keeps going");+ });+}++#[test]+fn fill_modes_and_delays() {+ Application::headless().run(|cx| {+ let w = page(cx, "body { margin: 0 } div { height: 10px; width: 30px }+ @keyframes k { from { width: 10px } to { width: 110px } }+ #a { animation: k 1s linear 1s backwards }+ #b { animation: k 1s linear 1s }+ #c { animation: k 1s linear -500ms forwards }");+ assert_eq!(width(cx, w, "a"), 10.0, "backwards: the first keyframe during the delay");+ assert_eq!(width(cx, w, "b"), 30.0, "no fill: the cascaded value during the delay");+ assert_eq!(width(cx, w, "c"), 60.0, "negative delay starts midway");+ ms(cx, 1500);+ assert_eq!(width(cx, w, "a"), 60.0);+ assert_eq!(width(cx, w, "b"), 60.0);+ assert_eq!(width(cx, w, "c"), 110.0, "forwards: the last keyframe after the end");+ ms(cx, 1000);+ assert_eq!(width(cx, w, "a"), 30.0, "backwards only: no fill after");+ assert_eq!(width(cx, w, "c"), 110.0);+ assert!(idle(cx, w), "filling forwards doesn't need frames");+ });+}++#[test]+fn steps_and_cubic_bezier() {+ Application::headless().run(|cx| {+ let w = page(cx, "body { margin: 0 } div { height: 10px; width: 30px }+ @keyframes k { from { width: 0 } to { width: 100px } }+ #a { animation: k 1s steps(4) }+ #b { animation: k 1s steps(4, jump-start) }+ #c { animation: k 1s cubic-bezier(0.25, 0.1, 0.25, 1) }");+ ms(cx, 300);+ assert_eq!(width(cx, w, "a"), 25.0);+ assert_eq!(width(cx, w, "b"), 50.0);+ ms(cx, 200);+ assert!(near(width(cx, w, "c"), 80.24), "ease at 50%: {}", width(cx, w, "c"));+ ms(cx, 499);+ assert_eq!(width(cx, w, "a"), 75.0);+ });+}++#[test]+fn per_keyframe_easing_and_shorthands() {+ Application::headless().run(|cx| {+ let w = page(cx, "body { margin: 0 } div { height: 10px; width: 30px }+ @keyframes k { from { width: 0; animation-timing-function: step-end } to { width: 100px } }+ @keyframes m { to { margin-left: 100px; opacity: 0 } }+ #a { animation: k 1s linear }+ #b { animation-name: m; animation-duration: 1s; animation-timing-function: linear }");+ ms(cx, 900);+ assert_eq!(width(cx, w, "a"), 0.0, "the keyframe's own easing holds the value");+ let b = cx.element_bounds(w, "b").unwrap();+ assert_eq!(b.origin.x, 90.0, "margin-left animates from the underlying 0");+ });+}++#[test]+fn paused_and_important() {+ Application::headless().run(|cx| {+ let w = page(cx, "body { margin: 0 } div { height: 10px; width: 30px }+ @keyframes k { from { width: 0 } to { width: 100px } }+ #a { animation: k 1s linear paused }+ #b { animation: k 1s linear; width: 40px !important }");+ ms(cx, 500);+ assert_eq!(width(cx, w, "a"), 0.0, "paused at its start");+ assert_eq!(width(cx, w, "b"), 40.0, "!important beats animations");+ ms(cx, 600);+ assert!(idle(cx, w), "paused animations request no frames");+ });+}++#[test]+fn unknown_keyframes_and_none_cost_nothing() {+ Application::headless().run(|cx| {+ let w = page(cx, "body { margin: 0 } div { height: 10px; width: 30px }+ #a { animation: nope 1s } #b { transition: width 1s } #c { animation: none }");+ assert_eq!(width(cx, w, "a"), 30.0);+ assert!(idle(cx, w), "nothing to animate: idle");+ });+}++struct Hover;++impl Render for Hover {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ body()+ .child(div().id("t"))+ .child(style().child("body { margin: 0; background: black }+ #t { width: 100px; height: 50px; background: rgb(255, 0, 0);+ transition: width 1s linear, background-color 1s linear }+ #t:hover { width: 200px; background: rgb(0, 0, 255) }"))+ }+}++#[test]+fn transition_on_hover_and_reverse() {+ Application::headless().run(|cx| {+ let win = open(cx, 400.0, 100.0, Hover).id;+ cx.draw(win);+ assert!(idle(cx, win), "transitions alone don't animate");+ cx.simulate_mouse_move(win, 10.0, 10.0);+ assert_eq!(width(cx, win, "t"), 100.0, "starts at the old value");+ assert!(cx.window(win).unwrap().is_animating());+ ms(cx, 500);+ assert_eq!(width(cx, win, "t"), 150.0);+ let img = cx.draw(win);+ let s = img.0 as f32 / 400.0;+ let p = img.2[(10.0 * s) as usize * img.0 + (10.0 * s) as usize];+ let (r, b) = ((p >> 16) & 0xff, p & 0xff);+ assert!((126..=129).contains(&r) && (126..=129).contains(&b), "halfway color {p:06x}");+ // leave midway: back to 100px, taking only as long as it ran+ cx.simulate_mouse_move(win, 300.0, 80.0);+ assert_eq!(width(cx, win, "t"), 150.0, "reverses from the current value");+ ms(cx, 250);+ assert_eq!(width(cx, win, "t"), 125.0);+ ms(cx, 250);+ assert_eq!(width(cx, win, "t"), 100.0);+ assert!(idle(cx, win), "no frames after the transition ends");+ });+}++struct Toggle {+ wide: bool,+}++impl Render for Toggle {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ body()+ .child(div().id("t").class(if self.wide { "wide" } else { "narrow" }))+ .child(style().child("body { margin: 0 }+ #t { height: 10px; transition: all 1s cubic-bezier(0, 0, 1, 1); opacity: 1 }+ .narrow { width: 100px } .wide { width: 300px; opacity: 0.5 }"))+ }+}++#[test]+fn transition_all_and_interrupt() {+ Application::headless().run(|cx| {+ let h = open(cx, 400.0, 100.0, Toggle { wide: false });+ let win = h.id;+ cx.draw(win);+ h.update(cx, |v, _, cx| {+ v.wide = true;+ cx.notify();+ });+ cx.draw(win);+ ms(cx, 500);+ assert_eq!(width(cx, win, "t"), 200.0);+ // back midway: from the current value, shortened to the time it ran+ h.update(cx, |v, _, cx| {+ v.wide = false;+ cx.notify();+ });+ assert_eq!(width(cx, win, "t"), 200.0);+ ms(cx, 250);+ assert_eq!(width(cx, win, "t"), 150.0, "reversed: half the duration (shortened)");+ ms(cx, 300);+ assert_eq!(width(cx, win, "t"), 100.0);+ assert!(idle(cx, win));+ });+}++struct Late {+ second: bool,+}++impl Render for Late {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let mut b = body().child(div().id("p").class("x").child(div().id("kid")));+ if self.second {+ b = b.child(div().id("q").class("x"));+ }+ b.child(style().child("body { margin: 0 } div { height: 10px }+ @keyframes k { from { width: 0; color: rgb(0, 0, 0) } to { width: 100px; color: rgb(200, 0, 0) } }+ .x { animation: k 1s linear } #kid { width: 5px; transition: color 1s }"))+ }+}++#[test]+fn each_element_has_its_own_clock_and_shared_styles_stay_clean() {+ Application::headless().run(|cx| {+ let h = open(cx, 400.0, 100.0, Late { second: false });+ let win = h.id;+ cx.draw(win);+ ms(cx, 500);+ assert_eq!(width(cx, win, "p"), 50.0);+ h.update(cx, |v, _, cx| {+ v.second = true;+ cx.notify();+ });+ assert_eq!(width(cx, win, "q"), 0.0, "same rules, started later: its own start time");+ assert_eq!(width(cx, win, "p"), 50.0, "the shared style isn't the animated one");+ ms(cx, 250);+ assert_eq!(width(cx, win, "p"), 75.0);+ assert_eq!(width(cx, win, "q"), 25.0);+ ms(cx, 1000);+ assert_eq!(width(cx, win, "p"), 400.0, "done: the cascaded `auto` width");+ assert_eq!(width(cx, win, "q"), 400.0);+ // #kid transitions the color it inherits from the animation's end+ assert!(cx.window(win).unwrap().is_animating());+ ms(cx, 1000);+ assert!(idle(cx, win));+ });+}diff --git a/bindings/rust/blenderui/tests/basic_css.rs b/bindings/rust/blenderui/tests/basic_css.rsindex e147f29..0c95cfb 100644--- a/bindings/rust/blenderui/tests/basic_css.rs+++ b/bindings/rust/blenderui/tests/basic_css.rs@@ -153,7 +153,7 @@ fn empty_cells_hide() {let (_, at) = page(cx, 200.0, 100.0, "html, body { margin: 0; background: #000 }table { width: 100px; empty-cells: hide; border-spacing: 0 }- td { height: 30px; background: #0f0; padding: 0 }+ td { width: 50px; height: 30px; background: #0f0; padding: 0 }", || {body().child(table().child(tr().child(td().child("x")).child(td().child(" "))))});diff --git a/bindings/rust/blenderui/tests/effects.rs b/bindings/rust/blenderui/tests/effects.rsnew file mode 100644index 0000000..910fe7e--- /dev/null+++ b/bindings/rust/blenderui/tests/effects.rs@@ -0,0 +1,241 @@+//! Pixel effects (filter, backdrop-filter, mix-blend-mode, clip-path, mask,+//! rotate / skew / scale transforms), rounded dashed borders, border-image,+//! table column sizing, scroll snapping, overflow-wrap in inline text and+//! the capitalized Blender components, end to end on headless pages.++use blenderui::prelude::*;++fn open<V: Render>(cx: &mut App, w: f32, h: f32, v: V) -> WindowHandle<V> {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds {+ origin: point(px(0.0), px(0.0)),+ size: size(px(w), px(h)),+ })),+ ..Default::default()+ };+ cx.open_window(opts, |_, cx| cx.new(|_| v)).unwrap()+}++struct Page {+ css: &'static str,+ body: fn() -> Div,+}++impl Render for Page {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ (self.body)().child(style().child(self.css))+ }+}++fn page(cx: &mut App, w: f32, h: f32, css: &'static str, body: fn() -> Div)+ -> (WindowId, impl Fn(f32, f32) -> u32 + use<>) {+ let win = open(cx, w, h, Page { css, body });+ let img = cx.draw(win.id);+ let s = img.0 as f32 / w;+ (win.id, move |x: f32, y: f32| img.2[(y * s) as usize * img.0 + (x * s) as usize])+}++fn rgb_of(p: u32) -> (i32, i32, i32) {+ ((p >> 16 & 255) as i32, (p >> 8 & 255) as i32, (p & 255) as i32)+}++fn near(p: u32, q: u32, tol: i32) -> bool {+ let (a, b) = (rgb_of(p), rgb_of(q));+ (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol && (a.2 - b.2).abs() <= tol+}++const BASE: &str = "html, body { margin: 0; background: #000 } .b { position: absolute }";++#[test]+fn filters() {+ Application::headless().run(|cx| {+ let (_, at) = page(cx, 300.0, 100.0, "+ html, body { margin: 0; background: #000 } .b { position: absolute; top: 10px; width: 40px; height: 40px }+ #g { left: 10px; background: #f00; filter: grayscale(1) }+ #i { left: 60px; background: #ff0000; filter: invert(1) }+ #o { left: 110px; background: #fff; filter: opacity(0.5) }+ #bl { left: 180px; background: #fff; filter: blur(4px) }+ ", || {+ body().child(div().id("g").class("b")).child(div().id("i").class("b"))+ .child(div().id("o").class("b")).child(div().id("bl").class("b"))+ });+ let (r, g, b) = rgb_of(at(30.0, 30.0));+ assert!((r - g).abs() <= 2 && (g - b).abs() <= 2 && r > 40 && r < 80, "grayscale red: {r} {g} {b}");+ assert!(near(at(80.0, 30.0), 0x00ffff, 3), "invert: {:06x}", at(80.0, 30.0));+ assert!(near(at(130.0, 30.0), 0x808080, 3), "opacity: {:06x}", at(130.0, 30.0));+ // blur spreads past the box and softens its edge+ assert!(rgb_of(at(176.0, 30.0)).0 > 10, "blurred outside: {:06x}", at(176.0, 30.0));+ assert!(rgb_of(at(181.0, 30.0)).0 < 250, "soft edge: {:06x}", at(181.0, 30.0));+ assert!(near(at(200.0, 30.0), 0xffffff, 8), "centre stays: {:06x}", at(200.0, 30.0));+ });+}++#[test]+fn transforms_rotate_scale_skew() {+ Application::headless().run(|cx| {+ let (_, at) = page(cx, 300.0, 200.0, "+ html, body { margin: 0; background: #000 } .b { position: absolute; background: #0f0 }+ #r { left: 50px; top: 50px; width: 80px; height: 20px; transform: rotate(90deg) }+ #s { left: 200px; top: 20px; width: 20px; height: 20px; scale: 2 }+ #k { left: 150px; top: 150px; width: 40px; height: 20px; transform: skewX(45deg) }+ ", || body().child(div().id("r").class("b")).child(div().id("s").class("b")).child(div().id("k").class("b")));+ // a 80x20 bar rotated about its centre (90, 60) stands 20 wide, 80 tall+ assert_eq!(at(90.0, 30.0), 0x00ff00, "rotated bar reaches up");+ assert_eq!(at(60.0, 60.0), 0x000000, "and no longer reaches left");+ // scale(2) about the centre (210, 30): 20px grows to 40px+ assert_eq!(at(193.0, 30.0), 0x00ff00, "scaled box grows");+ // skewX(45deg) about the centre leans the top right, the bottom left+ // (y points down, so the top edge moves left and the bottom right)+ assert_eq!(at(143.0, 152.0), 0x00ff00, "top edge pushed left");+ assert_eq!(at(193.0, 168.0), 0x00ff00, "bottom edge pushed right");+ });+}++#[test]+fn clip_path_and_mask() {+ Application::headless().run(|cx| {+ let (_, at) = page(cx, 300.0, 120.0, "+ html, body { margin: 0; background: #000 } .b { position: absolute; top: 10px; width: 80px; height: 80px; background: #f00 }+ #c { left: 10px; clip-path: circle(40%) }+ #p { left: 110px; clip-path: polygon(0 0, 100% 0, 0 100%) }+ #m { left: 210px; mask-image: linear-gradient(to right, #000, transparent) }+ ", || body().child(div().id("c").class("b")).child(div().id("p").class("b")).child(div().id("m").class("b")));+ assert_eq!(at(50.0, 50.0), 0xff0000, "circle centre");+ assert_eq!(at(13.0, 13.0), 0x000000, "circle corner clipped");+ assert_eq!(at(120.0, 20.0), 0xff0000, "triangle kept part");+ assert_eq!(at(180.0, 80.0), 0x000000, "triangle clipped part");+ let (l, r) = (rgb_of(at(215.0, 50.0)).0, rgb_of(at(285.0, 50.0)).0);+ assert!(l > 200 && r < 50, "mask fades left to right: {l} {r}");+ });+}++#[test]+fn blend_modes_and_backdrop_filter() {+ Application::headless().run(|cx| {+ let (_, at) = page(cx, 300.0, 120.0, "+ html, body { margin: 0; background: #000 }+ .under { position: absolute; top: 10px; width: 60px; height: 60px; background: #ffff00 }+ #m { position: absolute; top: 10px; left: 10px; width: 60px; height: 60px; background: #00ffff; mix-blend-mode: multiply }+ #d { position: absolute; top: 10px; left: 110px; width: 60px; height: 60px; background: #808080; mix-blend-mode: difference }+ #bd { position: absolute; top: 10px; left: 210px; width: 60px; height: 60px; backdrop-filter: invert(1) }+ ", || {+ body().child(div().class("under").style("left: 10px")).child(div().class("under").style("left: 110px"))+ .child(div().class("under").style("left: 210px"))+ .child(div().id("m")).child(div().id("d")).child(div().id("bd"))+ });+ assert!(near(at(40.0, 40.0), 0x00ff00, 3), "yellow x cyan = green: {:06x}", at(40.0, 40.0));+ assert!(near(at(140.0, 40.0), 0x7f7f80, 3), "difference: {:06x}", at(140.0, 40.0));+ assert!(near(at(240.0, 40.0), 0x0000ff, 3), "inverted backdrop: {:06x}", at(240.0, 40.0));+ });+}++#[test]+fn rounded_dashed_borders_and_border_image() {+ Application::headless().run(|cx| {+ let (_, at) = page(cx, 300.0, 120.0, "+ html, body { margin: 0; background: #000 }+ #d { position: absolute; left: 10px; top: 10px; width: 100px; height: 60px;+ border: 4px dashed #f00; border-radius: 20px }+ #i { position: absolute; left: 150px; top: 10px; width: 100px; height: 60px; border: 10px solid;+ border-image: linear-gradient(#0f0, #00f) 10 }+ ", || body().child(div().id("d")).child(div().id("i")));+ // a dashed rounded border: the corner region inside the radius stays empty+ assert_eq!(at(11.0, 11.0), 0x000000, "corner outside the curve");+ let top: Vec<bool> = (30..90).map(|x| at(x as f32 + 0.5, 12.0) == 0xff0000).collect();+ assert!(top.iter().any(|v| *v) && top.iter().any(|v| !*v), "dashes along the top");+ // the border image paints the border area, not the inside+ let edge = at(152.0, 40.0);+ assert!(edge != 0x000000, "border image drawn: {edge:06x}");+ assert_eq!(at(200.0, 40.0), 0x000000, "middle not filled without `fill`");+ });+}++#[test]+fn tables_size_columns_to_content() {+ Application::headless().run(|cx| {+ let (w, _) = page(cx, 600.0, 200.0, "+ body { margin: 0 } table { border-spacing: 0 } td { padding: 0 }+ #fixed { table-layout: fixed; width: 300px }+ ", || {+ body()+ .child(table().id("auto").child(tbody()+ .child(tr().child(td().id("a1").child("x")).child(td().id("b1").child("a much longer cell")))+ .child(tr().child(td().id("a2").child("y")).child(td().id("b2").child("z")))))+ .child(table().id("fixed").child(tbody()+ .child(tr().child(td().id("f1").style("width: 100px").child("x")).child(td().id("f2").child("y")))))+ });+ let r = |id: &str, cx: &mut App| cx.element_bounds(w, id).unwrap();+ let (a1, b1, a2, b2) = (r("a1", cx), r("b1", cx), r("a2", cx), r("b2", cx));+ assert!(b1.size.width > 2.0 * a1.size.width, "columns follow content");+ assert_eq!(a1.size.width, a2.size.width, "a column lines up across rows");+ assert_eq!(b1.origin.x, b2.origin.x);+ let t = r("auto", cx);+ assert!(t.size.width < 400.0, "an auto table shrinks to its columns: {}", t.size.width);+ assert_eq!(r("f1", cx).size.width, 100.0, "fixed layout uses the first row's widths");+ assert_eq!(r("f2", cx).size.width, 200.0);+ });+}++#[test]+fn scroll_snap_mandatory() {+ Application::headless().run(|cx| {+ let (w, _) = page(cx, 200.0, 200.0, "+ body { margin: 0 }+ #s { height: 100px; overflow-y: scroll; scroll-snap-type: y mandatory }+ .p { height: 100px; scroll-snap-align: start }+ ", || {+ body().child(div().id("s").child(div().class("p")).child(div().id("p2").class("p")).child(div().class("p")))+ });+ cx.simulate_scroll(w, 50.0, 50.0, -1);+ cx.draw(w);+ // one wheel notch lands exactly on the next page: the second child at the top+ let p2 = cx.element_bounds(w, "p2").unwrap();+ assert_eq!(p2.origin.y, 0.0, "snapped to the second child: {p2:?}");+ });+}++#[test]+fn overflow_wrap_in_inline_text() {+ Application::headless().run(|cx| {+ let (w, _) = page(cx, 400.0, 400.0, "+ body { margin: 0 } p { width: 60px; margin: 0; line-height: 20px; overflow-wrap: anywhere }+ ", || {+ body().child(p().id("p").child("short ").child(b().child("aaaaaaaaaaaaaaaaaaaaaaaaaaaa")))+ });+ cx.draw(w); // widths settle after one more layout+ let h = cx.element_bounds(w, "p").unwrap().size.height;+ assert!(h >= 60.0, "the long bold word breaks across lines: {h}");+ });+}++struct Blender;++impl Render for Blender {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ rsx! {+ <body m-0>+ <Button id="bb" onClick={|| {}}>"Apply"</Button>+ <NumberSlider id="ns" min={0.0} max={10.0} />+ <Checkbox id="cb" checked={true} />+ <input id="plain" type="range" />+ </body>+ }+ }+}++#[test]+fn blender_components_are_elements() {+ Application::headless().run(|cx| {+ let win = open(cx, 300.0, 200.0, Blender);+ cx.draw(win.id);+ for id in ["bb", "ns", "cb", "plain"] {+ assert!(cx.element_bounds(win.id, id).is_some(), "{id} laid out");+ }+ // gpui syntax: the same components are functions+ let d = Checkbox().checked(true);+ let _ = d;+ });+}++#[allow(dead_code)]+const _BASE: &str = BASE;diff --git a/docs/rust.md b/docs/rust.mdindex 74ef178..d815448 100644--- a/docs/rust.md+++ b/docs/rust.md@@ -240,10 +240,12 @@ The document is wrapped in `<html><body>` unless your root already is one, so### Blender styling: `styled`-Plain elements get the browsers' defaults: black text on white, 16 px,-`#0000ee` links. Mark an element `styled` and it, and everything inside it,-gets Blender's look instead: the `#303030` background, `#e6e6e6` 13 px text,-blue links, dark `code` / `pre`, themed tables, fieldsets and dialogs.+Plain elements look exactly like they do in a browser: black serif text+(Times New Roman) on white, 16 px, `#0000ee` links, and Chrome's form+controls. Mark an element `styled` and it, and everything inside it, gets+Blender's look instead: the `#303030` background, `#e6e6e6` 13 px UI-font+text, blue links, dark `code` / `pre`, themed tables, fieldsets and dialogs,+and Blender's widgets for the form controls.```rustbody().styled().child(h1().child("Blender look")) // gpui syntax@@ -251,11 +253,32 @@ rsx! { <div styled class="p-4">"Blender look"</div> } // rsx! / view! (Leptos-stdiv().styled().child(div().attr("styled", "false")) // opt a subtree back out```-Your own CSS still wins over either set of defaults. Form controls (`button`,-`input`, `select`, `textarea`, `progress` ...) are Blender widgets and look-the same inside or outside `styled`. From JavaScript use+Your own CSS still wins over either set of defaults. From JavaScript use`el.setAttribute('styled', '')`, or `<div styled>` in JSX.+### Blender components++The capitalized components are Blender's widgets, always, inside `styled` or+not: `Button`, `Checkbox`, `Radio`, `NumberField` (drag to scrub),+`NumberSlider`, `TextField`, `TextArea`, `ColorSwatch` (Blender's color+picker), `Dropdown` and `ProgressBar`. Each is the element it stands for, so+every element method and attribute works on it:++```rust+rsx! {+ <NumberSlider min={0.0} max={10.0} value="2.5" onChange={|e: &ChangeEvent| println!("{:?}", e.number)} />+ <Button onClick={|| println!("apply")}>"Apply"</Button>+ <Dropdown><option>"Cube"</option><option>"Sphere"</option></Dropdown>+}+div().child(Checkbox().checked(true)).child(Button().child("Apply")) // gpui syntax+```++In JavaScript they're exported from `@blender-ui/react` (`<NumberSlider min={0} max={10} />`)+and work as tag names with the DOM API (`win.createElement('NumberSlider')`).+The lowercase HTML elements (`button`, `input type="range"` ...) look like a+browser's controls, and like Blender inside `styled`. Run+`cargo run --example forms` to see all three side by side.+## StylingThree ways, one cascade:@@ -328,10 +351,20 @@ Layout is computed with [taffy](https://github.com/DioxusLabs/taffy):- **Flexbox** and **grid**: every property of both modules (except`grid-template-areas`), including `repeat()`, `minmax()`, `fr`,`auto-fill` / `auto-fit`, spans and line placement.-- **Tables**: rows and cells share the width (`colspan` weights cells),- `border-spacing`, `border-collapse` and `caption-side` apply.+- **Tables**: columns are as wide as their widest content and line up across+ rows; a table with an auto width shrinks to its columns (up to its+ container), like a browser's auto layout. `table-layout: fixed` takes the+ first row's widths. `colspan`, `border-spacing`, `border-collapse`,+ `caption-side` and `empty-cells` apply.- **Positioning**: `relative`, `absolute` (and `fixed` as absolute), `inset`- properties, `z-index` for painting and hit testing, `transform: translate()`.+ properties, `z-index` for painting and hit testing, and every 2D transform+ (`translate`, `scale`, `rotate`, `skew`, `matrix`, `transform-origin`, the+ individual `rotate` / `scale` / `translate` properties).+- **Bidirectional text**: Hebrew and Arabic runs are reordered inside+ left-to-right text (a compact Unicode Bidirectional Algorithm), `direction: rtl`+ and `unicode-bidi: bidi-override` apply.+- **Scroll snapping**: `scroll-snap-type` (`x` / `y` / `both`, `mandatory` /+ `proximity`) and `scroll-snap-align` on the children.- **Overflow**: `hidden` / `clip` clip, `scroll` / `auto` scroll with thewheel (Shift for horizontal) and show overlay scrollbars.- **Lists**: `list-style-type` (`disc`, `circle`, `square`, `decimal`,@@ -341,8 +374,11 @@ Layout is computed with [taffy](https://github.com/DioxusLabs/taffy):## Form controls-Form elements are Blender's widgets, with Blender's interaction (drag to-scrub numbers, Ctrl+Z, double-click to type, Escape to cancel):+Outside `styled`, form elements look and behave like Chrome's (its colors and+shapes, typed number fields with spin buttons, a range thumb that jumps to+the click). Inside `styled`, and as the capitalized Blender components, they+are Blender's widgets, with Blender's interaction (drag to scrub numbers,+Ctrl+Z, double-click to type, Escape to cancel):| HTML | Blender widget | `ChangeEvent` || ------------------------------------------------- | ------------------------------------ | ------------------------------------- |@@ -427,9 +463,9 @@ From `cargo test --test parity -- --nocapture`:| Area | Coverage || ------------------------------------- | -------------------------------------------------------------------------------- || HTML elements (WHATWG index) | **113 / 113** constructible, plus `svg` / `math` roots; 9 are Blender widgets |-| CSS properties | **226** change layout or rendering; **169** more parse but have no effect |-| W3C property index (745 properties) | **223** rendered (30%), **161** parsed without effect (22%), **361** not recognized (48%): most of these are drafts, speech, paged media and SVG |-| CSS 2.1, screen properties | **88 / 90** rendered, 90 / 90 parsed |+| CSS properties | **271** change layout or rendering; **137** more parse but have no effect |+| W3C property index (745 properties) | **261** rendered (35%), **129** parsed without effect (17%), **355** not recognized (48%): most of these are drafts, speech, paged media and SVG |+| CSS 2.1, screen properties | **90 / 90** rendered, 90 / 90 parsed || Flexbox | **12 / 12** || Grid | **23 / 23** (including `grid-template-areas` and named lines) || Tailwind CSS v4 | Classes compile on first use (v4 theme, variants, arbitrary values); `tw!` checks them at compile time |@@ -445,9 +481,22 @@ div().class(tw!("grid grid-cols-3 gap-4 md:grid-cols-6 hover:bg-sky-500/50"))div().style("width: calc(100% - 2 * var(--gap)); background: color-mix(in oklch, var(--brand) 60%, white)")```-The CSS 2.1 properties that parse without effect: `table-layout` (tables always share width like `fixed`) and `unicode-bidi` (no bidi reordering).+Every CSS 2.1 screen property renders.++**Effects** work on the element's pixels: `filter` and `backdrop-filter`+(`blur`, `brightness`, `contrast`, `grayscale`, `hue-rotate`, `invert`,+`opacity`, `saturate`, `sepia`, `drop-shadow`), `mix-blend-mode` (all 16 modes+and `plus-lighter`), `clip-path` (`inset()`, `circle()`, `ellipse()`,+`polygon()`, reference boxes), `mask` / `mask-image` (gradients and PNGs,+alpha or luminance, with size, position and repeat) and rotate / skew / scale+/ matrix transforms. The element's subtree is drawn offscreen with the+canvas' own drawing code, filtered, clipped, masked and resampled (bilinear,+like Blender's image transform), then composited back with the W3C formulas;+the result is cached, so a page that doesn't change costs nothing.+`border-image` (gradients and PNGs, slice, width, outset, `stretch` /+`repeat` / `round` / `space`, `fill`) draws the nine slices.-Also rendered: every `border-style` and `outline-style` (`dashed`, `dotted`, `double`, `groove`, `ridge`, `inset`, `outset`; corners of styled borders are square), `text-decoration-style` (including `wavy`), `-thickness` and `text-underline-offset`, `background-clip` / `background-origin` (`border-box`, `padding-box`, `content-box`), `background-attachment: fixed`, `clip: rect()` on absolutely positioned boxes, counters (`counter-reset` / `-increment` / `-set` with `counter()` and `counters()` in `content`), `empty-cells`, `list-style-image`, `word-break: break-all`, `overflow-wrap: anywhere | break-word` (in text that mixes inline elements, long words break only with `break-all`) and `tab-size`.+Also rendered: every `border-style` and `outline-style` (`dashed`, `dotted`, `double`, `groove`, `ridge`, `inset`, `outset`, following rounded corners with Blender's corner tessellation), `text-decoration-style` (including `wavy`), `-thickness` and `text-underline-offset`, `background-clip` / `background-origin` (`border-box`, `padding-box`, `content-box`), `background-attachment: fixed`, `clip: rect()` on absolutely positioned boxes, counters (`counter-reset` / `-increment` / `-set` with `counter()` and `counters()` in `content`), `empty-cells`, `list-style-image`, `word-break: break-all`, `overflow-wrap: anywhere | break-word` and `tab-size`.Also supported: `background-image: url()` (PNG) with `background-size` / `-position` (`-x` / `-y`) / `-repeat`, `object-fit` / `object-position`, logical border longhands (`border-inline-width` ...), `text-wrap-mode`, `white-space-collapse`, `scale`, `all`, `@container` size queries (`container-type`, `container-name`), `@font-face` (local font files) and `@property` initial values.@@ -456,11 +505,11 @@ How much is left, against all 745 properties in the| | Properties | Share ||---|---:|---:|-| Change layout or rendering | 223 | 30% |-| Parsed, no effect yet | 161 | 22% |-| Not recognized | 361 | 48% |+| Change layout or rendering | 261 | 35% |+| Parsed, no effect yet | 129 | 17% |+| Not recognized | 355 | 48% |-The 361 unrecognized properties break down as:+The 355 unrecognized properties break down as:| Group | Properties ||---|---:|@@ -473,14 +522,31 @@ The 361 unrecognized properties break down as:| Everything else | ~100 |The everyday screen CSS is much further along: Flexbox 12/12, Grid 23/23 and-CSS 2.1 88/90. The largest remaining gaps among common properties are visual-effects (transforms, filters, blend modes, `clip-path`, masks) and-animations and transitions.+CSS 2.1 90/90. The largest remaining gaps among common properties are 3D+transforms, OpenType font features and multi-column layout.++**Animations and transitions** run like a browser's: `@keyframes` (percent+lists, `from` / `to`, inside `@media`, per-keyframe+`animation-timing-function`), every `animation-*` longhand and the shorthand+(lists of animations, negative delays, `infinite`, every direction, fill mode+and play state), and `transition` / `transition-*` (`all` or property lists,+`transition-behavior: allow-discrete`; an interrupted transition starts from its+current value, and one sent back to where it came from takes only as long as it+ran). Easing: `linear`, `ease*`, `cubic-bezier()`, `steps()` with every jump+position, `step-start` / `-end` and `linear()` points. Lengths, percentages,+numbers, colors (in premultiplied sRGB), `box-shadow`, `text-shadow`,+`transform` (function by function), `rotate`, `scale`, `filter` /+`backdrop-filter` (function by function), `visibility` and `z-index` interpolate; other+properties flip at 50%. A window renders frames only while something moves:+finished or paused animations cost no CPU. Headless windows run on a virtual+clock that `App::advance_clock` moves, so tests step animations exactly.Not done yet:-- **Parsed, not applied:** `@keyframes`, transitions and animations; scroll snapping and OpenType font features.+- **Parsed, not applied:** OpenType font features (`font-feature-settings`, `font-variant-numeric` ...): the text engine has no shaping, and Blender's text library doesn't either. Multi-column layout (`columns`), `writing-mode`, `scroll-padding` / `scroll-margin`.+- **3D transforms:** `perspective`, `rotateX` / `rotateY`, `matrix3d` have no effect; 2D transforms don't change hit testing (clicks use the untransformed box).+- **Animations:** no `animationend` / `transitionend` events, no animations on `::before` / `::after`, and an element starts transitions only when it already had a `transition` in the previous frame (e.g. not when `transition` appears only under `:hover` on the first hover). Lengths mixing units that resolve differently (`50%` to `100px`, `auto`) flip at 50% instead of going through `calc()`.- **`@container` timing:** queries use the container's size from the previous layout; when it changes, the window renders once more.-- **Rendering effects:** 2D/3D `rotate` / `skew` transforms, `filter` / `backdrop-filter`, blend modes, `clip-path`, masks and `border-image`.+- **Effects:** `filter: url(#svg)`, `clip-path: path()`, and `mix-blend-mode` across stacking contexts (it blends with what was painted before it).- **The rest of the W3C property index:** about 360 entries this engine doesn't know, mostly drafts, speech, paged media and SVG.- **Box sizing:** the default is `border-box` (like Tailwind's preflight), not CSS's `content-box`.diff --git a/gpu/intern/gpu_raster.c b/gpu/intern/gpu_raster.cindex 9292220..c38614e 100644--- a/gpu/intern/gpu_raster.c+++ b/gpu/intern/gpu_raster.c@@ -2578,7 +2578,7 @@ typedef struct FamilyFiles {} FamilyFiles;static const FamilyFiles g_families[] = {- {"|sans|sans-serif|inter|segoe ui|system-ui|helvetica|arial|dejavu sans|liberation sans|noto "+ {"|sans|sans-serif|inter|segoe ui|system-ui|helvetica|dejavu sans|liberation sans|noto ""sans|tkdefaultfont|tktextfont|tkheadingfont|tkcaptionfont|tkmenufont|",{"segoeui.ttf|DejaVuSans.ttf|LiberationSans-Regular.ttf|NotoSans-Regular.ttf|Arial.ttf|""arial.ttf|Helvetica.ttc|SFNS.ttf",@@ -2605,6 +2605,12 @@ static const FamilyFiles g_families[] = {"New Roman Italic.ttf","timesbi.ttf|DejaVuSerif-BoldItalic.ttf|LiberationSerif-BoldItalic.ttf|NotoSerif-""BoldItalic.ttf|Times New Roman Bold Italic.ttf"}},+ /* browsers' form-control font on Windows (HTML-look widgets) */+ {"|arial|",+ {"arial.ttf|Arial.ttf|LiberationSans-Regular.ttf|DejaVuSans.ttf|Helvetica.ttc",+ "arialbd.ttf|Arial Bold.ttf|LiberationSans-Bold.ttf|DejaVuSans-Bold.ttf",+ "ariali.ttf|Arial Italic.ttf|LiberationSans-Italic.ttf|DejaVuSans-Oblique.ttf",+ "arialbi.ttf|Arial Bold Italic.ttf|LiberationSans-BoldItalic.ttf|DejaVuSans-BoldOblique.ttf"}},};static int family_index(const char *family)diff --git a/kit/include/BUI_kit.h b/kit/include/BUI_kit.hindex 7ac3e71..71d575e 100644--- a/kit/include/BUI_kit.h+++ b/kit/include/BUI_kit.h@@ -96,7 +96,7 @@ const char *BK_icon_list_name(int i);/* Types: column row grid box panel tabs sidetabs scroll label separator* progress button toggle checkbox decorator text search hotkey number slider* dropdown enum swatch popover menubutton menubar list tree gridview ramp- * curve normal histogram */+ * curve normal histogram radio textarea meter */BKNode *BK_node_new(const char *type);void BK_node_free(BKNode *node);const char *BK_node_type(const BKNode *node);@@ -113,7 +113,25 @@ void BK_node_invalidate(BKNode *node); /* redraw */void BK_node_relayout(BKNode *node); /* size/structure changed *//* Properties by name (see kit_props in kit_core.c for the list). Return 0 when- * the key is unknown for this node. */+ * the key is unknown for this node.+ *+ * "html" (number, any node, default 0): 1 switches the node to the browser+ * look — Chrome's default form controls (2020+ refresh, Windows, light) —+ * for drawing, natural size and interaction; 0 keeps Blender's. Values,+ * events and the other properties behave the same in both. It may change at+ * any time (the node relayouts). Classes with a browser look: button, toggle+ * (as a button, pressed while on), checkbox, radio, text, search, number+ * (typed, with spin buttons), slider (<input type=range>: absolute drag),+ * dropdown (<select>; its popup too), swatch (<input type=color>), progress+ * ("factor" < 0: indeterminate), meter, textarea. Others ignore it.+ * Natural sizes at scale 1: text/number 153x21, button text+16 x 21,+ * checkbox/radio 20x19 (13px box + 3px 3px 3px 4px margins, label after it),+ * range 129x16, select widest+24 x 19, color 50x27, progress 160x16,+ * meter 80x16, textarea 182 x (rows*15+6) with rows 2 unless "rows" is set.+ * Dropdown items starting with '\x01' are <optgroup> labels in the html look+ * (bold, not selectable, the following options indented).+ * "meter" nodes: value in min..max (default 0..1) plus "low", "high",+ * "optimum" (the HTML meter's green / yellow / red regions). */int BK_set_num(BKNode *node, const char *key, double value);int BK_set_str(BKNode *node, const char *key, const char *value);int BK_set_color(BKNode *node, const char *key, const float rgba[4]);diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.cindex ff33275..b14b7d8 100644--- a/kit/intern/kit_core.c+++ b/kit/intern/kit_core.c@@ -152,7 +152,7 @@ static const BKClass *const g_classes[] = {&bk_cls_menubutton, &bk_cls_menubar, &bk_cls_list, &bk_cls_tree,&bk_cls_gridview, &bk_cls_ramp, &bk_cls_curve, &bk_cls_normal,&bk_cls_histogram, &bk_cls_frame, &bk_cls_radio, &bk_cls_canvas,- &bk_cls_textarea, &bk_cls_image,+ &bk_cls_textarea, &bk_cls_image, &bk_cls_meter,};const BKClass *bk_class_find(const char *name)@@ -396,10 +396,12 @@ void bk_natural(BKNode *n, int *r_w, int *r_h){if (n->nat_gen != g_gen) {int w = 4 * bk_unit(), h = bk_unit();- if (n->cls->measure) {+ if (n->cls->measure || BK_HTML(n)) {const float saved = bk_text_scale;bk_text_scale = n->font_scale > 0.0f ? n->font_scale : 1.0f;- n->cls->measure(n, &w, &h);+ if (!(BK_HTML(n) && bk_html_measure(n, &w, &h)) && n->cls->measure) {+ n->cls->measure(n, &w, &h);+ }if (bk_text_scale > 1.0f) { /* taller text needs a taller widget */h = BK_MAX(h, (int)(h * bk_text_scale + 0.5f));}@@ -456,7 +458,9 @@ void bk_draw_tree(BKNode *n)if (n->cls->draw) {const float saved = bk_text_scale;bk_text_scale = n->font_scale > 0.0f ? n->font_scale : 1.0f;- n->cls->draw(n);+ if (!(BK_HTML(n) && bk_html_draw(n))) {+ n->cls->draw(n);+ }bk_text_scale = saved;}for (int i = 0; i < n->nkids; i++) {@@ -761,6 +765,7 @@ static const struct {{"events", NF_EVENTS, false}, {"nopropagate", NF_NOPROPAGATE, true},{"viewevents", NF_VIEWEVENTS, false}, {"noscrollbar", NF_NOSCROLLBAR, true},{"opaque", NF_OPAQUE, false},+ {"html", NF_HTML, true}, /* Chrome's form-control look (kit_widgets.c) */};static int g_view_watchers; /* > 0 once any node asked for view events */@@ -2136,7 +2141,7 @@ static void update_cursor(BKContext *ctx)if (ctx->modal) {name = ctx->modal->cls->cursor ? ctx->modal->cls->cursor : BK_CURSOR_CROSSHAIR;}- else if (ctx->grab && ctx->dragging && ctx->grab->cls->drag_cursor) {+ else if (ctx->grab && ctx->dragging && ctx->grab->cls->drag_cursor && !BK_HTML(ctx->grab)) {name = ctx->grab->cls->drag_cursor;}else {@@ -2160,7 +2165,7 @@ static void update_cursor(BKContext *ctx)static bool continuous(BKContext *ctx){- return ctx->host.warp && ctx->grab && ctx->dragging &&+ return ctx->host.warp && ctx->grab && ctx->dragging && !BK_HTML(ctx->grab) &&ctx->grab->cls->drag_cursor == BK_CURSOR_NONE;}diff --git a/kit/intern/kit_draw.c b/kit/intern/kit_draw.cindex 0a9160f..f05699d 100644--- a/kit/intern/kit_draw.c+++ b/kit/intern/kit_draw.c@@ -99,6 +99,14 @@ float bk_px(void)return (float)BK_MAX(1, bk_dpi() / 64); /* U.pixelsize */}float bk_text_scale = 1.0f;+/* The text scale browser-look widgets draw at (html_font_begin): text at+ * exactly this scale uses the browsers' form-control font. */+float bk_html_text_scale = -1.0f;++static const char *text_family(void)+{+ return bk_text_scale == bk_html_text_scale ? "arial" : g_font_family;+}const char *bk_font_family(void){@@ -282,6 +290,32 @@ void bk_checker(float x, float y, float w, float h)}}+void bk_argb(uint32_t c, float o[4])+{+ o[0] = ((c >> 16) & 0xff) / 255.0f;+ o[1] = ((c >> 8) & 0xff) / 255.0f;+ o[2] = (c & 0xff) / 255.0f;+ o[3] = ((c >> 24) & 0xff) / 255.0f;+}++void bk_html_box(float x, float y, float w, float h, float rad, const float fill[4],+ const float border[4], float bw)+{+ rad = fminf(rad, 0.5f * fminf(w, h));+ BUI_raster_widget(bk_draw.r, x, y, w, h, rad, CNR_ALL, fill, fill, border, border ? bw : 0.0f,+ NULL);+}++void bk_html_polyline(const float (*pts)[2], int n, const float c[4], float width)+{+ for (int i = 0; i + 1 < n; i++) {+ bk_line(pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1], c, width);+ }+ for (int i = 1; i + 1 < n; i++) { /* round joins */+ bk_circle(pts[i][0], pts[i][1], width * 0.5f, c);+ }+}+/** \} *//* -------------------------------------------------------------------- */@@ -1076,13 +1110,14 @@ float bk_text_width(const char *s, int len, bool bold)return 0.0f;}const float size = bk_font_size();- const uint64_t h = hash_str(s, len, bold);+ const char *fam = text_family();+ const uint64_t h = hash_str(s, len, bold) ^ (fam != g_font_family ? 0x9e3779b97f4a7c15ull : 0);MeasureSlot *slot = &g_measure[h & (MEASURE_SLOTS - 1)];if (slot->hash == h && slot->size == size) {return slot->width;}float w = 0.0f;- if (!BUI_text_measure(g_font_family, bold ? BUI_FONT_BOLD : 0, size, s, len, &w)) {+ if (!BUI_text_measure(fam, bold ? BUI_FONT_BOLD : 0, size, s, len, &w)) {w = len * size * 0.55f;}slot->hash = h;@@ -1113,7 +1148,7 @@ void bk_text_f(float x, float baseline, const char *s, int len, const float c[4]if (len == 0) {return;}- BUI_raster_set_font(bk_draw.r, g_font_family, bold ? BUI_FONT_BOLD : 0);+ BUI_raster_set_font(bk_draw.r, text_family(), bold ? BUI_FONT_BOLD : 0);const float px = floorf(x + 0.5f), py = floorf(baseline + 0.5f);if (bk_text_shadow == 1) {const float sc[4] = {0.0f, 0.0f, 0.0f, 0.5f * c[3]};diff --git a/kit/intern/kit_frame.c b/kit/intern/kit_frame.cindex 84e0dd6..66aad27 100644--- a/kit/intern/kit_frame.c+++ b/kit/intern/kit_frame.c@@ -1586,6 +1586,81 @@ static void canvas_draw(BKNode *n)bk_clip_pop();}+/* Offscreen rasterization for CSS effects (filters, blend modes, masks,+ * clip-path, rotate/skew): draws `items` (device pixels, as BK_canvas_put_item+ * takes them) with the canvas' own item code into a w x h buffer whose top+ * left is at (x0, y0), and writes straight-alpha RGBA8 to `rgba`. The CPU+ * raster has no alpha channel, so the items are drawn on black and on white:+ * alpha = 1 - (white - black), colour = black / alpha (exact for coverage+ * antialiasing). Declared in the Rust sys crate, not in BUI_kit.h.+ * Returns 1 on success. */+int BK_canvas_rasterize(const BKCanvasItem *items, int n, float x0, float y0, int w, int h,+ unsigned char *rgba)+{+ if (w <= 0 || h <= 0 || w > 8192 || h > 8192 || !rgba) {+ return 0;+ }+ CItem *ci = (CItem *)calloc((size_t)BK_MAX(n, 1), sizeof(CItem));+ if (!ci) {+ return 0;+ }+ for (int i = 0; i < n; i++) {+ citem_assign(&ci[i], &items[i]);+ }+ BuiRaster *r = BUI_raster_create(w, h);+ uint32_t *black = (uint32_t *)malloc(sizeof(uint32_t) * (size_t)w * (size_t)h);+ int ok = r && black;+ for (int pass = 0; ok && pass < 2; pass++) {+ const float bg[4] = {(float)pass, (float)pass, (float)pass, 1.0f};+ BUI_raster_begin_frame(r, w, h);+ BUI_raster_set_clip(r, 0, 0, w, h);+ BUI_raster_fill_rect(r, 0, 0, (float)w, (float)h, bg);+ for (int i = 0; i < n; i++) {+ const BKCanvasItem *it = &ci[i].it;+ if (it->clip_on) {+ BUI_raster_set_clip(r, (int)floorf(it->clip[0] - x0), (int)floorf(it->clip[1] - y0),+ (int)ceilf(it->clip[2]), (int)ceilf(it->clip[3]));+ }+ canvas_item_draw(r, &ci[i], -x0, -y0, NULL);+ if (it->clip_on) {+ BUI_raster_set_clip(r, 0, 0, w, h);+ }+ }+ BUI_raster_end_frame(r);+ const uint32_t *px = BUI_raster_pixels(r);+ if (pass == 0) {+ memcpy(black, px, sizeof(uint32_t) * (size_t)w * (size_t)h);+ continue;+ }+ for (size_t k = 0; k < (size_t)w * (size_t)h; k++) {+ const uint32_t b = black[k], wt = px[k];+ unsigned char *o = rgba + 4 * k;+ /* per channel: white - black = 255 * (1 - alpha); use the mean */+ const int dr = (int)((wt >> 16) & 255) - (int)((b >> 16) & 255);+ const int dg = (int)((wt >> 8) & 255) - (int)((b >> 8) & 255);+ const int db = (int)(wt & 255) - (int)(b & 255);+ const int a = BK_CLAMP(255 - (dr + dg + db) / 3, 0, 255);+ o[3] = (unsigned char)a;+ if (a == 0) {+ o[0] = o[1] = o[2] = 0;+ continue;+ }+ o[0] = (unsigned char)BK_MIN(255, (int)((b >> 16) & 255) * 255 / a);+ o[1] = (unsigned char)BK_MIN(255, (int)((b >> 8) & 255) * 255 / a);+ o[2] = (unsigned char)BK_MIN(255, (int)(b & 255) * 255 / a);+ }+ }+ free(black);+ if (r) {+ BUI_raster_free(r);+ }+ for (int i = 0; i < n; i++) {+ citem_free(&ci[i]);+ }+ free(ci);+ return ok;+}+/* create_window: place-managed children sit at canvas coordinates, scrolled* with the items. */static void canvas_arrange(BKNode *n)diff --git a/kit/intern/kit_intern.h b/kit/intern/kit_intern.hindex 2b2f7f8..2a33ae3 100644--- a/kit/intern/kit_intern.h+++ b/kit/intern/kit_intern.h@@ -165,6 +165,15 @@ float bk_content_width(const char *s, int icon, bool bold);void bk_tria(float cx, float cy, char dir, const float c[4], float size);void bk_chevron_down(float cx, float cy, const uchar c[4]);+/* Browser-look primitives (kit_draw.c). Colors are 0xAARRGGBB. */+void bk_argb(uint32_t argb, float r_out[4]);+/* Rounded box: `fill` (may be NULL) under a `bw` wide border inside the edge+ * (`border` may be NULL). */+void bk_html_box(float x, float y, float w, float h, float rad, const float fill[4],+ const float border[4], float bw);+/* Open polyline stroked `width` wide with round joins (check marks, chevrons). */+void bk_html_polyline(const float (*pts)[2], int n, const float c[4], float width);+/* Icons (kit_icons.c). */int bk_icons_lookup(const char *name);void bk_icons_draw(int id, float x, float y, float s, const float color[4]);@@ -287,8 +296,11 @@ enum {NF_NOSCROLLBAR = 1 << 22, /* an external scrollbar drives the view */NF_CONFIGURED = 1 << 23, /* geometry changed since the host was told (BK_EV_CONFIGURE) */NF_OPAQUE = 1 << 24, /* root: the host paints every pixel, skip the region clear */+ NF_HTML = 1 << 25, /* "html": Chrome's default form-control look and interaction */};+#define BK_HTML(n) (((n)->flags & NF_HTML) != 0)+typedef struct BKStrs {char **v;int n;@@ -549,6 +561,21 @@ extern const BKClass bk_cls_column, bk_cls_row, bk_cls_split, bk_cls_grid, bk_clbk_cls_pie, bk_cls_popover_panel, bk_cls_picker, bk_cls_eyedropper, bk_cls_frame,bk_cls_radio, bk_cls_canvas, bk_cls_textarea, bk_cls_image;+/* Browser look ("html" property, kit_widgets.c): Chrome's 2020+ form controls+ * (Windows, light). The core calls these for NF_HTML nodes before the class's+ * own measure/draw; they return false for classes without a browser look. */+#define BK_HTML_FONT (40.0f / 33.0f) /* 13.333px text over the 11px UI text */+extern float bk_html_text_scale;+bool bk_html_measure(BKNode *n, int *r_w, int *r_h);+bool bk_html_draw(BKNode *n);+/* CSS px -> device px */+float bk_hpx(float css);+/* Chrome's text field content: text, selection (#3390ff / white text) and caret. */+void bk_html_te_draw(BKTextEdit *te, const BKRect *content, const uchar color[4]);+extern const BKClass bk_cls_meter;+bool bk_textarea_html_measure(BKNode *n, int *r_w, int *r_h); /* kit_textarea.c */+void bk_textarea_html_draw(BKNode *n);+/* Small utilities */#define BK_MIN(a, b) ((a) < (b) ? (a) : (b))#define BK_MAX(a, b) ((a) > (b) ? (a) : (b))diff --git a/kit/intern/kit_menus.c b/kit/intern/kit_menus.cindex f28b9c0..35c1eff 100644--- a/kit/intern/kit_menus.c+++ b/kit/intern/kit_menus.c@@ -147,14 +147,26 @@ static BKMenuSpec *menu_items(BKNode *n, int *r_count)return m->all;}-static int menu_pad(void)+static int menu_pad_blender(void){return bk_iround(0.2f * u()); /* UI_MENU_PADDING */}-static int menu_sep_h(void)+/* Browser look (a <select>'s popup, Chrome on Windows): a 1px border around+ * 17px option rows (13.33px text, padding 0 2px 1px, min-height 1.2em). */+static int menu_pad_n(const BKNode *n){- return bk_iround(0.5f * u());+ return BK_HTML(n) ? BK_MAX(1, (int)floorf(bk_hpx(1.0f))) : menu_pad_blender();}+#define menu_pad() menu_pad_n(n)+static int menu_row_h(const BKNode *n)+{+ return BK_HTML(n) ? bk_iround(bk_hpx(17.0f)) : u();+}+static int menu_sep_h_n(const BKNode *n)+{+ return BK_HTML(n) ? bk_iround(bk_hpx(9.0f)) : bk_iround(0.5f * u());+}+#define menu_sep_h() menu_sep_h_n(n)static int menu_title_h(BKNode *n){return (MENU(n)->title || MENU(n)->query[0]) ? u() : 0;@@ -166,7 +178,7 @@ static void menu_row_geom(BKNode *n, int row, int *r_y, int *r_h)BKMenuSpec *items = menu_items(n, &count);int y = menu_pad() + menu_title_h(n);for (int i = 0; i < count; i++) {- const int h = is_sep(&items[i]) ? menu_sep_h() : u();+ const int h = is_sep(&items[i]) ? menu_sep_h() : menu_row_h(n);if (i == row) {*r_y = n->y + y;*r_h = h;@@ -202,8 +214,120 @@ static bool menu_has_icons(BKMenuSpec *items, int count)return false;}+/* -- browser look: a <select> popup -- */++#define HTML_GROUP_LABEL (-2) /* BKMenuSpec.checked of an <optgroup> label row */++static float html_menu_font_begin(void)+{+ const float saved = bk_text_scale;+ bk_text_scale = BK_HTML_FONT;+ bk_html_text_scale = bk_text_scale;+ return saved;+}++/* option text start: padding-inline 2px + 2px (Chrome's popup), +16px under an <optgroup> */+static float html_menu_text_x(const BKMenuSpec *items, int i)+{+ if (items[i].checked == HTML_GROUP_LABEL) {+ return bk_hpx(4.0f);+ }+ for (int k = i - 1; k >= 0; k--) {+ if (items[k].checked == HTML_GROUP_LABEL) {+ return bk_hpx(20.0f);+ }+ }+ return bk_hpx(4.0f);+}++static void html_menu_measure(BKNode *n, int *rw, int *rh)+{+ int count;+ BKMenuSpec *items = menu_items(n, &count);+ const float saved = html_menu_font_begin();+ float w = 0;+ int h = 0;+ for (int i = 0; i < count; i++) {+ if (is_sep(&items[i])) {+ h += menu_sep_h();+ continue;+ }+ h += menu_row_h(n);+ w = BK_MAX(w, html_menu_text_x(items, i) ++ bk_text_width(items[i].text, -1, items[i].checked == HTML_GROUP_LABEL) ++ bk_hpx(4.0f));+ }+ bk_text_scale = saved;+ *rw = (int)ceilf(w) + 2 * menu_pad();+ *rh = BK_MAX(h, menu_row_h(n)) + 2 * menu_pad();+}++static void html_menu_draw(BKNode *n)+{+ const float saved = html_menu_font_begin();+ float c[4];+ bk_argb(0xFFFFFFFFu, c);+ float b[4];+ bk_argb(0xFF767676u, b);+ bk_html_box(n->x, n->y, n->w, n->h, 0.0f, c, b, (float)menu_pad());+ int count;+ BKMenuSpec *items = menu_items(n, &count);+ const int p = menu_pad();+ bk_clip_push(n->x + p, n->y + p, n->w - 2 * p, n->h - 2 * p);+ for (int i = 0; i < count; i++) {+ int ry, rh;+ menu_row_geom(n, i, &ry, &rh);+ const BKMenuSpec *it = &items[i];+ const BKRect row = bk_rect(n->x + p, ry, n->w - 2 * p, rh);+ if (is_sep(it)) { /* <hr> in a select */+ bk_argb(0xFFC0C0C0u, c);+ bk_fill_f(row.xmin + bk_hpx(4.0f), ry + rh / 2, bk_rw(&row) - bk_hpx(8.0f),+ BK_MAX(1.0f, floorf(bk_hpx(1.0f))), c);+ continue;+ }+ const bool group = it->checked == HTML_GROUP_LABEL;+ const bool hot = i == n->hot && it->enabled && !group;+ static const uchar black[4] = {0, 0, 0, 255}, white[4] = {255, 255, 255, 255},+ gray[4] = {16, 16, 16, 77};+ if (hot) { /* the highlighted option: Highlight / HighlightText */+ bk_argb(0xFF1E90FFu, c);+ bk_fill_f(row.xmin, row.ymin, bk_rw(&row), rh, c);+ }+ const uchar *tc = hot ? white : ((it->enabled || group) ? black : gray);+ bk_text(row.xmin + html_menu_text_x(items, i), bk_text_baseline(&row), it->text, -1, tc,+ group);+ }+ bk_clip_pop();+ bk_text_scale = saved;+}++/* Typeahead: a printable key moves to the next option starting with it. */+static int html_menu_typeahead(BKNode *n, BKEvent *e)+{+ if (!e->text || (unsigned char)e->text[0] < 0x20 || EV_CTRL(e)) {+ return 0;+ }+ int count;+ BKMenuSpec *items = menu_items(n, &count);+ const int ch = tolower((unsigned char)e->text[0]);+ for (int k = 1; k <= count; k++) {+ const int i = ((n->hot < 0 ? -1 : n->hot) + k + count) % count;+ const BKMenuSpec *it = &items[i];+ if (!is_sep(it) && it->enabled && tolower((unsigned char)it->text[0]) == ch) {+ n->hot = i;+ bk_invalidate(n);+ break;+ }+ }+ return 1;+}+static void menu_measure(BKNode *n, int *rw, int *rh){+ if (BK_HTML(n)) {+ html_menu_measure(n, rw, rh);+ return;+ }int count;BKMenuSpec *items = menu_items(n, &count);const float uu = (float)u();@@ -377,6 +501,9 @@ static void menu_filter(BKNode *n)static int menu_move(BKNode *n, BKEvent *e){const int hot = menu_row_at(n, e->y);+ if (BK_HTML(n) && (hot < 0 || !bk_contains(n, e->x, e->y))) {+ return 0; /* the highlight stays on the last option (Chrome) */+ }if (hot == n->hot) {return 0;}@@ -469,6 +596,18 @@ static int menu_key(BKNode *n, BKEvent *e)bk_close_popups_after(bk_ctx(n), n->parent);return 1;}+ if (BK_HTML(n)) {+ if (bk_keysym_is(e->keysym, "Home") || bk_keysym_is(e->keysym, "End")) {+ n->hot = -1;+ menu_step(n, bk_keysym_is(e->keysym, "Home") ? 1 : -1);+ return 1;+ }+ if (bk_keysym_is(e->keysym, "space") || bk_keysym_is(e->keysym, "Tab")) {+ menu_pick(n, n->hot); /* Chrome: Space / Tab accept the highlighted option */+ return 1;+ }+ return html_menu_typeahead(n, e);+ }/* typing always searches from the top menu (Blender menu search) */return menu_search_key(menu_root(n), e);}@@ -484,6 +623,10 @@ static void menu_check_icon(float cx, float cy, bool on)static void menu_draw(BKNode *n){+ if (BK_HTML(n)) {+ html_menu_draw(n);+ return;+ }MenuData *m = MENU(n);BKRect r = bk_node_rect(n);bk_widget_menu_back(&r, CNR_ALL);@@ -653,9 +796,9 @@ void BK_menu_row_rect(BKNode *menu, int i, int r[4])}int ry, rh;menu_row_geom(menu, i, &ry, &rh);- r[0] = menu->x + menu_pad();+ r[0] = menu->x + menu_pad_n(menu);r[1] = ry;- r[2] = menu->w - 2 * menu_pad();+ r[2] = menu->w - 2 * menu_pad_n(menu);r[3] = rh;}diff --git a/kit/intern/kit_textarea.c b/kit/intern/kit_textarea.cindex 3956218..0238169 100644--- a/kit/intern/kit_textarea.c+++ b/kit/intern/kit_textarea.c@@ -33,6 +33,7 @@ typedef struct TAData {int nlines, caplines;Span *spans;int nspans;+ bool rows_set; /* "rows" was given (the browser look defaults to 2) */} TAData;#define TA(n) ((TAData *)(n)->ext)@@ -42,6 +43,32 @@ static int line_h(void)return bk_iround(0.8f * bk_unit());}+/* Browser look (Chrome's <textarea>): 1px border + 2px padding, 15px lines of+ * 13.33px text. Blender look: the text-field margins and 0.8 unit lines. */+static int ta_line_h(const BKNode *n)+{+ return BK_HTML(n) ? bk_iround(bk_hpx(15.0f)) : line_h();+}+static int ta_pad_x(const BKNode *n)+{+ return BK_HTML(n) ? bk_iround(bk_hpx(3.0f)) : bk_pad();+}+static int ta_pad_y(const BKNode *n)+{+ return BK_HTML(n) ? bk_iround(bk_hpx(3.0f)) : bk_pad() / 2;+}++/* Events measure text at the size it is drawn with. */+static float ta_font_begin(const BKNode *n)+{+ const float saved = bk_text_scale;+ if (BK_HTML(n)) {+ bk_text_scale = (n->font_scale > 0.0f ? n->font_scale : 1.0f) * BK_HTML_FONT;+ bk_html_text_scale = bk_text_scale;+ }+ return saved;+}+static void ta_reindex(TAData *t){t->nlines = 0;@@ -205,7 +232,7 @@ void BK_textarea_set_spans(BKNode *n, const BKTextSpan *spans, int count)static int visible_lines(const BKNode *n){- return BK_MAX(1, (n->h - bk_pad()) / line_h());+ return BK_MAX(1, (n->h - 2 * ta_pad_y(n)) / ta_line_h(n));}static void ta_view(BKNode *n, int axis, int *first, int *vis, int *total)@@ -279,13 +306,17 @@ static int col_at(const TAData *t, int line, float px)static int offset_at(BKNode *n, int x, int y){TAData *t = TA(n);- const int line = BK_CLAMP((y - n->y - bk_pad() / 2) / line_h() + t->scroll, 0, t->nlines - 1);- return col_at(t, line, (float)(x - n->x - bk_pad()));+ const int line = BK_CLAMP((y - n->y - ta_pad_y(n)) / ta_line_h(n) + t->scroll, 0,+ t->nlines - 1);+ return col_at(t, line, (float)(x - n->x - ta_pad_x(n)));}int BK_textarea_index_at(BKNode *n, int x, int y){- return offset_at(n, x, y);+ const float saved = ta_font_begin(n);+ const int off = offset_at(n, x, y);+ bk_text_scale = saved;+ return off;}static float caret_x(const TAData *t, int off)@@ -508,6 +539,105 @@ static void ta_measure(BKNode *n, int *rw, int *rh)*rh = n->rows * line_h() + bk_pad();}+static void draw_line_spans(TAData *t, int a, int b, float x, const BKRect *line,+ const uchar def[4]);++/* Handlers that measure text, at the size it is drawn with. */+#define TA_SCALED(name, impl) \+ static int name(BKNode *n, BKEvent *e) \+ { \+ const float saved = ta_font_begin(n); \+ const int r = impl(n, e); \+ bk_text_scale = saved; \+ return r; \+ }+TA_SCALED(ta_press_s, ta_press)+TA_SCALED(ta_dbl_s, ta_dbl)+TA_SCALED(ta_drag_s, ta_drag)+TA_SCALED(ta_key_s, ta_key)++static int ta_set_num(BKNode *n, const char *key, double v)+{+ if (strcmp(key, "rows") == 0) {+ n->rows = (int)v;+ TA(n)->rows_set = true;+ bk_relayout(n);+ return 1;+ }+ return 0;+}++bool bk_textarea_html_measure(BKNode *n, int *rw, int *rh)+{+ /* Chrome: cols=20 -> 182px; rows (default 2) x 15px + 2px padding + 1px border */+ const int rows = TA(n)->rows_set ? BK_MAX(1, n->rows) : 2;+ *rw = bk_iround(bk_hpx(182.0f));+ *rh = rows * ta_line_h(n) + 2 * ta_pad_y(n);+ return true;+}++void bk_textarea_html_draw(BKNode *n)+{+ TAData *t = TA(n);+ BKContext *ctx = bk_ctx(n);+ const bool focused = ctx && ctx->focus == n;+ const bool enabled = NODE_ENABLED(n), hover = enabled && bk_hovered(n);+ const float rad = bk_hpx(2.0f), bw = BK_MAX(1.0f, floorf(bk_hpx(1.0f)));+ float fill[4], border[4];+ if (!enabled) { /* lighten layer, translucent white, faded border */+ bk_argb(0x33A9A9A9u, fill);+ bk_html_box(n->x, n->y, n->w, n->h, rad, fill, NULL, 0);+ }+ bk_argb(enabled ? 0xFFFFFFFFu : 0x99FFFFFFu, fill);+ bk_argb(!enabled ? 0x4D767676u : (hover ? 0xFF4F4F4Fu : 0xFF767676u), border);+ bk_html_box(n->x, n->y, n->w, n->h, rad, fill, border, bw);+ if (focused) { /* the 2px focus ring, 1px outside */+ const float o = bk_hpx(1.0f);+ float ring[4];+ bk_argb(0xFF101010u, ring);+ bk_html_box(n->x - o, n->y - o, n->w + 2 * o, n->h + 2 * o, rad + o, NULL, ring,+ bk_hpx(2.0f));+ }+ static const uchar black[4] = {0, 0, 0, 255}, gray[4] = {0x54, 0x54, 0x54, 255},+ white[4] = {255, 255, 255, 255};+ const uchar *tc = enabled ? black : gray;+ const int px = ta_pad_x(n), py = ta_pad_y(n), lh = ta_line_h(n);+ const int b = (int)bw;+ bk_clip_push(n->x + b, n->y + b, n->w - 2 * b, n->h - 2 * b);+ t->scroll = BK_CLAMP(t->scroll, 0, BK_MAX(0, t->nlines - 1));+ int sa = -1, sb = -1;+ const bool sel = BK_textarea_selection(n, &sa, &sb);+ const float x0 = (float)(n->x + px);+ for (int line = t->scroll; line < t->nlines; line++) {+ const int y = n->y + py + (line - t->scroll) * lh;+ if (y > n->y + n->h) {+ break;+ }+ const int la = t->lines[line], lb = line_end(t, line);+ const BKRect lr = bk_rect(n->x, y, n->w, lh);+ draw_line_spans(t, la, lb, x0, &lr, tc);+ if (sel && sa < lb + 1 && sb > la) { /* #3390ff behind white text */+ const int s0 = BK_MAX(sa, la), s1 = BK_MIN(sb, lb);+ const float sx = x0 + bk_text_width(t->text + la, s0 - la, false);+ float sw = bk_text_width(t->text + s0, s1 - s0, false);+ if (sb > lb) {+ sw += bk_font_size() * 0.4f; /* the newline */+ }+ float sc[4];+ bk_argb(0xFF3390FFu, sc);+ bk_fill_f(sx, (float)y, sw, (float)lh, sc);+ bk_clip_push((int)floorf(sx), y, (int)ceilf(sw) + 1, lh);+ bk_text(x0, bk_text_baseline(&lr), t->text + la, lb - la, white, false);+ bk_clip_pop();+ }+ if (focused && !sel && t->caret >= la && t->caret <= lb) {+ const float cx = x0 + bk_text_width(t->text + la, t->caret - la, false);+ bk_fill(floorf(cx), (float)y, bw, (float)lh, tc);+ }+ }+ bk_clip_pop();+}+static void draw_line_spans(TAData *t, int a, int b, float x, const BKRect *line,const uchar def[4]){@@ -601,11 +731,12 @@ const BKClass bk_cls_textarea = {.name = "textarea",.free_ext = ta_free,.measure = ta_measure,.draw = ta_draw,- .press = ta_press,- .dbl = ta_dbl,- .drag = ta_drag,+ .press = ta_press_s,+ .dbl = ta_dbl_s,+ .drag = ta_drag_s,.wheel = ta_wheel,- .key = ta_key,+ .key = ta_key_s,+ .set_num = ta_set_num,.cursor_at = ta_cursor,.finish_edit = ta_finish,.view = ta_view,diff --git a/kit/intern/kit_widgets.c b/kit/intern/kit_widgets.cindex e21efbd..a5376e9 100644--- a/kit/intern/kit_widgets.c+++ b/kit/intern/kit_widgets.c@@ -105,6 +105,23 @@ static int item_icon(const BKNode *n, int i)return (n->item_icons && i >= 0 && i < n->item_icons_s.n) ? n->item_icons[i] : 0;}+/* Browser look interaction (defined in the "Browser look" section below). */+static int html_number_press(BKNode *n, BKEvent *e);+static int html_number_dbl(BKNode *n, BKEvent *e);+static int html_number_drag(BKNode *n, BKEvent *e);+static int html_number_release(BKNode *n, BKEvent *e);+static int html_number_key(BKNode *n, BKEvent *e);+static int html_number_move(BKNode *n, BKEvent *e);+static int html_number_cursor(BKNode *n, int x, int y);+static int html_range_press(BKNode *n, BKEvent *e);+static int html_range_drag(BKNode *n, BKEvent *e);+static int html_range_release(BKNode *n, BKEvent *e);+static int html_range_key(BKNode *n, BKEvent *e);+static void html_number_spin(BKNode *n, int dir);+static float html_font_begin(const BKNode *n);+static float hp(float css);+#define HTML_GROUP_PREFIX '\x01' /* dropdown item that is an <optgroup> label */+/** \} *//* -------------------------------------------------------------------- */@@ -1624,11 +1641,24 @@ static void bool_reset(BKNode *n, bool zero)static int bool_press(BKNode *n, BKEvent *e){+ if (BK_HTML(n)) { /* browsers toggle on click (release inside), no drag-toggle */+ bk_invalidate(n);+ return 1;+ }bool_toggle(n);bk_start_drag_toggle(bk_ctx(n), DRAG_GROUP_TOGGLE, n->value != 0);return 1;}+static int bool_release(BKNode *n, BKEvent *e)+{+ if (BK_HTML(n) && e->inside && NODE_ENABLED(n)) {+ bool_toggle(n);+ }+ bk_invalidate(n);+ return 1;+}+static void checkbox_measure(BKNode *n, int *rw, int *rh){if (!n->label || !n->label[0]) {@@ -1661,7 +1691,7 @@ static void checkbox_draw(BKNode *n)#define BOOL_CLASS_COMMON \.flags = CLS_INTERACTIVE | CLS_VALUE, .drag_group = DRAG_GROUP_TOGGLE, .press = bool_press, \- .to_text = bool_to_text, .from_text = bool_from_text, .step = bool_step, \+ .release = bool_release, .to_text = bool_to_text, .from_text = bool_from_text, .step = bool_step, \.reset = bool_reset, .activate = bool_toggleconst BKClass bk_cls_checkbox = {.name = "checkbox",@@ -1794,6 +1824,9 @@ static void number_finish(BKNode *n, bool confirm)static int number_cursor_at(BKNode *n, int x, int y){+ if (BK_HTML(n)) {+ return n->cls == &bk_cls_slider ? BK_CURSOR_DEFAULT : html_number_cursor(n, x, y);+ }return n->edit ? BK_CURSOR_TEXT : BK_CURSOR_EW;}@@ -1926,6 +1959,9 @@ static void drag_origin(BKNode *n, BKEvent *e)static int number_press(BKNode *n, BKEvent *e){+ if (BK_HTML(n)) {+ return n->cls == &bk_cls_slider ? html_range_press(n, e) : html_number_press(n, e);+ }if (n->edit) {bk_te_click(n->edit, (float)(e->lx - bk_pad()), EV_SHIFT(e));bk_invalidate(n);@@ -1947,6 +1983,10 @@ static int number_press(BKNode *n, BKEvent *e)static void number_cancel(BKNode *n){BKContext *ctx = bk_ctx(n);+ if (BK_HTML(n)) { /* a range drag keeps its value (Chrome has no cancel) */+ n->dragmode = 0;+ return;+ }if (n->dragmode >= 2 && ctx) {for (int i = 0; i < ctx->nmulti; i++) {bk_set_value(ctx->multi[i], ctx->multi_start[i]);@@ -2013,6 +2053,9 @@ static int multi_drag(BKNode *n, BKEvent *e)static int number_dbl(BKNode *n, BKEvent *e){+ if (BK_HTML(n)) {+ return n->cls == &bk_cls_slider ? html_range_press(n, e) : html_number_dbl(n, e);+ }if (n->edit) {bk_te_select_word(n->edit, bk_te_index_at(n->edit, (float)(e->lx - bk_pad())));bk_invalidate(n);@@ -2023,6 +2066,9 @@ static int number_dbl(BKNode *n, BKEvent *e)static int number_drag(BKNode *n, BKEvent *e){+ if (BK_HTML(n)) {+ return n->cls == &bk_cls_slider ? html_range_drag(n, e) : html_number_drag(n, e);+ }if (n->edit) {bk_te_drag(n->edit, (float)(e->lx - bk_pad()));bk_invalidate(n);@@ -2074,6 +2120,9 @@ static int arrow_w(const BKNode *n)static int number_release(BKNode *n, BKEvent *e){+ if (BK_HTML(n)) {+ return n->cls == &bk_cls_slider ? html_range_release(n, e) : html_number_release(n, e);+ }BKContext *ctx = bk_ctx(n);if (ctx && n->dragmode >= 2) {for (int i = 0; i < ctx->nmulti; i++) {@@ -2113,14 +2162,30 @@ static int number_release(BKNode *n, BKEvent *e)static int number_key(BKNode *n, BKEvent *e){+ if (BK_HTML(n)) {+ return n->cls == &bk_cls_slider ? html_range_key(n, e) : html_number_key(n, e);+ }if (n->edit) {return bk_edit_key(n, e);}return bk_value_key(n, e);}+static int number_wheel(BKNode *n, BKEvent *e)+{+ /* Chrome: the wheel steps a focused number input */+ if (BK_HTML(n) && n->cls == &bk_cls_number && n->edit && NODE_ENABLED(n)) {+ html_number_spin(n, e->delta > 0 ? 1 : -1);+ return 1;+ }+ return bk_value_wheel(n, e);+}+static int number_move(BKNode *n, BKEvent *e){+ if (BK_HTML(n)) {+ return n->cls == &bk_cls_number ? html_number_move(n, e) : 0;+ }if (n->cls != &bk_cls_number) {return 0;}@@ -2200,6 +2265,7 @@ static void number_draw(BKNode *n).drag_cursor = BK_CURSOR_NONE, .measure = number_measure, .press = number_press, \.dbl = number_dbl, .drag = number_drag, .release = number_release, .key = number_key, \.move = number_move, .leave = number_leave, .cursor_at = number_cursor_at, \+ .wheel = number_wheel, \.cancel = number_cancel, \.finish_edit = number_finish, .to_text = number_to_text, .from_text = number_from_text, \.step = number_step, .reset = number_reset, .negate = number_negate, \@@ -2285,15 +2351,20 @@ static void text_finish(BKNode *n, bool confirm)static float text_x(BKNode *n, BKEvent *e){+ if (BK_HTML(n)) { /* Chrome: 2px border + 2px padding before the text */+ return (float)e->lx - hp(4.0f);+ }return (float)(e->lx - bk_pad() - text_inset(n));}static int text_press(BKNode *n, BKEvent *e){+ const float saved = BK_HTML(n) ? html_font_begin(n) : bk_text_scale;if (!n->edit) {bk_begin_edit(n, n->text ? n->text : "", false);}bk_te_click(n->edit, text_x(n, e), EV_SHIFT(e));+ bk_text_scale = saved;bk_invalidate(n);return 1;}@@ -2303,7 +2374,9 @@ static int text_dbl(BKNode *n, BKEvent *e)if (!n->edit) {return text_press(n, e);}+ const float saved = BK_HTML(n) ? html_font_begin(n) : bk_text_scale;bk_te_select_word(n->edit, bk_te_index_at(n->edit, text_x(n, e)));+ bk_text_scale = saved;bk_invalidate(n);return 1;}@@ -2311,7 +2384,9 @@ static int text_dbl(BKNode *n, BKEvent *e)static int text_drag(BKNode *n, BKEvent *e){if (n->edit) {+ const float saved = BK_HTML(n) ? html_font_begin(n) : bk_text_scale;bk_te_drag(n->edit, text_x(n, e));+ bk_text_scale = saved;bk_invalidate(n);}return 1;@@ -2624,6 +2699,7 @@ static void dropdown_activate(BKNode *n)if (!ctx || !n->items.n) {return;}+ const bool html = BK_HTML(n);BKMenuSpec *items = (BKMenuSpec *)calloc((size_t)n->items.n, sizeof(BKMenuSpec));for (int i = 0; i < n->items.n; i++) {items[i].text = n->items.v[i];@@ -2632,10 +2708,20 @@ static void dropdown_activate(BKNode *n)items[i].enabled = 1;items[i].fn = NULL;items[i].data = (void *)(intptr_t)i; /* picked index (handled by the menu) */+ if (html && items[i].text && items[i].text[0] == HTML_GROUP_PREFIX) {+ items[i].text++; /* <optgroup> label: bold, not selectable (kit_menus.c) */+ items[i].checked = -2;+ items[i].enabled = 0;+ }}- BKNode *menu = bk_menu_new(items, n->items.n, n->label && n->label[0] ? n->label : NULL,+ BKNode *menu = bk_menu_new(items, n->items.n,+ (!html && n->label && n->label[0]) ? n->label : NULL,item_text(n, (int)n->value));free(items);+ if (html) {+ menu->flags |= NF_HTML;+ menu->hot = BK_CLAMP((int)n->value, -1, n->items.n - 1); /* the selected option */+ }bk_open_popup(ctx, menu, n, NULL);(void)dropdown_pick;}@@ -2695,12 +2781,39 @@ static void dropdown_draw(BKNode *n)bk_text_icon(&r, s, item_icon(n, i), w.text, BK_ALIGN_LEFT, NODE_ENABLED(n));}+static int dropdown_key(BKNode *n, BKEvent *e)+{+ if (BK_HTML(n)) {+ /* Chrome (Windows): arrows change a closed select, Space / F4 / Alt+Down open it */+ const bool down = bk_keysym_is(e->keysym, "Down"), up = bk_keysym_is(e->keysym, "Up");+ if ((down && EV_ALT(e)) || bk_keysym_is(e->keysym, "space") || bk_keysym_is(e->keysym, "F4")) {+ dropdown_activate(n);+ return 1;+ }+ const bool home = bk_keysym_is(e->keysym, "Home"), end = bk_keysym_is(e->keysym, "End");+ if (down || up || home || end) {+ /* step to the next option, skipping <optgroup> labels; Home/End: first/last */+ const int cnt = n->items.n, dir = (down || home) ? 1 : -1;+ int i = home ? -1 : (end ? cnt : (int)n->value);+ for (i += dir; i >= 0 && i < cnt; i += dir) {+ if (n->items.v[i][0] != HTML_GROUP_PREFIX) {+ bk_set_value(n, i);+ break;+ }+ }+ return 1;+ }+ }+ return bk_value_key(n, e);+}+const BKClass bk_cls_dropdown = {.name = "dropdown",.flags = CLS_INTERACTIVE | CLS_VALUE,.init = choice_init,.measure = dropdown_measure,.draw = dropdown_draw,.press = dropdown_press,+ .key = dropdown_key,.to_text = choice_to_text,.from_text = choice_from_text,.step = choice_step,@@ -3181,3 +3294,968 @@ const BKClass bk_cls_menubar = {.name = "menubar",.draw = menubar_draw};/** \} */++/* -------------------------------------------------------------------- */+/** \name Browser look ("html" property)+ *+ * Chrome's default form controls since the 2020 "form controls refresh"+ * (Windows, light scheme). Colors are Chromium's+ * CompleteDefaultWebNativeRendererColorIdsDefinition (ui/color/+ * color_provider_utils.cc), shapes follow NativeThemeBase (ui/native_theme/+ * native_theme_base.cc: PaintButton, PaintTextField, PaintCheckbox,+ * PaintRadio, PaintSliderTrack/Thumb, PaintProgressBar, PaintMenuList) and the+ * metrics come from Blink's html.css (2px borders + 1px 2px padding on text+ * inputs, 1px 6px on buttons, 13.33px text, 13px checkboxes with+ * 3px 3px 3px 4px margins, ...). All sizes are CSS px scaled by bk_scale_fac.+ * \{ */++/* NativeTheme::State order: the per-state color tables are indexed by it */+enum { HS_DISABLED = 0, HS_HOVER, HS_NORMAL, HS_PRESSED };++/* kColorWebNativeControl{Border,Accent,Fill,CheckboxBackground,Slider,SliderBorder} */+static const uint32_t kHtmlBorder[4] = {0x4D767676u, 0xFF4F4F4Fu, 0xFF767676u, 0xFF8D8D8Du};+static const uint32_t kHtmlAccent[4] = {0x4D767676u, 0xFF005CC8u, 0xFF0075FFu, 0xFF3793FFu};+static const uint32_t kHtmlFill[4] = {0x4DEFEFEFu, 0xFFE5E5E5u, 0xFFEFEFEFu, 0xFFF5F5F5u};+static const uint32_t kHtmlCheckBg[4] = {0x99FFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu, 0xFFFFFFFFu};+static const uint32_t kHtmlSlider[4] = {0xFFCBCBCBu, 0xFF005CC8u, 0xFF0075FFu, 0xFF3793FFu};+static const uint32_t kHtmlSliderBorder[4] = {0x4D767676u, 0x804F4F4Fu, 0x80767676u,+ 0x808D8D8Du};+#define HTML_LIGHTEN 0x33A9A9A9u /* kColorWebNativeControlLightenLayer (disabled) */+#define HTML_FOCUS_RING 0xFF101010u /* -webkit-focus-ring-color (light) */+#define HTML_SELECTION 0xFF3390FFu /* text selection behind white text */+/* spin buttons: kColorWebNativeControlScrollbarArrow{Background,Foreground}* */+#define HTML_SPIN_BG 0xFFF1F1F1u+#define HTML_SPIN_BG_HOVER 0xFFD2D2D2u+#define HTML_SPIN_BG_PRESSED 0xFF787878u+#define HTML_SPIN_FG 0xFF505050u+#define HTML_SPIN_FG_HOVER 0xFF000000u+#define HTML_SPIN_FG_PRESSED 0xFFFFFFFFu+#define HTML_SPIN_FG_DISABLED 0x4D505050u++static const uchar kHtmlText[4] = {0, 0, 0, 255}; /* FieldText */+static const uchar kHtmlTextDisabled[4] = {16, 16, 16, 77}; /* rgba(16,16,16,.3) */+static const uchar kHtmlFieldTextDisabled[4] = {0x54, 0x54, 0x54, 255}; /* input:disabled */+static const uchar kHtmlPlaceholder[4] = {0x75, 0x75, 0x75, 255}; /* ::placeholder */++float bk_hpx(float css)+{+ return css * bk_scale_fac;+}++static float hp(float css)+{+ return css * bk_scale_fac;+}++static int hpi(float css)+{+ return bk_iround(css * bk_scale_fac);+}++/* Chrome's 1px borders stay one device pixel wide at fractional zoom. */+static float html_bw(void)+{+ return BK_MAX(1.0f, floorf(hp(1.0f)));+}++/* Text at 13.33px for this node (its own font scale on top). */+static float html_font_begin(const BKNode *n)+{+ const float saved = bk_text_scale;+ bk_text_scale = (n->font_scale > 0.0f ? n->font_scale : 1.0f) * BK_HTML_FONT;+ bk_html_text_scale = bk_text_scale; /* text in this bracket uses the form-control font */+ return saved;+}++static int html_state(const BKNode *n)+{+ if (!NODE_ENABLED(n)) {+ return HS_DISABLED;+ }+ const BKContext *ctx = bk_ctx(n);+ if (ctx && ctx->grab == n && (ctx->hover == n || ctx->dragging)) {+ return HS_PRESSED;+ }+ return bk_hovered(n) ? HS_HOVER : HS_NORMAL;+}++static void html_box(float x, float y, float w, float h, float rad, uint32_t fill,+ uint32_t border, float bw)+{+ float f[4], b[4];+ bk_argb(fill, f);+ bk_argb(border, b);+ bk_html_box(x, y, w, h, rad, (fill >> 24) ? f : NULL, (border >> 24) ? b : NULL, bw);+}++static void html_box_r(const BKRect *r, float rad, uint32_t fill, uint32_t border, float bw)+{+ html_box((float)r->xmin, (float)r->ymin, (float)bk_rw(r), (float)bk_rh(r), rad, fill, border,+ bw);+}++static BKRect html_inset(const BKRect *r, float l, float t, float rr, float b)+{+ BKRect o = {r->xmin + hpi(l), r->ymin + hpi(t), r->xmax - hpi(rr), r->ymax - hpi(b)};+ if (o.xmax < o.xmin) {+ o.xmax = o.xmin;+ }+ if (o.ymax < o.ymin) {+ o.ymax = o.ymin;+ }+ return o;+}++/* The focus ring of text controls (outline: auto 1px -webkit-focus-ring-color,+ * outline-offset 0): a 2px dark ring over the border, 1px outside it. */+static void html_focus_ring(const BKRect *r, float rad)+{+ const float o = hp(1.0f);+ float c[4];+ bk_argb(HTML_FOCUS_RING, c);+ bk_html_box(r->xmin - o, r->ymin - o, bk_rw(r) + 2 * o, bk_rh(r) + 2 * o, rad + o, NULL, c,+ hp(2.0f));+}++/* One line of text clipped (not ellipsized) to `cr`, vertically centered. */+static void html_text(const BKRect *cr, const char *s, int len, const uchar c[4], int align,+ bool bold)+{+ if (!s || !s[0]) {+ return;+ }+ const float tw = bk_text_width(s, len, bold);+ float x = (float)cr->xmin;+ if (align == BK_ALIGN_CENTER) {+ x += (bk_rw(cr) - tw) * 0.5f;+ }+ else if (align == BK_ALIGN_RIGHT) {+ x = cr->xmax - tw;+ }+ const int m = hpi(3); /* room for ascenders/descenders */+ bk_clip_push(cr->xmin, cr->ymin - m, bk_rw(cr), bk_rh(cr) + 2 * m);+ bk_text(floorf(x + 0.5f), bk_text_baseline(cr), s, len, c, bold);+ bk_clip_pop();+}++void bk_html_te_draw(BKTextEdit *te, const BKRect *cr, const uchar color[4])+{+ const float inner = BK_MAX(1.0f, (float)bk_rw(cr) - 1.0f);+ const float caret_px = bk_masked_width(te->text, te->caret, te->mask, false);+ if (caret_px - te->scroll > inner) {+ te->scroll = caret_px - inner;+ }+ else if (caret_px - te->scroll < 0) {+ te->scroll = caret_px;+ }+ const float tx = cr->xmin - te->scroll;+ const int m = hpi(3), h = bk_rh(cr);+ char buf[1024];+ const char *s = te->text;+ int len = te->len;+ if (te->mask[0]) {+ len = bk_mask_text(te->text, te->len, te->mask, buf, sizeof(buf));+ s = buf;+ }+ const float base = bk_text_baseline(cr);+ bk_clip_push(cr->xmin, cr->ymin - m, bk_rw(cr) + 1, h + 2 * m);+ bk_text(tx, base, s, len, color, false);+ if (te->anchor >= 0 && te->anchor != te->caret) {+ const int a = BK_MIN(te->anchor, te->caret), b = BK_MAX(te->anchor, te->caret);+ const float sx = tx + bk_masked_width(te->text, a, te->mask, false);+ const float sw = bk_masked_width(te->text, b, te->mask, false) -+ bk_masked_width(te->text, a, te->mask, false);+ float sel[4];+ bk_argb(HTML_SELECTION, sel);+ bk_fill_f(sx, (float)cr->ymin, sw, (float)h, sel);+ static const uchar white[4] = {255, 255, 255, 255};+ bk_clip_push((int)floorf(sx), cr->ymin - m, (int)ceilf(sw) + 1, h + 2 * m);+ bk_text(tx, base, s, len, white, false);+ bk_clip_pop();+ }+ else { /* Chrome hides the caret over a range selection */+ bk_fill(floorf(tx + caret_px), (float)cr->ymin, html_bw(), (float)h, color);+ }+ bk_clip_pop();+}++/* -- buttons (push buttons, toggles, color input frame) -- */++static void html_button_frame(const BKRect *r, int hs)+{+ const float rad = hp(2.0f), bw = html_bw();+ if (hs == HS_DISABLED) {+ html_box_r(r, rad, HTML_LIGHTEN, 0, 0); /* PaintLightenLayer */+ }+ html_box_r(r, rad, kHtmlFill[hs], kHtmlBorder[hs], bw);+}++static void html_button_measure(BKNode *n, const char *s, int *rw, int *rh)+{+ const BKImage *img = (const BKImage *)n->image;+ if (img) {+ *rw = img->w + hpi(16);+ *rh = BK_MAX(hpi(21), img->h + hpi(6));+ return;+ }+ /* padding 1px 6px + 2px borders; line-height normal of 13.33px = 15px */+ *rw = (int)ceilf(bk_text_width(s ? s : "", -1, false)) + hpi(16);+ *rh = hpi(21);+}++static void html_button_draw(BKNode *n, const char *s, bool on)+{+ BKRect r = bk_node_rect(n);+ int hs = html_state(n);+ if (on && hs != HS_DISABLED) {+ hs = HS_PRESSED; /* a toggle that is on looks pressed */+ }+ html_button_frame(&r, hs);+ const BKImage *img = (const BKImage *)n->image;+ if (img) {+ bk_image_draw(img, r.xmin + (bk_rw(&r) - img->w) / 2, r.ymin + (bk_rh(&r) - img->h) / 2,+ img->w, img->h, NODE_ENABLED(n) ? 1.0f : 0.5f);+ return;+ }+ const BKRect cr = html_inset(&r, 8, 3, 8, 3);+ BKRect tr = {r.xmin + hpi(2), cr.ymin, r.xmax - hpi(2), cr.ymax}; /* may overflow the padding */+ html_text(&tr, s, -1, hs == HS_DISABLED ? kHtmlTextDisabled : kHtmlText, BK_ALIGN_CENTER,+ false);+}++/* -- checkbox / radio -- */++/* 13x13 box after the 4px left / 3px top margins (vertically centered when the+ * node is taller than its natural 19px). */+static void html_check_box(const BKNode *n, float *x, float *y, float *s)+{+ *s = (float)hpi(13);+ *x = (float)(n->x + hpi(4));+ *y = (float)(n->y + (n->h - hpi(19)) / 2 + hpi(3));+}++static void html_check_label(const BKNode *n)+{+ if (n->label && n->label[0]) {+ BKRect lr = bk_rect(n->x + hpi(20), n->y, BK_MAX(0, n->w - hpi(20)), n->h);+ html_text(&lr, n->label, -1, NODE_ENABLED(n) ? kHtmlText : kHtmlTextDisabled,+ BK_ALIGN_LEFT, false);+ }+}++static void html_checkbox_draw(BKNode *n)+{+ float x, y, s;+ html_check_box(n, &x, &y, &s);+ const int hs = html_state(n);+ const bool checked = n->value != 0, mixed = n->value < 0; /* value -1: indeterminate */+ const float rad = hp(2.0f), bw = html_bw();+ if (hs == HS_DISABLED) {+ html_box(x, y, s, s, rad, HTML_LIGHTEN, 0, 0);+ }+ /* PaintCheckboxRadioCommon: background, then the border unless checked */+ html_box(x, y, s, s, rad, kHtmlCheckBg[hs], checked ? 0 : kHtmlBorder[hs], bw);+ if (checked) {+ html_box(x, y, s, s, rad, kHtmlAccent[hs], 0, 0);+ float c[4];+ bk_argb(kHtmlCheckBg[hs], c);+ if (mixed) { /* the 8x2 dash */+ html_box(x + s * (2.5f / 13.0f), y + s * (5.5f / 13.0f), s * (8.0f / 13.0f),+ s * (2.0f / 13.0f), rad, kHtmlCheckBg[hs], 0, 0);+ }+ else {+ const float pts[3][2] = {{x + s * 0.2f, y + s * 0.5f},+ {x + s * 0.4f, y + s * 0.7f},+ {x + s * 0.8f, y + s * 0.2f}};+ bk_html_polyline(pts, 3, c, s * 0.16f);+ }+ }+ html_check_label(n);+}++static void html_radio_draw(BKNode *n)+{+ float x, y, s;+ html_check_box(n, &x, &y, &s);+ const int hs = html_state(n);+ const bool checked = n->value != 0;+ const float cx = x + s * 0.5f, cy = y + s * 0.5f, rad = s * 0.5f, bw = html_bw();+ float c[4];+ if (hs == HS_DISABLED) {+ bk_argb(HTML_LIGHTEN, c);+ bk_circle(cx, cy, rad, c);+ }+ bk_argb(kHtmlCheckBg[hs], c);+ bk_circle(cx, cy, rad - 0.2f * bw, c);+ bk_argb(checked ? kHtmlAccent[hs] : kHtmlBorder[hs], c);+ bk_ring(cx, cy, rad - bw * 0.5f, c, bw);+ if (checked) { /* the dot, inset 20% each side */+ bk_circle(cx, cy, rad * 0.6f, c);+ }+ html_check_label(n);+}++static void html_check_measure(BKNode *n, int *rw, int *rh)+{+ *rw = hpi(20); /* 13 + margins 4 + 3 */+ *rh = hpi(19); /* 13 + margins 3 + 3 */+ if (n->label && n->label[0]) {+ *rw += (int)ceilf(bk_text_width(n->label, -1, false));+ }+}++/* -- text fields -- */++static void html_field_frame(const BKRect *r, int hs, bool focused)+{+ const float rad = hp(2.0f), bw = html_bw();+ if (hs == HS_DISABLED) {+ html_box_r(r, rad, HTML_LIGHTEN, 0, 0);+ }+ html_box_r(r, rad, kHtmlCheckBg[hs], kHtmlBorder[hs == HS_PRESSED ? HS_HOVER : hs], bw);+ if (focused) {+ html_focus_ring(r, rad);+ }+}++static void html_text_draw(BKNode *n)+{+ const BKRect r = bk_node_rect(n);+ const int hs = html_state(n);+ html_field_frame(&r, hs, n->edit != NULL);+ const BKRect cr = html_inset(&r, 4, 3, 4, 3);+ const uchar *tc = hs == HS_DISABLED ? kHtmlFieldTextDisabled : kHtmlText;+ if (n->edit) {+ bk_html_te_draw(n->edit, &cr, tc);+ return;+ }+ const char *shown = n->text ? n->text : "";+ char masked[512];+ if (!shown[0]) {+ html_text(&cr, n->placeholder, -1, kHtmlPlaceholder, BK_ALIGN_LEFT, false);+ return;+ }+ if (n->mask[0]) {+ bk_mask_text(shown, (int)strlen(shown), n->mask, masked, sizeof(masked));+ shown = masked;+ }+ html_text(&cr, shown, -1, tc, BK_ALIGN_LEFT, false);+}++/* -- number: a text field with an inner spin button -- */++static BKRect html_spin_rect(const BKNode *n)+{+ /* ::-webkit-inner-spin-button: 15px wide, stretched over the content box */+ const BKRect r = bk_node_rect(n);+ const BKRect cr = html_inset(&r, 4, 3, 4, 3);+ return bk_rect(cr.xmax - hpi(15), cr.ymin, hpi(15), bk_rh(&cr));+}++/* 1: up half, 2: down half, 0: elsewhere */+static int html_spin_part(const BKNode *n, int x, int y)+{+ const BKRect s = html_spin_rect(n);+ if (x < s.xmin || x >= s.xmax || y < s.ymin || y >= s.ymax) {+ return 0;+ }+ return y < s.ymin + bk_rh(&s) / 2 ? 1 : 2;+}++static void html_spin_draw(BKNode *n, int hs)+{+ const BKRect s = html_spin_rect(n);+ const BKContext *ctx = bk_ctx(n);+ const int pressed = (ctx && ctx->grab == n && n->dragmode >= 11) ? n->dragmode - 10 : 0;+ const int hh = bk_rh(&s) / 2;+ for (int part = 1; part <= 2; part++) {+ const BKRect pr = part == 1 ? bk_rect(s.xmin, s.ymin, bk_rw(&s), hh) :+ bk_rect(s.xmin, s.ymin + hh, bk_rw(&s), bk_rh(&s) - hh);+ uint32_t bg = HTML_SPIN_BG, fg = HTML_SPIN_FG;+ if (hs == HS_DISABLED) {+ fg = HTML_SPIN_FG_DISABLED;+ }+ else if (pressed == part) {+ bg = HTML_SPIN_BG_PRESSED;+ fg = HTML_SPIN_FG_PRESSED;+ }+ else if (n->hot == part) {+ bg = HTML_SPIN_BG_HOVER;+ fg = HTML_SPIN_FG_HOVER;+ }+ float c[4];+ bk_argb(bg, c);+ bk_fill_f((float)pr.xmin, (float)pr.ymin, (float)bk_rw(&pr), (float)bk_rh(&pr), c);+ /* a 7x4 arrow, like Windows' up/down control */+ const float aw = BK_MIN(hp(7.0f), bk_rw(&pr) - hp(4.0f)), ah = aw * 0.5f;+ const float cx = pr.xmin + bk_rw(&pr) * 0.5f, cy = pr.ymin + bk_rh(&pr) * 0.5f;+ const float dy = part == 1 ? ah * 0.5f : -ah * 0.5f;+ const float tri[3][2] = {{cx - aw * 0.5f, cy + dy}, {cx + aw * 0.5f, cy + dy}, {cx, cy - dy}};+ bk_argb(fg, c);+ bk_polygon(tri, 3, c);+ }+}++static void html_number_draw(BKNode *n)+{+ const BKRect r = bk_node_rect(n);+ const int hs = html_state(n);+ html_field_frame(&r, hs, n->edit != NULL);+ BKRect cr = html_inset(&r, 4, 3, 4, 3);+ cr.xmax = BK_MAX(cr.xmin, cr.xmax - hpi(15)); /* the spin button's space is always kept */+ const uchar *tc = hs == HS_DISABLED ? kHtmlFieldTextDisabled : kHtmlText;+ if (n->edit) {+ bk_html_te_draw(n->edit, &cr, tc);+ }+ else {+ char buf[128];+ format_number(n, n->value, buf, sizeof(buf));+ html_text(&cr, buf, -1, tc, BK_ALIGN_LEFT, false);+ }+ /* :enabled:-webkit-any(:focus, :hover)::-webkit-inner-spin-button { opacity: 1 } */+ if (hs != HS_DISABLED && (n->edit || bk_hovered(n))) {+ html_spin_draw(n, hs);+ }+}++static void html_number_set_edit_text(BKNode *n)+{+ char buf[128];+ format_number(n, n->value, buf, sizeof(buf));+ BKTextEdit *te = bk_te_new(buf, false);+ memcpy(te->mask, n->edit->mask, sizeof(te->mask));+ bk_te_free(n->edit);+ n->edit = te;+}++/* stepUp / stepDown: from a value off the step grid, go to the next grid value */+static void html_number_spin(BKNode *n, int dir)+{+ if (n->edit) {+ number_from_text(n, n->edit->text); /* what was typed is the base */+ }+ const double st = n->step > 0 ? n->step : 1.0;+ const double base = (n->flags & NF_HAS_MIN) ? n->vmin : 0.0;+ const double k = (n->value - base) / st;+ const double kk = dir > 0 ? floor(k + 1e-9) + 1.0 : ceil(k - 1e-9) - 1.0;+ double v = base + kk * st;+ v = round(v * 1e9) / 1e9; /* 0.1 * 3 -> 0.3 */+ bk_set_value(n, v);+ if (n->edit) {+ html_number_set_edit_text(n);+ }+ bk_invalidate(n);+}++static void html_number_begin(BKNode *n)+{+ char buf[128];+ format_number(n, n->value, buf, sizeof(buf));+ bk_begin_edit(n, buf, false);+}++static int html_number_press(BKNode *n, BKEvent *e)+{+ const int part = html_spin_part(n, e->x, e->y);+ if (part) { /* Chrome steps on mouse down and focuses the field */+ if (!n->edit) {+ html_number_begin(n);+ }+ n->dragmode = 10 + part;+ html_number_spin(n, part == 1 ? 1 : -1);+ return 1;+ }+ const float saved = html_font_begin(n);+ if (!n->edit) {+ html_number_begin(n);+ }+ bk_te_click(n->edit, (float)e->lx - hp(4.0f), EV_SHIFT(e));+ bk_text_scale = saved;+ n->dragmode = 1; /* a drag selects text */+ bk_invalidate(n);+ return 1;+}++static int html_number_dbl(BKNode *n, BKEvent *e)+{+ if (!n->edit || html_spin_part(n, e->x, e->y)) {+ return html_number_press(n, e);+ }+ const float saved = html_font_begin(n);+ bk_te_select_word(n->edit, bk_te_index_at(n->edit, (float)e->lx - hp(4.0f)));+ bk_text_scale = saved;+ n->dragmode = 0;+ bk_invalidate(n);+ return 1;+}++static int html_number_drag(BKNode *n, BKEvent *e)+{+ if (n->edit && n->dragmode == 1) {+ const float saved = html_font_begin(n);+ bk_te_drag(n->edit, (float)e->lx - hp(4.0f));+ bk_text_scale = saved;+ bk_invalidate(n);+ }+ return 1;+}++static int html_number_release(BKNode *n, BKEvent *e)+{+ n->dragmode = 0;+ bk_invalidate(n);+ return 1;+}++static int html_number_key(BKNode *n, BKEvent *e)+{+ const bool up = bk_keysym_is(e->keysym, "Up"), down = bk_keysym_is(e->keysym, "Down");+ if ((up || down) && NODE_ENABLED(n)) {+ html_number_spin(n, up ? 1 : -1);+ return 1;+ }+ if (n->edit) {+ return bk_edit_key(n, e);+ }+ return bk_value_key(n, e);+}++static int html_number_move(BKNode *n, BKEvent *e)+{+ const int part = html_spin_part(n, e->x, e->y);+ if (part != n->hot) {+ n->hot = part;+ bk_invalidate(n);+ return 1;+ }+ return 0;+}++static int html_number_cursor(BKNode *n, int x, int y)+{+ return html_spin_part(n, x, y) ? BK_CURSOR_DEFAULT : BK_CURSOR_TEXT;+}++/* -- range -- */++static double html_range_snap(const BKNode *n, double v)+{+ double st = n->step;+ if ((n->flags & NF_INTEGER) && st < 1.0) {+ st = 1.0;+ }+ if (st > 0) { /* the step base is the minimum */+ v = n->vmin + round((v - n->vmin) / st) * st;+ if (v > n->vmax + 1e-9) {+ v -= st;+ }+ v = round(v * 1e9) / 1e9;+ }+ return BK_CLAMP(v, n->vmin, n->vmax);+}++static float html_range_frac(const BKNode *n)+{+ const double span = n->vmax - n->vmin;+ return span > 0 ? (float)BK_CLAMP((n->value - n->vmin) / span, 0.0, 1.0) : 0.0f;+}++/* The thumb's center follows the pointer: absolute, not Blender's relative scrub. */+static void html_range_set_from(BKNode *n, int x)+{+ const float th = hp(16.0f), avail = BK_MAX(1.0f, n->w - th);+ const double f = BK_CLAMP((x - n->x - th * 0.5f) / avail, 0.0f, 1.0f);+ bk_set_value(n, html_range_snap(n, n->vmin + f * (n->vmax - n->vmin)));+}++static int html_range_press(BKNode *n, BKEvent *e)+{+ html_range_set_from(n, e->x);+ n->dragmode = 20;+ bk_invalidate(n);+ return 1;+}++static int html_range_drag(BKNode *n, BKEvent *e)+{+ if (n->dragmode == 20) {+ html_range_set_from(n, e->x);+ }+ return 1;+}++static int html_range_release(BKNode *n, BKEvent *e)+{+ n->dragmode = 0;+ bk_invalidate(n);+ return 1;+}++static int html_range_key(BKNode *n, BKEvent *e)+{+ const char *k = e->keysym;+ if (!NODE_ENABLED(n)) {+ return 0;+ }+ double st = n->step > 0 ? n->step : (n->vmax - n->vmin) / 100.0;+ if ((n->flags & NF_INTEGER) && st < 1.0) {+ st = 1.0;+ }+ /* Blink's SliderThumbElement: PageUp/Down move by max(step, range / 10) */+ const double page = BK_MAX(st, (n->vmax - n->vmin) / 10.0);+ double v;+ if (bk_keysym_is(k, "Right") || bk_keysym_is(k, "Up")) {+ v = n->value + st;+ }+ else if (bk_keysym_is(k, "Left") || bk_keysym_is(k, "Down")) {+ v = n->value - st;+ }+ else if (bk_keysym_is(k, "Prior")) {+ v = n->value + page;+ }+ else if (bk_keysym_is(k, "Next")) {+ v = n->value - page;+ }+ else if (bk_keysym_is(k, "Home")) {+ v = n->vmin;+ }+ else if (bk_keysym_is(k, "End")) {+ v = n->vmax;+ }+ else {+ return bk_value_key(n, e);+ }+ bk_set_value(n, html_range_snap(n, v));+ return 1;+}++static void html_range_draw(BKNode *n)+{+ const int hs = html_state(n);+ const float th = hp(16.0f), thick = hp(8.0f), bw = html_bw();+ const float cy = n->y + n->h * 0.5f;+ const float thumb_x = html_range_frac(n) * BK_MAX(0.0f, n->w - th);+ /* AlignSliderTrack: centered, 8px thick, inset 1px at both ends */+ const float tx = n->x + hp(1.0f), tw = n->w - 2 * hp(1.0f);+ const float ty = cy - thick * 0.5f, rad = thick * 0.5f;+ html_box(tx, ty, tw, thick, rad, kHtmlFill[hs], 0, 0);+ /* the value part: the track clipped to the thumb center + half the thickness */+ const int vx1 = (int)ceilf(n->x + thumb_x + thick * 0.5f);+ bk_clip_push(n->x, (int)floorf(ty) - 1, vx1 - n->x, (int)ceilf(thick) + 2);+ html_box(tx, ty, tw, thick, rad, kHtmlSlider[hs], 0, 0);+ bk_clip_pop();+ html_box(tx, ty, tw, thick, rad, 0, kHtmlSliderBorder[hs], bw);+ /* the 16px round thumb (drawn inset 0.5px, like Chrome) */+ float c[4];+ bk_argb(kHtmlSlider[hs], c);+ bk_circle(n->x + thumb_x + th * 0.5f, cy, th * 0.5f - hp(0.5f), c);+}++/* -- select -- */++static const char *html_item(const BKNode *n, int i)+{+ const char *s = item_text(n, i);+ return s[0] == HTML_GROUP_PREFIX ? s + 1 : s;+}++static void html_select_measure(BKNode *n, int *rw, int *rh)+{+ float widest = 0;+ for (int i = 0; i < n->items.n; i++) {+ if (n->items.v[i][0] != HTML_GROUP_PREFIX) {+ widest = BK_MAX(widest, bk_text_width(n->items.v[i], -1, false));+ }+ }+ /* 1px borders, 4px internal start padding, 1px + the arrow box (17px) at the end */+ *rw = (int)ceilf(widest) + hpi(1 + 4 + 18 + 1);+ *rh = hpi(19); /* 15px line + 1px internal padding + 1px borders */+}++static void html_select_draw(BKNode *n)+{+ const BKRect r = bk_node_rect(n);+ int hs = html_state(n);+ if (hs != HS_DISABLED && bk_owns_popup(bk_ctx(n), n)) {+ hs = HS_PRESSED;+ }+ /* PaintMenuList without a CSS radius: PaintTextField, then the arrow */+ html_field_frame(&r, hs, false);+ const uchar *tc = hs == HS_DISABLED ? kHtmlTextDisabled : kHtmlText;+ const BKRect cr = html_inset(&r, 5, 2, 19, 2);+ html_text(&cr, html_item(n, (int)n->value), -1, tc, BK_ALIGN_LEFT, false);+ /* the "v" chevron: 2:1, stroked in the text color, centered in the arrow box */+ const float aw = hp(8.0f), ah = floorf(aw * 0.5f);+ const float acx = r.xmax - hp(1.0f) - hp(18.0f) * 0.5f, acy = r.ymin + bk_rh(&r) * 0.5f;+ const float pts[3][2] = {{acx - aw * 0.5f, acy - ah * 0.5f},+ {acx, acy + ah * 0.5f},+ {acx + aw * 0.5f, acy - ah * 0.5f}};+ float c[4];+ bk_rgba(tc, c);+ bk_html_polyline(pts, 3, c, hp(2.0f)); /* PaintMenuList: stroke width 2 */+}++/* -- color input -- */++static void html_color_draw(BKNode *n)+{+ const BKRect r = bk_node_rect(n);+ int hs = html_state(n);+ if (hs != HS_DISABLED && bk_owns_popup(bk_ctx(n), n)) {+ hs = HS_PRESSED;+ }+ html_button_frame(&r, hs);+ /* padding 1px 2px + swatch wrapper 4px 2px, swatch border 1px #777777 */+ const BKRect sr = html_inset(&r, 5, 6, 5, 6);+ const float c[4] = {n->color[0], n->color[1], n->color[2], 1.0f};+ float b[4];+ bk_argb(0xFF777777u, b);+ bk_html_box((float)sr.xmin, (float)sr.ymin, (float)bk_rw(&sr), (float)bk_rh(&sr), 0.0f, c, b,+ html_bw());+ if (hs == HS_DISABLED) { /* the swatch dims with the control */+ html_box_r(&sr, 0.0f, 0xB3FAFAFAu, 0, 0);+ }+}++/* -- progress / meter -- */++static void html_progress_draw(BKNode *n)+{+ /* PaintProgressBar: the track is 8/16 of the height, a pill */+ const float thick = n->h * 0.5f, rad = thick * 0.5f;+ const float x = (float)n->x, w = (float)n->w, y = n->y + (n->h - thick) * 0.5f;+ html_box(x, y, w, thick, rad, kHtmlFill[HS_NORMAL], 0, 0);+ const double f = n->factor;+ if (f >= 0.0) { /* determinate: a rect clipped to the pill, at least 2px */+ const float vw = (float)BK_MAX(f > 0 ? hp(2.0f) : 0.0f, BK_MIN(1.0, f) * w);+ if (vw > 0) {+ bk_clip_push(n->x, (int)floorf(y) - 1, (int)ceilf(vw), (int)ceilf(thick) + 2);+ html_box(x, y, w, thick, rad, kHtmlAccent[HS_NORMAL], 0, 0);+ bk_clip_pop();+ }+ }+ else { /* indeterminate (factor < 0): a rounded segment (static) */+ html_box(x + w * 0.1f, y, w * 0.3f, thick, rad, kHtmlAccent[HS_NORMAL], 0, 0);+ }+ html_box(x, y, w, thick, rad, 0, kHtmlSliderBorder[HS_NORMAL], html_bw());+}++typedef struct MeterData {+ double low, high, optimum;+ unsigned has; /* 1 low, 2 high, 4 optimum */+} MeterData;++#define METER(n) ((MeterData *)(n)->ext)++static void meter_init(BKNode *n)+{+ n->vmin = 0.0;+ n->vmax = 1.0;+ n->flags |= NF_HAS_MIN | NF_HAS_MAX;+ n->ext = calloc(1, sizeof(MeterData));+}++static void meter_free(BKNode *n)+{+ free(n->ext);+ n->ext = NULL;+}++static int meter_set_num(BKNode *n, const char *key, double v)+{+ MeterData *m = METER(n);+ if (strcmp(key, "low") == 0) {+ m->low = v;+ m->has |= 1u;+ }+ else if (strcmp(key, "high") == 0) {+ m->high = v;+ m->has |= 2u;+ }+ else if (strcmp(key, "optimum") == 0) {+ m->optimum = v;+ m->has |= 4u;+ }+ else {+ return 0;+ }+ bk_invalidate(n);+ return 1;+}++/* The HTML spec's clamped low / high / optimum. */+static int meter_get_num(BKNode *n, const char *key, double *r_v)+{+ const MeterData *m = METER(n);+ const double lo = n->vmin, hi = BK_MAX(n->vmin, n->vmax);+ const double low = (m->has & 1u) ? BK_CLAMP(m->low, lo, hi) : lo;+ const double high = (m->has & 2u) ? BK_CLAMP(m->high, low, hi) : hi;+ if (strcmp(key, "low") == 0) {+ *r_v = low;+ }+ else if (strcmp(key, "high") == 0) {+ *r_v = high;+ }+ else if (strcmp(key, "optimum") == 0) {+ *r_v = (m->has & 4u) ? BK_CLAMP(m->optimum, lo, hi) : (lo + hi) * 0.5;+ }+ else {+ return 0;+ }+ return 1;+}++/* The gauge region: 0 optimum, 1 suboptimum, 2 even less good. */+static int meter_region(BKNode *n)+{+ double low, high, opt;+ meter_get_num(n, "low", &low);+ meter_get_num(n, "high", &high);+ meter_get_num(n, "optimum", &opt);+ const double v = BK_CLAMP(n->value, n->vmin, BK_MAX(n->vmin, n->vmax));+ if (opt < low) { /* the low region is optimal */+ return v <= low ? 0 : (v <= high ? 1 : 2);+ }+ if (opt > high) { /* the high region is optimal */+ return v >= high ? 0 : (v >= low ? 1 : 2);+ }+ return (v >= low && v <= high) ? 0 : 1; /* the middle is optimal */+}++static void html_meter_draw(BKNode *n)+{+ /* ::-webkit-meter-bar: the middle half of the height (grid rows 1fr 2fr 1fr),+ * #efefef, border-radius 20px, thin rgba(118,118,118,.3) border; the value+ * fills it from the start, clipped by the bar's rounded overflow */+ static const uint32_t kRegion[3] = {0xFF107C10u, 0xFFFFB900u, 0xFFD83B01u};+ const float bh = n->h * 0.5f, rad = bh * 0.5f;+ const float x = (float)n->x, w = (float)n->w, y = n->y + (n->h - bh) * 0.5f;+ html_box(x, y, w, bh, rad, 0xFFEFEFEFu, 0, 0);+ const double span = n->vmax - n->vmin;+ const double f = span > 0 ? BK_CLAMP((n->value - n->vmin) / span, 0.0, 1.0) : 0.0;+ const float bw = html_bw(), inner = w - 2 * bw;+ if (f > 0 && inner > 0) {+ bk_clip_push(n->x, (int)floorf(y) - 1, (int)ceilf(bw + f * inner), (int)ceilf(bh) + 2);+ html_box(x + bw, y + bw, inner, bh - 2 * bw, rad - bw, kRegion[meter_region(n)], 0, 0);+ bk_clip_pop();+ }+ html_box(x, y, w, bh, rad, 0, 0x4D767676u, bw);+}++static void meter_draw(BKNode *n)+{+ /* Blender look: a progress bar of the value */+ BKRect r = bk_node_rect(n);+ BKWCol w;+ bk_widget_state(&w, &bk_theme.progress, NODE_ENABLED(n) ? 0 : ST_DISABLED);+ const double span = n->vmax - n->vmin;+ bk_widget_progress(&w, &r, n->corners,+ span > 0 ? (float)BK_CLAMP((n->value - n->vmin) / span, 0.0, 1.0) : 0.0f);+}++const BKClass bk_cls_meter = {.name = "meter",+ .init = meter_init,+ .free_ext = meter_free,+ .measure = progress_measure,+ .draw = meter_draw,+ .set_num = meter_set_num,+ .get_num = meter_get_num};++/* -- dispatch from the core (bk_natural / bk_draw_tree) -- */++bool bk_html_measure(BKNode *n, int *rw, int *rh)+{+ const BKClass *c = n->cls;+ const float saved = html_font_begin(n);+ bool ok = true;+ if (c == &bk_cls_button) {+ html_button_measure(n, n->text, rw, rh);+ }+ else if (c == &bk_cls_toggle) {+ html_button_measure(n, n->label, rw, rh);+ }+ else if (c == &bk_cls_checkbox || c == &bk_cls_radio) {+ html_check_measure(n, rw, rh);+ }+ else if (c == &bk_cls_text || c == &bk_cls_search || c == &bk_cls_number) {+ *rw = hpi(153); /* size=20 at 13.33px + 2px borders + 2px padding */+ *rh = hpi(21);+ }+ else if (c == &bk_cls_slider) {+ *rw = hpi(129);+ *rh = hpi(16);+ }+ else if (c == &bk_cls_dropdown) {+ html_select_measure(n, rw, rh);+ }+ else if (c == &bk_cls_swatch) {+ *rw = hpi(50);+ *rh = hpi(27);+ }+ else if (c == &bk_cls_progress) {+ *rw = hpi(160); /* 10em x 1em at 16px */+ *rh = hpi(16);+ }+ else if (c == &bk_cls_meter) {+ *rw = hpi(80); /* 5em x 1em at 16px */+ *rh = hpi(16);+ }+ else if (c == &bk_cls_textarea) {+ ok = bk_textarea_html_measure(n, rw, rh);+ }+ else {+ ok = false;+ }+ bk_text_scale = saved;+ return ok;+}++bool bk_html_draw(BKNode *n)+{+ const BKClass *c = n->cls;+ const float saved = html_font_begin(n);+ bool ok = true;+ if (c == &bk_cls_button) {+ html_button_draw(n, n->text, false);+ }+ else if (c == &bk_cls_toggle) {+ html_button_draw(n, n->label, n->value != 0);+ }+ else if (c == &bk_cls_checkbox) {+ html_checkbox_draw(n);+ }+ else if (c == &bk_cls_radio) {+ html_radio_draw(n);+ }+ else if (c == &bk_cls_text || c == &bk_cls_search) {+ html_text_draw(n);+ }+ else if (c == &bk_cls_number) {+ html_number_draw(n);+ }+ else if (c == &bk_cls_slider) {+ html_range_draw(n);+ }+ else if (c == &bk_cls_dropdown) {+ html_select_draw(n);+ }+ else if (c == &bk_cls_swatch) {+ html_color_draw(n);+ }+ else if (c == &bk_cls_progress) {+ html_progress_draw(n);+ }+ else if (c == &bk_cls_meter) {+ html_meter_draw(n);+ }+ else if (c == &bk_cls_textarea) {+ bk_textarea_html_draw(n);+ }+ else {+ ok = false;+ }+ bk_text_scale = saved;+ return ok;+}++/** \} */