Skip to content

armgit / BUI

Public Imported from GitHub
0

Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI

feat: add styled ^ css methods

Preetham Pemmasani014cb2ed3b1f
diff --git a/README.md b/README.md
index 2960023..370e860 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 82/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 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 |
| 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 (207 of 745 W3C properties render, 177 more parse) | Rendering effects: `rotate`/`skew` transforms, `filter`/`backdrop-filter`, blend modes, `clip-path`, masks, `border-image`, non-solid borders. Also animations and transitions. Most of the remaining W3C list is drafts, speech, print and SVG ([breakdown](docs/rust.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)) |
| 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/examples/counter.js b/bindings/node/examples/counter.js
index c9c1394..1a1c276 100644
--- a/bindings/node/examples/counter.js
+++ b/bindings/node/examples/counter.js
@@ -5,6 +5,7 @@ const { App } = require('..')
const app = new App({ gpu: process.env.BUI_GPU === '1' })
const win = app.window({ title: 'BUI from Node', width: 360, height: 220 })
+win.body.setAttribute('styled', '')
win.body.className = 'm-0 p-6 flex flex-col gap-3 bg-[#2b2b2b] text-[#e6e6e6]'
const title = win.createElement('h1')
diff --git a/bindings/python/bui/theme.py b/bindings/python/bui/theme.py
index a188488..67141dc 100644
--- a/bindings/python/bui/theme.py
+++ b/bindings/python/bui/theme.py
@@ -63,6 +63,7 @@ WCOL = {
"tooltip": _wcol(0x242424ff, 0x1d1d1dff, 0x4772b3ff, 0xd9d9d9ff, 0xd9d9d9ff, 0xffffffff, roundness=0.2),
"tab": _wcol(0x1d1d1dff, 0x1d1d1dff, 0x303030ff, 0x1d1d1dff, 0x989898ff, 0xffffffff, roundness=0.2),
"pie_menu": _wcol(0x242424ff, 0x181818ff, 0x4772b3ff, 0x545454ff, 0xd9d9d9ff, 0xffffffff, roundness=0.2),
+ "curve": _wcol(0x727272ff, 0x545454ff, 0x000000ff, 0x00000059, 0x08080800, 0xc9c9c900, roundness=0.2),
}
# --- region / panel colors ----------------------------------------------------
diff --git a/bindings/react/examples/counter.js b/bindings/react/examples/counter.js
index 1991a7d..cf4da38 100644
--- a/bindings/react/examples/counter.js
+++ b/bindings/react/examples/counter.js
@@ -19,5 +19,6 @@ function Counter () {
}
const { app, window } = render(h(Counter), { title: 'BUI + React', width: 420, height: 260 })
+window.body.setAttribute('styled', '')
window.body.className = 'm-0 bg-[#2b2b2b] text-[#e6e6e6]'
if (process.env.BUI_EXAMPLE_SECONDS) setTimeout(() => app.quit(), Number(process.env.BUI_EXAMPLE_SECONDS) * 1000)
diff --git a/bindings/react/examples/counter.jsx b/bindings/react/examples/counter.jsx
index 64e84d9..8ea906a 100644
--- a/bindings/react/examples/counter.jsx
+++ b/bindings/react/examples/counter.jsx
@@ -20,5 +20,6 @@ function Counter () {
}
const { app, window } = render(<Counter />, { title: 'BUI + React', width: 420, height: 260 })
+window.body.setAttribute('styled', '')
window.body.className = 'm-0 bg-[#2b2b2b] text-[#e6e6e6]'
if (process.env.BUI_EXAMPLE_SECONDS) setTimeout(() => app.quit(), Number(process.env.BUI_EXAMPLE_SECONDS) * 1000)
diff --git a/bindings/rust/blenderui-macros/src/rsx.rs b/bindings/rust/blenderui-macros/src/rsx.rs
index 2e2ed93..0a2f28c 100644
--- a/bindings/rust/blenderui-macros/src/rsx.rs
+++ b/bindings/rust/blenderui-macros/src/rsx.rs
@@ -473,7 +473,7 @@ const BOOLEAN_ATTRS: &[&str] = &[
"allowfullscreen", "async", "autofocus", "autoplay", "checked", "controls", "default", "defer", "disabled",
"formnovalidate", "hidden", "inert", "ismap", "itemscope", "loop", "multiple", "muted", "nomodule",
"novalidate", "open", "playsinline", "readonly", "required", "reversed", "selected", "popover", "draggable",
- "contenteditable", "spellcheck", "translate",
+ "contenteditable", "spellcheck", "translate", "styled",
];
/// A bare attribute (`<div p-4 hover:bg-sky-500>`): Some(class) when it is
diff --git a/bindings/rust/blenderui/examples/counter.rs b/bindings/rust/blenderui/examples/counter.rs
index 324a1a1..9610790 100644
--- a/bindings/rust/blenderui/examples/counter.rs
+++ b/bindings/rust/blenderui/examples/counter.rs
@@ -6,7 +6,7 @@ struct Counter { count: i32 }
impl Render for Counter {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
- div().flex().flex_col().gap_2().p_4()
+ div().styled().flex().flex_col().gap_2().p_4()
.child(h1().child(format!("Count: {}", self.count)))
.child(p().child("Any ").child(b().child("HTML element")).child(", styled with ")
.child(code().child(".css()")).child(" or a <style> sheet."))
diff --git a/bindings/rust/blenderui/examples/golden.rs b/bindings/rust/blenderui/examples/golden.rs
index e6a720a..ca5011b 100644
--- a/bindings/rust/blenderui/examples/golden.rs
+++ b/bindings/rust/blenderui/examples/golden.rs
@@ -8,6 +8,7 @@ struct Scene;
impl Render for Scene {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
body()
+ .styled()
.m_0()
.child(style().child(".hdr { color: #e6a23c; } li:nth-child(2) { color: #78aef0 } .box:hover { opacity: 0.5 }"))
.child(
diff --git a/bindings/rust/blenderui/examples/hello.rs b/bindings/rust/blenderui/examples/hello.rs
index 4b6eb6d..0300254 100644
--- a/bindings/rust/blenderui/examples/hello.rs
+++ b/bindings/rust/blenderui/examples/hello.rs
@@ -23,7 +23,7 @@ struct Hello;
impl Render for Hello {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
rsx! {
- <body m-0 p-6 min-h-screen flex flex-col gap-4 bg-zinc-900 text-white>
+ <body styled m-0 p-6 min-h-screen flex flex-col gap-4 bg-zinc-900 text-white>
<h1 text-2xl font-bold>"Hello, BUI"</h1>
<counter label="Clicks" />
<input type="range" min={0.0} max={10.0} />
diff --git a/bindings/rust/blenderui/examples/raster_probe.rs b/bindings/rust/blenderui/examples/raster_probe.rs
index 406c97b..160cae9 100644
--- a/bindings/rust/blenderui/examples/raster_probe.rs
+++ b/bindings/rust/blenderui/examples/raster_probe.rs
@@ -15,9 +15,9 @@ impl Render for Scene {
if self.text { d.child(format!("{}", (i as u64 * 13 + t) % 1000)) } else { d }
}));
if std::env::var_os("FLEXROOT").is_some() {
- html().flex().child(body().m_0().flex().flex_1().child(grid))
+ html().flex().child(body().styled().m_0().flex().flex_1().child(grid))
} else {
- body().m_0().child(grid)
+ body().styled().m_0().child(grid)
}
}
}
diff --git a/bindings/rust/blenderui/examples/showcase.rs b/bindings/rust/blenderui/examples/showcase.rs
index 6d3fbb0..ad86f7c 100644
--- a/bindings/rust/blenderui/examples/showcase.rs
+++ b/bindings/rust/blenderui/examples/showcase.rs
@@ -36,6 +36,7 @@ impl Render for Showcase {
div().class("card").child(h4().child(title)).child(small().child(body))
};
html()
+ .styled()
.child(head().child(title().child("BUI showcase")).child(style().child(CSS)))
.child(body().child(
div().class("app")
diff --git a/bindings/rust/blenderui/src/element.rs b/bindings/rust/blenderui/src/element.rs
index f4f56d7..024c310 100644
--- a/bindings/rust/blenderui/src/element.rs
+++ b/bindings/rust/blenderui/src/element.rs
@@ -150,6 +150,14 @@ impl Div {
self
}
+ /// Give this element and everything inside it Blender's look (dark
+ /// theme, UI font size, themed links, code, tables ...). Without it,
+ /// elements get the browsers' defaults: black text on white. Form
+ /// widgets look like Blender either way. `<div styled>` in `rsx!`.
+ pub fn styled(self) -> Self {
+ self.attr("styled", "")
+ }
+
/// Add CSS classes (matched by stylesheets).
pub fn class(mut self, classes: impl Into<SharedString>) -> Self {
let add = classes.into();
diff --git a/bindings/rust/blenderui/src/html.rs b/bindings/rust/blenderui/src/html.rs
index 004e3f6..df40d3d 100644
--- a/bindings/rust/blenderui/src/html.rs
+++ b/bindings/rust/blenderui/src/html.rs
@@ -67,9 +67,73 @@ pub fn custom(tag: &'static str) -> Div {
}
/// The user-agent stylesheet: the browsers' defaults (WHATWG rendering
-/// section) in Blender's dark theme.
+/// section: black text on white). An element with the `styled` attribute
+/// (`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: #303030; color: #e6e6e6; font-size: 13px; }
+html { display: block; background-color: #ffffff; color: #000000; font-size: 16px; }
+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,
+p, pre, search, section, ul, noscript, optgroup, option { display: block; }
+head, title, base, link, meta, style, script, template, source, track, area, datalist, wbr,
+map, [hidden], input[type=hidden], col, colgroup { display: none; }
+li, summary { display: list-item; }
+p, dl, pre { margin: 1em 0; }
+figure, blockquote { margin: 1em 40px; }
+h1 { font-size: 2em; margin: 0.67em 0; font-weight: bold; }
+h2 { font-size: 1.5em; margin: 0.83em 0; font-weight: bold; }
+h3 { font-size: 1.17em; margin: 1em 0; font-weight: bold; }
+h4 { font-size: 1em; margin: 1.33em 0; font-weight: bold; }
+h5 { font-size: 0.83em; margin: 1.67em 0; font-weight: bold; }
+h6 { font-size: 0.67em; margin: 2.33em 0; font-weight: bold; }
+b, strong, th, dt, caption { font-weight: bold; }
+i, em, cite, dfn, var, address { font-style: italic; }
+u, ins { text-decoration: underline; }
+s, del { text-decoration: line-through; }
+small { font-size: smaller; }
+sub { vertical-align: sub; font-size: smaller; }
+sup { vertical-align: super; font-size: smaller; }
+code, kbd, samp, pre, var { font-family: monospace; }
+pre { white-space: pre; }
+mark { background-color: #ffff00; color: #000000; }
+a { color: #0000ee; text-decoration: underline; cursor: pointer; }
+abbr[title] { text-decoration: underline dotted; }
+rt { font-size: 50%; }
+ul, menu { list-style-type: disc; padding-left: 40px; margin: 1em 0; }
+ol { list-style-type: decimal; padding-left: 40px; margin: 1em 0; }
+ul ul, ol ul, menu ul { list-style-type: circle; margin: 0; }
+ul ul ul, ol ol ul { list-style-type: square; }
+ol ol, ul ol { margin: 0; }
+dd { margin-left: 40px; }
+hr { border: 1px inset #808080; margin: 0.5em 0; }
+table { display: table; border-spacing: 2px; }
+thead, tbody, tfoot { display: table-row-group; }
+tr { display: table-row; }
+td, th { display: table-cell; padding: 1px; }
+th { text-align: center; }
+caption { display: table-caption; text-align: center; }
+fieldset { margin: 0 2px; padding: 0.35em 0.75em 0.625em; border: 2px groove #c0c0c0; }
+legend { padding: 0 2px; }
+summary { cursor: pointer; }
+dialog { position: absolute; left: 10%; right: 10%; top: 15%; padding: 1em;
+ background-color: #ffffff; color: #000000; border: 2px solid #000000; z-index: 100; }
+dialog:not([open]) { display: none; }
+img, video, iframe, embed, object, audio, canvas, svg, math { display: inline-block; }
+button, input, select, textarea, progress, meter { display: inline-block; }
+audio:not([controls]) { display: none; }
+iframe { border: 2px inset #808080; }
+label { cursor: default; }
+output { display: inline; }
+
+"#;
+
+/// The user-agent stylesheet inside `styled` subtrees: the same defaults in
+/// Blender's dark theme. The `styled` element itself gets the theme's
+/// 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; }
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,
@@ -139,6 +203,12 @@ pub fn ua_stylesheet() -> &'static Stylesheet {
SHEET.get_or_init(|| Stylesheet::parse(UA_CSS))
}
+/// The parsed [`UA_STYLED_CSS`] (shared, parsed once).
+pub fn ua_styled_stylesheet() -> &'static Stylesheet {
+ static SHEET: OnceLock<Stylesheet> = OnceLock::new();
+ SHEET.get_or_init(|| Stylesheet::parse(UA_STYLED_CSS))
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/bindings/rust/blenderui/src/layout.rs b/bindings/rust/blenderui/src/layout.rs
index 538cb56..5444a4c 100644
--- a/bindings/rust/blenderui/src/layout.rs
+++ b/bindings/rust/blenderui/src/layout.rs
@@ -22,7 +22,7 @@ use taffy::style::Overflow;
use crate::css::{Decl, Prop, Rule, Stylesheet, Subject};
use crate::element::{AnyElement, Div, Listeners, PaintFn, ParentElement, SharedString};
use crate::geometry::{rect, Bounds, Units};
-use crate::html::{tag_kind, ua_stylesheet, TagKind};
+use crate::html::{tag_kind, ua_styled_stylesheet, ua_stylesheet, TagKind};
use crate::paint::{Image, ImageCache};
use crate::prof::{span, Phase};
use crate::style::ContentPart;
@@ -274,6 +274,8 @@ pub(crate) struct BoxNode {
/// Position among siblings of the same tag, and their count.
pub tpos: (u32, u32),
pub marker: Option<String>,
+ /// Inside a `styled` subtree: matched against the Blender UA sheet.
+ pub styled: bool,
// filled after layout
pub bounds: Bounds<f32>,
pub clip: Option<Bounds<f32>>,
@@ -302,7 +304,7 @@ pub(crate) struct Frame {
pub(crate) enum Measure {
/// Text of the box registered under `key` this frame (already
/// whitespace-processed and transformed); `hash` identifies the text.
- Text { key: Key, hash: u64, size: f32, flags: i32, line: f32, nowrap: bool },
+ Text { key: Key, hash: u64, size: f32, flags: i32, line: f32, nowrap: bool, brk: u8 },
}
/// The persistent taffy tree's nodes by box key (with the frame they were
@@ -439,11 +441,15 @@ struct Builder<'a> {
containers: &'a Containers,
/// Media query results of the UA and author sheets this frame.
ua_media: Vec<bool>,
+ ua_styled_media: Vec<bool>,
au_media: Vec<bool>,
state: &'a UiState,
viewport: (f32, f32),
title: Option<String>,
widgets: &'a mut dyn FnMut(Key, &WidgetSpec) -> (f32, f32),
+ /// 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)>,
}
/// Child box indices / layout nodes being assembled: on the stack for the usual few.
@@ -822,11 +828,12 @@ impl<'a> Builder<'a> {
/// 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>) {
- let ua_sheet = ua_stylesheet();
+ let (ua_sheet, ua_media) = self.ua_for(i);
let author: &'a Stylesheet = self.author;
let memo = {
let mut h = Fnv::default();
self.nodes[i].fp.hash(&mut h);
+ self.nodes[i].styled.hash(&mut h);
self.containers.generation.hash(&mut h);
self.viewport.0.to_bits().hash(&mut h);
self.viewport.1.to_bits().hash(&mut h);
@@ -837,13 +844,23 @@ impl<'a> Builder<'a> {
a.iter().map(|&k| &author.rules[k as usize]).collect());
}
let subj = self.subject(i);
- let ua = ua_sheet.matches(&subj, &self.ua_media, None);
+ let ua = ua_sheet.matches(&subj, ua_media, None);
let au = author.matches(&subj, &self.au_media, None);
self.matched.map.insert(memo, (ua.iter().map(|r| r.order as u32).collect(),
au.iter().map(|r| r.order as u32).collect()));
(ua, au)
}
+ /// The UA sheet for box `i` (plain, or Blender's inside `styled`) and
+ /// its media query results.
+ fn ua_for(&self, i: usize) -> (&'static Stylesheet, &Vec<bool>) {
+ if self.nodes[i].styled {
+ (ua_styled_stylesheet(), &self.ua_styled_media)
+ } else {
+ (ua_stylesheet(), &self.ua_media)
+ }
+ }
+
/// The fingerprint of element `i` (see [`BoxNode::fp`]).
fn fingerprint(&self, i: usize) -> u64 {
let n = &self.nodes[i];
@@ -989,6 +1006,7 @@ impl<'a> Builder<'a> {
pos: (1, 1),
tpos: (1, 1),
marker: None,
+ styled: false,
bounds: rect(0.0, 0.0, 0.0, 0.0),
clip: None,
opacity: 1.0,
@@ -1064,6 +1082,11 @@ impl<'a> Builder<'a> {
}
}
self.nodes[i].fp = self.fingerprint(i);
+ // `styled` (any value but "false") turns Blender's theme on for the subtree
+ self.nodes[i].styled = match self.els.last().and_then(|e| e.attrs.iter().find(|(n, _)| n == "styled")) {
+ Some((_, v)) => v.as_ref() != "false",
+ None => parent.is_some_and(|p| self.nodes[p].styled),
+ };
let kind = tag_kind(div.tag);
// widgets and replaced elements are atomic inlines; flex/grid items are blockified
let fixup = if kind == TagKind::Widget || kind == TagKind::Replaced {
@@ -1081,6 +1104,7 @@ impl<'a> Builder<'a> {
return None;
}
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
div.attrs = Vec::new();
match kind {
@@ -1122,7 +1146,7 @@ impl<'a> Builder<'a> {
children.insert(0, AnyElement::Text(open.into()));
children.push(AnyElement::Text(close.into()));
}
- let pseudo = self.author.uses_pseudo() || ua_stylesheet().uses_pseudo();
+ let pseudo = self.author.uses_pseudo() || self.ua_for(i).0.uses_pseudo();
if pseudo {
self.generated(i, crate::css::PseudoElement::Before);
}
@@ -1132,16 +1156,52 @@ impl<'a> Builder<'a> {
}
}
}
+ // counters this element's children created go out of scope
+ while self.counters.last().is_some_and(|c| c.2 == i) {
+ self.counters.pop();
+ }
Some(i)
}
+ /// Apply `counter-reset`, then `-increment`, then `-set` of style `sid`; new counters are scoped to `scope` (the parent: an element's
+ /// counter is seen by its following siblings).
+ fn counter_ops(&mut self, sid: StyleId, scope: usize) {
+ let Some(ops) = self.styles[sid].counters.clone() else { return };
+ for (name, v) in &ops.reset {
+ // a sibling's reset replaces the instance a previous sibling made
+ let same_scope = self.counters.iter_mut().rev().take_while(|c| c.2 == scope).find(|c| c.0 == *name);
+ match same_scope {
+ Some(c) => c.1 = *v,
+ None => self.counters.push((name.clone(), *v, scope)),
+ }
+ }
+ let find = |b: &mut Self, name: &str| -> usize {
+ match b.counters.iter().rposition(|c| &*c.0 == name) {
+ Some(k) => k,
+ None => {
+ // using a counter that doesn't exist instantiates it here
+ b.counters.push((name.into(), 0, scope));
+ b.counters.len() - 1
+ }
+ }
+ };
+ for (name, v) in &ops.increment {
+ let k = find(self, name);
+ self.counters[k].1 = self.counters[k].1.wrapping_add(*v);
+ }
+ for (name, v) in &ops.set {
+ let k = find(self, name);
+ self.counters[k].1 = *v;
+ }
+ }
+
/// The `::before` / `::after` box of element `i`, when a rule gives it content.
fn generated(&mut self, i: usize, pe: crate::css::PseudoElement) {
- let ua_sheet = ua_stylesheet();
+ let (ua_sheet, ua_media) = self.ua_for(i);
let author: &'a Stylesheet = self.author;
let (ua, au) = {
let subj = self.subject(i);
- (ua_sheet.matches(&subj, &self.ua_media, Some(pe)), author.matches(&subj, &self.au_media, Some(pe)))
+ (ua_sheet.matches(&subj, ua_media, Some(pe)), author.matches(&subj, &self.au_media, Some(pe)))
};
if ua.is_empty() && au.is_empty() {
return;
@@ -1181,10 +1241,12 @@ impl<'a> Builder<'a> {
}
};
let st = &self.styles[sid];
- let Some(parts) = st.content.as_ref() else { return };
- if st.display == DisplayKind::None {
+ if st.content.is_none() || st.display == DisplayKind::None {
return;
}
+ self.counter_ops(sid, i);
+ let st = &self.styles[sid];
+ let Some(parts) = st.content.as_ref() else { return };
let quotes = st.quotes.clone().unwrap_or_else(|| ("\u{201c}".into(), "\u{201d}".into()));
let mut text = String::new();
for p in parts.iter() {
@@ -1193,6 +1255,15 @@ impl<'a> Builder<'a> {
ContentPart::Attr(n) => text.push_str(self.attr(i, n).unwrap_or("")),
ContentPart::OpenQuote => text.push_str(&quotes.0),
ContentPart::CloseQuote => text.push_str(&quotes.1),
+ ContentPart::Counter(name, ls) => {
+ let v = self.counters.iter().rev().find(|c| c.0 == *name).map_or(0, |c| c.1);
+ text.push_str(&ls.format(v));
+ }
+ ContentPart::Counters(name, sep, ls) => {
+ let all: Vec<String> = self.counters.iter().filter(|c| c.0 == *name)
+ .map(|c| ls.format(c.1)).collect();
+ text.push_str(&if all.is_empty() { ls.format(0) } else { all.join(sep) });
+ }
}
}
let key = child_key(self.nodes[i].key, tag, 0);
@@ -1217,7 +1288,7 @@ impl<'a> Builder<'a> {
let idx = self.nodes[i].pos.0 + self.nodes[i].parent
.and_then(|p| self.attr(p, "start"))
.and_then(|s| s.parse::<usize>().ok()).map(|s| s - 1).unwrap_or(0);
- ls.marker(idx)
+ ls.marker(idx).or_else(|| self.st(i).list_image.as_ref().map(|_| String::new()))
};
match marker {
Some(m) if self.st(i).marker_inside => {
@@ -1378,9 +1449,9 @@ 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) = (self.styles[c].text_transform, self.styles[c].white_space);
+ let (tt, ws, tab) = (self.styles[c].text_transform, self.styles[c].white_space, self.styles[c].tab_size);
if let Content::Text(t) = &self.nodes[k].content {
- if let std::borrow::Cow::Owned(s) = transform(t, tt, ws) {
+ if let std::borrow::Cow::Owned(s) = transform(t, tt, ws, tab) {
self.nodes[k].content = Content::Text(s);
}
}
@@ -1394,7 +1465,8 @@ impl<'a> Builder<'a> {
_ => 0,
};
let c = &self.styles[c];
- Measure::Text { key, hash, size: c.font_size, flags: text::flags(c), line: c.line_px(), nowrap }
+ Measure::Text { key, hash, size: c.font_size, flags: text::flags(c), line: c.line_px(), nowrap,
+ brk: text::break_mode(c) }
}
/// The taffy node for box `i` (and its subtree). Marks it dirty when
@@ -1635,12 +1707,13 @@ impl<'a> Builder<'a> {
let sid = self.nodes[owner].style;
let c = &self.styles[sid];
let (ws, tt, size, letter, word_sp) = (c.white_space, c.text_transform, c.font_size, c.letter_spacing, c.word_spacing);
+ let (tab, break_all) = (c.tab_size, c.break_all);
let flags = text::flags(c);
let line_h = c.line_px();
let indent = if first { c.text_indent.resolve(&self.units(size), 0.0) } else { 0.0 };
// the processed text, kept in the box
let Content::Text(raw) = std::mem::replace(&mut self.nodes[src].content, Content::Anon) else { return };
- let mut text = match transform(&raw, tt, ws) {
+ let mut text = match transform(&raw, tt, ws, tab) {
std::borrow::Cow::Borrowed(_) => raw,
std::borrow::Cow::Owned(s) => s,
};
@@ -1686,6 +1759,21 @@ impl<'a> Builder<'a> {
}
}
}
+ 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 {
+ let piece = &text[a..b];
+ let n = piece.char_indices().count();
+ for (j, (o, ch)) in piece.char_indices().enumerate() {
+ let last = j + 1 == n;
+ chars.push((a + o, a + o + ch.len_utf8(), trailing && last, brk && last));
+ }
+ if n == 0 {
+ chars.push((a, b, trailing, brk));
+ }
+ }
+ pieces = chars;
+ }
let space = self.text.width(" ", size, flags) + word_sp;
let src_key = self.nodes[src].key;
for (n, &(a, b, trailing, brk)) in pieces.iter().enumerate() {
@@ -1742,13 +1830,41 @@ fn collapse(s: &str) -> String {
}
/// Whitespace processing and `text-transform`; borrows when nothing changes.
-fn transform(s: &str, t: TextTransform, ws: WhiteSpace) -> std::borrow::Cow<'_, str> {
+fn transform(s: &str, t: TextTransform, ws: WhiteSpace, tab: u8) -> std::borrow::Cow<'_, str> {
use std::borrow::Cow;
let collapse_ws = (ws == WhiteSpace::Normal || ws == WhiteSpace::NoWrap) && s.contains(['\n', '\t', '\r']);
- if !collapse_ws && t == TextTransform::None {
+ // preserved tabs advance to the next multiple of `tab-size` spaces
+ let expand_tabs = matches!(ws, WhiteSpace::Pre | WhiteSpace::PreWrap) && s.contains('\t');
+ if !collapse_ws && !expand_tabs && t == TextTransform::None {
return Cow::Borrowed(s);
}
- let s = if collapse_ws { s.replace(['\n', '\t', '\r'], " ") } else { s.to_string() };
+ let s = if collapse_ws {
+ s.replace(['\n', '\t', '\r'], " ")
+ } else if expand_tabs {
+ let mut out = String::with_capacity(s.len() + 16);
+ let mut col = 0usize;
+ for ch in s.chars() {
+ match ch {
+ '\t' if tab > 0 => {
+ let n = tab as usize - col % tab as usize;
+ out.extend(std::iter::repeat_n(' ', n));
+ col += n;
+ }
+ '\t' => {}
+ '\n' => {
+ out.push('\n');
+ col = 0;
+ }
+ c => {
+ out.push(c);
+ col += 1;
+ }
+ }
+ }
+ out
+ } else {
+ s.to_string()
+ };
Cow::Owned(match t {
TextTransform::None => s,
TextTransform::Upper => s.to_uppercase(),
@@ -1813,11 +1929,13 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca
author: &author.sheet,
author_hash: author.hash,
ua_media: ua_stylesheet().media_results(&crate::css::MediaEnv::viewport(viewport)),
+ ua_styled_media: ua_styled_stylesheet().media_results(&crate::css::MediaEnv::viewport(viewport)),
au_media: author.sheet.media_results(&crate::css::MediaEnv::viewport(viewport)),
state,
viewport,
title,
widgets,
+ counters: Vec::new(),
};
// the document: <html><body> unless the app built them itself
let root_div = match root {
@@ -1854,12 +1972,12 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca
let Builder { nodes, els, taffy, styles, text: tc, title, text_box, .. } = b;
taffy.compute(root_id, avail, |known, available, ctx| {
match ctx {
- Measure::Text { key, size, flags, line, nowrap, .. } => {
+ Measure::Text { key, size, flags, line, nowrap, brk, .. } => {
let text = match text_box.get(key).map(|&k| &nodes[k].content) {
Some(Content::Text(t)) => t.as_str(),
_ => "",
};
- if !text.contains([' ', '\n']) {
+ if !text.contains([' ', '\n']) && *brk == 0 {
// one word: no wrapping to do
let w = tc.width(text, *size, *flags);
return Size { width: known.width.unwrap_or(w.ceil()),
@@ -1870,7 +1988,7 @@ pub(crate) fn layout(root: AnyElement, viewport: (f32, f32), state: &UiState, ca
AvailableSpace::MinContent => 0.0,
AvailableSpace::MaxContent => f32::INFINITY,
});
- let lines = tc.wrap(text, *size, *flags, if *nowrap { f32::INFINITY } else { max_w });
+ let lines = tc.wrap(text, *size, *flags, if *nowrap { f32::INFINITY } else { max_w }, *brk);
let w = lines.iter().map(|l| tc.width(l, *size, *flags)).fold(0.0, f32::max);
Size { width: known.width.unwrap_or(w.ceil()),
height: known.height.unwrap_or(*line * lines.len().max(1) as f32) }
@@ -1931,6 +2049,18 @@ impl Walk<'_> {
}
nodes[i].bounds = rect(x, y, w, h);
nodes[i].clip = clip;
+ if let Some(cr) = st.clip_rect.filter(|_| matches!(st.layout.position, Position::Absolute | Position::Fixed)) {
+ // edges from the border box's top-left corner; auto = that edge
+ let e = |k: usize, auto: f32, basis: f32| cr[k].map_or(auto, |l| l.resolve(&u, basis));
+ let (top, right, bottom, left) = (e(0, 0.0, h), e(1, w, w), e(2, h, h), e(3, 0.0, w));
+ let r = rect(x + left, y + top, (right - left).max(0.0), (bottom - top).max(0.0));
+ let r = match clip {
+ Some(c) => c.intersect(&r),
+ None => r,
+ };
+ nodes[i].clip = Some(r);
+ child_clip = Some(r);
+ }
let ov = st.layout.overflow;
if ov.x != Overflow::Visible || ov.y != Overflow::Visible {
let b = l.border;
@@ -1982,11 +2112,12 @@ fn place_folded_text(nodes: &mut [BoxNode], i: usize, k: usize, b: Bounds<f32>,
let Content::Text(t) = &nodes[k].content else { return };
let flags = text::flags(c);
let line = c.line_px();
- let (tw, th) = if !t.contains([' ', '\n']) {
+ let brk = text::break_mode(c);
+ let (tw, th) = if !t.contains([' ', '\n']) && brk == 0 {
(tc.width(t, c.font_size, flags).ceil(), line)
} else {
let max = if c.white_space == WhiteSpace::NoWrap { f32::INFINITY } else { cb.size.width + 0.5 };
- let lines = tc.wrap(t, c.font_size, flags, max);
+ let lines = tc.wrap(t, c.font_size, flags, max, brk);
let w = lines.iter().map(|s| tc.width(s, c.font_size, flags)).fold(0.0, f32::max);
(w.ceil(), line * lines.len().max(1) as f32)
};
@@ -2088,6 +2219,15 @@ impl Frame {
el_attr(&self.nodes, &self.els, i, name)
}
+ /// 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 {
+ Content::Text(t) => t.trim().is_empty(),
+ Content::Anon => kids(&self.nodes, k).next().is_none(),
+ _ => false,
+ })
+ }
+
/// The text a box draws: a text run's text, or a word's slice of it.
pub(crate) fn text(&self, i: usize) -> &str {
match &self.nodes[i].content {
diff --git a/bindings/rust/blenderui/src/paint.rs b/bindings/rust/blenderui/src/paint.rs
index e5c9354..4f31cc4 100644
--- a/bindings/rust/blenderui/src/paint.rs
+++ b/bindings/rust/blenderui/src/paint.rs
@@ -9,7 +9,7 @@ use taffy::prelude::*;
use crate::color::Rgba;
use crate::geometry::{rect, Bounds, Units};
use crate::layout::{BoxNode, Content, Frame, Replaced, StyleStore};
-use crate::style::{Computed, DisplayKind, TextAlign, WhiteSpace};
+use crate::style::{BorderStyle, BoxEdge, Computed, DecoStyle, DisplayKind, TextAlign, WhiteSpace};
use crate::text::{self, TextCache};
use blenderui_sys as sys;
@@ -426,7 +426,7 @@ fn paint_node(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize,
Content::Text(t) if n.taffy.is_some() || n.folded => {
let flags = text::flags(c);
let nowrap = matches!(c.white_space, WhiteSpace::NoWrap | WhiteSpace::Pre);
- if !c.ellipsis && !t.contains([' ', '\n']) {
+ if !c.ellipsis && !t.contains([' ', '\n']) && text::break_mode(c) == 0 {
// one word: one line (the common label case)
let lw = tc.width(t, c.font_size, flags);
let x = match c.text_align {
@@ -440,7 +440,7 @@ fn paint_node(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize,
let lines = if nowrap {
vec![t.clone()]
} else {
- tc.wrap(t, c.font_size, flags, b.size.width + 0.5)
+ tc.wrap(t, c.font_size, flags, b.size.width + 0.5, text::break_mode(c))
};
let lh = c.line_px();
for (k, line) in lines.iter().enumerate() {
@@ -456,8 +456,22 @@ fn paint_node(frame: &Frame, styles: &StyleStore, tc: &mut TextCache, i: usize,
}
}
Content::Element | Content::Replaced(_) if n.taffy.is_some() => {
- paint_box(n, c, p, vp, redundant_background(frame, styles, n));
- if let Some(m) = &n.marker {
+ let hidden_cell = c.empty_cells_hide && c.display == DisplayKind::TableCell
+ && !c.border_collapse && frame.is_empty(i);
+ if !hidden_cell {
+ paint_box(n, c, p, vp, redundant_background(frame, styles, n));
+ }
+ let marker_img = n.marker.as_ref().and(c.list_image.as_deref()).and_then(background_file);
+ if let Some(img) = marker_img {
+ // `list-style-image`: the image, at most a line tall, left of the box
+ let bw = border_widths(c, b.size.width);
+ let pad = lp(c.layout.padding.top, b.size.width);
+ let lh = c.line_px();
+ let (iw, ih) = (img.width as f32, img.height as f32);
+ let s = (lh / ih.max(1.0)).min(1.0);
+ let (w, h) = (iw * s, ih * s);
+ p.image(rect(b.origin.x - w - 6.0, b.origin.y + bw[0] + pad + (lh - h) / 2.0, w, h), &img);
+ } else if let Some(m) = n.marker.as_ref().filter(|m| !m.is_empty()) {
let bw = border_widths(c, b.size.width);
let pad = lp(c.layout.padding.top, b.size.width);
let flags = text::flags(c);
@@ -528,17 +542,49 @@ fn paint_text_line(p: &mut Painter, tc: &mut TextCache, c: &Computed, s: &str, x
}
if c.underline || c.line_through || c.overline {
let w = width.unwrap_or_else(|| tc.width(s.trim_end(), size_draw, flags));
- let thick = (size / 14.0).max(1.0);
+ let thick = c.decoration_thickness.unwrap_or(size / 14.0).max(1.0);
let dc = c.decoration_color.unwrap_or(c.color);
- let mut deco = |yy: f32| p.fill(rect(x, yy, w, thick), dc);
if c.underline {
- deco(top + size * 0.92);
+ // the offset is measured from the baseline (about 0.8em down)
+ let y = match c.underline_offset {
+ Some(o) => top + size * 0.8 + o,
+ None => top + size * 0.92,
+ };
+ decoration(p, c.decoration_style, x, y, w, thick, dc);
}
if c.line_through {
- deco(top + size * 0.48);
+ decoration(p, c.decoration_style, x, top + size * 0.48, w, thick, dc);
}
if c.overline {
- deco(top);
+ decoration(p, c.decoration_style, x, top, w, thick, dc);
+ }
+ }
+}
+
+/// One text decoration line of `text-decoration-style` from `x` to `x + w`.
+fn decoration(p: &mut Painter, style: DecoStyle, x: f32, y: f32, w: f32, t: f32, col: Rgba) {
+ match style {
+ DecoStyle::Solid => p.fill(rect(x, y, w, t), col),
+ DecoStyle::Double => {
+ p.fill(rect(x, y, w, t), col);
+ p.fill(rect(x, y + t * 2.0, w, t), col);
+ }
+ DecoStyle::Dotted | DecoStyle::Dashed => {
+ let (on, gap) = if style == DecoStyle::Dotted { (t, t) } else { (t * 3.0, t * 2.0) };
+ let mut cx = x;
+ while cx < x + w {
+ p.fill(rect(cx, y, on.min(x + w - cx), t), col);
+ cx += on + gap;
+ }
+ }
+ DecoStyle::Wavy => {
+ let (amp, period) = (t * 1.5, t * 6.0);
+ let steps = ((w / (period / 8.0)).ceil() as usize).clamp(2, 4096);
+ let pts: Vec<(f32, f32)> = (0..=steps).map(|k| {
+ let px = x + w * k as f32 / steps as f32;
+ (px, y + amp * (std::f32::consts::TAU * (px - x) / period).sin())
+ }).collect();
+ p.line(&pts, col, t);
}
}
}
@@ -560,13 +606,20 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba
p.quad(sb, r + grow, s.color.alpha(a), Rgba::TRANSPARENT, 0.0);
}
}
+ // `background-clip`: the painting area; its radius shrinks with it
+ let bw = border_widths(c, b.size.width);
+ let clip_box = edge_box(c, b, c.bg_clip, &bw);
+ let clip_r = (r - (clip_box.origin.x - b.origin.x)).max(0.0);
match &c.gradient {
- Some(g) => p.with_clip(b, |p| paint_gradient(p, g, b)),
- None if skip_background => {}
- None => p.quad(b, r, c.background, Rgba::TRANSPARENT, 0.0),
+ Some(g) => p.with_clip(clip_box, |p| paint_gradient(p, g, clip_box)),
+ None if skip_background && c.bg_clip == BoxEdge::Border => {}
+ None => p.quad(clip_box, clip_r, c.background, Rgba::TRANSPARENT, 0.0),
}
if let Some(st) = c.images.as_deref().filter(|st| st.bg_url.is_some()) {
- paint_background_image(p, c, st, b);
+ // `background-origin` positions the image, `-attachment: fixed` against the viewport
+ let area = if st.bg_fixed { rect(0.0, 0.0, vp.0, vp.1) } else { edge_box(c, b, c.bg_origin, &bw) };
+ let clip_to = if st.bg_fixed { clip_box } else { clip_box.intersect(&b) };
+ paint_background_image(p, st, area, clip_to);
}
for s in c.shadows.iter().filter(|s| s.inset) {
let w = s.blur.max(1.0) + s.spread;
@@ -575,12 +628,16 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba
Rgba::TRANSPARENT, s.color, w);
});
}
- let bw = border_widths(c, b.size.width);
let visible: Vec<usize> = (0..4).filter(|&k| bw[k] > 0.0 && c.border_drawn[k]
&& !c.border_color[k].is_transparent()).collect();
let uniform = visible.len() == 4 && bw.iter().all(|w| *w == bw[0])
&& c.border_color.iter().all(|x| *x == c.border_color[0]);
- if uniform {
+ let styled = visible.iter().any(|&k| c.border_style[k] != BorderStyle::Solid);
+ 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);
+ } else if uniform {
let h = bw[0] / 2.0;
p.quad(rect(b.origin.x + h, b.origin.y + h, b.size.width - bw[0], b.size.height - bw[0]),
(r - h).max(0.0), Rgba::TRANSPARENT, c.border_color[0], bw[0]);
@@ -597,13 +654,100 @@ fn paint_box(n: &BoxNode, c: &Computed, p: &mut Painter, vp: (f32, f32), skip_ba
}
}
let (ow, oc, off) = c.outline;
- if ow > 0.0 && !oc.is_transparent() {
+ if ow > 0.0 && !oc.is_transparent() && c.outline_style != BorderStyle::Solid {
+ let g = off + ow;
+ let ob = rect(b.origin.x - g, b.origin.y - g, b.size.width + 2.0 * g, b.size.height + 2.0 * g);
+ paint_edges(p, ob, [ow; 4], [oc; 4], [c.outline_style; 4]);
+ } else if ow > 0.0 && !oc.is_transparent() {
let g = off + ow / 2.0;
p.quad(rect(b.origin.x - g, b.origin.y - g, b.size.width + 2.0 * g, b.size.height + 2.0 * g),
r + g, Rgba::TRANSPARENT, oc, ow);
}
}
+/// 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 {
+ BoxEdge::Border => b,
+ 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)),
+ BoxEdge::Content => content_box(c, b),
+ }
+}
+
+/// A colour darkened (`f` < 1) or lightened toward white (`f` > 1), for 3D borders.
+fn shade(c: Rgba, f: f32) -> Rgba {
+ if f <= 1.0 {
+ Rgba { r: c.r * f, g: c.g * f, b: c.b * f, a: c.a }
+ } else {
+ mix(c, Rgba { r: 1.0, g: 1.0, b: 1.0, a: c.a }, f - 1.0)
+ }
+}
+
+/// Borders (or an outline) with non-solid styles, side by side inside
+/// `b`: dashes and dots run along each side, `double` is two lines, and
+/// groove / ridge / inset / outset shade the sides. Corners are square.
+fn paint_edges(p: &mut Painter, b: Bounds<f32>, w: [f32; 4], col: [Rgba; 4], style: [BorderStyle; 4]) {
+ let (x, y, bw, bh) = (b.origin.x, b.origin.y, b.size.width, b.size.height);
+ // the band of side k, inset by `from` and `to` (fractions of its width)
+ let band = |k: usize, from: f32, to: f32| -> Bounds<f32> {
+ let (a, t) = (w[k] * from, w[k] * (to - from));
+ match k {
+ 0 => rect(x, y + a, bw, t),
+ 1 => rect(x + bw - w[1] + a, y, t, bh),
+ 2 => rect(x, y + bh - w[2] + a, bw, t),
+ _ => rect(x + a, y, t, bh),
+ }
+ };
+ for k in 0..4 {
+ if w[k] <= 0.0 || col[k].is_transparent() {
+ continue;
+ }
+ let c = col[k];
+ // top and left are the "light source" sides for inset / outset
+ let lit = k == 0 || k == 3;
+ match style[k] {
+ BorderStyle::Solid => p.fill(band(k, 0.0, 1.0), c),
+ BorderStyle::Double if w[k] >= 3.0 => {
+ p.fill(band(k, 0.0, 1.0 / 3.0), c);
+ p.fill(band(k, 2.0 / 3.0, 1.0), c);
+ }
+ BorderStyle::Double => p.fill(band(k, 0.0, 1.0), c),
+ BorderStyle::Inset => p.fill(band(k, 0.0, 1.0), if lit { shade(c, 0.5) } else { c }),
+ BorderStyle::Outset => p.fill(band(k, 0.0, 1.0), if lit { c } else { shade(c, 0.5) }),
+ BorderStyle::Groove | BorderStyle::Ridge => {
+ let (dark, light) = (shade(c, 0.5), c);
+ let outer_dark = (style[k] == BorderStyle::Groove) == lit;
+ p.fill(band(k, 0.0, 0.5), if outer_dark { dark } else { light });
+ p.fill(band(k, 0.5, 1.0), if outer_dark { light } else { dark });
+ }
+ BorderStyle::Dashed | BorderStyle::Dotted => {
+ let horizontal = k == 0 || k == 2;
+ let full = band(k, 0.0, 1.0);
+ let len = if horizontal { full.size.width } else { full.size.height };
+ let t = w[k];
+ let (on, gap) = if style[k] == BorderStyle::Dotted { (t, t) } else { (t * 3.0, t * 3.0) };
+ // spread the segments so both ends start and end with one
+ let n = ((len + gap) / (on + gap)).floor().max(1.0);
+ let gap = if n > 1.0 { (len - n * on) / (n - 1.0) } else { 0.0 };
+ for j in 0..n as usize {
+ let o = j as f32 * (on + gap);
+ let seg = if horizontal {
+ rect(full.origin.x + o, full.origin.y, on.min(len - o), t)
+ } else {
+ rect(full.origin.x, full.origin.y + o, t, on.min(len - o))
+ };
+ if style[k] == BorderStyle::Dotted && t >= 3.0 {
+ p.oval(seg, c, Rgba::TRANSPARENT, 0.0);
+ } else {
+ p.fill(seg, c);
+ }
+ }
+ }
+ }
+ }
+}
+
fn mix(a: Rgba, b: Rgba, t: f32) -> Rgba {
Rgba { r: a.r + (b.r - a.r) * t, g: a.g + (b.g - a.g) * t, b: a.b + (b.b - a.b) * t,
a: a.a + (b.a - a.a) * t }
@@ -702,12 +846,12 @@ fn background_file(url: &str) -> Option<Arc<Image>> {
img
}
-/// A background image over the padding box: sized, positioned and tiled.
-fn paint_background_image(p: &mut Painter, c: &Computed, st: &crate::style::ImageStyle, b: Bounds<f32>) {
+/// A background image in its positioning `area` (`background-origin`, or the
+/// viewport when fixed): sized, positioned and tiled, clipped to `clip_to`.
+fn paint_background_image(p: &mut Painter, st: &crate::style::ImageStyle, area: Bounds<f32>,
+ clip_to: Bounds<f32>) {
let Some(img) = st.bg_url.as_deref().and_then(background_file) else { return };
- let bw = border_widths(c, b.size.width);
- let (ax, ay) = (b.origin.x + bw[3], b.origin.y + bw[0]);
- let (aw, ah) = (b.size.width - bw[1] - bw[3], b.size.height - bw[0] - bw[2]);
+ let (ax, ay, aw, ah) = (area.origin.x, area.origin.y, area.size.width, area.size.height);
let (tw, th) = st.tile((aw, ah), (img.width as f32, img.height as f32));
if tw < 0.5 || th < 0.5 || aw <= 0.0 || ah <= 0.0 {
return;
@@ -717,12 +861,16 @@ fn paint_background_image(p: &mut Painter, c: &Computed, st: &crate::style::Imag
// first tile at or before the area's start, when repeating
let sx = if st.bg_repeat.0 { x0 - ((x0 - ax) / tw).ceil() * tw } else { x0 };
let sy = if st.bg_repeat.1 { y0 - ((y0 - ay) / th).ceil() * th } else { y0 };
- let nx = if st.bg_repeat.0 { ((ax + aw - sx) / tw).ceil() as usize } else { 1 };
- let ny = if st.bg_repeat.1 { ((ay + ah - sy) / th).ceil() as usize } else { 1 };
+ // repeated tiles cover the painting area, which may reach past the positioning area
+ let (ex, ey) = (clip_to.origin.x + clip_to.size.width, clip_to.origin.y + clip_to.size.height);
+ let sx = if st.bg_repeat.0 && clip_to.origin.x < sx { sx - ((sx - clip_to.origin.x) / tw).ceil() * tw } else { sx };
+ let sy = if st.bg_repeat.1 && clip_to.origin.y < sy { sy - ((sy - clip_to.origin.y) / th).ceil() * th } else { sy };
+ let nx = if st.bg_repeat.0 { ((ex.max(ax + aw) - sx) / tw).ceil() as usize } else { 1 };
+ let ny = if st.bg_repeat.1 { ((ey.max(ay + ah) - sy) / th).ceil() as usize } else { 1 };
if nx.saturating_mul(ny) > 4096 {
return; // tiny tiles over a huge box: not worth thousands of quads
}
- p.with_clip(rect(ax, ay, aw, ah), |p| {
+ p.with_clip(clip_to, |p| {
for j in 0..ny {
for i in 0..nx {
p.image(rect(sx + i as f32 * tw, sy + j as f32 * th, tw, th), &img);
diff --git a/bindings/rust/blenderui/src/style.rs b/bindings/rust/blenderui/src/style.rs
index f47dea0..f227ff2 100644
--- a/bindings/rust/blenderui/src/style.rs
+++ b/bindings/rust/blenderui/src/style.rs
@@ -96,6 +96,75 @@ pub enum VAlign {
Super,
}
+/// `border-style` / `outline-style` (`none` and `hidden` clear the width instead).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub enum BorderStyle {
+ #[default]
+ Solid,
+ Dashed,
+ Dotted,
+ Double,
+ Groove,
+ Ridge,
+ Inset,
+ Outset,
+}
+
+impl BorderStyle {
+ fn parse(s: &str) -> Option<BorderStyle> {
+ Some(match s {
+ "solid" | "none" | "hidden" | "auto" => BorderStyle::Solid,
+ "dashed" => BorderStyle::Dashed,
+ "dotted" => BorderStyle::Dotted,
+ "double" => BorderStyle::Double,
+ "groove" => BorderStyle::Groove,
+ "ridge" => BorderStyle::Ridge,
+ "inset" => BorderStyle::Inset,
+ "outset" => BorderStyle::Outset,
+ _ => return None,
+ })
+ }
+}
+
+/// `text-decoration-style`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub enum DecoStyle {
+ #[default]
+ Solid,
+ Double,
+ Dotted,
+ Dashed,
+ Wavy,
+}
+
+/// A box edge for `background-clip` / `background-origin`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub enum BoxEdge {
+ #[default]
+ Border,
+ Padding,
+ Content,
+}
+
+impl BoxEdge {
+ fn parse(s: &str) -> Option<BoxEdge> {
+ Some(match s {
+ "border-box" => BoxEdge::Border,
+ "padding-box" => BoxEdge::Padding,
+ "content-box" => BoxEdge::Content,
+ _ => return None,
+ })
+ }
+}
+
+/// `counter-reset` / `counter-set` / `counter-increment` of one element.
+#[derive(Clone, Debug, PartialEq, Default)]
+pub struct CounterOps {
+ pub reset: Vec<(Box<str>, i32)>,
+ pub set: Vec<(Box<str>, i32)>,
+ pub increment: Vec<(Box<str>, i32)>,
+}
+
#[derive(Clone, Debug, PartialEq)]
pub struct Gradient {
pub radial: bool,
@@ -163,6 +232,8 @@ pub struct ImageStyle {
pub bg_position: [Pos; 2],
/// repeat along x, y
pub bg_repeat: (bool, bool),
+ /// `background-attachment: fixed`: positioned against the viewport.
+ pub bg_fixed: bool,
}
impl Default for ImageStyle {
@@ -174,6 +245,7 @@ impl Default for ImageStyle {
bg_size: BgSize::Auto,
bg_position: [Pos::START; 2],
bg_repeat: (true, true),
+ bg_fixed: false,
}
}
}
@@ -237,9 +309,19 @@ pub struct Computed {
pub container_name: Option<Box<str>>,
pub border_color: [Rgba; 4],
pub border_drawn: [bool; 4],
+ pub border_style: [BorderStyle; 4],
pub radius: [Length; 4],
pub shadows: Vec<Shadow>,
pub outline: (f32, Rgba, f32),
+ pub outline_style: BorderStyle,
+ /// `background-clip` and `background-origin`.
+ pub bg_clip: BoxEdge,
+ pub bg_origin: BoxEdge,
+ /// `clip: rect(top, right, bottom, left)` (absolutely positioned boxes;
+ /// `auto` edges are None).
+ pub clip_rect: Option<[Option<Length>; 4]>,
+ /// `counter-*` operations (None: none).
+ pub counters: Option<Box<CounterOps>>,
pub opacity: f32,
pub z_index: Option<i32>,
pub translate: (Length, Length),
@@ -279,6 +361,21 @@ pub struct Computed {
pub quotes: Option<(String, String)>,
pub text_shadow: Option<Shadow>,
pub decoration_color: Option<Rgba>,
+ pub decoration_style: DecoStyle,
+ /// `text-decoration-thickness` in px (None: auto / from-font).
+ pub decoration_thickness: Option<f32>,
+ /// `text-underline-offset` in px (None: auto).
+ pub underline_offset: Option<f32>,
+ /// `empty-cells: hide` (inherited).
+ pub empty_cells_hide: bool,
+ /// `list-style-image: url()` (inherited).
+ pub list_image: Option<std::sync::Arc<str>>,
+ /// `word-break: break-all` (inherited).
+ pub break_all: bool,
+ /// `overflow-wrap: anywhere | break-word` (inherited).
+ pub wrap_anywhere: bool,
+ /// `tab-size` in spaces (inherited).
+ pub tab_size: u8,
/// Custom properties in scope (inherited), in the style store's var arena.
pub vars: u32,
/// `content` (for `::before` / `::after`): None = `normal` / `none`.
@@ -293,6 +390,10 @@ pub enum ContentPart {
Attr(String),
OpenQuote,
CloseQuote,
+ /// `counter(name, style)`.
+ Counter(Box<str>, ListStyle),
+ /// `counters(name, separator, style)`.
+ Counters(Box<str>, Box<str>, ListStyle),
}
impl Default for Computed {
@@ -308,9 +409,15 @@ impl Default for Computed {
container_name: None,
border_color: [Rgba::TRANSPARENT; 4],
border_drawn: [true; 4],
+ border_style: [BorderStyle::Solid; 4],
radius: [Length::Px(0.0); 4],
shadows: Vec::new(),
outline: (0.0, Rgba::TRANSPARENT, 0.0),
+ outline_style: BorderStyle::Solid,
+ bg_clip: BoxEdge::Border,
+ bg_origin: BoxEdge::Padding,
+ clip_rect: None,
+ counters: None,
opacity: 1.0,
z_index: None,
translate: (Length::Px(0.0), Length::Px(0.0)),
@@ -318,7 +425,7 @@ impl Default for Computed {
visible: true,
cursor: None,
pointer_events: true,
- color: crate::color::rgb(0xe6e6e6),
+ color: crate::color::rgb(0x000000), // initial: CanvasText
accent: None,
font_size: 13.0,
weight: 400,
@@ -346,6 +453,14 @@ impl Default for Computed {
quotes: None,
text_shadow: None,
decoration_color: None,
+ decoration_style: DecoStyle::Solid,
+ decoration_thickness: None,
+ underline_offset: None,
+ empty_cells_hide: false,
+ list_image: None,
+ break_all: false,
+ wrap_anywhere: false,
+ tab_size: 8,
vars: 0,
content: None,
}
@@ -380,6 +495,14 @@ impl Computed {
line_through: parent.line_through,
overline: parent.overline,
decoration_color: parent.decoration_color,
+ decoration_style: parent.decoration_style,
+ decoration_thickness: parent.decoration_thickness,
+ underline_offset: parent.underline_offset,
+ empty_cells_hide: parent.empty_cells_hide,
+ list_image: parent.list_image.clone(),
+ break_all: parent.break_all,
+ wrap_anywhere: parent.wrap_anywhere,
+ tab_size: parent.tab_size,
border_spacing: parent.border_spacing,
border_collapse: parent.border_collapse,
caption_bottom: parent.caption_bottom,
@@ -484,23 +607,21 @@ 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] = &[
- "background-attachment", "background-clip", "background-origin", "clip", "clip-path",
- "counter-increment", "counter-reset", "counter-set", "unicode-bidi",
- "writing-mode", "empty-cells", "list-style-image", "table-layout",
+ "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", "overflow-wrap",
- "word-wrap", "word-break", "tab-size", "font-feature-settings", "font-kerning",
+ "scroll-snap-align", "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",
- "box-decoration-break", "image-rendering", "shape-outside", "text-underline-offset",
- "text-decoration-thickness", "text-decoration-style", "text-justify", "line-break",
+ "box-decoration-break", "image-rendering", "shape-outside",
+ "text-justify", "line-break",
"all",
// scrolling
"scroll-margin", "scroll-margin-top", "scroll-margin-right", "scroll-margin-bottom",
@@ -583,7 +704,8 @@ const INHERITED: &[&str] = &[
"color", "cursor", "font", "font-family", "font-size", "font-style", "font-variant",
"font-weight", "letter-spacing", "line-height", "list-style", "list-style-type",
"text-align", "text-indent", "text-transform", "visibility", "white-space", "word-spacing",
- "accent-color", "caret-color", "pointer-events",
+ "accent-color", "caret-color", "pointer-events", "list-style-image", "word-break",
+ "overflow-wrap", "word-wrap", "tab-size", "text-underline-offset",
];
/// FNV-1a: property names are short, so this beats the default SipHash.
@@ -846,6 +968,11 @@ fn border_sides(ctx: &mut Ctx, v: &[Tok], sides: &[usize]) -> bool {
set_border_width(ctx, s, width);
ctx.c.border_color[s] = col.unwrap_or(ctx.c.color);
ctx.c.border_drawn[s] = !none;
+ if let Some(bs) = style.as_deref().and_then(BorderStyle::parse) {
+ ctx.c.border_style[s] = bs;
+ } else if style.is_none() {
+ ctx.c.border_style[s] = BorderStyle::Solid;
+ }
}
true
}
@@ -1285,6 +1412,37 @@ fn roman(mut n: usize, upper: bool) -> String {
}
impl ListStyle {
+ /// A counter value in this style, without the marker's trailing dot
+ /// (`counter()` in `content`).
+ pub fn format(self, n: i32) -> String {
+ let alpha = |upper: bool| {
+ if n < 1 {
+ return n.to_string();
+ }
+ // bijective base 26: a..z, aa, ab ...
+ let (mut k, mut out) = (n as u32, Vec::new());
+ while k > 0 {
+ k -= 1;
+ out.push(((if upper { b'A' } else { b'a' }) + (k % 26) as u8) as char);
+ k /= 26;
+ }
+ out.iter().rev().collect()
+ };
+ match self {
+ ListStyle::None => String::new(),
+ ListStyle::Disc => "\u{2022}".into(),
+ ListStyle::Circle => "\u{25e6}".into(),
+ ListStyle::Square => "\u{25aa}".into(),
+ ListStyle::Decimal => n.to_string(),
+ ListStyle::LowerAlpha => alpha(false),
+ ListStyle::UpperAlpha => alpha(true),
+ ListStyle::LowerRoman | ListStyle::UpperRoman if (1..4000).contains(&n) => {
+ roman(n as usize, self == ListStyle::UpperRoman)
+ }
+ _ => n.to_string(),
+ }
+ }
+
/// The marker text for the `index`-th (1-based) item.
pub fn marker(self, index: usize) -> Option<String> {
Some(match self {
@@ -1316,6 +1474,37 @@ fn list_style(s: &str) -> Option<ListStyle> {
})
}
+fn deco_style(s: &str) -> Option<DecoStyle> {
+ Some(match s {
+ "solid" => DecoStyle::Solid,
+ "double" => DecoStyle::Double,
+ "dotted" => DecoStyle::Dotted,
+ "dashed" => DecoStyle::Dashed,
+ "wavy" => DecoStyle::Wavy,
+ _ => return None,
+ })
+}
+
+/// `none | [<name> <integer>?]+` for the `counter-*` properties.
+fn counter_list(v: &[Tok], default: i32) -> Option<Vec<(Box<str>, i32)>> {
+ if kw(v) == Some("none") {
+ return Some(Vec::new());
+ }
+ let mut out: Vec<(Box<str>, i32)> = Vec::new();
+ for t in v {
+ match t {
+ Tok::Ident(s) => out.push((s.as_ref().into(), default)),
+ Tok::Num(n) => out.last_mut()?.1 = *n as i32,
+ Tok::Func(fx) if fx.name == "reversed" => {
+ let name = fx.args.first().and_then(|a| a.first()).and_then(Tok::ident)?;
+ out.push((name.into(), default));
+ }
+ _ => return None,
+ }
+ }
+ (!out.is_empty()).then_some(out)
+}
+
fn overflow(s: &str) -> Option<Overflow> {
Some(match s {
"visible" => Overflow::Visible,
@@ -1853,6 +2042,18 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
delegate(c, "background-repeat", &reps);
}
let mut ok = !pos.is_empty() || !reps.is_empty();
+ // <box> keywords: one sets origin and clip, two set origin then clip
+ let boxes: Vec<BoxEdge> = layer.iter().filter_map(|t| t.ident().and_then(BoxEdge::parse)).collect();
+ match boxes.as_slice() {
+ [b] => (c.c.bg_origin, c.c.bg_clip) = (*b, *b),
+ [o, k, ..] => (c.c.bg_origin, c.c.bg_clip) = (*o, *k),
+ [] => {}
+ }
+ ok |= !boxes.is_empty();
+ if layer.iter().any(|t| t.ident() == Some("fixed")) {
+ c.c.images_mut().bg_fixed = true;
+ ok = true;
+ }
for t in v {
if let Tok::Func(fx) = t {
if fx.name == "url" {
@@ -1940,7 +2141,8 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
for t in v {
if t.ident().is_some_and(|s| s == "none") {
w = 0.0;
- } else if t.ident().is_some_and(|s| BORDER_STYLES.contains(&s) || s == "auto") {
+ } else if let Some(s) = t.ident().filter(|s| BORDER_STYLES.contains(s) || *s == "auto") {
+ c.c.outline_style = BorderStyle::parse(s).unwrap_or_default();
} else if let Some(cc) = color(t, c.c.color).filter(|_| !matches!(t, Tok::Dim(..))) {
col = cc;
} else if let Some(px) = border_width_tok(c, t) {
@@ -1955,11 +2157,13 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
}),
h("outline-width", |c, v| v.first().and_then(|t| border_width_tok(c, t)).map(|w| c.c.outline.0 = w).is_some()),
h("outline-color", |c, v| v.first().and_then(|t| color(t, c.c.color)).map(|col| c.c.outline.1 = col).is_some()),
- h("outline-style", |c, v| {
- if kw(v) == Some("none") {
+ h("outline-style", |c, v| match kw(v) {
+ Some("none") => {
c.c.outline.0 = 0.0;
+ true
}
- true
+ Some(s) => BorderStyle::parse(s).map(|b| c.c.outline_style = b).is_some(),
+ None => false,
}),
h("outline-offset", |c, v| v.first().and_then(length).map(|l| c.c.outline.2 = px(c, l)).is_some()),
// -- effects ------------------------------------------------------------------------
@@ -2079,13 +2283,40 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
true
}),
h("text-decoration", |c, v| {
+ // a shorthand: what it doesn't name goes back to the initial value
+ c.c.decoration_style = DecoStyle::Solid;
+ c.c.decoration_thickness = None;
+ c.c.decoration_color = None;
let words: Vec<&str> = v.iter().filter_map(Tok::ident).collect();
c.c.underline = words.contains(&"underline");
c.c.line_through = words.contains(&"line-through");
c.c.overline = words.contains(&"overline");
+ for t in v {
+ let one = std::slice::from_ref(t);
+ match t.ident() {
+ Some("underline" | "line-through" | "overline" | "none" | "blink" | "spelling-error"
+ | "grammar-error") => {}
+ Some(s) if deco_style(s).is_some() => c.c.decoration_style = deco_style(s).unwrap(),
+ _ if matches!(t, Tok::Dim(..) | Tok::Pct(_) | Tok::Calc(_))
+ || t.ident() == Some("from-font") => {
+ delegate(c, "text-decoration-thickness", one);
+ }
+ _ => {
+ if !delegate(c, "text-decoration-color", one) {
+ return false;
+ }
+ }
+ }
+ }
true
}),
- h("text-decoration-line", |c, v| delegate(c, "text-decoration", v)),
+ h("text-decoration-line", |c, v| {
+ let words: Vec<&str> = v.iter().filter_map(Tok::ident).collect();
+ c.c.underline = words.contains(&"underline");
+ c.c.line_through = words.contains(&"line-through");
+ c.c.overline = words.contains(&"overline");
+ !words.is_empty()
+ }),
h("white-space", |c, v| {
c.c.white_space = match kw(v) {
Some("normal") => WhiteSpace::Normal,
@@ -2189,9 +2420,26 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
};
ContentPart::Attr(n.to_string())
}
- // counters and images: no counter state / inline images here
- Tok::Func(fx) if matches!(fx.name.as_ref(), "counter" | "counters" | "url" | "image"
- | "linear-gradient" | "image-set") => continue,
+ Tok::Func(fx) if fx.name == "counter" || fx.name == "counters" => {
+ let args: Vec<&[Tok]> = fx.args.iter().map(|a| a.as_slice()).collect();
+ let Some(name) = args.first().and_then(|a| a.first()).and_then(Tok::ident) else {
+ return false;
+ };
+ let style_at = |k: usize| args.get(k).and_then(|a| a.first()).and_then(Tok::ident)
+ .and_then(list_style).unwrap_or(ListStyle::Decimal);
+ if fx.name == "counter" {
+ ContentPart::Counter(name.into(), style_at(1))
+ } else {
+ let sep = match args.get(1).and_then(|a| a.first()) {
+ Some(Tok::Str(s)) => s.as_ref().into(),
+ _ => ".".into(),
+ };
+ ContentPart::Counters(name.into(), sep, style_at(2))
+ }
+ }
+ // inline images in generated content: not drawn
+ Tok::Func(fx) if matches!(fx.name.as_ref(), "url" | "image" | "linear-gradient"
+ | "image-set") => continue,
_ => return false,
});
}
@@ -2256,8 +2504,161 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
}
_ => false,
}),
- h("list-style", |c, v| v.iter().filter_map(Tok::ident).find_map(list_style)
- .map(|l| c.c.list_style = l).is_some()),
+ h("list-style", |c, v| {
+ let mut ok = false;
+ for t in v {
+ match t {
+ Tok::Func(fx) if fx.name == "url" => ok |= delegate(c, "list-style-image", std::slice::from_ref(t)),
+ Tok::Ident(s) if s.as_ref() == "inside" || s.as_ref() == "outside" => {
+ ok |= delegate(c, "list-style-position", std::slice::from_ref(t))
+ }
+ Tok::Ident(s) => {
+ if let Some(l) = list_style(s) {
+ c.c.list_style = l;
+ ok = true;
+ }
+ }
+ _ => {}
+ }
+ }
+ ok
+ }),
+ h("background-clip", |c, v| {
+ let first = v.split(|t| matches!(t, Tok::Comma)).next().unwrap_or(&[]);
+ match kw(first) {
+ // `text`: no glyph masks here; keep the colour behind the text box
+ Some("text") => true,
+ Some(s) => BoxEdge::parse(s).map(|e| c.c.bg_clip = e).is_some(),
+ None => false,
+ }
+ }),
+ h("background-origin", |c, v| {
+ let first = v.split(|t| matches!(t, Tok::Comma)).next().unwrap_or(&[]);
+ kw(first).and_then(BoxEdge::parse).map(|e| c.c.bg_origin = e).is_some()
+ }),
+ h("background-attachment", |c, v| {
+ let first = v.split(|t| matches!(t, Tok::Comma)).next().unwrap_or(&[]);
+ match kw(first) {
+ Some(k @ ("scroll" | "fixed" | "local")) => {
+ let fixed = k == "fixed";
+ if fixed || c.c.images.is_some() {
+ c.c.images_mut().bg_fixed = fixed;
+ }
+ true
+ }
+ _ => false,
+ }
+ }),
+ h("clip", |c, v| match v.first() {
+ Some(Tok::Ident(s)) if s.as_ref() == "auto" => {
+ c.c.clip_rect = None;
+ true
+ }
+ Some(Tok::Func(fx)) if fx.name == "rect" => {
+ // rect(top, right, bottom, left), commas optional
+ let toks: Vec<&Tok> = fx.args.iter().flatten().filter(|t| !matches!(t, Tok::Comma)).collect();
+ if toks.len() != 4 {
+ return false;
+ }
+ let mut r = [None; 4];
+ for (k, t) in toks.iter().enumerate() {
+ if t.ident() == Some("auto") {
+ continue;
+ }
+ let Some(l) = length(t) else { return false };
+ r[k] = Some(l);
+ }
+ c.c.clip_rect = Some(r);
+ true
+ }
+ _ => false,
+ }),
+ h("text-decoration-style", |c, v| kw(v).and_then(deco_style).map(|s| c.c.decoration_style = s).is_some()),
+ h("text-decoration-thickness", |c, v| match (kw(v), v.first()) {
+ (Some("auto" | "from-font"), _) => {
+ c.c.decoration_thickness = None;
+ true
+ }
+ // a percentage is of 1em
+ (_, Some(Tok::Pct(p))) => {
+ c.c.decoration_thickness = Some(c.c.font_size * p / 100.0);
+ true
+ }
+ (_, Some(t)) => length(t).map(|l| c.c.decoration_thickness = Some(px(c, l))).is_some(),
+ _ => false,
+ }),
+ h("text-underline-offset", |c, v| match (kw(v), v.first()) {
+ (Some("auto"), _) => {
+ c.c.underline_offset = None;
+ true
+ }
+ (_, Some(Tok::Pct(p))) => {
+ c.c.underline_offset = Some(c.c.font_size * p / 100.0);
+ true
+ }
+ (_, Some(t)) => length(t).map(|l| c.c.underline_offset = Some(px(c, l))).is_some(),
+ _ => false,
+ }),
+ // -- text breaking --------------------------------------------------------------------
+ h("word-break", |c, v| {
+ c.c.break_all = match kw(v) {
+ Some("break-all") => true,
+ Some("normal" | "keep-all" | "auto-phrase") => false,
+ // deprecated: overflow-wrap: anywhere plus word-break: normal
+ Some("break-word") => {
+ c.c.wrap_anywhere = true;
+ false
+ }
+ _ => return false,
+ };
+ true
+ }),
+ h("overflow-wrap", |c, v| {
+ c.c.wrap_anywhere = match kw(v) {
+ Some("anywhere" | "break-word") => true,
+ Some("normal") => false,
+ _ => return false,
+ };
+ true
+ }),
+ h("word-wrap", |c, v| delegate(c, "overflow-wrap", v)),
+ h("tab-size", |c, v| match v.first() {
+ Some(Tok::Num(n)) if *n >= 0.0 => {
+ c.c.tab_size = n.round().min(64.0) as u8;
+ true
+ }
+ // a length: as many spaces as fit
+ Some(t) => length(t).map(|l| {
+ let sp = (c.c.font_size * 0.3).max(1.0);
+ c.c.tab_size = (px(c, l) / sp).round().clamp(0.0, 64.0) as u8;
+ }).is_some(),
+ None => false,
+ }),
+ h("list-style-image", |c, v| match v.first() {
+ Some(Tok::Ident(s)) if s.as_ref() == "none" => {
+ c.c.list_image = None;
+ true
+ }
+ Some(Tok::Func(fx)) if fx.name == "url" => match fx.args.first().and_then(|a| a.first()) {
+ Some(Tok::Str(u)) => {
+ c.c.list_image = Some(u.as_ref().into());
+ true
+ }
+ _ => false,
+ },
+ _ => false,
+ }),
+ h("empty-cells", |c, v| match kw(v) {
+ Some(k @ ("show" | "hide")) => {
+ c.c.empty_cells_hide = k == "hide";
+ true
+ }
+ _ => false,
+ }),
+ // -- counters ---------------------------------------------------------------------------
+ h("counter-reset", |c, v| counter_list(v, 0).map(|l| c.c.counters.get_or_insert_with(Default::default).reset = l).is_some()),
+ h("counter-set", |c, v| counter_list(v, 0).map(|l| c.c.counters.get_or_insert_with(Default::default).set = l).is_some()),
+ h("counter-increment", |c, v| counter_list(v, 1).map(|l| c.c.counters.get_or_insert_with(Default::default).increment = l).is_some()),
// -- interaction --------------------------------------------------------------------
h("cursor", |c, v| {
let name = v.iter().filter_map(Tok::ident).next_back();
@@ -2282,6 +2683,7 @@ pub(crate) const HANDLERS: &[(&str, Handler)] = &{
]
};
+
/// A `<position>` (`center`, `left 10px top`, `25% 75%`, `right 8px bottom 4px` ...)
/// as x and y.
fn position(c: &Ctx, v: &[Tok]) -> Option<[Pos; 2]> {
@@ -2384,6 +2786,7 @@ fn border_style(c: &mut Ctx, side: usize, t: &Tok) -> bool {
if none {
set_border_width(c, side, 0.0);
}
+ c.c.border_style[side] = BorderStyle::parse(s).unwrap_or_default();
true
}
_ => false,
diff --git a/bindings/rust/blenderui/src/text.rs b/bindings/rust/blenderui/src/text.rs
index 2a3ff62..64e70f6 100644
--- a/bindings/rust/blenderui/src/text.rs
+++ b/bindings/rust/blenderui/src/text.rs
@@ -11,6 +11,15 @@ pub(crate) fn flags(c: &Computed) -> i32 {
| ((c.font_id as i32) << FAMILY_SHIFT)
}
+/// Where lines may break inside words: `overflow-wrap: anywhere` /
+/// `break-word` ([`BREAK_ANYWHERE`]) or `word-break: break-all` ([`BREAK_ALL`]).
+pub(crate) fn break_mode(c: &Computed) -> u8 {
+ if c.break_all { BREAK_ALL } else if c.wrap_anywhere { BREAK_ANYWHERE } else { 0 }
+}
+
+pub(crate) const BREAK_ANYWHERE: u8 = 1;
+pub(crate) const BREAK_ALL: u8 = 2;
+
/// Font flags live in the low byte; the family id above it.
pub(crate) const FAMILY_SHIFT: i32 = 8;
@@ -109,17 +118,51 @@ impl TextCache {
w
}
- /// Greedy word wrap of `s` into lines no wider than `max` (explicit newlines kept).
- pub(crate) fn wrap(&mut self, s: &str, size: f32, flags: i32, max: f32) -> Vec<String> {
+ /// Greedy word wrap of `s` into lines no wider than `max` (explicit
+ /// newlines kept). `brk` ([`break_mode`]) allows breaks inside words:
+ /// anywhere only for a word too wide for a line of its own, break-all
+ /// between any two characters.
+ pub(crate) fn wrap(&mut self, s: &str, size: f32, flags: i32, max: f32, brk: u8) -> Vec<String> {
let mut out = Vec::new();
for para in s.split('\n') {
let mut line = String::new();
for word in para.split(' ').filter(|w| !w.is_empty()) {
let candidate = if line.is_empty() { word.to_owned() } else { format!("{line} {word}") };
- if !line.is_empty() && self.width(&candidate, size, flags) > max {
- out.push(std::mem::replace(&mut line, word.to_owned()));
- } else {
+ if self.width(&candidate, size, flags) <= max || (line.is_empty() && brk == 0) {
line = candidate;
+ continue;
+ }
+ if brk == BREAK_ALL {
+ // fill the current line with as much of the word as fits
+ let mut cur = if line.is_empty() { String::new() } else { format!("{line} ") };
+ for ch in word.chars() {
+ let mut t = cur.clone();
+ t.push(ch);
+ if self.width(&t, size, flags) > max && !cur.trim().is_empty() {
+ out.push(cur.trim_end().to_owned());
+ cur = ch.to_string();
+ } else {
+ cur = t;
+ }
+ }
+ line = cur;
+ continue;
+ }
+ if !line.is_empty() {
+ out.push(std::mem::take(&mut line));
+ }
+ if brk == BREAK_ANYWHERE && self.width(word, size, flags) > max {
+ for ch in word.chars() {
+ let mut t = line.clone();
+ t.push(ch);
+ if self.width(&t, size, flags) > max && !line.is_empty() {
+ out.push(std::mem::replace(&mut line, ch.to_string()));
+ } else {
+ line = t;
+ }
+ }
+ } else {
+ line = word.to_owned();
}
}
out.push(line);
diff --git a/bindings/rust/blenderui/tests/basic_css.rs b/bindings/rust/blenderui/tests/basic_css.rs
new file mode 100644
index 0000000..e147f29
--- /dev/null
+++ b/bindings/rust/blenderui/tests/basic_css.rs
@@ -0,0 +1,265 @@
+//! The CSS 2.1 leftovers and everyday visual properties: border and outline
+//! styles, decoration styles, background clip / origin, `clip`, counters,
+//! `empty-cells`, `word-break` / `overflow-wrap` and `tab-size`. Each test
+//! lays out a page headless and checks boxes or pixels.
+
+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))
+ }
+}
+
+/// Lay out a page; returns the window and its pixels (0x00RRGGBB) with a
+/// lookup in logical coordinates.
+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 width(cx: &mut App, win: WindowId, id: &str) -> f32 {
+ cx.element_bounds(win, id).unwrap_or_else(|| panic!("no element {id}")).size.width
+}
+
+fn height(cx: &mut App, win: WindowId, id: &str) -> f32 {
+ cx.element_bounds(win, id).unwrap_or_else(|| panic!("no element {id}")).size.height
+}
+
+const BG: u32 = 0x000000;
+
+#[test]
+fn border_and_outline_styles() {
+ Application::headless().run(|cx| {
+ let (_, at) = page(cx, 300.0, 200.0, "
+ html, body { margin: 0; background: #000 }
+ div { width: 100px; height: 20px; margin-bottom: 10px }
+ #solid { border: 2px solid #f00 }
+ #dashed { border: 2px dashed #f00 }
+ #double { border: 6px double #f00 }
+ #inset { border: 4px inset #f00 }
+ #outl { outline: 2px dashed #0f0; outline-offset: 0; margin-left: 10px }
+ ", || {
+ body().child(div().id("solid")).child(div().id("dashed")).child(div().id("double"))
+ .child(div().id("inset")).child(div().id("outl"))
+ });
+ // solid: the whole top edge
+ assert_eq!(at(9.0, 1.5), 0xff0000);
+ // dashed (y = 30): a dash at the start, a gap after it (dash 6px, gap > 6px)
+ assert_eq!(at(2.0, 30.5), 0xff0000);
+ assert_eq!(at(9.0, 30.5), BG, "gap between dashes");
+ // double (y = 60): outer and inner thirds drawn, the middle third empty
+ assert_eq!(at(50.0, 60.5), 0xff0000);
+ assert_eq!(at(50.0, 62.5), BG, "middle of a double border");
+ assert_eq!(at(50.0, 64.5), 0xff0000);
+ // inset (y = 90): the top side darker than the bottom side
+ let (top, bottom) = (at(50.0, 91.0), at(50.0, 90.0 + 20.0 - 2.0));
+ assert_eq!(bottom, 0xff0000);
+ assert!(top >> 16 < 0xc0 && top >> 16 > 0x40, "inset top is shaded: {top:06x}");
+ // dashed outline (y = 120, outside the box): dash then gap
+ assert_eq!(at(10.0 - 1.0, 120.0 - 1.0), 0x00ff00);
+ assert_eq!(at(10.0 - 2.0 + 9.0, 120.0 - 1.0), BG);
+ });
+}
+
+#[test]
+fn background_clip_and_origin() {
+ Application::headless().run(|cx| {
+ let (_, at) = page(cx, 200.0, 100.0, "
+ html, body { margin: 0; background: #000 }
+ #a { width: 60px; height: 60px; padding: 10px; border: 10px solid transparent;
+ background: #00f; background-clip: content-box }
+ #b { position: absolute; left: 100px; top: 0; width: 60px; height: 60px;
+ border: 10px solid transparent; background-color: #00f; background-clip: padding-box }
+ ", || body().child(div().id("a")).child(div().id("b")));
+ assert_eq!(at(5.0, 5.0), BG, "border area unpainted");
+ assert_eq!(at(15.0, 15.0), BG, "padding area unpainted");
+ assert_eq!(at(25.0, 25.0), 0x0000ff, "content painted");
+ assert_eq!(at(105.0, 5.0), BG, "padding-box: border unpainted");
+ assert_eq!(at(115.0, 15.0), 0x0000ff);
+ });
+}
+
+#[test]
+fn clip_rect_on_absolute_boxes() {
+ Application::headless().run(|cx| {
+ let (_, at) = page(cx, 200.0, 100.0, "
+ html, body { margin: 0; background: #000 }
+ #a { position: absolute; left: 0; top: 0; width: 80px; height: 80px; background: #f00;
+ clip: rect(10px, 50px, auto, 20px) }
+ ", || body().child(div().id("a")));
+ assert_eq!(at(5.0, 5.0), BG, "above / left of the clip");
+ assert_eq!(at(30.0, 20.0), 0xff0000);
+ assert_eq!(at(60.0, 20.0), BG, "right of the clip");
+ assert_eq!(at(30.0, 79.0), 0xff0000, "auto bottom = the box's bottom");
+ });
+}
+
+#[test]
+fn counters_in_generated_content() {
+ Application::headless().run(|cx| {
+ let (w, _) = page(cx, 400.0, 200.0, r#"
+ body { margin: 0; counter-reset: n }
+ span { display: inline-block }
+ .i { counter-increment: n }
+ .i::before { content: counter(n, upper-roman) }
+ .nest { counter-reset: n 4 }
+ #deep::before { content: counters(n, "-") }
+ #r1::before { content: "I" }
+ #r3::before { content: "III" }
+ #rdeep::before { content: "3-5" }
+ #after-nest::before { content: counter(n) }
+ #r4::before { content: "4" }
+ "#, || {
+ body()
+ .child(span().id("i1").class("i"))
+ .child(span().id("i2").class("i"))
+ .child(span().id("i3").class("i"))
+ .child(div().class("nest").child(span().id("deep").class("i")))
+ // the nested reset is out of scope again: the outer counter goes on
+ .child(span().id("after-nest").class("i"))
+ .child(span().id("r1")).child(span().id("r3")).child(span().id("rdeep")).child(span().id("r4"))
+ });
+ assert_eq!(width(cx, w, "i1"), width(cx, w, "r1"));
+ assert_eq!(width(cx, w, "i3"), width(cx, w, "r3"));
+ assert!(width(cx, w, "i3") > width(cx, w, "i1"));
+ assert_eq!(width(cx, w, "deep"), width(cx, w, "rdeep"), "counters() joins nested instances");
+ assert_eq!(width(cx, w, "after-nest"), width(cx, w, "r4"));
+ });
+}
+
+#[test]
+fn empty_cells_hide() {
+ Application::headless().run(|cx| {
+ 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 }
+ ", || {
+ body().child(table().child(tr().child(td().child("x")).child(td().child(" "))))
+ });
+ assert_eq!(at(10.0, 25.0), 0x00ff00, "a cell with content paints");
+ assert_eq!(at(90.0, 25.0), BG, "an empty cell doesn't");
+ });
+}
+
+#[test]
+fn word_break_overflow_wrap_and_tabs() {
+ Application::headless().run(|cx| {
+ let (w, _) = page(cx, 400.0, 400.0, "
+ body { margin: 0 }
+ p { margin: 0; width: 60px; line-height: 20px }
+ #normal { }
+ #anywhere { overflow-wrap: anywhere }
+ #all { word-break: break-all }
+ #mixed { word-break: break-all }
+ pre { margin: 0; display: inline-block }
+ #t8 { tab-size: 8 }
+ #t2 { tab-size: 2 }
+ ", || {
+ body()
+ .child(p().id("normal").child("aaaaaaaaaaaaaaaaaaaaaaaa"))
+ .child(p().id("anywhere").child("aaaaaaaaaaaaaaaaaaaaaaaa"))
+ .child(p().id("all").child("aaaaaaaaaaaaaaaaaaaaaaaa"))
+ .child(p().id("mixed").child("ab aaaaaaaaaaaaaaaaaaaaaa"))
+ .child(pre().id("t8").child("\tx"))
+ .child(pre().id("t2").child("\tx"))
+ });
+ assert_eq!(height(cx, w, "normal"), 20.0, "a long word overflows on one line");
+ assert!(height(cx, w, "anywhere") >= 40.0, "overflow-wrap breaks it");
+ assert!(height(cx, w, "all") >= 40.0, "word-break: break-all breaks it");
+ assert!(height(cx, w, "mixed") >= 40.0, "break-all inside line boxes");
+ assert!(width(cx, w, "t8") > width(cx, w, "t2"), "tab-size widens the tab");
+ });
+}
+
+#[test]
+fn decoration_styles_parse_and_paint() {
+ Application::headless().run(|cx| {
+ let (_, at) = page(cx, 200.0, 100.0, "
+ html, body { margin: 0; background: #000 }
+ p { margin: 0; font-size: 20px; line-height: 30px; color: #000;
+ text-decoration: underline wavy #f00 3px; text-underline-offset: 2px }
+ #b { position: absolute; top: 50px; left: 0; width: 100px; height: 20px;
+ font-size: 20px; line-height: 20px; color: #000;
+ text-decoration: underline dotted #0f0; text-decoration-thickness: 4px }
+ ", || {
+ body().child(p().child("mmmmmmmm")).child(div().id("b").child("mmmmmmmm"))
+ });
+ // wavy: red appears somewhere on the decoration band
+ let red = (0..60).flat_map(|x| (20..32).map(move |y| (x as f32, y as f32)))
+ .any(|(x, y)| at(x, y) == 0xff0000);
+ assert!(red, "wavy underline painted");
+ // dotted 4px: green dots with gaps along one row
+ let row: Vec<bool> = (0..40).map(|x| {
+ (50..75).any(|y| at(x as f32 + 0.5, y as f32 + 0.5) == 0x00ff00)
+ }).collect();
+ assert!(row.iter().any(|g| *g) && row.iter().any(|g| !*g), "dots with gaps: {row:?}");
+ });
+}
+
+#[test]
+fn styled_scopes_the_blender_theme() {
+ Application::headless().run(|cx| {
+ let (w, at) = page(cx, 300.0, 200.0, "
+ body { margin: 0 }
+ .box { height: 40px }
+ ", || {
+ body()
+ .child(div().id("plain").class("box").child(pre().id("plain-pre").child("x")))
+ .child(div().id("themed").class("box").styled().child(pre().id("themed-pre").child("x")))
+ .child(div().styled().child(div().id("opt-out").class("box").attr("styled", "false")))
+ });
+ // the page itself: browser defaults
+ assert_eq!(at(290.0, 5.0), 0xffffff, "unstyled page is white");
+ let t = cx.element_bounds(w, "themed").unwrap();
+ assert_eq!(at(290.0, t.origin.y + t.size.height - 2.0), 0x303030,
+ "a styled element gets Blender's background");
+ // UA rules differ inside: Blender's <pre> has padding and a dark background
+ let plain = cx.element_bounds(w, "plain-pre").unwrap();
+ let themed = cx.element_bounds(w, "themed-pre").unwrap();
+ assert!(themed.size.height > plain.size.height, "Blender pre is padded");
+ assert_eq!(at(themed.origin.x + 2.0, themed.origin.y + 2.0), 0x232323);
+ // styled="false" turns it back off for a subtree
+ let o = cx.element_bounds(w, "opt-out").unwrap();
+ assert_eq!(at(o.origin.x + 2.0, o.origin.y + 2.0), 0x303030,
+ "the styled parent's background shows through");
+ assert!(height(cx, w, "opt-out") == 40.0);
+ });
+}
+
+#[test]
+fn styled_in_rsx() {
+ struct V;
+ impl Render for V {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ rsx! { <body m-0><div id="t" styled h-10>"hi"</div></body> }
+ }
+ }
+ Application::headless().run(|cx| {
+ let win = open(cx, 100.0, 100.0, V);
+ let img = cx.draw(win.id);
+ let s = img.0 as f32 / 100.0;
+ assert_eq!(img.2[(30.0 * s) as usize * img.0 + (90.0 * s) as usize], 0x303030);
+ assert_eq!(img.2[(80.0 * s) as usize * img.0 + (90.0 * s) as usize], 0xffffff);
+ });
+}
diff --git a/bindings/rust/blenderui/tests/headless.rs b/bindings/rust/blenderui/tests/headless.rs
index f3e1393..880abe3 100644
--- a/bindings/rust/blenderui/tests/headless.rs
+++ b/bindings/rust/blenderui/tests/headless.rs
@@ -54,7 +54,7 @@ fn block_and_flex_layout_paint() {
assert_eq!(at(35.0, 40.0), 0x0000ff);
assert_eq!(at(10.0, 40.0), 0x00ff00);
assert_eq!(at(20.0, 55.0), 0xffff00);
- assert_eq!(at(150.0, 90.0), 0x303030); // html background
+ assert_eq!(at(150.0, 90.0), 0xffffff); // html background: browser default
});
}
diff --git a/bindings/rust/blenderui/tests/hooks.rs b/bindings/rust/blenderui/tests/hooks.rs
index 9e7a87c..fe60081 100644
--- a/bindings/rust/blenderui/tests/hooks.rs
+++ b/bindings/rust/blenderui/tests/hooks.rs
@@ -48,7 +48,7 @@ impl Render for Page {
provide_context(Theme("dark"));
let show_bob = self.show_bob;
rsx! {
- <body style="margin: 0">
+ <body styled style="margin: 0">
<profile username="Alice" id={"alice".to_string()} />
{if show_bob { <profile username="Bob" id={"bob".to_string()} /> }}
<Counter start={5} />
@@ -133,7 +133,7 @@ impl Render for List {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let keyed = self.keyed;
rsx! {
- <body style="margin: 0">
+ <body styled style="margin: 0">
{for name in self.items.clone() {
if keyed {
rsx! { <Row key={name} name={name} /> }.into_any_element()
diff --git a/docs/javascript.md b/docs/javascript.md
index 221470c..a018384 100644
--- a/docs/javascript.md
+++ b/docs/javascript.md
@@ -24,6 +24,7 @@ const { App, signal } = require('@blender-ui/native')
const app = new App({ gpu: true })
const win = app.window({ title: 'Hello', width: 360, height: 220 })
+win.body.setAttribute('styled', '') // Blender's look for the page (default: browser styling)
win.body.className = 'm-0 p-6 flex flex-col gap-3 bg-[#2b2b2b] text-[#e6e6e6]'
const clicks = signal(0)
diff --git a/docs/rust.md b/docs/rust.md
index d8072fb..74ef178 100644
--- a/docs/rust.md
+++ b/docs/rust.md
@@ -236,9 +236,25 @@ Text children are `&'static str`, `String` or `SharedString`.
> `fn main`. Inside `fn main` call it as `blenderui::html::main()`.
The document is wrapped in `<html><body>` unless your root already is one, so
-`body { margin: 0 }` and the user-agent defaults behave as in a browser. The
-defaults are Blender's dark theme: `#303030` background, 13 px text, blue
-links.
+`body { margin: 0 }` and the user-agent defaults behave as in a browser.
+
+### 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.
+
+```rust
+body().styled().child(h1().child("Blender look")) // gpui syntax
+rsx! { <div styled class="p-4">"Blender look"</div> } // rsx! / view! (Leptos-style)
+div().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
+`el.setAttribute('styled', '')`, or `<div styled>` in JSX.
## Styling
@@ -411,9 +427,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 | **210** change layout or rendering; **185** more parse but have no effect |
-| W3C property index (745 properties) | **207** rendered (28%), **177** parsed without effect (24%), **361** not recognized (48%): most of these are drafts, speech, paged media and SVG |
-| CSS 2.1, screen properties | **82 / 90** rendered, 90 / 90 parsed |
+| 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 |
| 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 |
@@ -429,7 +445,9 @@ 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: `clip`, `counter-increment`, `counter-reset`, `empty-cells`, `table-layout`, `unicode-bidi`, `list-style-image` and `background-attachment`.
+The CSS 2.1 properties that parse without effect: `table-layout` (tables always share width like `fixed`) and `unicode-bidi` (no bidi reordering).
+
+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 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.
@@ -438,8 +456,8 @@ How much is left, against all 745 properties in the
| | Properties | Share |
|---|---:|---:|
-| Change layout or rendering | 207 | 28% |
-| Parsed, no effect yet | 177 | 24% |
+| Change layout or rendering | 223 | 30% |
+| Parsed, no effect yet | 161 | 22% |
| Not recognized | 361 | 48% |
The 361 unrecognized properties break down as:
@@ -455,14 +473,14 @@ 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 82/90. The largest remaining gaps among common properties are visual
+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.
Not done yet:
- **Parsed, not applied:** `@keyframes`, transitions and animations; scroll snapping and OpenType font features.
- **`@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, `border-image` and border styles other than solid.
+- **Rendering effects:** 2D/3D `rotate` / `skew` transforms, `filter` / `backdrop-filter`, blend modes, `clip-path`, masks and `border-image`.
- **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/kit/intern/kit_color.c b/kit/intern/kit_color.c
index d907c6f..84e6bc9 100644
--- a/kit/intern/kit_color.c
+++ b/kit/intern/kit_color.c
@@ -1099,14 +1099,35 @@ static void curve_measure(BKNode *n, int *rw, int *rh)
static void curve_draw(BKNode *n)
{
+ /* draw_but_CURVE (interface_draw.cc) with the theme's wcol_curve: backdrop in inner, grid every
+ * 0.25 in outline_sel at alpha 64 (every 1.0 at 92), the current curve filled down to the
+ * bottom in item and stroked in inner_sel, points in text / text_sel, outline box in outline. */
CurveData *d = CURVE(n);
- const float back[4] = {0.16f, 0.16f, 0.16f, 1};
- bk_roundbox(n->x, n->y, n->w, n->h, bk_widget_radius(&bk_theme.regular), CNR_ALL, back);
+ const BKWCol *wc = &bk_theme.curve;
+ float back[4];
+ bk_rgba(wc->inner, back);
+ bk_fill_f((float)n->x, (float)n->y, (float)n->w, (float)n->h, back);
bk_clip_push(n->x, n->y, n->w, n->h);
- for (int k = 1; k < 8; k++) {
- const float g[4] = {1, 1, 1, (k % 2 == 0) ? 0.1f : 0.05f};
- bk_fill_f(floorf(n->x + n->w * k / 8.0f + 0.5f), n->y, 1, n->h, g);
- bk_fill_f(n->x, floorf(n->y + n->h * k / 8.0f + 0.5f), n->w, 1, g);
+ for (int k = 0; k <= 4; k++) {
+ float g[4];
+ bk_rgba(wc->outline_sel, g);
+ g[3] = (k % 4 == 0 ? 92 : 64) / 255.0f;
+ bk_fill_f(floorf(n->x + (n->w - 1) * k / 4.0f + 0.5f), n->y, 1, n->h, g);
+ bk_fill_f(n->x, floorf(n->y + (n->h - 1) * k / 4.0f + 0.5f), n->w, 1, g);
+ }
+ {
+ enum { STEPS = 96 };
+ float poly[STEPS + 3][2];
+ for (int i = 0; i <= STEPS; i++) {
+ const float x = i / (float)STEPS;
+ curve_to_px(n, x, curve_eval(d, d->channel, x), &poly[i][0], &poly[i][1]);
+ }
+ poly[STEPS + 1][0] = (float)(n->x + n->w);
+ poly[STEPS + 1][1] = poly[STEPS + 2][1] = (float)(n->y + n->h);
+ poly[STEPS + 2][0] = (float)n->x;
+ float fill[4];
+ bk_rgba(wc->item, fill);
+ bk_polygon((const float(*)[2])poly, STEPS + 3, fill);
}
for (int pass = 0; pass < 2; pass++) {
for (int ch = 0; ch < d->nchannels; ch++) {
@@ -1119,6 +1140,9 @@ static void curve_draw(BKNode *n)
if (!current) {
col[3] = 0.25f;
}
+ else {
+ bk_rgba(wc->inner_sel, col);
+ }
float px, py;
curve_to_px(n, 0, curve_eval(d, ch, 0), &px, &py);
const int steps = 96;
@@ -1126,23 +1150,31 @@ static void curve_draw(BKNode *n)
const float x = i / (float)steps;
float sx, sy;
curve_to_px(n, x, curve_eval(d, ch, x), &sx, &sy);
- bk_line(px, py, sx, sy, col, current ? BK_MAX(1.2f, 0.08f * u()) : 1.0f);
+ bk_line(px, py, sx, sy, col, 1.0f); /* GPU_line_width(1.0f), smooth */
px = sx;
py = sy;
}
}
}
const int ch = d->channel;
- const float r = 0.17f * u();
+ /* point_size = max(2 * pixelsize, min(6 * UI_SCALE_FAC, 20)); the selected point is also the
+ * active one (1.4x, text_sel); others use wcol_curve.text, alpha forced opaque */
+ const float point_size = BK_MAX(2.0f * bk_px(), BK_MIN(6.0f * bk_scale_fac, 20.0f));
+ float pt[4], pt_sel[4];
+ bk_rgba(wc->text, pt);
+ bk_rgba(wc->text_sel, pt_sel);
+ pt[3] = pt_sel[3] = 1.0f;
for (int i = 0; i < d->npts[ch]; i++) {
float sx, sy;
curve_to_px(n, d->pts[ch][i][0], d->pts[ch][i][1], &sx, &sy);
- const float black[4] = {0, 0, 0, 1}, sel[4] = {1, 1, 1, 1}, grey[4] = {0.55f, 0.55f, 0.55f, 1};
- bk_circle(sx, sy, r + 1, black);
- bk_circle(sx, sy, r, i == d->selected ? sel : grey);
+ const bool sel = i == d->selected;
+ bk_circle(sx, sy, point_size * (sel ? 1.4f : 1.0f) * 0.5f, sel ? pt_sel : pt);
}
bk_clip_pop();
- outline_rect(n);
+ BuiWidgetBase wb = {{(float)n->x, (float)n->y, (float)n->w, (float)n->h}, 0, 0, CNR_ALL};
+ bk_rgba(wc->outline, wb.outline);
+ wb.pixelsize = 1.0f;
+ BUI_raster_widget_base(bk_draw.r, &wb);
}
static int curve_set_num(BKNode *n, const char *key, double v)
diff --git a/kit/intern/kit_core.c b/kit/intern/kit_core.c
index d133711..ff33275 100644
--- a/kit/intern/kit_core.c
+++ b/kit/intern/kit_core.c
@@ -1626,6 +1626,57 @@ void bk_start_drag_toggle(BKContext *ctx, int group, int value)
ctx->dt_group = group;
ctx->dt_value = value;
ctx->dt_active = 1;
+ ctx->dt_init_x = ctx->dt_last_x = ctx->pointer_x;
+ ctx->dt_init_y = ctx->dt_last_y = ctx->pointer_y;
+}
+
+/* Sets one drag-toggle target to the dragged state (button_execute / panel open-close). */
+static int drag_toggle_apply(BKContext *ctx, BKNode *under)
+{
+ if (!under || under->cls->drag_group != ctx->dt_group || !NODE_ENABLED(under) ||
+ under == ctx->grab || (int)(under->value != 0) == ctx->dt_value)
+ {
+ return 0;
+ }
+ if (under->cls->drag_group == DRAG_GROUP_PANEL) {
+ if (!bk_anim_running(under)) {
+ under->anim = (under->flags & NF_COLLAPSED) ? 0.0f : 1.0f;
+ }
+ under->flags = ctx->dt_value ? (under->flags & ~NF_COLLAPSED) : (under->flags | NF_COLLAPSED);
+ under->value = ctx->dt_value;
+ bk_anim_start(under);
+ bk_relayout(under);
+ }
+ else {
+ bk_set_value(under, ctx->dt_value);
+ }
+ return 1;
+}
+
+static BKNode *hit_all(BKContext *ctx, int x, int y);
+
+/* drag_toggle_set_xy_xy (interface_handlers.cc): touch every toggle whose rect the segment from
+ * the last pointer position to this one crosses (BLI_rctf_isect_segment), so fast drags don't
+ * skip buttons; the segment is sampled every 2 px through the regular hit test. Panel headers
+ * follow panel_drag_collapse: the segment runs from the drag start with x locked to it. No
+ * xy axis lock for toggles: BL only locks for BUT_DRAG_LOCK buttons (tabs, decorators). */
+static int drag_toggle_segment(BKContext *ctx, int x, int y)
+{
+ int x0 = ctx->dt_last_x, y0 = ctx->dt_last_y;
+ if (ctx->dt_group == DRAG_GROUP_PANEL) {
+ x0 = x = ctx->dt_init_x;
+ y0 = ctx->dt_init_y;
+ }
+ const int steps = BK_MAX(1, (int)(hypotf((float)(x - x0), (float)(y - y0)) / 2.0f));
+ int changed = 0;
+ for (int i = 0; i <= steps; i++) {
+ const int sx = x0 + (int)lroundf((x - x0) * (float)i / steps);
+ const int sy = y0 + (int)lroundf((y - y0) * (float)i / steps);
+ changed |= drag_toggle_apply(ctx, hit_all(ctx, sx, sy));
+ }
+ ctx->dt_last_x = x;
+ ctx->dt_last_y = y;
+ return changed;
}
static void update_cursor(BKContext *ctx);
@@ -1707,29 +1758,118 @@ static void layout(BKContext *ctx)
ctx->layout_dirty = false;
}
-static void tooltip_rect(BKContext *ctx, BKRect *r_rect)
+/* interface_region_tooltip.cc: portions of the line height, and the wrap width. */
+#define TIP_SPACER 0.3f
+#define TIP_PADDING_X 1.95f
+#define TIP_PADDING_Y 1.28f
+#define TIP_MAXWIDTH 600
+
+/* Bytes of the next wrapped line (BLFWrapMode Typographical | HardLimit): break at the last
+ * space that fits, else inside the word at a UTF-8 boundary. */
+static int tip_wrap_len(const char *s, int len, float maxw)
{
- const BKNode *n = ctx->tip_node;
- const char *desc = n && n->desc ? n->desc : "";
- const int u = bk_unit(), p = bk_pad();
- int lines = 1;
- float w = 0.0f;
- const char *s = desc;
- while (1) {
+ if (bk_text_width(s, len, false) <= maxw) {
+ return len;
+ }
+ int brk = -1;
+ for (int i = 1; i < len; i++) {
+ if (s[i] == ' ') {
+ if (bk_text_width(s, i, false) > maxw) {
+ break;
+ }
+ brk = i;
+ }
+ }
+ if (brk > 0) {
+ return brk;
+ }
+ int i = 1;
+ while (i < len && ((uchar)s[i] & 0xC0) == 0x80) {
+ i++;
+ }
+ for (int j = i; j < len;) {
+ int k = j + 1;
+ while (k < len && ((uchar)s[k] & 0xC0) == 0x80) {
+ k++;
+ }
+ if (bk_text_width(s, k, false) > maxw) {
+ break;
+ }
+ i = j = k;
+ }
+ return i;
+}
+
+/* Lays out (and with `r`, draws) the tooltip text like tooltip_create_with_data /
+ * tooltip_region_draw_cb: the first line is the TIP_STYLE_HEADER label in the theme text color,
+ * followed by a TIP_SPACER gap; later lines use TIP_LC_VALUE, the text color blended 20% toward
+ * the background (color_blend_f3_f3). Returns the text height, width in r_w. */
+static float tooltip_text(BKContext *ctx, const BKRect *r, float *r_w)
+{
+ const char *s = ctx->tip_node && ctx->tip_node->desc ? ctx->tip_node->desc : "";
+ const float h = bk_line_height(), pad_x = h * TIP_PADDING_X, pad_y = h * TIP_PADDING_Y;
+ const float wrap = BK_MAX(h, BK_MIN(TIP_MAXWIDTH * bk_scale_fac, ctx->win_w - pad_x));
+ uchar value[4];
+ for (int i = 0; i < 3; i++) {
+ value[i] = (uchar)(0.8f * bk_theme.tooltip.text[i] + 0.2f * bk_theme.tooltip.inner[i] + 0.5f);
+ }
+ value[3] = 255;
+ float y = 0.0f, w = 0.0f;
+ for (int para = 0;; para++) {
const char *nl = strchr(s, '\n');
- const int len = nl ? (int)(nl - s) : (int)strlen(s);
- w = BK_MAX(w, bk_text_width(s, len, false));
+ int len = nl ? (int)(nl - s) : (int)strlen(s);
+ const char *p = s;
+ do {
+ const int n = tip_wrap_len(p, len, wrap);
+ w = BK_MAX(w, bk_text_width(p, n, false));
+ if (r) {
+ const BKRect lr = bk_rect(r->xmin, (int)(r->ymin + 0.5f * pad_y + y), bk_rw(r), (int)h);
+ bk_text(r->xmin + 0.5f * pad_x, bk_text_baseline(&lr), p, n,
+ para == 0 ? bk_theme.tooltip.text : value, false);
+ }
+ y += h;
+ p += n;
+ len -= n;
+ while (len > 0 && *p == ' ') {
+ p++;
+ len--;
+ }
+ } while (len > 0);
if (!nl) {
break;
}
- lines++;
+ if (para == 0) {
+ y += h * TIP_SPACER;
+ }
s = nl + 1;
}
- const int tw = (int)w + 2 * p, th = lines * u + p / 2;
- int tx = BK_MAX(0, BK_MIN(ctx->tip_x - tw / 4, ctx->win_w - tw));
- int ty = ctx->tip_y + (int)(0.9f * u);
- if (ty + th > ctx->win_h) {
- ty = BK_MAX(0, ctx->tip_y - th - (int)(0.4f * u));
+ if (r_w) {
+ *r_w = w;
+ }
+ return y;
+}
+
+/* tooltip_create_from_button_or_extra_icon + tooltip_create_with_data: anchored under the
+ * hovered button (rect.ymin - UI_POPUP_MARGIN / 2) at the pointer's x, offset by 0.2 line
+ * heights, padded by TIP_PADDING, clamped 5/7 px (scaled) inside the window. */
+static void tooltip_rect(BKContext *ctx, BKRect *r_rect)
+{
+ float fontw;
+ const float fonth = tooltip_text(ctx, NULL, &fontw);
+ const float h = bk_line_height(), pad_x = h * TIP_PADDING_X, pad_y = h * TIP_PADDING_Y;
+ const BKRect br = bk_node_rect(ctx->tip_node);
+ const float init_x = (float)ctx->tip_x, init_y = br.ymax + 6.0f * bk_scale_fac;
+ const int tw = (int)(fontw + pad_x + 0.5f), th = (int)(fonth + pad_y + 0.5f);
+ int tx = (int)(init_x - 0.2f * h - pad_x);
+ int ty = (int)(init_y + 0.2f * h);
+ const int cx = (int)(5.0f * bk_scale_fac), cy = (int)(7.0f * bk_scale_fac);
+ tx = BK_MAX(cx, BK_MIN(tx, ctx->win_w - cx - tw));
+ ty = BK_MAX(cy, BK_MIN(ty, ctx->win_h - cy - th));
+ /* near the bottom and overlapping the pointer: move up by 3 lines */
+ if (ctx->tip_x >= tx && ctx->tip_x < tx + tw && ctx->tip_y >= ty && ctx->tip_y < ty + th &&
+ ty + th > ctx->win_h * 3 / 4)
+ {
+ ty -= (int)(3.0f * h);
}
*r_rect = bk_rect(tx, ty, tw, th);
}
@@ -1741,29 +1881,54 @@ static void draw_tooltip(BKContext *ctx)
}
const BKRect r = ctx->tip_rect;
bk_widget_tooltip_back(&r);
- const int u = bk_unit(), p = bk_pad();
- const char *s = ctx->tip_node->desc;
- int line = 0;
- while (1) {
- const char *nl = strchr(s, '\n');
- const int len = nl ? (int)(nl - s) : (int)strlen(s);
- BKRect lr = bk_rect(r.xmin, r.ymin + p / 4 + line * u, bk_rw(&r), u);
- uchar c[4];
- memcpy(c, bk_theme.tooltip.text, 4);
- if (line > 0) {
- c[3] = (uchar)(c[3] * 0.65f); /* details are dimmer than the title */
- }
- char buf[256];
- const int bl = BK_MIN(len, 255);
- memcpy(buf, s, (size_t)bl);
- buf[bl] = 0;
- bk_text_in(&lr, buf, c, BK_ALIGN_LEFT, false);
- if (!nl) {
- break;
- }
- s = nl + 1;
- line++;
+ tooltip_text(ctx, &r, NULL);
+}
+
+/* Region (View2D) vertical scroller, view2d_scroller_size_get + view2d_scrollers_calc: width
+ * lerps from V2D_SCROLL_MIN_WIDTH (5 px * scale + 2 * pixelsize) to V2D_SCROLL_WIDTH
+ * (0.45 * widget_unit + 2 * pixelsize) by alpha_vert, padded 0.1 units from the region edge; the
+ * thumb is at least V2D_SCROLL_THUMB_SIZE_MIN (30 px * scale). */
+static void region_scroll_rects(BKContext *ctx, BKRect *r_track, BKRect *r_thumb)
+{
+ const int top = ctx->header_h, view_h = ctx->win_h - top;
+ const float min_w = 5.0f * bk_scale_fac + 2.0f * bk_px();
+ const float max_w = 0.45f * bk_unit() + 2.0f * bk_px();
+ const int sw = (int)((max_w - min_w) * (ctx->scroll_alpha / 255.0f) + min_w);
+ const int xmax = ctx->win_w - (int)(0.1f * bk_unit());
+ *r_track = bk_rect(xmax - sw, top, sw, view_h);
+ const float thumb_min = 30.0f * bk_scale_fac;
+ float t0 = top + (float)view_h * ctx->scroll / ctx->content_h;
+ float t1 = top + (float)view_h * (ctx->scroll + view_h) / ctx->content_h;
+ if (t1 - t0 < thumb_min) {
+ t1 = BK_CLAMP(t0 + thumb_min, top + thumb_min, (float)(top + view_h));
+ t0 = BK_CLAMP(t0, (float)top, top + view_h - thumb_min);
}
+ *r_thumb = bk_rect(r_track->xmin, (int)t0, sw, (int)(t1 - t0));
+}
+
+/* screen_ops.cc area_azone (AZ_SCROLL_VERT): alpha_vert = 1 - distance in x from the scroller /
+ * V2D_SCROLL_HIDE_HEIGHT (HEADERY * scale); 255 while over it. Dirties it when it changes. */
+static int region_scroll_update_alpha(BKContext *ctx, int x, int y)
+{
+ const int top = ctx->header_h;
+ if (ctx->content_h <= ctx->win_h - top) {
+ return 0;
+ }
+ BKRect track, thumb;
+ region_scroll_rects(ctx, &track, &thumb);
+ const int dx = x < track.xmin ? track.xmin - x : (x > track.xmax ? x - track.xmax : 0);
+ float alpha = 1.0f - BK_CLAMP(dx / (26.0f * bk_scale_fac), 0.0f, 1.0f);
+ if (y < top) {
+ alpha = 0.0f;
+ }
+ const int a = (int)(alpha * 255);
+ if (a == ctx->scroll_alpha) {
+ return 0;
+ }
+ const int full = (int)(0.45f * bk_unit() + 2.0f * bk_px()) + bk_unit();
+ ctx->scroll_alpha = a;
+ bk_ctx_dirty_rect(ctx, bk_rect(ctx->win_w - full, top, full, ctx->win_h - top));
+ return 1;
}
static void draw_region(BKContext *ctx, const BKRect *rect)
@@ -1784,12 +1949,16 @@ static void draw_region(BKContext *ctx, const BKRect *rect)
bk_draw_tree(ctx->header);
}
if (ctx->content_h > view_h) { /* region scrollbar */
- const int sb = BK_MAX(2, (int)(0.15f * bk_unit()));
- const float th = BK_MAX((float)bk_unit(), (float)view_h * view_h / ctx->content_h);
- const float ty = top + (view_h - th) * ctx->scroll / (float)(ctx->content_h - view_h);
- float c[4];
- bk_rgba(bk_theme.scroll.item, c);
- bk_roundbox(w - sb - 2, ty, sb, th, sb * 0.5f, CNR_ALL, c);
+ BKRect track, thumb;
+ region_scroll_rects(ctx, &track, &thumb);
+ /* view2d_scrollers_draw_ex: alpha_fac maps alpha_vert 0..255 to V2D_SCROLL_MIN_ALPHA..1 */
+ const float a = ctx->scroll_alpha / 255.0f, alpha_fac = a * (1.0f - 0.4f) + 0.4f;
+ BKWCol wc = bk_theme.scroll;
+ wc.inner[3] = wc.inner[3] == 0 ? (uchar)(0.25f * ctx->scroll_alpha) :
+ (uchar)(wc.inner[3] * alpha_fac);
+ wc.item[3] = (uchar)(wc.item[3] * alpha_fac);
+ wc.outline[3] = 0; /* also disables the emboss, as widget_emboss[3] = 0 does */
+ bk_widget_scroll(&wc, &track, &thumb, false);
}
for (int i = 0; i < ctx->npopups; i++) {
bk_draw_tree(ctx->popups[i]);
@@ -1867,7 +2036,7 @@ int BK_render(BKContext *ctx, BuiRaster *r, int w, int h, int full)
#define DOUBLE_CLICK_S 0.35
#define DOUBLE_CLICK_PX 4
-#define TOOLTIP_DELAY_MS 600
+#define TOOLTIP_DELAY_MS 500 /* UI_TOOLTIP_DELAY 0.5 */
static BKNode *hit_all(BKContext *ctx, int x, int y)
{
@@ -2032,6 +2201,7 @@ static int in_BK_motion(BKContext *ctx, int x, int y, int mods)
ctx->pointer_x = x;
ctx->pointer_y = y;
int changed = hide_tooltip(ctx);
+ changed |= region_scroll_update_alpha(ctx, x, y);
if (ctx->modal) {
BKEvent e = make_event(ctx, ctx->modal, x, y, mods);
if (ctx->modal->cls->move) {
@@ -2061,27 +2231,10 @@ static int in_BK_motion(BKContext *ctx, int x, int y, int mods)
if (!ctx->grab) { /* the drag handler may have closed things */
return 1;
}
- BKNode *under = hit_all(ctx, x, y);
- if (ctx->dt_active && under && under->cls->drag_group == ctx->dt_group &&
- NODE_ENABLED(under) && under != ctx->grab)
- {
- if ((int)(under->value != 0) != ctx->dt_value) { /* Blender: drag across toggles */
- if (under->cls->drag_group == DRAG_GROUP_PANEL) {
- if (!bk_anim_running(under)) {
- under->anim = (under->flags & NF_COLLAPSED) ? 0.0f : 1.0f;
- }
- under->flags = ctx->dt_value ? (under->flags & ~NF_COLLAPSED) :
- (under->flags | NF_COLLAPSED);
- under->value = ctx->dt_value;
- bk_anim_start(under);
- bk_relayout(under);
- }
- else {
- bk_set_value(under, ctx->dt_value);
- }
- changed = 1;
- }
+ if (ctx->dt_active) { /* Blender: drag across toggles */
+ changed |= drag_toggle_segment(ctx, x, y);
}
+ BKNode *under = hit_all(ctx, x, y);
if (under != ctx->hover) {
set_hover(ctx, under);
changed = 1;
diff --git a/kit/intern/kit_draw.c b/kit/intern/kit_draw.c
index 1b512e7..0a9160f 100644
--- a/kit/intern/kit_draw.c
+++ b/kit/intern/kit_draw.c
@@ -45,6 +45,7 @@ BKTheme bk_theme = {
/* tooltip */ WCOL(0x242424ffu, 0x242424ffu, 0x1d1d1dffu, 0x4772b3ffu, 0xd9d9d9ffu, 0xd9d9d9ffu, 0xffffffffu, 0.2f),
/* tab */ WCOL(0x1d1d1dffu, 0x1d1d1dffu, 0x1d1d1dffu, 0x303030ffu, 0x1d1d1dffu, 0x989898ffu, 0xffffffffu, 0.2f),
/* pie_menu */ WCOL(0x242424ffu, 0x242424ffu, 0x181818ffu, 0x4772b3ffu, 0x545454ffu, 0xd9d9d9ffu, 0xffffffffu, 0.2f),
+ /* curve (wcol_curve) */ WCOL(0x727272ffu, 0x9a9a9affu, 0x545454ffu, 0x000000ffu, 0x00000059u, 0x08080800u, 0xc9c9c900u, 0.2f),
RGBA(0x303030ff), /* region_bg */
RGBA(0x181818ff), /* header_bg (top bar) */
RGBA(0x181818ff), /* tabs_bg (navigation bar: regions.sidebars.tab_back) */
@@ -82,13 +83,20 @@ void BK_set_font(const char *family)
strncpy(g_font_family, family ? family : "", sizeof(g_font_family) - 1);
}
+/* wm_window.cc WM_window_dpi_set_userdef: U.dpi = int(72 * ui_scale), pixelsize =
+ * max(1, dpi / 64) (integer division), widget_unit = round(18 * dpi / 72) + 2 * pixelsize.
+ * Scale 1.0 -> dpi 72, pixelsize 1, unit 20. */
+static int bk_dpi(void)
+{
+ return (int)(72.0f * bk_scale_fac + 1e-4f);
+}
int bk_unit(void)
{
- return (int)floorf(20.0f * bk_scale_fac + 0.5f); /* U.widget_unit */
+ return (int)roundf(18.0f * ((float)bk_dpi() / 72.0f)) + 2 * (int)bk_px(); /* U.widget_unit */
}
float bk_px(void)
{
- return bk_scale_fac >= 1.5f ? 2.0f : 1.0f; /* U.pixelsize */
+ return (float)BK_MAX(1, bk_dpi() / 64); /* U.pixelsize */
}
float bk_text_scale = 1.0f;
diff --git a/kit/intern/kit_intern.h b/kit/intern/kit_intern.h
index 3f03008..2b2f7f8 100644
--- a/kit/intern/kit_intern.h
+++ b/kit/intern/kit_intern.h
@@ -46,7 +46,7 @@ typedef struct BKWCol {
typedef struct BKTheme {
BKWCol regular, tool, toggle, radio, option, textfield, num, numslider, menu, pulldown, menu_back,
- menu_item, list_item, box, scroll, progress, tooltip, tab, pie_menu;
+ menu_item, list_item, box, scroll, progress, tooltip, tab, pie_menu, curve;
uchar region_bg[4], header_bg[4], tabs_bg[4];
uchar panel_header[4], panel_back[4], panel_sub_back[4], panel_outline[4];
uchar text[4], text_hi[4], emboss[4], cursor[4], selection[4];
@@ -459,6 +459,7 @@ struct BKContext {
BKRect tip_rect;
/* drag-toggle */
int dt_group, dt_value, dt_active;
+ int dt_init_x, dt_init_y, dt_last_x, dt_last_y; /* uiDragToggleHandle xy_init / xy_last */
/* pointer */
bool dragging;
int press_x, press_y, off_x, off_y, skip_x, skip_y;
@@ -473,6 +474,7 @@ struct BKContext {
int cursor;
/* window / region */
int win_w, win_h, scroll, content_h, header_h;
+ int scroll_alpha; /* View2D.alpha_vert of the region scrollbar (0..255) */
/* damage */
bool layout_dirty, full_dirty;
BKRect dirty[BK_MAX_DIRTY];
diff --git a/kit/intern/kit_menus.c b/kit/intern/kit_menus.c
index a49c7d9..f28b9c0 100644
--- a/kit/intern/kit_menus.c
+++ b/kit/intern/kit_menus.c
@@ -672,23 +672,42 @@ const char *BK_menu_row_text(BKNode *menu, int i)
/** \name Pie menu (Blender order: W, E, S, N, NW, NE, SW, SE)
* \{ */
-static const float g_pie_dirs[8][2] = {{-1, 0}, {1, 0}, {0, 1},
- {0, -1}, {-0.71f, -0.71f}, {0.71f, -0.71f},
- {-0.71f, 0.71f}, {0.71f, 0.71f}};
+/* RadialDirection (interface_intern.hh: N=0, NE, E, SE, S, SW, W, NW, clockwise) of the
+ * i-th item (radial_dir_order) and radial_dir_to_angle in degrees, y-up. */
+static const int g_pie_rdir[8] = {6, 2, 4, 0, 7, 1, 5, 3};
+static const short g_pie_angle[8] = {90, 45, 0, 315, 270, 225, 180, 135};
typedef struct PieData {
MenuData menu; /* items in menu.all */
float cx, cy;
int at_x, at_y;
+ float dir[2]; /* pie_data->pie_dir: normalized pointer direction, y-up */
+ bool dir_valid; /* !(flags & PIE_INVALID_DIR) */
} PieData;
#define PIE(n) ((PieData *)(n)->ext)
+/* button_pie_dir: unit vector of a RadialDirection, y-up. */
+static void pie_rdir_vec(int rdir, float r_vec[2])
+{
+ const float a = g_pie_angle[rdir] * (float)M_PI / 180.0f;
+ r_vec[0] = cosf(a);
+ r_vec[1] = sinf(a);
+}
+
static float pie_radius(void)
{
- return 4.2f * u();
+ return 100.0f * bk_scale_fac; /* U.pie_menu_radius * UI_SCALE_FAC */
}
+static float pie_threshold(void)
+{
+ return 12.0f * bk_scale_fac; /* U.pie_menu_threshold * UI_SCALE_FAC */
+}
+
+/* LayoutRadial::resolve_impl: buttons are 1.5x taller and 1.5 units wider, placed on a circle of
+ * pie_menu_radius; x factor aligns E items' left / W items' right edge to the circle, y factor
+ * puts the N item's bottom and the S item's top edge on it (others centered). */
static BKRect pie_item_rect(BKNode *n, int i)
{
PieData *pd = PIE(n);
@@ -696,20 +715,15 @@ static BKRect pie_item_rect(BKNode *n, int i)
const float uu = (float)u();
float w = bk_text_width(it->text, -1, false) + 2 * bk_pad() +
(it->icon ? bk_icon_size() + 0.3f * uu : 0);
- w = BK_MAX(w, 3 * uu);
- const float px = pd->cx + g_pie_dirs[i][0] * pie_radius();
- const float py = pd->cy + g_pie_dirs[i][1] * pie_radius() * 0.8f;
- float x;
- if (g_pie_dirs[i][0] < -0.1f) {
- x = px - w;
- }
- else if (g_pie_dirs[i][0] > 0.1f) {
- x = px;
- }
- else {
- x = px - w * 0.5f;
- }
- return bk_rect((int)x, (int)(py - uu * 0.5f), (int)w, (int)uu);
+ w = BK_MAX(w, 3 * uu) + 1.5f * uu;
+ const float h = 1.5f * uu;
+ float vec[2];
+ pie_rdir_vec(g_pie_rdir[i], vec);
+ const float fx = vec[0] > 0.01f ? 0.0f : (vec[0] < -0.01f ? -1.0f : -0.5f);
+ const float fy = vec[1] > 0.99f ? 0.0f : (vec[1] < -0.99f ? -1.0f : -0.5f);
+ const float x = pd->cx + vec[0] * pie_radius() + fx * w;
+ const float y_up = vec[1] * pie_radius() + fy * h; /* bottom edge relative to center, y-up */
+ return bk_rect((int)x, (int)(pd->cy - y_up - h), (int)w, (int)h);
}
static BKRect pie_item_rect_pub(BKNode *n, int i)
@@ -717,39 +731,68 @@ static BKRect pie_item_rect_pub(BKNode *n, int i)
return pie_item_rect(n, i);
}
+/* but_isect_pie_seg (interface_query.cc): an item owns the pointer direction when it lies within
+ * 45 degrees and is closer than the adjacent direction (8th if that item exists, else 4th). */
+static bool pie_isect_seg(PieData *pd, int i, int mask)
+{
+ if (!pd->dir_valid) {
+ return false;
+ }
+ const float angle_4th_cos = (float)M_SQRT1_2, angle_8th_cos = 0.9238795f, eps = 1e-4f;
+ const int rd = g_pie_rdir[i];
+ float bd[2], ad[2];
+ pie_rdir_vec(rd, bd);
+ const float c = bd[0] * pd->dir[0] + bd[1] * pd->dir[1];
+ if (c < angle_4th_cos - eps) {
+ return false;
+ }
+ if (c > angle_8th_cos + eps) {
+ return true;
+ }
+ /* angle_signed_v2v2(but_dir, pie_dir) < 0 -> previous (counter-clockwise) neighbours */
+ const float perp = bd[1] * pd->dir[0] - bd[0] * pd->dir[1];
+ const bool prev = atan2f(perp, c) < 0.0f;
+ const int adj8 = prev ? (rd + 7) % 8 : (rd + 1) % 8;
+ const int adj4 = prev ? (adj8 + 7) % 8 : (adj8 + 1) % 8;
+ const int adj = (mask & (1 << adj8)) ? adj8 : adj4;
+ pie_rdir_vec(adj, ad);
+ const float ca = ad[0] * pd->dir[0] + ad[1] * pd->dir[1];
+ if (c == ca) {
+ return rd > adj;
+ }
+ return c > ca;
+}
+
+/* ui_block_calc_pie_segment + ui_but_find_mouse_over: no item inside the
+ * pie_menu_threshold dead zone, otherwise the item owning the pointer direction. */
static int pie_dir_hot(BKNode *n, int x, int y)
{
PieData *pd = PIE(n);
const int count = BK_MIN(8, pd->menu.nall);
+ const float dx = x - pd->cx, dy = pd->cy - y; /* y-up */
+ const float len = hypotf(dx, dy);
+ pd->dir_valid = len >= pie_threshold();
+ if (len > 0.0f) {
+ pd->dir[0] = dx / len;
+ pd->dir[1] = dy / len;
+ }
+ int mask = 0;
for (int i = 0; i < count; i++) {
- BKRect r = pie_item_rect(n, i);
- if (x >= r.xmin && x < r.xmax && y >= r.ymin && y < r.ymax) {
- return i;
- }
+ mask |= 1 << g_pie_rdir[i];
}
- const float dx = x - pd->cx, dy = y - pd->cy;
- if (hypotf(dx, dy) < 0.8f * u()) {
- return -1;
- }
- const float a = atan2f(dy, dx);
- int best = -1;
- float best_d = 9.0f;
for (int i = 0; i < count; i++) {
- const float da = a - atan2f(g_pie_dirs[i][1], g_pie_dirs[i][0]);
- const float d = fabsf(atan2f(sinf(da), cosf(da)));
- if (d < best_d) {
- best = i;
- best_d = d;
+ if (pie_isect_seg(pd, i, mask)) {
+ return i;
}
}
- return best;
+ return -1;
}
static void pie_arrange(BKNode *n)
{
PieData *pd = PIE(n);
const float r = pie_radius(), uu = (float)u();
- const float mx = r + 6 * uu, my = r * 0.8f + uu;
+ const float mx = r + 6 * uu, my = r + 2.5f * uu;
const float ax = pd->at_x > PLACE_NONE ? pd->at_x : n->w * 0.5f;
const float ay = pd->at_y > PLACE_NONE ? pd->at_y : n->h * 0.5f;
pd->cx = BK_MAX(mx, BK_MIN(n->w - mx, ax));
@@ -787,8 +830,11 @@ static void pie_pick(BKNode *n, int i)
static int pie_move(BKNode *n, BKEvent *e)
{
+ PieData *pd = PIE(n);
+ const bool was_valid = pd->dir_valid;
const int hot = pie_dir_hot(n, e->x, e->y);
- if (hot != n->hot) {
+ /* the center sector tracks the pointer direction, so redraw whenever it is shown */
+ if (hot != n->hot || pd->dir_valid || was_valid) {
n->hot = hot;
bk_invalidate(n);
return 1;
@@ -796,6 +842,23 @@ static int pie_move(BKNode *n, BKEvent *e)
return 0;
}
+/* draw_disk_shaded (interface_widgets.cc, unshaded): an annulus sector from `start` spanning
+ * `angle` radians (y-up, like BL), as one even-odd polygon. */
+static void pie_draw_disk(
+ float cx, float cy, float start, float angle, float r_in, float r_out, const float c[4])
+{
+ enum { SUBD = 40 };
+ float pts[2 * (SUBD + 1)][2];
+ for (int i = 0; i <= SUBD; i++) {
+ const float a = start + angle * i / SUBD;
+ pts[i][0] = cx + r_out * cosf(a);
+ pts[i][1] = cy - r_out * sinf(a);
+ pts[2 * SUBD + 1 - i][0] = cx + r_in * cosf(a);
+ pts[2 * SUBD + 1 - i][1] = cy - r_in * sinf(a);
+ }
+ bk_polygon((const float(*)[2])pts, 2 * (SUBD + 1), c);
+}
+
static int pie_press(BKNode *n, BKEvent *e)
{
pie_pick(n, pie_dir_hot(n, e->x, e->y));
@@ -820,25 +883,31 @@ static void pie_draw(BKNode *n)
PieData *pd = PIE(n);
const float uu = (float)u();
float c[4];
- /* center disc with a direction indicator (draw_pie_center) */
- bk_rgba_alpha(bk_theme.pie_menu.inner, 0.85f, c);
- bk_circle(pd->cx, pd->cy, 0.9f * uu, c);
- bk_rgba(bk_theme.menu_back.outline, c);
- bk_ring(pd->cx, pd->cy, 0.9f * uu, c, 1.0f);
- if (n->hot >= 0) {
- const float a = atan2f(g_pie_dirs[n->hot][1], g_pie_dirs[n->hot][0]);
- float ic[4];
- bk_rgba(bk_theme.pie_menu.item, ic);
- for (int t = -4; t < 4; t++) {
- bk_line(pd->cx + 0.9f * uu * cosf(a + t / 10.0f), pd->cy + 0.9f * uu * sinf(a + t / 10.0f),
- pd->cx + 0.9f * uu * cosf(a + (t + 1) / 10.0f),
- pd->cy + 0.9f * uu * sinf(a + (t + 1) / 10.0f), ic, BK_MAX(2.0f, 0.15f * uu));
+ /* draw_pie_center (interface_widgets.cc): ring between pie_menu_threshold and threshold + 7
+ * filled with wcol_pie_menu.inner, the pointer direction's sector in inner_sel (PI/4 wide when
+ * the menu mixes axis-aligned and diagonal items, else PI/2), outline circles. */
+ const float r_in = pie_threshold(), r_out = (12.0f + 7.0f) * bk_scale_fac;
+ bk_rgba(bk_theme.pie_menu.inner, c);
+ pie_draw_disk(pd->cx, pd->cy, 0.0f, 2.0f * (float)M_PI, r_in, r_out, c);
+ if (pd->dir_valid) {
+ int mask = 0;
+ for (int i = 0; i < BK_MIN(8, pd->menu.nall); i++) {
+ mask |= 1 << g_pie_rdir[i];
}
- }
+ const bool has_aligned = (mask & 0x55) != 0, has_diagonal = (mask & 0xAA) != 0;
+ const float range = (has_aligned && has_diagonal) ? (float)M_PI_4 : (float)M_PI_2;
+ const float angle = atan2f(pd->dir[1], pd->dir[0]);
+ bk_rgba(bk_theme.pie_menu.inner_sel, c);
+ pie_draw_disk(pd->cx, pd->cy, angle - range / 2.0f, range, r_in, r_out, c);
+ }
+ bk_rgba(bk_theme.pie_menu.outline, c);
+ bk_ring(pd->cx, pd->cy, r_in, c, 1.0f);
+ bk_ring(pd->cx, pd->cy, r_out, c, 1.0f);
if (pd->menu.title) {
+ /* LayoutRootPieMenu::resolve_impl: title bottom at threshold + 9 above the center */
const float tw = bk_text_width(pd->menu.title, -1, false) + 2 * bk_pad();
- BKRect tr = bk_rect((int)(pd->cx - tw * 0.5f), (int)(pd->cy - pie_radius() * 0.8f - 2.2f * uu),
- (int)tw, (int)uu);
+ BKRect tr = bk_rect((int)(pd->cx - tw * 0.5f),
+ (int)(pd->cy - (12.0f + 9.0f) * bk_scale_fac - uu), (int)tw, (int)uu);
bk_widget_menu_back(&tr, CNR_ALL);
bk_text_in(&tr, pd->menu.title, bk_theme.menu_back.text, BK_ALIGN_CENTER, false);
}
@@ -855,7 +924,19 @@ static void pie_draw(BKNode *n)
bk_shadow(&r, bk_widget_radius(&w));
BKRect wr = r;
bk_widget_but(&w, &wr, 0, CNR_ALL);
- bk_text_icon(&r, it->text, it->icon, w.text, BK_ALIGN_CENTER, it->enabled);
+ if (it->icon && it->text && it->text[0]) {
+ /* BUT_ICON_LEFT pie item (widget_draw_text_icon): rect.xmin += 0.3 * widget_unit, icon
+ * at xmin + 4 * scale, text centered in the space after icon_size + 2 * scale. */
+ const float is = (float)bk_icon_size(), x0 = r.xmin + 0.3f * uu;
+ bk_icon(it->icon, x0 + 4.0f * bk_scale_fac + is * 0.5f, r.ymin + bk_rh(&r) * 0.5f, NULL,
+ it->enabled ? 1.0f : 0.5f, 0);
+ BKRect tr = r;
+ tr.xmin = (int)(x0 + is + 2.0f * bk_scale_fac);
+ bk_text_in(&tr, it->text, w.text, BK_ALIGN_CENTER, false);
+ }
+ else {
+ bk_text_icon(&r, it->text, it->icon, w.text, BK_ALIGN_CENTER, it->enabled);
+ }
}
}
diff --git a/kit/intern/kit_nodes.c b/kit/intern/kit_nodes.c
index e56ca57..21ec015 100644
--- a/kit/intern/kit_nodes.c
+++ b/kit/intern/kit_nodes.c
@@ -174,8 +174,9 @@ static void socket_color(const char *type, float c[4])
{"color", 0xc7c729}, {"rgba", 0xc7c729}, {"shader", 0x63c763},
{"geometry", 0x00d6a3}, {"string", 0x70b2ff}, {"object", 0xed9e5c},
{"image", 0x633863}, {"collection", 0xf5f5f5}, {"texture", 0x9e4fa3},
- {"material", 0xeb7582}, {"rotation", 0xa663c7}, {"menu", 0x4d4d4d},
- {"matrix", 0x4d1a75}, {"bundle", 0x52525e}, {"closure", 0x3d3d47},
+ {"material", 0xeb7582}, {"rotation", 0xa663c7}, {"menu", 0x666666},
+ {"matrix", 0xb83385}, {"bundle", 0x4d8080}, {"closure", 0x7d7d3a},
+ {"int_vector", 0x5c789c}, {"font", 0x635742}, {"sound", 0x635742},
};
uint32_t rgb = 0xa1a1a1;
for (size_t i = 0; i < sizeof(colors) / sizeof(colors[0]); i++) {
@@ -386,38 +387,62 @@ static void color_u(uint32_t rgba, float c[4])
c[3] = (rgba & 255) / 255.0f;
}
-/* UI_view2d_dot_grid_draw: dots at the grid levels, the finer ones fading in */
+/* view2d_dot_grid_draw (view2d.cc), called by node_draw_space with min_step =
+ * NODE_GRID_STEP_SIZE (20 * UI_SCALE_FAC view units) and the theme's grid_levels (3). View units
+ * are graph units * UI_SCALE_FAC, so zoom_x (px per view unit) is the editor zoom. Each level is
+ * 5x the previous; dot size is 2 * pixelsize * level_scale * zoom clamped to [2, 3] * pixelsize,
+ * alpha (precise / drawn)^2, and the finest level fades by 1 - fract(view_level). */
static void draw_grid(BKNode *e)
{
+ const int grid_subdivisions = 3; /* space_node.grid_levels */
float c[4];
color_u(0x303030ff, c); /* space_node.grid */
- const float s = scale_of(e);
- const float base = NODE_DY; /* one widget unit in graph space */
- const int levels = 3; /* theme grid_levels */
- for (int level = levels - 1; level >= 0; level--) {
- const float step = base * powf(5.0f, (float)level) * s; /* screen pixels between dots */
- if (step < 4.0f * bk_scale_fac) {
+ const float zoom = BK_MAX(1e-4f, ed(e)->zoom), px = bk_px();
+ const float min_point_size = 2.0f * px, max_point_size = 1.5f * min_point_size;
+ const float view_level = logf(NODE_DY * bk_scale_fac / zoom) / logf(5.0f);
+ const int largest_visible_level = (int)view_level;
+ for (int level_offset = 0; level_offset <= grid_subdivisions; level_offset++) {
+ const int level = largest_visible_level - level_offset;
+ if (level < 0) {
+ break;
+ }
+ const float level_scale = powf(5.0f, (float)level);
+ const float precise = min_point_size * level_scale * zoom;
+ const float drawn = ceilf(BK_CLAMP(precise, min_point_size, max_point_size));
+ const float offset = (drawn / 2.0f - px) * zoom; /* view-space offset, in pixels */
+ const float alpha = (precise / drawn) * (precise / drawn);
+ const float alpha_cutoff = 0.01f;
+ if (alpha < alpha_cutoff) {
+ break;
+ }
+ const float alpha_clamped = BK_CLAMP((1.0f + alpha_cutoff) * alpha - alpha_cutoff, 0.0f, 1.0f);
+ const float fade = level_offset == grid_subdivisions ?
+ 1.0f - (view_level - floorf(view_level)) :
+ 1.0f;
+ const float dc[4] = {c[0], c[1], c[2], alpha_clamped * fade};
+ const float step = NODE_DY * level_scale * scale_of(e); /* screen pixels between dots */
+ if (step < 1.0f) {
continue;
}
- /* fade a level in as its dots spread apart */
- const float fade = BK_CLAMP((step - 4.0f * bk_scale_fac) / (12.0f * bk_scale_fac), 0.0f, 1.0f);
- float dc[4] = {c[0], c[1], c[2], fade};
- const float r = BK_MAX(0.75f, 1.0f * bk_scale_fac * (level ? 1.25f : 1.0f));
const float ox = fmodf(ed(e)->panx, step), oy = fmodf(ed(e)->pany, step);
for (float y = (float)e->y + oy - step; y < e->y + e->h + step; y += step) {
for (float x = (float)e->x + ox - step; x < e->x + e->w + step; x += step) {
if (x >= e->x && y >= e->y) {
- bk_fill_f(x - r * 0.5f, y - r * 0.5f, r, r, dc);
+ bk_circle(x + offset, y - offset, drawn * 0.5f, dc); /* POINT_..._COLOR_AA */
}
}
}
}
}
-/* node_link_bezier_handles + evaluation: NODE_LINK_RESOL * 2 segments */
+/* calculate_inner_link_bezier_points + evaluation: NODE_LINK_RESOL * 2 segments.
+ * The handles shrink as the link nears horizontal; curving 0 is a straight line. */
static void bezier_points(float x0, float y0, float x3, float y3, float pts[][2], int n)
{
- const float dist = NOODLE_CURVING * 0.10f * fabsf(x0 - x3);
+ const float dist_x = fabsf(x0 - x3), dist_y = fabsf(y0 - y3);
+ const float slope = dist_x != 0.0f ? dist_y / dist_x : 0.0f;
+ const float clamp_factor = BK_MIN(1.0f, slope * (4.5f - 0.25f * NOODLE_CURVING));
+ const float dist = NOODLE_CURVING * 0.10f * dist_x * clamp_factor;
const float x1 = x0 + dist, x2 = x3 - dist;
for (int i = 0; i <= n; i++) {
const float t = (float)i / n, it = 1.0f - t;
@@ -433,8 +458,11 @@ static void draw_noodle(float x0, float y0, float x3, float y3, const float colo
enum { N = NODE_LINK_RESOL * 2 };
float pts[N + 1][2];
bezier_points(x0, y0, x3, y3, pts, N);
- /* node_draw_link: an outline in the wire color, the link color inside */
- const float th = BK_MAX(1.0f, 1.5f * bk_scale_fac * BK_MIN(1.0f, zoom * 1.25f));
+ /* node_draw_link: LINK_WIDTH 2.5 * max(UI_SCALE_FAC * zoom, 1). The link
+ * shader draws the outline 2 * thickness wide and the colored line on top
+ * at 0.65 of that. */
+ const float link_w = 2.5f * BK_MAX(bk_scale_fac * zoom, 1.0f);
+ const float th = 2.0f * link_w * 0.65f, outline_w = 2.0f * link_w;
float wire[4];
color_u(0x1a1a1aff, wire); /* space_node.wire */
float inner[4];
@@ -445,7 +473,7 @@ static void draw_noodle(float x0, float y0, float x3, float y3, const float colo
}
}
for (int i = 0; i < N; i++) {
- bk_line(pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1], wire, th + 2.0f * bk_scale_fac);
+ bk_line(pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1], wire, outline_w);
}
for (int i = 0; i < N; i++) {
bk_line(pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1], inner, th);
@@ -454,7 +482,9 @@ static void draw_noodle(float x0, float y0, float x3, float y3, const float colo
static void draw_socket(float x, float y, const char *type, float s)
{
- float c[4], o[4] = {0.0f, 0.0f, 0.0f, 0.6f};
+ /* node_socket_outline_color_get: the theme wire color, opaque */
+ float c[4], o[4];
+ color_u(0x1a1a1aff, o);
socket_color(type, c);
const float r = NODE_SOCKSIZE * s;
bk_circle(x, y, r + BK_MAX(1.0f, bk_scale_fac), o);
@@ -553,7 +583,7 @@ static void link_ends(const BKNode *e, const Link *l, float *x0, float *y0, floa
static void editor_draw(BKNode *e)
{
float back[4];
- color_u(0x1d1d1dff, back); /* space_node.back */
+ color_u(0x1a1a1aff, back); /* space_node.back */
bk_fill_f((float)e->x, (float)e->y, (float)e->w, (float)e->h, back);
bk_clip_push(e->x, e->y, e->w, e->h);
draw_grid(e);
diff --git a/kit/intern/kit_widgets.c b/kit/intern/kit_widgets.c
index a817d82..e21efbd 100644
--- a/kit/intern/kit_widgets.c
+++ b/kit/intern/kit_widgets.c
@@ -1123,7 +1123,7 @@ const BKClass bk_cls_sidetabs = {.name = "sidetabs",
static int scroll_bar_w(void)
{
/* V2D_SCROLL_WIDTH: 0.45 units + 2 px */
- return bk_iround(0.45f * u() + 2.0f * bk_scale_fac);
+ return bk_iround(0.45f * u() + 2.0f * bk_px()); /* UI_view2d.hh */
}
static int scroll_content_h(BKNode *n)
@@ -1759,7 +1759,13 @@ static int number_from_text(BKNode *n, const char *s)
static void number_step(BKNode *n, int dir)
{
- bk_set_value(n, n->value + dir * n->step);
+ /* Ctrl+wheel: number fields step by their click step; sliders by a fixed
+ * 0.01 (floats) or 1 (ints), ui_do_but_SLI click == 2 */
+ double step = n->step;
+ if (n->cls == &bk_cls_slider) {
+ step = (n->flags & NF_INTEGER) ? 1.0 : 0.01;
+ }
+ bk_set_value(n, n->value + dir * step);
}
static void number_reset(BKNode *n, bool zero)
@@ -1972,7 +1978,8 @@ static int multi_drag(BKNode *n, BKEvent *e)
if (!ctx) {
return 0;
}
- const int threshold = BK_MAX(3, (int)(0.5f * u()));
+ /* DRAG_MULTINUM_THRESHOLD_DRAG_X: UI_UNIT_Y / 4 */
+ const int threshold = BK_MAX(3, (int)(0.25f * u()));
if (n->dragmode == 2) { /* collecting */
BKNode *under = bk_hit_at(ctx, n->x + n->w / 2, e->y);
if (under && under != n && is_number(under) && NODE_ENABLED(under) &&
@@ -2024,10 +2031,18 @@ static int number_drag(BKNode *n, BKEvent *e)
if (n->dragmode < 0) {
return 1; /* cancelled */
}
- if (n->dragmode == 0) { /* first motion decides: vertical = multi-drag */
+ if (n->dragmode == 0) { /* the gesture decides: vertical = multi-drag */
+ /* ui_numedit_but_NUM multi-drag init: decided once the drag is longer than
+ * DRAG_MULTINUM_THRESHOLD_DRAG_Y (UI_UNIT_Y / 4), vertical when
+ * |dot(dir, y)| > DRAG_MULTINUM_THRESHOLD_VERTICAL (0.75) */
+ const float len2 = (float)e->dx * e->dx + (float)e->dy * e->dy;
+ const float margin = 0.25f * u();
+ if (len2 <= margin * margin) {
+ return 1;
+ }
drag_origin(n, e);
BKContext *ctx = bk_ctx(n);
- if (ctx && abs(e->dy) > abs(e->dx)) {
+ if (ctx && (float)e->dy * e->dy > 0.75f * 0.75f * len2) {
n->dragmode = 2;
n->flags |= NF_SELECTED;
ctx->nmulti = 1;