From 9ae50fc735ee4c5f41d982ec7c50395bbf78d9ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:05:51 -0800 Subject: [PATCH 01/31] craft-mesh-ops: auto_unwrap checks limits first, leaves the mesh unchanged on error and packs in f64 auto_unwrap now checks the mesh before it changes anything. The size limits come first: at most 20 million vertices, and at most 4 million triangles counting a triangle once for each submesh that lists it. Then it checks indices, submesh ranges and materials, finite positions, finite normals and colors when present, and that a triangle is not listed by submeshes of two materials. Smooth normals are computed apart from the mesh, and the new arrays replace the mesh's only after the tangents and the final validation have passed, so any error leaves the mesh as it was. Charts are projected relative to the seed face's first corner and measured, rotated and packed in f64, and a face's plane comes from an f64 cross product, so small charts far from the origin keep their shape and the packing scale stays above zero. When the padding leaves no room for a positive scale, the packing square doubles. --- crates/mesh-ops/README.md | 4 +- crates/mesh-ops/src/unwrap.rs | 363 ++++++++++++++++++++++++++-------- 2 files changed, 281 insertions(+), 86 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index d7b1852d6a..22de3dd12b 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -11,7 +11,9 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form glTF 2.0 recommends for meshes without tangents (): `w` holds the bitangent sign. - **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting - vertices where charts meet. + vertices where charts meet. It checks the mesh against its size limits and its attribute data + first and returns an error without changing the mesh when a check fails. Charts are projected + and packed in `f64`. - **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle and barycentrics under the texel center; `surface_at` turns them into a position, normal and tangent frame. diff --git a/crates/mesh-ops/src/unwrap.rs b/crates/mesh-ops/src/unwrap.rs index 2f2eafc0a0..47b77fdcc5 100644 --- a/crates/mesh-ops/src/unwrap.rs +++ b/crates/mesh-ops/src/unwrap.rs @@ -8,10 +8,15 @@ use std::collections::{HashMap, VecDeque}; -use glam::{Vec2, Vec3}; +use glam::{DVec2, DVec3, Vec2, Vec3}; use crate::{GeomError, Mesh, Result}; +/// Vertices an unwrap accepts, and the most it produces. +const MAX_UNWRAP_VERTICES: usize = 20_000_000; +/// Triangles an unwrap accepts, counting a triangle once for each submesh that lists it. +const MAX_UNWRAP_TRIANGLES: usize = 4_000_000; + /// Faces of a chart stay within this angle of the seed face normal (cos 60°). const CHART_COS: f32 = 0.5; /// Packing never goes beyond this virtual resolution (texels per side). @@ -46,61 +51,142 @@ pub fn all_triangles_degenerate(mesh: &Mesh) -> bool { struct Chart { material: usize, + /// The seed face's first corner. Projections are taken relative to it, in `f64`, so they + /// keep the chart's own detail wherever the chart lies. + origin: DVec3, /// Projection basis (right-handed with the seed normal). - t: Vec3, - b: Vec3, + t: DVec3, + b: DVec3, /// Rotation to the chart's principal axes (cos, sin). - rot: Vec2, - lo: Vec2, - hi: Vec2, - /// Texel offset of the chart's packed rectangle and the material's scale and resolution. - offset: Vec2, + rot: DVec2, + /// Bounds of the rotated chart. Charts are measured and packed in `f64`, where the extent of + /// any chart of finite `f32` positions and the scale that packs it neither overflow nor + /// round to zero. + lo: DVec2, + hi: DVec2, + /// Texel offset of the chart's packed rectangle. + offset: DVec2, } impl Chart { - fn local(&self, p: Vec3) -> Vec2 { - let q = Vec2::new(p.dot(self.t), p.dot(self.b)); - Vec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x) + fn local(&self, p: Vec3) -> DVec2 { + let d = p.as_dvec3() - self.origin; + let q = DVec2::new(d.dot(self.t), d.dot(self.b)); + DVec2::new(q.x * self.rot.x - q.y * self.rot.y, q.x * self.rot.y + q.y * self.rot.x) } - fn size(&self) -> Vec2 { - (self.hi - self.lo).max(Vec2::ZERO) + fn size(&self) -> DVec2 { + (self.hi - self.lo).max(DVec2::ZERO) } } -/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its -/// own 0..1 space with charts at least `padding_texels` (minimum 1) away from each other and -/// the borders at `resolution`. Vertices are split at chart borders; tangents are recomputed. -/// Returns the number of charts. -pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result { +/// Area-weighted smooth normals over the index buffer, as [`Mesh::compute_normals`] computes +/// them, returned instead of stored. +fn smooth_normals(mesh: &Mesh) -> Vec { + let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; + for &[a, b, c] in mesh.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); + let (Some(pa), Some(pb), Some(pc)) = (mesh.positions.get(a), mesh.positions.get(b), mesh.positions.get(c)) else { continue }; + let face = (*pb - *pa).cross(*pc - *pa); + for v in [a, b, c] { + if let Some(x) = normals.get_mut(v) { + *x += face; + } + } + } + normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect() +} + +/// The checks [`auto_unwrap`] makes before it changes anything. The size limits come first. +fn check_input(mesh: &Mesh) -> Result<()> { + if mesh.positions.len() > MAX_UNWRAP_VERTICES { + return Err(GeomError::Invalid(format!("mesh has {} vertices; unwrapping accepts at most {MAX_UNWRAP_VERTICES}", mesh.positions.len()))); + } + if mesh.triangle_count() > MAX_UNWRAP_TRIANGLES { + return Err(GeomError::Invalid(format!("mesh has {} triangles; unwrapping accepts at most {MAX_UNWRAP_TRIANGLES}", mesh.triangle_count()))); + } + let listed = mesh.submeshes.iter().fold(0u64, |sum, s| sum.saturating_add(u64::from(s.count / 3))); + if listed > MAX_UNWRAP_TRIANGLES as u64 { + return Err(GeomError::Invalid(format!("submeshes list {listed} triangles; unwrapping accepts at most {MAX_UNWRAP_TRIANGLES}"))); + } mesh.validate_indices()?; + for s in &mesh.submeshes { + if u64::from(s.start) + u64::from(s.count) > mesh.indices.len() as u64 || s.material >= mesh.materials.len().max(1) { + return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); + } + } + if mesh.positions.iter().any(|p| !p.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite positions".into())); + } + if mesh.normals.len() == mesh.positions.len() && mesh.normals.iter().any(|v| !v.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite normals".into())); + } + if !mesh.colors.is_empty() && (mesh.colors.len() != mesh.positions.len() || mesh.colors.iter().any(|c| !c.is_finite())) { + return Err(GeomError::Invalid("mesh colors are not one finite color per vertex".into())); + } if all_triangles_degenerate(mesh) { return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into())); } - if mesh.normals.len() != mesh.positions.len() { - mesh.compute_normals(); + Ok(()) +} + +/// The material of every triangle. Each material is packed into its own 0..1 square, so a +/// triangle that submeshes of two materials list would be laid out over another chart of one of +/// them, and is an error. Triangles no submesh lists get material 0. +fn face_materials(mesh: &Mesh) -> Result> { + let n = mesh.triangle_count(); + let mut material = vec![usize::MAX; n]; + for s in &mesh.submeshes { + let end = (u64::from(s.start) + u64::from(s.count)) / 3; + for t in (s.start / 3) as usize..(end as usize).min(n) { + if let Some(m) = material.get_mut(t) { + if *m != usize::MAX && *m != s.material { + return Err(GeomError::Invalid(format!("triangle {t} is in submeshes of materials {} and {}", *m, s.material))); + } + *m = s.material; + } + } } + for m in &mut material { + if *m == usize::MAX { + *m = 0; + } + } + Ok(material) +} + +/// Replace the UVs of `mesh` with an automatic non-overlapping layout: each material gets its +/// own 0..1 space with charts at least `padding_texels` (minimum 1, which a NaN counts as) away +/// from each other and the borders at `resolution`. Vertices are split at chart borders; +/// tangents are recomputed. Returns the number of charts. +/// +/// A mesh that fails a check is returned unchanged: indices, submesh ranges and materials, no +/// triangle listed by submeshes of two materials, finite positions, finite normals and colors +/// when it has them, at least one triangle that is not degenerate, and the size limits (20 +/// million vertices; 4 million triangles, counting a triangle once for each submesh that lists +/// it). The limits are checked before any other work. More than 20 million new vertices is an +/// error as well. +pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Result { + check_input(mesh)?; + // Kept apart from the mesh until the layout is packed, so an error leaves the mesh as it was. + let computed_normals = if mesh.normals.len() != mesh.positions.len() { Some(smooth_normals(mesh)) } else { None }; + let old_normals = computed_normals.as_deref().unwrap_or(&mesh.normals); let n = mesh.triangle_count(); let weld = weld_ids(&mesh.positions); let pos = |v: usize| mesh.positions.get(v).copied().unwrap_or_default(); let wid = |v: usize| weld.get(v).copied().unwrap_or(u32::MAX); - // Face normals (None for degenerate faces) and materials. + // Face normals (None for degenerate faces) and materials. The cross products are taken in + // `f64` from the positions as given, where they neither overflow nor round to zero, so a + // small face far from the origin keeps its plane. let mut normal: Vec> = Vec::with_capacity(n); let mut area = Vec::with_capacity(n); for t in 0..n { - let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]); - let cr = (pos(b) - pos(a)).cross(pos(c) - pos(a)); + let [a, b, c] = mesh.tri(t).unwrap_or([0; 3]).map(|v| pos(v).as_dvec3()); + let cr = (b - a).cross(c - a); area.push(cr.length() * 0.5); - normal.push(cr.try_normalize()); - } - let mut material = vec![0usize; n]; - for s in &mesh.submeshes { - for t in (s.start / 3) as usize..((s.start as usize + s.count as usize) / 3) { - if let Some(m) = material.get_mut(t) { - *m = s.material; - } - } + normal.push(cr.try_normalize().map(|n| n.as_vec3())); } + let material = face_materials(mesh)?; // Manifold edge adjacency over welded vertices: edge → (face, face, count). let mut edges: HashMap<(u32, u32), (u32, u32, u8)> = HashMap::with_capacity(n * 2); @@ -138,7 +224,20 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res let id = charts.len() as u32; let sn = normal[seed].unwrap_or(Vec3::Z); let t = sn.any_orthonormal_vector(); - charts.push(Chart { material: material[seed], t, b: sn.cross(t), rot: Vec2::X, lo: Vec2::ZERO, hi: Vec2::ZERO, offset: Vec2::ZERO }); + let b = sn.cross(t); + // Relative to the seed's first corner, so the rounding of a projection follows the + // chart's size rather than its distance from the origin. + let origin = pos(mesh.tri(seed).unwrap_or([0; 3])[0]).as_dvec3(); + charts.push(Chart { + material: material[seed], + origin, + t: t.as_dvec3(), + b: b.as_dvec3(), + rot: DVec2::X, + lo: DVec2::ZERO, + hi: DVec2::ZERO, + offset: DVec2::ZERO, + }); chart_of[seed] = id; queue.push_back(seed); while let Some(f) = queue.pop_front() { @@ -154,30 +253,30 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res } } - // Principal axes and bounds of every chart. - let mut cov = vec![(Vec2::ZERO, [0.0f64; 3], 0usize); charts.len()]; + // Principal axes and bounds of every chart, in f64 from the positions as given. + let mut cov = vec![(DVec2::ZERO, [0.0f64; 3], 0usize); charts.len()]; for (t, &c) in chart_of.iter().enumerate() { let c = c as usize; for v in mesh.tri(t).unwrap_or([0; 3]) { if let (Some(ch), Some(acc)) = (charts.get(c), cov.get_mut(c)) { let q = ch.local(pos(v)); acc.0 += q; - acc.1[0] += (q.x * q.x) as f64; - acc.1[1] += (q.y * q.y) as f64; - acc.1[2] += (q.x * q.y) as f64; + acc.1[0] += q.x * q.x; + acc.1[1] += q.y * q.y; + acc.1[2] += q.x * q.y; acc.2 += 1; } } } for (ch, (sum, m, k)) in charts.iter_mut().zip(&cov) { let k = (*k).max(1) as f64; - let (mx, my) = (sum.x as f64 / k, sum.y as f64 / k); + let (mx, my) = (sum.x / k, sum.y / k); let (cxx, cyy, cxy) = (m[0] / k - mx * mx, m[1] / k - my * my, m[2] / k - mx * my); let angle = 0.5 * (2.0 * cxy).atan2(cxx - cyy); // Rotate so the principal axis lies along x. - ch.rot = Vec2::new((-angle).cos() as f32, (-angle).sin() as f32); - ch.lo = Vec2::splat(f32::MAX); - ch.hi = Vec2::splat(f32::MIN); + ch.rot = DVec2::new((-angle).cos(), (-angle).sin()); + ch.lo = DVec2::splat(f64::MAX); + ch.hi = DVec2::splat(f64::MIN); } for (t, &c) in chart_of.iter().enumerate() { let c = c as usize; @@ -192,10 +291,10 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res for ch in &mut charts { if ch.size().y > ch.size().x { // Quarter turn (x, y) → (y, −x) so shelves stay low. - ch.rot = Vec2::new(ch.rot.y, -ch.rot.x); + ch.rot = DVec2::new(ch.rot.y, -ch.rot.x); let (lo, hi) = (ch.lo, ch.hi); - ch.lo = Vec2::new(lo.y, -hi.x); - ch.hi = Vec2::new(hi.y, -lo.x); + ch.lo = DVec2::new(lo.y, -hi.x); + ch.hi = DVec2::new(hi.y, -lo.x); } } @@ -205,7 +304,7 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res let mats: std::collections::BTreeSet = charts.iter().map(|c| c.material).collect(); for m in mats { let ids: Vec = (0..charts.len()).filter(|i| charts[*i].material == m).collect(); - let sizes: Vec = ids.iter().map(|i| charts[*i].size()).collect(); + let sizes: Vec = ids.iter().map(|i| charts[*i].size()).collect(); let (s, res, offsets) = pack(&sizes, resolution.max(16) as f32, pad)?; for (i, o) in ids.iter().zip(offsets) { charts[*i].offset = o; @@ -219,47 +318,63 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res let mut indices = Vec::with_capacity(mesh.indices.len()); for (t, &c) in chart_of.iter().enumerate() { let Some(ch) = charts.get(c as usize) else { continue }; - let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0)); + let (s, res) = scale.get(&ch.material).copied().unwrap_or((0.0, 1.0f32)); for v in mesh.tri(t).unwrap_or([0; 3]) { let idx = *remap.entry((v as u32, c)).or_insert_with(|| { let q = ch.local(pos(v)); // Chart y points up; UV v points down the image. - let texel = ch.offset + Vec2::splat(pad) + Vec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s; + let texel = ch.offset + DVec2::splat(f64::from(pad)) + DVec2::new(q.x - ch.lo.x, ch.hi.y - q.y) * s; positions.push(pos(v)); - normals.push(mesh.normals.get(v).copied().unwrap_or(Vec3::Y)); + normals.push(old_normals.get(v).copied().unwrap_or(Vec3::Y)); if let Some(c) = mesh.colors.get(v) { colors.push(*c); } - uvs.push((texel / res).clamp(Vec2::ZERO, Vec2::ONE)); + uvs.push((texel / f64::from(res)).as_vec2().clamp(Vec2::ZERO, Vec2::ONE)); (positions.len() - 1) as u32 }); indices.push(idx); } + if positions.len() > MAX_UNWRAP_VERTICES { + return Err(GeomError::Invalid(format!("unwrapping would produce more than {MAX_UNWRAP_VERTICES} vertices"))); + } } - mesh.positions = positions; - mesh.normals = normals; - mesh.uvs = uvs; - mesh.colors = colors; - mesh.indices = indices; + let charts = charts.len(); + // The new arrays replace the mesh's only once the tangents and the final check have passed. + let old = ( + std::mem::replace(&mut mesh.positions, positions), + std::mem::replace(&mut mesh.normals, normals), + std::mem::replace(&mut mesh.uvs, uvs), + std::mem::replace(&mut mesh.colors, colors), + std::mem::replace(&mut mesh.indices, indices), + std::mem::take(&mut mesh.tangents), + ); mesh.compute_tangents(); - mesh.validate()?; - Ok(charts.len()) + if let Err(e) = mesh.validate() { + (mesh.positions, mesh.normals, mesh.uvs, mesh.colors, mesh.indices, mesh.tangents) = old; + return Err(e); + } + Ok(charts) } /// Shelf-pack rectangles of world `sizes` (each grown by `pad` texels per side) into a square of /// `res` texels with the largest uniform scale that fits. Returns (texels per world unit, -/// resolution used, texel offset per rectangle). The resolution doubles when the padding alone -/// cannot fit (very many charts), so the result always fits in 0..1. -fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec)> { +/// resolution used, texel offset per rectangle). The resolution doubles while the padding leaves +/// no room for a positive scale (very many charts, or padding as wide as the square), so the +/// result always fits in 0..1 and charts with a size keep it. The sizes and the scale are in +/// `f64`, where the scale of any chart of finite `f32` positions is finite and above zero. +fn pack(sizes: &[DVec2], mut res: f32, pad: f32) -> Result<(f64, f32, Vec)> { let mut order: Vec = (0..sizes.len()).collect(); order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y)); - let place = |s: f32, res: f32| -> Option> { - let mut out = vec![Vec2::ZERO; sizes.len()]; - let (mut x, mut y, mut shelf) = (0.0f32, 0.0f32, 0.0f32); + let mut out = vec![DVec2::ZERO; sizes.len()]; + let pad = f64::from(pad); + // Shelf-place every rectangle at scale `s` into `out`; false when they do not fit. + let place = |s: f64, res: f32, out: &mut [DVec2]| -> bool { + let res = f64::from(res); + let (mut x, mut y, mut shelf) = (0.0f64, 0.0f64, 0.0f64); for &i in &order { - let r = sizes[i] * s + Vec2::splat(2.0 * pad); + let r = sizes[i] * s + DVec2::splat(2.0 * pad); if r.x > res { - return None; + return false; } if x + r.x > res { y += shelf; @@ -267,36 +382,43 @@ fn pack(sizes: &[Vec2], mut res: f32, pad: f32) -> Result<(f32, f32, Vec)> shelf = 0.0; } if y + r.y > res { - return None; + return false; + } + if let Some(o) = out.get_mut(i) { + *o = DVec2::new(x, y); } - out[i] = Vec2::new(x, y); x += r.x; shelf = shelf.max(r.y); } - Some(out) + true }; - while place(0.0, res).is_none() { + let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f64, f64::max); + loop { + if place(0.0, res, &mut out) { + if largest <= 0.0 { + return Ok((0.0, res, out)); + } + // The largest scale that fits, by bisection; none above zero means a larger square. + let (mut lo, mut hi) = (0.0f64, (f64::from(res) - 2.0 * pad).max(0.0) / largest); + if hi > 0.0 && place(hi, res, &mut out) { + lo = hi; + } + for _ in 0..40 { + if hi - lo <= lo * 1e-4 { + break; + } + let mid = 0.5 * (lo + hi); + if place(mid, res, &mut out) { lo = mid } else { hi = mid } + } + if lo > 0.0 && place(lo, res, &mut out) { + return Ok((lo, res, out)); + } + } res *= 2.0; if res > MAX_PACK_RES { return Err(GeomError::Invalid("too many UV charts to pack".into())); } } - let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f32, f32::max); - if largest <= 0.0 { - return Ok((0.0, res, place(0.0, res).unwrap_or_default())); - } - let (mut lo, mut hi) = (0.0f32, (res - 2.0 * pad).max(0.0) / largest); - if place(hi, res).is_some() { - lo = hi; - } - for _ in 0..40 { - if hi - lo <= lo * 1e-4 { - break; - } - let mid = 0.5 * (lo + hi); - if place(mid, res).is_some() { lo = mid } else { hi = mid } - } - Ok((lo, res, place(lo, res).unwrap_or_default())) } impl Mesh { @@ -315,6 +437,8 @@ impl Mesh { #[cfg(test)] mod tests { + use glam::Vec4; + use super::*; use crate::{UvGBuffer, primitives}; @@ -381,4 +505,73 @@ mod tests { assert!(all_triangles_degenerate(&point)); assert!(auto_unwrap(&mut point, 4.0, 256).is_err()); } + + fn quad() -> Mesh { + let p = vec![Vec3::ZERO, Vec3::X, Vec3::new(1.0, 1.0, 0.0), Vec3::Y]; + Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2, 0, 2, 3], "m").unwrap() + } + + fn submesh(material: usize, start: u32, count: u32) -> crate::SubMesh { + crate::SubMesh { name: "s".into(), material, start, count } + } + + #[test] + fn rejected_meshes_are_left_unchanged() { + let mut two_materials = quad(); + two_materials.materials = vec!["a".into(), "b".into()]; + two_materials.submeshes = vec![submesh(0, 0, 6), submesh(1, 3, 3)]; + let mut nan_normal = quad(); + nan_normal.normals = vec![Vec3::INFINITY; 4]; + let mut short_colors = quad(); + short_colors.colors = vec![Vec4::ONE; 2]; + let mut range = quad(); + range.submeshes = vec![submesh(0, 6, 3)]; + let mut nan_position = quad(); + nan_position.positions[2] = Vec3::INFINITY; + for (name, mut m) in [ + ("two materials", two_materials), + ("infinite normal", nan_normal), + ("short colors", short_colors), + ("range", range), + ("infinite position", nan_position), + ] { + m.uvs.clear(); + let before = m.clone(); + assert!(auto_unwrap(&mut m, 4.0, 256).is_err(), "{name}"); + assert_eq!(m, before, "{name}"); + } + } + + #[test] + fn size_limits_are_checked_before_anything_else() { + // Indices out of range as well: the limit is the error reported. + let mut m = quad(); + m.indices = vec![0, 1, 9]; + m.submeshes = vec![submesh(0, 0, u32::MAX)]; + let before = m.clone(); + let message = auto_unwrap(&mut m, 4.0, 256).unwrap_err().to_string(); + assert!(message.contains("accepts at most"), "{message}"); + assert_eq!(m, before); + } + + #[test] + fn small_charts_far_from_the_origin_keep_their_shape() { + // A right triangle with 16-unit legs at 1e8, where an f32 position is 8 units apart. + let o = Vec3::splat(1e8); + let p = vec![o, o + Vec3::X * 16.0, o + Vec3::Y * 16.0]; + let mut m = Mesh::from_parts(p, None, Vec::new(), vec![0, 1, 2], "m").unwrap(); + auto_unwrap(&mut m, 4.0, 256).unwrap(); + let (a, b, c) = (m.uvs[m.indices[0] as usize], m.uvs[m.indices[1] as usize], m.uvs[m.indices[2] as usize]); + let (e1, e2) = (b - a, c - a); + assert!(e1.length() > 0.1 && (e1.length() - e2.length()).abs() < 1e-3, "legs {e1} and {e2}"); + assert!(e1.dot(e2).abs() < 1e-3, "legs {e1} and {e2} are not at a right angle"); + } + + #[test] + fn padding_that_fills_the_square_still_leaves_charts_a_size() { + let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, Vec::new(), vec![0, 1, 2], "m").unwrap(); + auto_unwrap(&mut m, 128.0, 256).unwrap(); + let (a, b, c) = (m.uvs[m.indices[0] as usize], m.uvs[m.indices[1] as usize], m.uvs[m.indices[2] as usize]); + assert!((b - a).length() > 1e-4 && (c - a).length() > 1e-4, "uvs {a} {b} {c}"); + } } From 94b5ddd71b3cde4190c3379ddd663142fd4563c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:06:46 -0800 Subject: [PATCH 02/31] Separate projected UV overlaps and preserve requested padding --- crates/mesh-ops/README.md | 4 +- crates/mesh-ops/src/unwrap.rs | 178 +++++++++---- crates/mesh-ops/src/unwrap/projection.rs | 309 +++++++++++++++++++++++ 3 files changed, 441 insertions(+), 50 deletions(-) create mode 100644 crates/mesh-ops/src/unwrap/projection.rs diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 22de3dd12b..9b6778fc29 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -13,7 +13,9 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form - **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting vertices where charts meet. It checks the mesh against its size limits and its attribute data first and returns an error without changing the mesh when a check fails. Charts are projected - and packed in `f64`. + and packed in `f64`. Overlapping projected interiors get separate charts. Padding uses the + requested resolution, with a minimum resolution of 16. A layout that cannot fit returns an + error without changing the mesh. - **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle and barycentrics under the texel center; `surface_at` turns them into a position, normal and tangent frame. diff --git a/crates/mesh-ops/src/unwrap.rs b/crates/mesh-ops/src/unwrap.rs index 47b77fdcc5..ef746eba4a 100644 --- a/crates/mesh-ops/src/unwrap.rs +++ b/crates/mesh-ops/src/unwrap.rs @@ -1,10 +1,9 @@ //! Automatic UV unwrapping for meshes imported without texture coordinates. //! //! Triangles are grouped into charts by flood fill across shared (welded) edges while each face -//! normal stays within 60° of the chart's seed face, so every chart is a height field over its -//! seed plane and projects onto it without flipping. Charts are rotated to their principal axes -//! and shelf-packed per material into 0..1 with one uniform scale, so texel density is the same -//! everywhere within a material. +//! normal stays within 60° of the chart's seed face. Faces whose projected interiors overlap +//! get separate charts. Charts are rotated to their principal axes and shelf-packed per material +//! into 0..1 with one uniform scale. Texel density is the same everywhere within a material. use std::collections::{HashMap, VecDeque}; @@ -12,6 +11,8 @@ use glam::{DVec2, DVec3, Vec2, Vec3}; use crate::{GeomError, Mesh, Result}; +mod projection; + /// Vertices an unwrap accepts, and the most it produces. const MAX_UNWRAP_VERTICES: usize = 20_000_000; /// Triangles an unwrap accepts, counting a triangle once for each submesh that lists it. @@ -19,19 +20,18 @@ const MAX_UNWRAP_TRIANGLES: usize = 4_000_000; /// Faces of a chart stay within this angle of the seed face normal (cos 60°). const CHART_COS: f32 = 0.5; -/// Packing never goes beyond this virtual resolution (texels per side). -const MAX_PACK_RES: f32 = 65_536.0; /// Welded vertex id per vertex: vertices at the same position (snapped to a grid of 1e-6 of /// the bounding diagonal) share an id. Ids are dense, in order of first appearance. pub fn weld_ids(positions: &[Vec3]) -> Vec { - let (lo, hi) = positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))); + let (lo, hi) = + positions.iter().map(|p| p.as_dvec3()).fold((DVec3::splat(f64::MAX), DVec3::splat(f64::MIN)), |(lo, hi), p| (lo.min(p), hi.max(p))); let cell = ((hi - lo).length() * 1e-6).max(1e-12); let mut map: HashMap<[i64; 3], u32> = HashMap::with_capacity(positions.len()); positions .iter() .map(|p| { - let q = ((*p - lo) / cell).round(); + let q = ((p.as_dvec3() - lo) / cell).round(); let next = map.len() as u32; *map.entry([q.x as i64, q.y as i64, q.z as i64]).or_insert(next) }) @@ -49,6 +49,7 @@ pub fn all_triangles_degenerate(mesh: &Mesh) -> bool { }) } +#[derive(Clone)] struct Chart { material: usize, /// The seed face's first corner. Projections are taken relative to it, in `f64`, so they @@ -110,6 +111,9 @@ fn check_input(mesh: &Mesh) -> Result<()> { } mesh.validate_indices()?; for s in &mesh.submeshes { + if !s.start.is_multiple_of(3) || !s.count.is_multiple_of(3) { + return Err(GeomError::Invalid(format!("submesh {} is not triangle-aligned", s.name))); + } if u64::from(s.start) + u64::from(s.count) > mesh.indices.len() as u64 || s.material >= mesh.materials.len().max(1) { return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); } @@ -131,7 +135,7 @@ fn check_input(mesh: &Mesh) -> Result<()> { /// The material of every triangle. Each material is packed into its own 0..1 square, so a /// triangle that submeshes of two materials list would be laid out over another chart of one of -/// them, and is an error. Triangles no submesh lists get material 0. +/// them, and is an error. Every triangle must be listed by a submesh. fn face_materials(mesh: &Mesh) -> Result> { let n = mesh.triangle_count(); let mut material = vec![usize::MAX; n]; @@ -146,10 +150,8 @@ fn face_materials(mesh: &Mesh) -> Result> { } } } - for m in &mut material { - if *m == usize::MAX { - *m = 0; - } + if material.contains(&usize::MAX) { + return Err(GeomError::Invalid("submeshes do not cover every triangle".into())); } Ok(material) } @@ -158,8 +160,11 @@ fn face_materials(mesh: &Mesh) -> Result> { /// own 0..1 space with charts at least `padding_texels` (minimum 1, which a NaN counts as) away /// from each other and the borders at `resolution`. Vertices are split at chart borders; /// tangents are recomputed. Returns the number of charts. +/// The effective resolution is at least 16. A layout that cannot fit with the requested +/// padding returns an error without changing the mesh. /// -/// A mesh that fails a check is returned unchanged: indices, submesh ranges and materials, no +/// A mesh that fails a check is returned unchanged: indices, triangle-aligned submesh ranges +/// that cover every triangle, materials, no /// triangle listed by submeshes of two materials, finite positions, finite normals and colors /// when it has them, at least one triangle that is not degenerate, and the size limits (20 /// million vertices; 4 million triangles, counting a triangle once for each submesh that lists @@ -253,6 +258,17 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res } } + let mut chart_faces = vec![Vec::new(); charts.len()]; + for (face, &chart) in chart_of.iter().enumerate() { + chart_faces[chart as usize].push(face); + } + for (chart, faces) in chart_faces.into_iter().enumerate() { + for face in projection::overlapping_faces(mesh, &charts[chart], &faces) { + chart_of[face] = charts.len() as u32; + charts.push(charts[chart].clone()); + } + } + // Principal axes and bounds of every chart, in f64 from the positions as given. let mut cov = vec![(DVec2::ZERO, [0.0f64; 3], 0usize); charts.len()]; for (t, &c) in chart_of.iter().enumerate() { @@ -301,9 +317,11 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res // Pack each material's charts into its own 0..1 square. let pad = padding_texels.max(1.0); let mut scale = HashMap::new(); - let mats: std::collections::BTreeSet = charts.iter().map(|c| c.material).collect(); - for m in mats { - let ids: Vec = (0..charts.len()).filter(|i| charts[*i].material == m).collect(); + let mut by_material: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (id, chart) in charts.iter().enumerate() { + by_material.entry(chart.material).or_default().push(id); + } + for (m, ids) in by_material { let sizes: Vec = ids.iter().map(|i| charts[*i].size()).collect(); let (s, res, offsets) = pack(&sizes, resolution.max(16) as f32, pad)?; for (i, o) in ids.iter().zip(offsets) { @@ -358,11 +376,10 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res /// Shelf-pack rectangles of world `sizes` (each grown by `pad` texels per side) into a square of /// `res` texels with the largest uniform scale that fits. Returns (texels per world unit, -/// resolution used, texel offset per rectangle). The resolution doubles while the padding leaves -/// no room for a positive scale (very many charts, or padding as wide as the square), so the -/// result always fits in 0..1 and charts with a size keep it. The sizes and the scale are in +/// resolution used, texel offset per rectangle). A layout without room for a positive scale +/// returns an error. The sizes and the scale are in /// `f64`, where the scale of any chart of finite `f32` positions is finite and above zero. -fn pack(sizes: &[DVec2], mut res: f32, pad: f32) -> Result<(f64, f32, Vec)> { +fn pack(sizes: &[DVec2], res: f32, pad: f32) -> Result<(f64, f32, Vec)> { let mut order: Vec = (0..sizes.len()).collect(); order.sort_by(|a, b| sizes[*b].y.total_cmp(&sizes[*a].y)); let mut out = vec![DVec2::ZERO; sizes.len()]; @@ -393,32 +410,26 @@ fn pack(sizes: &[DVec2], mut res: f32, pad: f32) -> Result<(f64, f32, Vec true }; let largest = sizes.iter().map(|s| s.max_element()).fold(0.0f64, f64::max); - loop { - if place(0.0, res, &mut out) { - if largest <= 0.0 { - return Ok((0.0, res, out)); - } - // The largest scale that fits, by bisection; none above zero means a larger square. - let (mut lo, mut hi) = (0.0f64, (f64::from(res) - 2.0 * pad).max(0.0) / largest); - if hi > 0.0 && place(hi, res, &mut out) { - lo = hi; - } - for _ in 0..40 { - if hi - lo <= lo * 1e-4 { - break; - } - let mid = 0.5 * (lo + hi); - if place(mid, res, &mut out) { lo = mid } else { hi = mid } - } - if lo > 0.0 && place(lo, res, &mut out) { - return Ok((lo, res, out)); - } + if place(0.0, res, &mut out) { + if largest <= 0.0 { + return Ok((0.0, res, out)); } - res *= 2.0; - if res > MAX_PACK_RES { - return Err(GeomError::Invalid("too many UV charts to pack".into())); + let (mut lo, mut hi) = (0.0f64, (f64::from(res) - 2.0 * pad).max(0.0) / largest); + if hi > 0.0 && place(hi, res, &mut out) { + lo = hi; + } + for _ in 0..40 { + if hi - lo <= lo * 1e-4 { + break; + } + let mid = 0.5 * (lo + hi); + if place(mid, res, &mut out) { lo = mid } else { hi = mid } + } + if lo > 0.0 && place(lo, res, &mut out) { + return Ok((lo, res, out)); } } + Err(GeomError::Invalid("UV charts cannot fit with the requested padding and resolution".into())) } impl Mesh { @@ -437,6 +448,70 @@ impl Mesh { #[cfg(test)] mod tests { + #[test] + fn tiny_coincident_sheets_keep_separate_charts() { + let side = 2.0f32.powi(-40); + let gap = Vec3::Z * 2.0f32.powi(-64); + let positions = vec![Vec3::ZERO, Vec3::X * side, Vec3::Y * side, gap, gap + Vec3::X * side, gap + Vec3::Y * side]; + let mut mesh = Mesh::from_parts(positions, None, Vec::new(), vec![0, 1, 2, 3, 4, 5], "sheets").unwrap(); + assert_eq!(auto_unwrap(&mut mesh, 4.0, 256).unwrap(), 2); + } + + #[test] + fn a_planar_fan_keeps_one_chart() { + let faces = 1024u32; + let mut positions = vec![Vec3::ZERO]; + for i in 0..faces { + let angle = i as f32 * std::f32::consts::TAU / faces as f32; + positions.push(Vec3::new(angle.cos(), angle.sin(), 0.0)); + } + let indices = (0..faces).flat_map(|i| [0, i + 1, (i + 1) % faces + 1]).collect(); + let mut mesh = Mesh::from_parts(positions, None, Vec::new(), indices, "fan").unwrap(); + assert_eq!(auto_unwrap(&mut mesh, 4.0, 256).unwrap(), 1); + } + + #[test] + fn incomplete_or_unaligned_submeshes_leave_the_layout_unchanged() { + let original = primitives::cube(1.0); + for variant in 0..3 { + let mut mesh = original.clone(); + match variant { + 0 => mesh.submeshes.clear(), + 1 => mesh.submeshes[0].count -= 3, + _ => { + mesh.submeshes[0].start = 1; + mesh.submeshes[0].count = 3; + } + } + let before = mesh.clone(); + assert!(auto_unwrap(&mut mesh, 4.0, 256).is_err(), "variant {variant}"); + assert_eq!(mesh, before); + } + } + + #[test] + fn packing_preserves_the_requested_resolution_and_border() { + assert!(pack(&[DVec2::ONE; 2000], 128.0, 4.0).is_err()); + assert!(pack(&[DVec2::ONE], 16.0, 8.0).is_err()); + let (_, resolution, offsets) = pack(&[DVec2::ONE; 2], 128.0, 4.0).unwrap(); + assert_eq!(resolution, 128.0); + assert_eq!((offsets[0].x + 4.0) / f64::from(resolution) * 128.0, 4.0); + } + + #[test] + fn weld_grid_keeps_distinct_extreme_positions() { + let positions = [Vec3::splat(-f32::MAX), Vec3::ZERO, Vec3::splat(f32::MAX)]; + assert_eq!(weld_ids(&positions), vec![0, 1, 2]); + } + + #[test] + fn nearby_welded_positions_do_not_hide_projected_overlap() { + let inside = 1.0 - 2.0f32.powi(-22); + let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * inside, Vec3::new(1.0, 1.0, 0.0), Vec3::Y * inside]; + let mut mesh = Mesh::from_parts(positions, None, Vec::new(), vec![0, 1, 2, 3, 4, 5], "nearby").unwrap(); + assert_eq!(auto_unwrap(&mut mesh, 4.0, 256).unwrap(), 2); + } + use glam::Vec4; use super::*; @@ -478,8 +553,7 @@ mod tests { } #[test] - fn many_tiny_charts_still_fit() { - // 2000 disconnected triangles: the packer grows its virtual resolution. + fn many_tiny_charts_require_room_at_the_requested_resolution() { let mut p = Vec::new(); let mut idx = Vec::new(); for i in 0..2000u32 { @@ -488,7 +562,10 @@ mod tests { idx.extend([i * 3, i * 3 + 1, i * 3 + 2]); } let mut m = Mesh::from_parts(p, None, Vec::new(), idx, "m").unwrap(); - auto_unwrap(&mut m, 4.0, 128).unwrap(); + let before = m.clone(); + assert!(auto_unwrap(&mut m, 4.0, 128).is_err()); + assert_eq!(m, before); + auto_unwrap(&mut m, 4.0, 512).unwrap(); assert!(m.uvs.iter().all(|uv| (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y))); } @@ -568,9 +645,12 @@ mod tests { } #[test] - fn padding_that_fills_the_square_still_leaves_charts_a_size() { + fn padding_that_fills_the_square_does_not_replace_the_mesh() { let mut m = Mesh::from_parts(vec![Vec3::ZERO, Vec3::X, Vec3::Y], None, Vec::new(), vec![0, 1, 2], "m").unwrap(); - auto_unwrap(&mut m, 128.0, 256).unwrap(); + let before = m.clone(); + assert!(auto_unwrap(&mut m, 128.0, 256).is_err()); + assert_eq!(m, before); + auto_unwrap(&mut m, 128.0, 512).unwrap(); let (a, b, c) = (m.uvs[m.indices[0] as usize], m.uvs[m.indices[1] as usize], m.uvs[m.indices[2] as usize]); assert!((b - a).length() > 1e-4 && (c - a).length() > 1e-4, "uvs {a} {b} {c}"); } diff --git a/crates/mesh-ops/src/unwrap/projection.rs b/crates/mesh-ops/src/unwrap/projection.rs new file mode 100644 index 0000000000..869a8ff4c4 --- /dev/null +++ b/crates/mesh-ops/src/unwrap/projection.rs @@ -0,0 +1,309 @@ +use glam::DVec2; + +use super::Chart; +use crate::Mesh; + +#[cfg(test)] +thread_local! { + static QUERY_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +struct Cone { + center: DVec2, + low: DVec2, + high: DVec2, + low_bound: f64, + high_bound: f64, +} + +struct Node { + lo: DVec2, + hi: DVec2, + range: std::ops::Range, + children: Option<(usize, usize)>, + cone: Option, + axis: DVec2, + local_lo: DVec2, + local_hi: DVec2, +} + +fn oriented_bounds(order: &[usize], triangles: &[[DVec2; 3]]) -> (DVec2, DVec2, DVec2) { + let center = order.iter().flat_map(|i| triangles[*i]).sum::() / (order.len() * 3) as f64; + let mut covariance = [0.0; 3]; + for p in order.iter().flat_map(|i| triangles[*i]) { + let d = p - center; + covariance[0] += d.x * d.x; + covariance[1] += d.y * d.y; + covariance[2] += d.x * d.y; + } + let angle = 0.5 * (2.0 * covariance[2]).atan2(covariance[0] - covariance[1]); + let axis = DVec2::new(angle.cos(), angle.sin()); + let (lo, hi) = order + .iter() + .flat_map(|i| triangles[*i]) + .map(|p| DVec2::new(axis.dot(p), axis.perp_dot(p))) + .fold((DVec2::splat(f64::MAX), DVec2::splat(f64::MIN)), |(lo, hi), p| (lo.min(p), hi.max(p))); + (axis, lo, hi) +} + +fn cone(order: &[usize], triangles: &[[DVec2; 3]]) -> Option { + let center = *triangles[*order.first()?].iter().find(|p| order.iter().all(|i| triangles[*i].contains(p)))?; + let directions = || order.iter().flat_map(|i| triangles[*i]).map(|p| p - center).filter(|p| *p != DVec2::ZERO); + let axis = directions().filter_map(|p| p.try_normalize()).sum::().try_normalize()?; + let mut low = (f64::MAX, DVec2::ZERO); + let mut high = (f64::MIN, DVec2::ZERO); + for p in directions() { + let angle = axis.perp_dot(p).atan2(axis.dot(p)); + if angle < low.0 { + low = (angle, p); + } + if angle > high.0 { + high = (angle, p); + } + } + (high.0 - low.0 < std::f64::consts::PI).then_some(Cone { center, low: low.1, high: high.1, low_bound: 0.0, high_bound: 0.0 }) +} + +fn supported_cone(order: &[usize], triangles: &[[DVec2; 3]], center: DVec2) -> Option { + let radius = order.iter().flat_map(|i| triangles[*i]).map(|p| (p - center).length_squared()).fold(0.0, f64::max); + let directions = || { + order.iter().flat_map(|i| { + let triangle = triangles[*i]; + let mut near = triangle[0]; + for p in &triangle[1..] { + if (*p - center).length_squared() < (near - center).length_squared() { + near = *p; + } + } + triangle.map(|p| p - near).into_iter().filter(move |p| p.length_squared() > radius * 0.25) + }) + }; + let axis = directions().filter_map(|p| p.try_normalize()).sum::().try_normalize()?; + let mut low = (f64::MAX, DVec2::ZERO); + let mut high = (f64::MIN, DVec2::ZERO); + for p in directions() { + let angle = axis.perp_dot(p).atan2(axis.dot(p)); + if angle < low.0 { + low = (angle, p); + } + if angle > high.0 { + high = (angle, p); + } + } + if high.0 - low.0 >= std::f64::consts::PI { + return None; + } + let low_bound = order.iter().flat_map(|i| triangles[*i]).map(|p| low.1.perp_dot(p - center)).fold(f64::MAX, f64::min); + let high_bound = order.iter().flat_map(|i| triangles[*i]).map(|p| high.1.perp_dot(p - center)).fold(f64::MIN, f64::max); + Some(Cone { center, low: low.1, high: high.1, low_bound, high_bound }) +} + +fn bounds(triangle: &[DVec2; 3]) -> (DVec2, DVec2) { + triangle.iter().fold((DVec2::splat(f64::MAX), DVec2::splat(f64::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))) +} + +fn projection_center(triangles: &[[DVec2; 3]]) -> DVec2 { + let (lo, hi) = triangles.iter().flatten().fold((DVec2::splat(f64::MAX), DVec2::splat(f64::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))); + let radius_squared = (hi - lo).length_squared() * 1e-12; + triangles[0] + .map(|candidate| { + let (count, sum) = triangles + .iter() + .flatten() + .filter(|p| (**p - candidate).length_squared() <= radius_squared) + .fold((0usize, DVec2::ZERO), |(count, sum), p| (count + 1, sum + *p)); + (count, sum / count as f64) + }) + .into_iter() + .max_by_key(|(count, _)| *count) + .map_or(DVec2::ZERO, |(_, center)| center) +} + +fn build(order: &mut [usize], offset: usize, triangles: &[[DVec2; 3]], nodes: &mut Vec, center: DVec2) -> usize { + let (lo, hi) = order + .iter() + .map(|i| bounds(&triangles[*i])) + .fold((DVec2::splat(f64::MAX), DVec2::splat(f64::MIN)), |(lo, hi), (a, b)| (lo.min(a), hi.max(b))); + let index = nodes.len(); + let (axis, local_lo, local_hi) = oriented_bounds(order, triangles); + nodes.push(Node { + lo, + hi, + range: offset..offset + order.len(), + children: None, + cone: cone(order, triangles).or_else(|| supported_cone(order, triangles, center)), + axis, + local_lo, + local_hi, + }); + if order.len() > 8 { + let axis = usize::from(hi.y - lo.y > hi.x - lo.x); + let centroid = |i: usize| triangles[i].iter().map(|p| p[axis]).sum::(); + let middle = order.len() / 2; + order.select_nth_unstable_by(middle, |a, b| centroid(*a).total_cmp(¢roid(*b))); + let (left, right) = order.split_at_mut(middle); + let a = build(left, offset, triangles, nodes, center); + let b = build(right, offset + middle, triangles, nodes, center); + nodes[index].children = Some((a, b)); + } + index +} + +fn intersects(a: &[DVec2; 3], b: &[DVec2; 3]) -> bool { + let area = |t: &[DVec2; 3]| (t[1] - t[0]).perp_dot(t[2] - t[0]); + if area(a) == 0.0 || area(b) == 0.0 { + return false; + } + for (triangle, other) in [(a, b), (b, a)] { + let positive = area(triangle) > 0.0; + for edge in 0..3 { + let d = triangle[(edge + 1) % 3] - triangle[edge]; + if other.iter().all(|p| { + let side = d.perp_dot(*p - triangle[edge]); + if positive { side <= 0.0 } else { side >= 0.0 } + }) { + return false; + } + } + } + true +} + +fn query(node: usize, face: usize, triangles: &[[DVec2; 3]], order: &[usize], nodes: &[Node]) -> bool { + #[cfg(test)] + QUERY_WORK.with(|work| work.set(work.get() + 1)); + let n = &nodes[node]; + let (lo, hi) = bounds(&triangles[face]); + if n.hi.x < lo.x || n.hi.y < lo.y || hi.x < n.lo.x || hi.y < n.lo.y { + return false; + } + let local = triangles[face].map(|p| DVec2::new(n.axis.dot(p), n.axis.perp_dot(p))); + let (lo, hi) = bounds(&local); + if n.local_hi.x < lo.x || n.local_hi.y < lo.y || hi.x < n.local_lo.x || hi.y < n.local_lo.y { + return false; + } + if let Some(c) = &n.cone { + let outside_low = triangles[face].iter().all(|p| c.low.perp_dot(*p - c.center) <= c.low_bound); + let outside_high = triangles[face].iter().all(|p| c.high.perp_dot(*p - c.center) >= c.high_bound); + if outside_low || outside_high { + return false; + } + } + match n.children { + Some((left, right)) => query(left, face, triangles, order, nodes) || query(right, face, triangles, order, nodes), + None => order[n.range.clone()].iter().any(|i| *i > face && intersects(&triangles[face], &triangles[*i])), + } +} + +pub(super) fn overlapping_faces(mesh: &Mesh, chart: &Chart, faces: &[usize]) -> Vec { + if faces.len() < 2 { + return Vec::new(); + } + let (source_faces, triangles): (Vec, Vec<[DVec2; 3]>) = faces + .iter() + .filter_map(|f| { + let t = mesh.tri(*f).unwrap_or([0; 3]).map(|i| chart.local(mesh.positions[i])); + ((t[1] - t[0]).perp_dot(t[2] - t[0]) != 0.0).then_some((*f, t)) + }) + .unzip(); + if triangles.len() < 2 { + return Vec::new(); + } + let mut order: Vec = (0..triangles.len()).collect(); + let mut nodes = Vec::new(); + let center = projection_center(&triangles); + let root = build(&mut order, 0, &triangles, &mut nodes, center); + (0..triangles.len()).filter(|face| query(root, *face, &triangles, &order, &nodes)).map(|face| source_faces[face]).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn nearly_welded_fan(count: usize) -> Vec<[DVec2; 3]> { + let point = |angle: f64, radius: f32| glam::Vec2::new(angle.cos() as f32 * radius, angle.sin() as f32 * radius).as_dvec2(); + (0..count) + .map(|index| { + let low = index as f64 * std::f64::consts::TAU / count as f64; + let high = (index + 1) as f64 * std::f64::consts::TAU / count as f64; + [point((low + high) * 0.5, 1e-8), point(low, 1.0), point(high, 1.0)] + }) + .collect() + } + + #[test] + fn nearly_welded_fan_has_bounded_query_work() { + let count = 10_000; + let triangles = nearly_welded_fan(count); + let positions: Vec<_> = triangles.iter().flatten().map(|p| p.as_vec2().extend(0.0)).collect(); + let ids = crate::unwrap::weld_ids(&positions); + assert!(ids.as_chunks::<3>().0.iter().all(|face| face[0] == ids[0])); + assert_bounded_query_work(&triangles); + } + + #[test] + fn exactly_welded_fan_has_bounded_query_work() { + let mut triangles = nearly_welded_fan(10_000); + for triangle in &mut triangles { + triangle[0] = DVec2::ZERO; + } + assert_bounded_query_work(&triangles); + } + + #[test] + fn nearly_welded_half_fan_has_bounded_query_work() { + let mut triangles = nearly_welded_fan(20_000); + for (index, triangle) in triangles.iter_mut().enumerate() { + triangle.rotate_left(index % 3); + } + for count in [2_500, 5_000, 10_000] { + assert_bounded_query_work(&triangles[..count]); + } + } + + fn assert_bounded_query_work(triangles: &[[DVec2; 3]]) { + let count = triangles.len(); + let mut order: Vec<_> = (0..count).collect(); + let mut nodes = Vec::new(); + let center = projection_center(triangles); + let root = build(&mut order, 0, triangles, &mut nodes, center); + QUERY_WORK.with(|work| work.set(0)); + for face in 0..count { + assert!(!query(root, face, triangles, &order, &nodes), "overlapping face {face}"); + let work = QUERY_WORK.with(|work| work.get()); + assert!(work <= count * 100, "query work {work} for {count} faces"); + } + println!("query work {} for {count} faces", QUERY_WORK.with(|work| work.get())); + } + + fn agrees_with_all_pairs(triangles: &[[DVec2; 3]]) { + let mut order: Vec<_> = (0..triangles.len()).collect(); + let mut nodes = Vec::new(); + let center = projection_center(triangles); + let root = build(&mut order, 0, triangles, &mut nodes, center); + for face in 0..triangles.len() { + let expected = (face + 1..triangles.len()).any(|other| intersects(&triangles[face], &triangles[other])); + assert_eq!(query(root, face, triangles, &order, &nodes), expected, "face {face}: {:?}", triangles[face]); + } + } + + #[test] + fn supported_planes_preserve_overlaps_and_boundary_contacts() { + let mut fan = nearly_welded_fan(256); + agrees_with_all_pairs(&fan); + fan[37] = fan[201]; + fan[38] = fan[101].map(|p| p * 0.75); + agrees_with_all_pairs(&fan); + for scale in [2.0f64.powi(-40), 1.0, 2.0f64.powi(40)] { + let shifted: Vec<_> = fan.iter().map(|triangle| triangle.map(|p| (p + DVec2::new(4.0, -8.0)) * scale)).collect(); + agrees_with_all_pairs(&shifted); + } + let mut state = 7u64; + let mut coordinate = || { + state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((state >> 32) % 65) as f64 - 32.0 + }; + let triangles: Vec<_> = (0..256).map(|_| std::array::from_fn(|_| DVec2::new(coordinate(), coordinate()))).collect(); + agrees_with_all_pairs(&triangles); + } +} From 3aa554d3a89235a7dd42495efa53c4f744213199 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 15:18:22 -0800 Subject: [PATCH 03/31] Describe face normal calculation without a precision guarantee --- crates/mesh-ops/src/unwrap.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/mesh-ops/src/unwrap.rs b/crates/mesh-ops/src/unwrap.rs index ef746eba4a..8780b10441 100644 --- a/crates/mesh-ops/src/unwrap.rs +++ b/crates/mesh-ops/src/unwrap.rs @@ -180,9 +180,7 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res let pos = |v: usize| mesh.positions.get(v).copied().unwrap_or_default(); let wid = |v: usize| weld.get(v).copied().unwrap_or(u32::MAX); - // Face normals (None for degenerate faces) and materials. The cross products are taken in - // `f64` from the positions as given, where they neither overflow nor round to zero, so a - // small face far from the origin keeps its plane. + // Face normals (None for degenerate faces) and materials. let mut normal: Vec> = Vec::with_capacity(n); let mut area = Vec::with_capacity(n); for t in 0..n { From 00cc98f8ea3fe270b89bbd322c45f98e0c9b15c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:46:20 -0800 Subject: [PATCH 04/31] Close primitive seams with identical boundary positions --- crates/mesh-ops/README.md | 2 + crates/mesh-ops/src/primitives.rs | 146 +++++++++++++++++++++++++++--- 2 files changed, 135 insertions(+), 13 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 160927896d..385da24f17 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -20,6 +20,8 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form return `Result`. They reject non-finite or nonpositive dimensions and dimensions whose doubled half extents overflow. A box bevel must be finite and between zero and 95% of its smallest half extent; an invalid bevel returns `GeomError::Invalid`. + Sphere and torus seam endpoints have identical positions and retain distinct UV endpoints. + Cylinder caps share exact rim positions with the side, and rounded-box faces share exact boundary positions. - **BVH.** `Bvh` is a binned SAH tree on all three axes with a median split when no split beats a leaf. It answers closest-hit, any-hit and filtered ray casts, nearest-point queries and box queries. diff --git a/crates/mesh-ops/src/primitives.rs b/crates/mesh-ops/src/primitives.rs index b48d637a19..006e51e71a 100644 --- a/crates/mesh-ops/src/primitives.rs +++ b/crates/mesh-ops/src/primitives.rs @@ -88,7 +88,8 @@ impl Builder { } } -/// UV sphere of `radius` centred at `center`. +/// A UV sphere of `radius` centered at the origin. The seam endpoints have identical positions +/// at each ring. Vertices at each pole share one position. pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh { let mut b = Builder::default(); sphere_into(&mut b, Vec3::ZERO, radius, segments.max(3), rings.max(2), UvRect::FULL); @@ -98,8 +99,14 @@ pub fn sphere(radius: f32, segments: usize, rings: usize) -> Mesh { fn sphere_into(b: &mut Builder, center: Vec3, radius: f32, segs: usize, rings: usize, r: UvRect) { b.grid(rings, segs, |i, j| { let (u, v) = (j as f32 / segs as f32, i as f32 / rings as f32); - let (theta, phi) = (v * PI, u * TAU + PI * 1.5); - let n = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + let (theta, phi) = (v * PI, if j == segs { PI * 1.5 } else { u * TAU + PI * 1.5 }); + let n = if i == 0 { + Vec3::Y + } else if i == rings { + -Vec3::Y + } else { + Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()) + }; (center + n * radius, n, r.map(u, v)) }); } @@ -153,7 +160,10 @@ fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: Uv v.push(inner * (2.0 * (i as f32 / kc as f32) - 1.0)); } for i in 1..=kb { - v.push(inner + bevel * (i as f32 / kb as f32)); + v.push(if i == kb { h } else { inner + bevel * (i as f32 / kb as f32) }); + } + for i in 0..v.len() / 2 { + v[i] = -v[v.len() - 1 - i]; } v }; @@ -167,7 +177,7 @@ fn rounded_box_into(b: &mut Builder, center: Vec3, half: Vec3, bevel: f32, r: Uv let (a, c) = (cu[j], cv[i]); let q = *n * hn + *u * a + *v * c; let clamped = q.clamp(-inner, inner); - let dir = (q - clamped).try_normalize().unwrap_or(*n); + let dir = (q - clamped).as_dvec3().try_normalize().map(|v| v.as_vec3()).unwrap_or(*n); let p = if bevel > 0.0 { clamped + dir * bevel } else { q }; let nn = if bevel > 0.0 { dir } else { *n }; (center + p, nn, cell.map((a + hu) / (2.0 * hu), (c + hv) / (2.0 * hv))) @@ -196,8 +206,7 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize let t = Vec2::new(next.0 - prev.0, next.1 - prev.1).try_normalize().unwrap_or(Vec2::NEG_Y); let n2 = Vec2::new(-t.y, t.x); let u = j as f32 / segs as f32; - let phi = u * TAU + PI * 1.5; - let dir = Vec3::new(phi.cos(), 0.0, -phi.sin()); + let dir = circle_sample(j, segs); let p = center + dir * rad + Vec3::Y * y; let n = dir * n2.x + Vec3::Y * n2.y; (p, n, r.map(u, len[i] / total)) @@ -331,14 +340,19 @@ fn preview_orb_radius(d: Vec3) -> f32 { radius + relief } +fn circle_sample(column: usize, segments: usize) -> Vec3 { + let angle = if column == segments { PI * 1.5 } else { column as f32 / segments as f32 * TAU + PI * 1.5 }; + Vec3::new(angle.cos(), 0.0, -angle.sin()) +} + /// A flat disk facing up (+Y) or down, with planar UVs inside `r`. fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { let n = if up { Vec3::Y } else { Vec3::NEG_Y }; let c = b.vert(center, n, r.map(0.5, 0.5)); let first = b.p.len() as u32; for j in 0..segs { - let a = j as f32 / segs as f32 * TAU; - let (x, z) = (a.cos(), a.sin()); + let sample = circle_sample(j, segs); + let (x, z) = (sample.x, sample.z); // Top view: +X right, +Z down the texture; bottom view mirrors X. let uv = if up { r.map(0.5 + x * 0.5, 0.5 + z * 0.5) } else { r.map(0.5 + x * 0.5, 0.5 - z * 0.5) }; b.vert(center + Vec3::new(x, 0.0, z) * radius, n, uv); @@ -346,9 +360,9 @@ fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, for j in 0..segs as u32 { let (a, bb) = (first + j, first + (j + 1) % segs as u32); if up { - b.idx.extend_from_slice(&[c, bb, a]); - } else { b.idx.extend_from_slice(&[c, a, bb]); + } else { + b.idx.extend_from_slice(&[c, bb, a]); } b.diag.push(0); } @@ -370,8 +384,8 @@ pub fn torus(major: f32, minor: f32, segs: usize, sides: usize) -> Mesh { let (segs, sides) = (segs.max(3), sides.max(3)); b.grid(sides, segs, |i, j| { let (u, v) = (j as f32 / segs as f32, i as f32 / sides as f32); - let phi = u * TAU + PI * 1.5; - let theta = v * TAU; + let phi = if j == segs { PI * 1.5 } else { u * TAU + PI * 1.5 }; + let theta = if i == sides { 0.0 } else { v * TAU }; let dir = Vec3::new(phi.cos(), 0.0, -phi.sin()); let n = dir * theta.cos() - Vec3::Y * theta.sin(); (dir * major + n * minor, n, Vec2::new(u, v)) @@ -503,6 +517,112 @@ pub const BUILTINS: [(&str, &str); 9] = [ #[cfg(test)] mod tests { + #[test] + fn rounded_box_face_boundaries_share_exact_positions() { + for (half, bevel) in [(1.038, 0.037), (1e21, 1e20)] { + let mut builder = Builder::default(); + rounded_box_into(&mut builder, Vec3::ZERO, Vec3::splat(half), bevel, UvRect::FULL); + assert!(builder.n[0].abs().min_element() > 0.5, "rounded corner normal {:?}, half={half}", builder.n[0]); + let key = |p: Vec3| p.to_array().map(|v| if v == 0.0 { 0 } else { v.to_bits() }); + let mut counts = std::collections::HashMap::new(); + for &position in &builder.p { + *counts.entry(key(position)).or_insert(0usize) += 1; + } + let side = 23; + for face in 0..6 { + for row in 0..side { + for column in 0..side { + if row == 0 || column == 0 || row == side - 1 || column == side - 1 { + let position = builder.p[face * side * side + row * side + column]; + assert!(counts[&key(position)] >= 2, "unmatched boundary {position:?}, half={half}"); + } + } + } + } + } + } + + #[test] + fn cylinder_caps_match_the_wall_at_every_segment_count() { + for segments in [3, 6, 7, 32] { + let mesh = cylinder(1.0, 2.0, segments); + for row in 0..=1 { + let (first, last) = (row * (segments + 1), row * (segments + 1) + segments); + assert_eq!(mesh.positions[first], mesh.positions[last]); + assert_eq!(mesh.normals[first], mesh.normals[last]); + assert!(mesh.uvs[first].x < mesh.uvs[last].x); + } + for y in [-1.0, 1.0] { + let wall: Vec<_> = mesh + .positions + .iter() + .zip(&mesh.normals) + .filter_map(|(position, normal)| (position.y == y && normal.y == 0.0).then_some(*position)) + .collect(); + let rim: Vec<_> = mesh + .positions + .iter() + .zip(&mesh.normals) + .filter_map(|(position, normal)| { + (position.y == y && normal.y != 0.0 && position.x * position.x + position.z * position.z > 0.5).then_some(*position) + }) + .collect(); + assert_eq!(rim.len(), segments); + assert!(rim.iter().all(|position| wall.contains(position)), "{segments} segments at height {y}: {rim:?} vs {wall:?}"); + } + } + } + + #[test] + fn sphere_poles_use_identical_endpoint_positions() { + for segments in [3, 7, 32] { + let rings = 8; + let mesh = sphere(1.0, segments, rings); + for (row, expected) in [(0, Vec3::Y), (rings, -Vec3::Y)] { + for column in 0..=segments { + let index = row * (segments + 1) + column; + assert_eq!(mesh.positions[index], expected); + assert_eq!(mesh.normals[index], expected); + } + } + } + } + + #[test] + fn sphere_geometry_closes_its_longitudinal_uv_seam_exactly() { + for segments in [3, 7, 32] { + let rings = 8; + let mesh = sphere(1.0, segments, rings); + let width = segments + 1; + for row in 0..=rings { + let (a, b) = (row * width, row * width + segments); + assert_eq!(mesh.positions[a], mesh.positions[b], "seam row {row}"); + assert_eq!(mesh.normals[a], mesh.normals[b], "seam normal row {row}"); + assert_eq!((mesh.uvs[a].x, mesh.uvs[b].x), (0.0, 1.0)); + } + } + } + + #[test] + fn torus_geometry_closes_both_uv_seams_exactly() { + for (segs, sides) in [(3, 3), (7, 5), (32, 12)] { + let mesh = torus(1.0, 0.35, segs, sides); + let width = segs + 1; + for row in 0..=sides { + let (a, b) = (row * width, row * width + segs); + assert_eq!(mesh.positions[a], mesh.positions[b], "u seam row {row}"); + assert_eq!(mesh.normals[a], mesh.normals[b], "u seam normal row {row}"); + assert_eq!((mesh.uvs[a].x, mesh.uvs[b].x), (0.0, 1.0)); + } + for col in 0..=segs { + let (a, b) = (col, sides * width + col); + assert_eq!(mesh.positions[a], mesh.positions[b], "v seam column {col}"); + assert_eq!(mesh.normals[a], mesh.normals[b], "v seam normal column {col}"); + assert_eq!((mesh.uvs[a].y, mesh.uvs[b].y), (0.0, 1.0)); + } + } + } + use super::*; #[test] From e7fd8f4dae8a2ce8236d737402698f8937d64914 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:10:26 -0800 Subject: [PATCH 05/31] Cover accepted small box dimensions --- crates/mesh-ops/src/primitives.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/mesh-ops/src/primitives.rs b/crates/mesh-ops/src/primitives.rs index 006e51e71a..09b21541bd 100644 --- a/crates/mesh-ops/src/primitives.rs +++ b/crates/mesh-ops/src/primitives.rs @@ -517,6 +517,17 @@ pub const BUILTINS: [(&str, &str); 9] = [ #[cfg(test)] mod tests { + #[test] + fn accepted_small_box_dimensions_are_preserved() { + let cube = cube(1e-7).unwrap(); + let (lo, hi) = cube.bounds(); + assert_eq!(hi - lo, Vec3::splat(1e-7)); + let half = Vec3::new(5e-8, 2e-7, 3e-7); + let mesh = rounded_box(half, 0.0).unwrap(); + let (lo, hi) = mesh.bounds(); + assert_eq!((lo, hi), (-half, half)); + } + #[test] fn rounded_box_face_boundaries_share_exact_positions() { for (half, bevel) in [(1.038, 0.037), (1e21, 1e20)] { From 5cf4d4f7643da332d0dacd2feb1f2faafa344707 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:19:07 -0800 Subject: [PATCH 06/31] Preserve missing UV unwrap normals at small and large scales --- crates/mesh-ops/README.md | 2 +- crates/mesh-ops/src/unwrap.rs | 14 +++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 9b6778fc29..2084fb0178 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -15,7 +15,7 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form first and returns an error without changing the mesh when a check fails. Charts are projected and packed in `f64`. Overlapping projected interiors get separate charts. Padding uses the requested resolution, with a minimum resolution of 16. A layout that cannot fit returns an - error without changing the mesh. + error without changing the mesh. Missing normals use area-weighted `f64` accumulation and normalization. - **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle and barycentrics under the texel center; `surface_at` turns them into a position, normal and tangent frame. diff --git a/crates/mesh-ops/src/unwrap.rs b/crates/mesh-ops/src/unwrap.rs index 8780b10441..7fef3a6971 100644 --- a/crates/mesh-ops/src/unwrap.rs +++ b/crates/mesh-ops/src/unwrap.rs @@ -83,18 +83,18 @@ impl Chart { /// Area-weighted smooth normals over the index buffer, as [`Mesh::compute_normals`] computes /// them, returned instead of stored. fn smooth_normals(mesh: &Mesh) -> Vec { - let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; + let mut normals = vec![DVec3::ZERO; mesh.positions.len()]; for &[a, b, c] in mesh.indices.as_chunks::<3>().0 { let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (mesh.positions.get(a), mesh.positions.get(b), mesh.positions.get(c)) else { continue }; - let face = (*pb - *pa).cross(*pc - *pa); + let face = (pb.as_dvec3() - pa.as_dvec3()).cross(pc.as_dvec3() - pa.as_dvec3()); for v in [a, b, c] { if let Some(x) = normals.get_mut(v) { *x += face; } } } - normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect() + normals.into_iter().map(|v| v.try_normalize().map(|normal| normal.as_vec3()).unwrap_or(Vec3::Y)).collect() } /// The checks [`auto_unwrap`] makes before it changes anything. The size limits come first. @@ -446,6 +446,14 @@ impl Mesh { #[cfg(test)] mod tests { + #[test] + fn missing_normals_keep_tiny_and_large_face_directions() { + for scale in [1e-25, 1e25] { + let mesh = Mesh { positions: vec![Vec3::ZERO, Vec3::Y * scale, Vec3::Z * scale], indices: vec![0, 1, 2], ..Mesh::default() }; + assert_eq!(smooth_normals(&mesh), vec![Vec3::X; 3], "scale={scale}"); + } + } + #[test] fn tiny_coincident_sheets_keep_separate_charts() { let side = 2.0f32.powi(-40); From 345dd20a27348859b4797da741622ade6bf4bd3e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 18:30:04 -0800 Subject: [PATCH 07/31] Preserve tiny UV chart edges and reject collinear input --- crates/mesh-ops/src/unwrap.rs | 60 +++++++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/crates/mesh-ops/src/unwrap.rs b/crates/mesh-ops/src/unwrap.rs index 7fef3a6971..03c0d12afc 100644 --- a/crates/mesh-ops/src/unwrap.rs +++ b/crates/mesh-ops/src/unwrap.rs @@ -26,7 +26,8 @@ const CHART_COS: f32 = 0.5; pub fn weld_ids(positions: &[Vec3]) -> Vec { let (lo, hi) = positions.iter().map(|p| p.as_dvec3()).fold((DVec3::splat(f64::MAX), DVec3::splat(f64::MIN)), |(lo, hi), p| (lo.min(p), hi.max(p))); - let cell = ((hi - lo).length() * 1e-6).max(1e-12); + let diagonal = (hi - lo).length(); + let cell = if diagonal > 0.0 && diagonal.is_finite() { diagonal * 1e-6 } else { 1.0 }; let mut map: HashMap<[i64; 3], u32> = HashMap::with_capacity(positions.len()); positions .iter() @@ -49,6 +50,33 @@ pub fn all_triangles_degenerate(mesh: &Mesh) -> bool { }) } +fn face_has_area(positions: [Vec3; 3]) -> bool { + (0..3).any(|axis| { + let next = (axis + 1) % 3; + let [a, b, c] = positions.map(|position| [f64::from(position[axis]), f64::from(position[next])]); + let products = [a[0] * b[1], b[0] * c[1], c[0] * a[1], -a[1] * b[0], -b[1] * c[0], -c[1] * a[0]]; + let (mut expansion, mut len) = ([0.0; 6], 0); + for mut value in products { + let mut kept = 0; + for index in 0..len { + let part = expansion[index]; + let sum = value + part; + let part_virtual = sum - value; + let value_virtual = sum - part_virtual; + let error = (value - value_virtual) + (part - part_virtual); + if error != 0.0 { + expansion[kept] = error; + kept += 1; + } + value = sum; + } + expansion[kept] = value; + len = kept + 1; + } + expansion[..len].iter().any(|part| *part != 0.0) + }) +} + #[derive(Clone)] struct Chart { material: usize, @@ -130,6 +158,11 @@ fn check_input(mesh: &Mesh) -> Result<()> { if all_triangles_degenerate(mesh) { return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into())); } + if !mesh.indices.is_empty() + && mesh.indices.as_chunks::<3>().0.iter().all(|vertices| !face_has_area(vertices.map(|vertex| mesh.positions[vertex as usize]))) + { + return Err(GeomError::Invalid("every triangle of the mesh is degenerate".into())); + } Ok(()) } @@ -329,7 +362,7 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res } // Rebuild vertices: one per (vertex, chart). - let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len() * 2); + let mut remap: HashMap<(u32, u32), u32> = HashMap::with_capacity(mesh.positions.len().saturating_mul(2).min(mesh.indices.len())); let (mut positions, mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); let mut indices = Vec::with_capacity(mesh.indices.len()); for (t, &c) in chart_of.iter().enumerate() { @@ -446,6 +479,29 @@ impl Mesh { #[cfg(test)] mod tests { + #[test] + fn tiny_quads_keep_their_shared_chart_edge() { + let mut mesh = quad(); + for position in &mut mesh.positions { + *position *= 2.0_f32.powi(-42); + } + assert_eq!(auto_unwrap(&mut mesh, 4.0, 16).unwrap(), 1); + assert_eq!(weld_ids(&[Vec3::ONE; 4]), vec![0; 4]); + } + + #[test] + fn nonempty_all_collinear_meshes_are_rejected_unchanged() { + for positions in [vec![Vec3::ZERO, Vec3::X, Vec3::X * 2.0], { + let d = Vec3::new(1.0, 17.0, 0.0); + vec![Vec3::ZERO, d * (3.0 * 2.0_f32.powi(-49)), d] + }] { + let mut mesh = Mesh::from_parts(positions, Some(vec![Vec3::Z; 3]), Vec::new(), vec![0, 1, 2], "m").unwrap(); + let before = mesh.clone(); + assert!(auto_unwrap(&mut mesh, 4.0, 256).is_err()); + assert_eq!(mesh, before); + } + } + #[test] fn missing_normals_keep_tiny_and_large_face_directions() { for scale in [1e-25, 1e25] { From f04f94b529fe59a583f86da909e282f56e3dd7b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 19:04:27 -0800 Subject: [PATCH 08/31] Preserve lathe UVs across finite profile scales --- crates/mesh-ops/README.md | 1 + crates/mesh-ops/src/primitives.rs | 37 ++++++++++++++++++++++++++----- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 385da24f17..20b59d2302 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -22,6 +22,7 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form smallest half extent; an invalid bevel returns `GeomError::Invalid`. Sphere and torus seam endpoints have identical positions and retain distinct UV endpoints. Cylinder caps share exact rim positions with the side, and rounded-box faces share exact boundary positions. + Lathe profile lengths and direction normalization use `f64` before the UVs and normals are stored as `f32`. - **BVH.** `Bvh` is a binned SAH tree on all three axes with a median split when no split beats a leaf. It answers closest-hit, any-hit and filtered ray casts, nearest-point queries and box queries. diff --git a/crates/mesh-ops/src/primitives.rs b/crates/mesh-ops/src/primitives.rs index 09b21541bd..9bfc17af1d 100644 --- a/crates/mesh-ops/src/primitives.rs +++ b/crates/mesh-ops/src/primitives.rs @@ -3,7 +3,7 @@ use std::f32::consts::{PI, TAU}; -use glam::{Vec2, Vec3}; +use glam::{DVec2, Vec2, Vec3}; use crate::mesh::{Mesh, SubMesh}; use crate::{GeomError, Result}; @@ -191,25 +191,28 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize if profile.len() < 2 { return; } - let mut len = vec![0.0f32]; + let mut len = vec![0.0f64]; for w in profile.windows(2) { - let d = Vec2::new(w[1].0 - w[0].0, w[1].1 - w[0].1).length(); + let d = DVec2::new(f64::from(w[1].0) - f64::from(w[0].0), f64::from(w[1].1) - f64::from(w[0].1)).length(); len.push(len.last().copied().unwrap_or(0.0) + d); } - let total = len.last().copied().unwrap_or(1.0).max(1e-6); + let total = len.last().copied().filter(|total| *total > 0.0).unwrap_or(1.0); let rows = profile.len() - 1; b.grid(rows, segs, |i, j| { let (rad, y) = profile[i]; // Profile tangent (downwards) → outward normal in the (r, y) plane. let prev = profile[i.saturating_sub(1)]; let next = profile[(i + 1).min(rows)]; - let t = Vec2::new(next.0 - prev.0, next.1 - prev.1).try_normalize().unwrap_or(Vec2::NEG_Y); + let t = DVec2::new(f64::from(next.0) - f64::from(prev.0), f64::from(next.1) - f64::from(prev.1)) + .try_normalize() + .map(|t| t.as_vec2()) + .unwrap_or(Vec2::NEG_Y); let n2 = Vec2::new(-t.y, t.x); let u = j as f32 / segs as f32; let dir = circle_sample(j, segs); let p = center + dir * rad + Vec3::Y * y; let n = dir * n2.x + Vec3::Y * n2.y; - (p, n, r.map(u, len[i] / total)) + (p, n, r.map(u, (len[i] / total) as f32)) }); } @@ -517,6 +520,28 @@ pub const BUILTINS: [(&str, &str); 9] = [ #[cfg(test)] mod tests { + #[test] + fn lathe_profile_uvs_are_independent_of_height() { + let side_range = |mesh: &Mesh| { + mesh.uvs + .iter() + .zip(&mesh.normals) + .filter(|(_, normal)| normal.y.abs() < 0.5) + .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), (uv, _)| (lo.min(uv.y), hi.max(uv.y))) + }; + let expected = side_range(&cylinder(1.0, 1.0, 16)); + let actual = side_range(&cylinder(1.0, 1e-20, 16)); + assert!((actual.0 - expected.0).abs() < 1e-6 && (actual.1 - expected.1).abs() < 1e-6, "{actual:?} {expected:?}"); + } + + #[test] + fn tall_cylinders_keep_finite_profile_uvs_and_unit_normals() { + let mesh = cylinder(1.0, 1e20, 16); + mesh.validate().unwrap(); + assert!(mesh.uvs.iter().all(|uv| uv.is_finite() && uv.min_element() >= 0.0 && uv.max_element() <= 1.0)); + assert!(mesh.normals.iter().all(|normal| normal.is_finite() && (normal.length_squared() - 1.0).abs() < 1e-5)); + } + #[test] fn accepted_small_box_dimensions_are_preserved() { let cube = cube(1e-7).unwrap(); From 461c12798e0ea9e9bf110e748aa855eb1383ace4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 21:13:35 -0800 Subject: [PATCH 09/31] Report only real UV seams at shared pole positions The sphere's pole vertices now share one position, so uv_seam_edges grouped every pole spoke with its neighbors and listed zero-length edges between pole vertices. It now skips edges between vertices at one position, and a triangle with two corners at one position joins its two other edges in UV space. The sphere reports only the meridian where u = 0 meets u = 1. --- crates/mesh-ops/src/mesh.rs | 68 +++++++++++++++++++++++++++++++------ 1 file changed, 58 insertions(+), 10 deletions(-) diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 77c993d3c6..58fe6db988 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -110,34 +110,69 @@ impl Mesh { .collect() } - /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)` + /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)`. + /// An edge between two vertices at one position is not listed, and a triangle with two corners at one position + /// connects its two other edges in UV space, as the corners of a pole row do. pub fn uv_seam_edges(&self) -> Vec> { // Signed zero denotes the same position on either side of an imported seam let bits = |position: Vec3| position.to_array().map(|coordinate| if coordinate == 0.0 { 0 } else { coordinate.to_bits() }); let mut seams = vec![Vec::new(); self.materials.len().max(1)]; // Match across materials before grouping the lines for texture-set visibility let mut sides: std::collections::HashMap> = std::collections::HashMap::new(); + // A triangle with two corners at one position joins its two edges to the third corner in UV space + let mut joins: std::collections::HashMap> = std::collections::HashMap::new(); + let canonical = |from: u32, to: u32, from_bits: [u32; 3], to_bits: [u32; 3]| { + if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) } + }; for material in 0..seams.len() { for triangle in self.triangles_of(material) { let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; + let Some(corner_bits) = + corners.iter().map(|&corner| self.positions.get(corner as usize).map(|p| bits(*p))).collect::>>() + else { + continue; + }; - for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] { - let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else { + for (a, b) in [(0, 1), (1, 2), (2, 0)] { + // An edge between two vertices at one position has no length to draw + if corner_bits[a] == corner_bits[b] { + let c = 3 - a - b; + if corner_bits[c] != corner_bits[a] { + let (edge, first) = canonical(corners[a], corners[c], corner_bits[a], corner_bits[c]); + let (_, second) = canonical(corners[b], corners[c], corner_bits[b], corner_bits[c]); + joins.entry(edge).or_default().push([first, second]); + } continue; - }; - - let (from_bits, to_bits) = (bits(*from_position), bits(*to_position)); - let (edge, pair) = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) }; + } + let (edge, pair) = canonical(corners[a], corners[b], corner_bits[a], corner_bits[b]); sides.entry(edge).or_default().push((pair.0, pair.1, material)); } } } let uv = |index: u32| self.uvs.get(index as usize).copied(); - for pairs in sides.into_values() { - let Some(&(first_from, first_to, _)) = pairs.first() else { continue }; + for (edge, pairs) in sides { + // Group the UV layouts of this edge, joining the layouts a collapsed triangle connects + let mut layouts = Vec::new(); + for &(from, to, _) in &pairs { + if !layouts.contains(&(uv(from), uv(to))) { + layouts.push((uv(from), uv(to))); + } + } + let mut group: Vec = (0..layouts.len()).collect(); + for [first, second] in joins.get(&edge).into_iter().flatten() { + let find = |(from, to): (u32, u32)| layouts.iter().position(|layout| *layout == (uv(from), uv(to))); + if let (Some(first), Some(second)) = (find(*first), find(*second)) { + let (kept, merged) = (group[first], group[second]); + for g in &mut group { + if *g == merged { + *g = kept; + } + } + } + } - if pairs.iter().any(|&(from, to, _)| (uv(from), uv(to)) != (uv(first_from), uv(first_to))) { + if group.iter().any(|&g| g != group[0]) { for (from, to, material) in pairs { if let Some(edges) = seams.get_mut(material) { edges.push((from.min(to), from.max(to))); @@ -564,6 +599,19 @@ mod tests { assert_eq!(mesh.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); } + #[test] + fn uv_seams_skip_edges_between_vertices_at_one_position() { + let (segments, rings) = (3, 2); + let mesh = crate::primitives::sphere(1.0, segments, rings); + let seams = mesh.uv_seam_edges(); + assert!( + seams[0].iter().all(|&(from, to)| mesh.positions[from as usize] != mesh.positions[to as usize]), + "zero-length seam edges at a pole: {seams:?}" + ); + // Only the meridian where u = 0 meets u = 1 is a seam: columns 0 and 3, with the collapsed pole triangles + assert_eq!(seams, vec![vec![(0, 4), (2, 7), (3, 7), (4, 8), (4, 9), (7, 11)]]); + } + #[test] fn uv_seams_between_materials_belong_to_both_materials() { let mut mesh = quad(); From 276a6f6e1993f73f6c677b3ee2e512a6d4139435 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:10:16 -0800 Subject: [PATCH 10/31] craft-mesh-ops: move projected-overlap chart splitting out of this change auto_unwrap no longer splits charts whose projected faces overlap. The projection module and its call site go to their own pull request, so this one keeps the limit checks, the unchanged mesh on error and the f64 packing. --- crates/mesh-ops/README.md | 2 +- crates/mesh-ops/src/unwrap.rs | 50 +--- crates/mesh-ops/src/unwrap/projection.rs | 309 ----------------------- 3 files changed, 4 insertions(+), 357 deletions(-) delete mode 100644 crates/mesh-ops/src/unwrap/projection.rs diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index 2084fb0178..cdaa2cbc9f 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -13,7 +13,7 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form - **UV unwrapping.** `unwrap::auto_unwrap` makes a non-overlapping layout per material, splitting vertices where charts meet. It checks the mesh against its size limits and its attribute data first and returns an error without changing the mesh when a check fails. Charts are projected - and packed in `f64`. Overlapping projected interiors get separate charts. Padding uses the + and packed in `f64`. Padding uses the requested resolution, with a minimum resolution of 16. A layout that cannot fit returns an error without changing the mesh. Missing normals use area-weighted `f64` accumulation and normalization. - **UV G-buffer.** `UvGBuffer` records, for each texel of one material's UV space, the triangle diff --git a/crates/mesh-ops/src/unwrap.rs b/crates/mesh-ops/src/unwrap.rs index 03c0d12afc..719c55246b 100644 --- a/crates/mesh-ops/src/unwrap.rs +++ b/crates/mesh-ops/src/unwrap.rs @@ -1,9 +1,9 @@ //! Automatic UV unwrapping for meshes imported without texture coordinates. //! //! Triangles are grouped into charts by flood fill across shared (welded) edges while each face -//! normal stays within 60° of the chart's seed face. Faces whose projected interiors overlap -//! get separate charts. Charts are rotated to their principal axes and shelf-packed per material -//! into 0..1 with one uniform scale. Texel density is the same everywhere within a material. +//! normal stays within 60° of the chart's seed face. Charts are rotated to their principal axes +//! and shelf-packed per material into 0..1 with one uniform scale. Texel density is the same +//! everywhere within a material. use std::collections::{HashMap, VecDeque}; @@ -11,8 +11,6 @@ use glam::{DVec2, DVec3, Vec2, Vec3}; use crate::{GeomError, Mesh, Result}; -mod projection; - /// Vertices an unwrap accepts, and the most it produces. const MAX_UNWRAP_VERTICES: usize = 20_000_000; /// Triangles an unwrap accepts, counting a triangle once for each submesh that lists it. @@ -77,7 +75,6 @@ fn face_has_area(positions: [Vec3; 3]) -> bool { }) } -#[derive(Clone)] struct Chart { material: usize, /// The seed face's first corner. Projections are taken relative to it, in `f64`, so they @@ -289,17 +286,6 @@ pub fn auto_unwrap(mesh: &mut Mesh, padding_texels: f32, resolution: u32) -> Res } } - let mut chart_faces = vec![Vec::new(); charts.len()]; - for (face, &chart) in chart_of.iter().enumerate() { - chart_faces[chart as usize].push(face); - } - for (chart, faces) in chart_faces.into_iter().enumerate() { - for face in projection::overlapping_faces(mesh, &charts[chart], &faces) { - chart_of[face] = charts.len() as u32; - charts.push(charts[chart].clone()); - } - } - // Principal axes and bounds of every chart, in f64 from the positions as given. let mut cov = vec![(DVec2::ZERO, [0.0f64; 3], 0usize); charts.len()]; for (t, &c) in chart_of.iter().enumerate() { @@ -510,28 +496,6 @@ mod tests { } } - #[test] - fn tiny_coincident_sheets_keep_separate_charts() { - let side = 2.0f32.powi(-40); - let gap = Vec3::Z * 2.0f32.powi(-64); - let positions = vec![Vec3::ZERO, Vec3::X * side, Vec3::Y * side, gap, gap + Vec3::X * side, gap + Vec3::Y * side]; - let mut mesh = Mesh::from_parts(positions, None, Vec::new(), vec![0, 1, 2, 3, 4, 5], "sheets").unwrap(); - assert_eq!(auto_unwrap(&mut mesh, 4.0, 256).unwrap(), 2); - } - - #[test] - fn a_planar_fan_keeps_one_chart() { - let faces = 1024u32; - let mut positions = vec![Vec3::ZERO]; - for i in 0..faces { - let angle = i as f32 * std::f32::consts::TAU / faces as f32; - positions.push(Vec3::new(angle.cos(), angle.sin(), 0.0)); - } - let indices = (0..faces).flat_map(|i| [0, i + 1, (i + 1) % faces + 1]).collect(); - let mut mesh = Mesh::from_parts(positions, None, Vec::new(), indices, "fan").unwrap(); - assert_eq!(auto_unwrap(&mut mesh, 4.0, 256).unwrap(), 1); - } - #[test] fn incomplete_or_unaligned_submeshes_leave_the_layout_unchanged() { let original = primitives::cube(1.0); @@ -566,14 +530,6 @@ mod tests { assert_eq!(weld_ids(&positions), vec![0, 1, 2]); } - #[test] - fn nearby_welded_positions_do_not_hide_projected_overlap() { - let inside = 1.0 - 2.0f32.powi(-22); - let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::X * inside, Vec3::new(1.0, 1.0, 0.0), Vec3::Y * inside]; - let mut mesh = Mesh::from_parts(positions, None, Vec::new(), vec![0, 1, 2, 3, 4, 5], "nearby").unwrap(); - assert_eq!(auto_unwrap(&mut mesh, 4.0, 256).unwrap(), 2); - } - use glam::Vec4; use super::*; diff --git a/crates/mesh-ops/src/unwrap/projection.rs b/crates/mesh-ops/src/unwrap/projection.rs deleted file mode 100644 index 869a8ff4c4..0000000000 --- a/crates/mesh-ops/src/unwrap/projection.rs +++ /dev/null @@ -1,309 +0,0 @@ -use glam::DVec2; - -use super::Chart; -use crate::Mesh; - -#[cfg(test)] -thread_local! { - static QUERY_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -struct Cone { - center: DVec2, - low: DVec2, - high: DVec2, - low_bound: f64, - high_bound: f64, -} - -struct Node { - lo: DVec2, - hi: DVec2, - range: std::ops::Range, - children: Option<(usize, usize)>, - cone: Option, - axis: DVec2, - local_lo: DVec2, - local_hi: DVec2, -} - -fn oriented_bounds(order: &[usize], triangles: &[[DVec2; 3]]) -> (DVec2, DVec2, DVec2) { - let center = order.iter().flat_map(|i| triangles[*i]).sum::() / (order.len() * 3) as f64; - let mut covariance = [0.0; 3]; - for p in order.iter().flat_map(|i| triangles[*i]) { - let d = p - center; - covariance[0] += d.x * d.x; - covariance[1] += d.y * d.y; - covariance[2] += d.x * d.y; - } - let angle = 0.5 * (2.0 * covariance[2]).atan2(covariance[0] - covariance[1]); - let axis = DVec2::new(angle.cos(), angle.sin()); - let (lo, hi) = order - .iter() - .flat_map(|i| triangles[*i]) - .map(|p| DVec2::new(axis.dot(p), axis.perp_dot(p))) - .fold((DVec2::splat(f64::MAX), DVec2::splat(f64::MIN)), |(lo, hi), p| (lo.min(p), hi.max(p))); - (axis, lo, hi) -} - -fn cone(order: &[usize], triangles: &[[DVec2; 3]]) -> Option { - let center = *triangles[*order.first()?].iter().find(|p| order.iter().all(|i| triangles[*i].contains(p)))?; - let directions = || order.iter().flat_map(|i| triangles[*i]).map(|p| p - center).filter(|p| *p != DVec2::ZERO); - let axis = directions().filter_map(|p| p.try_normalize()).sum::().try_normalize()?; - let mut low = (f64::MAX, DVec2::ZERO); - let mut high = (f64::MIN, DVec2::ZERO); - for p in directions() { - let angle = axis.perp_dot(p).atan2(axis.dot(p)); - if angle < low.0 { - low = (angle, p); - } - if angle > high.0 { - high = (angle, p); - } - } - (high.0 - low.0 < std::f64::consts::PI).then_some(Cone { center, low: low.1, high: high.1, low_bound: 0.0, high_bound: 0.0 }) -} - -fn supported_cone(order: &[usize], triangles: &[[DVec2; 3]], center: DVec2) -> Option { - let radius = order.iter().flat_map(|i| triangles[*i]).map(|p| (p - center).length_squared()).fold(0.0, f64::max); - let directions = || { - order.iter().flat_map(|i| { - let triangle = triangles[*i]; - let mut near = triangle[0]; - for p in &triangle[1..] { - if (*p - center).length_squared() < (near - center).length_squared() { - near = *p; - } - } - triangle.map(|p| p - near).into_iter().filter(move |p| p.length_squared() > radius * 0.25) - }) - }; - let axis = directions().filter_map(|p| p.try_normalize()).sum::().try_normalize()?; - let mut low = (f64::MAX, DVec2::ZERO); - let mut high = (f64::MIN, DVec2::ZERO); - for p in directions() { - let angle = axis.perp_dot(p).atan2(axis.dot(p)); - if angle < low.0 { - low = (angle, p); - } - if angle > high.0 { - high = (angle, p); - } - } - if high.0 - low.0 >= std::f64::consts::PI { - return None; - } - let low_bound = order.iter().flat_map(|i| triangles[*i]).map(|p| low.1.perp_dot(p - center)).fold(f64::MAX, f64::min); - let high_bound = order.iter().flat_map(|i| triangles[*i]).map(|p| high.1.perp_dot(p - center)).fold(f64::MIN, f64::max); - Some(Cone { center, low: low.1, high: high.1, low_bound, high_bound }) -} - -fn bounds(triangle: &[DVec2; 3]) -> (DVec2, DVec2) { - triangle.iter().fold((DVec2::splat(f64::MAX), DVec2::splat(f64::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))) -} - -fn projection_center(triangles: &[[DVec2; 3]]) -> DVec2 { - let (lo, hi) = triangles.iter().flatten().fold((DVec2::splat(f64::MAX), DVec2::splat(f64::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))); - let radius_squared = (hi - lo).length_squared() * 1e-12; - triangles[0] - .map(|candidate| { - let (count, sum) = triangles - .iter() - .flatten() - .filter(|p| (**p - candidate).length_squared() <= radius_squared) - .fold((0usize, DVec2::ZERO), |(count, sum), p| (count + 1, sum + *p)); - (count, sum / count as f64) - }) - .into_iter() - .max_by_key(|(count, _)| *count) - .map_or(DVec2::ZERO, |(_, center)| center) -} - -fn build(order: &mut [usize], offset: usize, triangles: &[[DVec2; 3]], nodes: &mut Vec, center: DVec2) -> usize { - let (lo, hi) = order - .iter() - .map(|i| bounds(&triangles[*i])) - .fold((DVec2::splat(f64::MAX), DVec2::splat(f64::MIN)), |(lo, hi), (a, b)| (lo.min(a), hi.max(b))); - let index = nodes.len(); - let (axis, local_lo, local_hi) = oriented_bounds(order, triangles); - nodes.push(Node { - lo, - hi, - range: offset..offset + order.len(), - children: None, - cone: cone(order, triangles).or_else(|| supported_cone(order, triangles, center)), - axis, - local_lo, - local_hi, - }); - if order.len() > 8 { - let axis = usize::from(hi.y - lo.y > hi.x - lo.x); - let centroid = |i: usize| triangles[i].iter().map(|p| p[axis]).sum::(); - let middle = order.len() / 2; - order.select_nth_unstable_by(middle, |a, b| centroid(*a).total_cmp(¢roid(*b))); - let (left, right) = order.split_at_mut(middle); - let a = build(left, offset, triangles, nodes, center); - let b = build(right, offset + middle, triangles, nodes, center); - nodes[index].children = Some((a, b)); - } - index -} - -fn intersects(a: &[DVec2; 3], b: &[DVec2; 3]) -> bool { - let area = |t: &[DVec2; 3]| (t[1] - t[0]).perp_dot(t[2] - t[0]); - if area(a) == 0.0 || area(b) == 0.0 { - return false; - } - for (triangle, other) in [(a, b), (b, a)] { - let positive = area(triangle) > 0.0; - for edge in 0..3 { - let d = triangle[(edge + 1) % 3] - triangle[edge]; - if other.iter().all(|p| { - let side = d.perp_dot(*p - triangle[edge]); - if positive { side <= 0.0 } else { side >= 0.0 } - }) { - return false; - } - } - } - true -} - -fn query(node: usize, face: usize, triangles: &[[DVec2; 3]], order: &[usize], nodes: &[Node]) -> bool { - #[cfg(test)] - QUERY_WORK.with(|work| work.set(work.get() + 1)); - let n = &nodes[node]; - let (lo, hi) = bounds(&triangles[face]); - if n.hi.x < lo.x || n.hi.y < lo.y || hi.x < n.lo.x || hi.y < n.lo.y { - return false; - } - let local = triangles[face].map(|p| DVec2::new(n.axis.dot(p), n.axis.perp_dot(p))); - let (lo, hi) = bounds(&local); - if n.local_hi.x < lo.x || n.local_hi.y < lo.y || hi.x < n.local_lo.x || hi.y < n.local_lo.y { - return false; - } - if let Some(c) = &n.cone { - let outside_low = triangles[face].iter().all(|p| c.low.perp_dot(*p - c.center) <= c.low_bound); - let outside_high = triangles[face].iter().all(|p| c.high.perp_dot(*p - c.center) >= c.high_bound); - if outside_low || outside_high { - return false; - } - } - match n.children { - Some((left, right)) => query(left, face, triangles, order, nodes) || query(right, face, triangles, order, nodes), - None => order[n.range.clone()].iter().any(|i| *i > face && intersects(&triangles[face], &triangles[*i])), - } -} - -pub(super) fn overlapping_faces(mesh: &Mesh, chart: &Chart, faces: &[usize]) -> Vec { - if faces.len() < 2 { - return Vec::new(); - } - let (source_faces, triangles): (Vec, Vec<[DVec2; 3]>) = faces - .iter() - .filter_map(|f| { - let t = mesh.tri(*f).unwrap_or([0; 3]).map(|i| chart.local(mesh.positions[i])); - ((t[1] - t[0]).perp_dot(t[2] - t[0]) != 0.0).then_some((*f, t)) - }) - .unzip(); - if triangles.len() < 2 { - return Vec::new(); - } - let mut order: Vec = (0..triangles.len()).collect(); - let mut nodes = Vec::new(); - let center = projection_center(&triangles); - let root = build(&mut order, 0, &triangles, &mut nodes, center); - (0..triangles.len()).filter(|face| query(root, *face, &triangles, &order, &nodes)).map(|face| source_faces[face]).collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - fn nearly_welded_fan(count: usize) -> Vec<[DVec2; 3]> { - let point = |angle: f64, radius: f32| glam::Vec2::new(angle.cos() as f32 * radius, angle.sin() as f32 * radius).as_dvec2(); - (0..count) - .map(|index| { - let low = index as f64 * std::f64::consts::TAU / count as f64; - let high = (index + 1) as f64 * std::f64::consts::TAU / count as f64; - [point((low + high) * 0.5, 1e-8), point(low, 1.0), point(high, 1.0)] - }) - .collect() - } - - #[test] - fn nearly_welded_fan_has_bounded_query_work() { - let count = 10_000; - let triangles = nearly_welded_fan(count); - let positions: Vec<_> = triangles.iter().flatten().map(|p| p.as_vec2().extend(0.0)).collect(); - let ids = crate::unwrap::weld_ids(&positions); - assert!(ids.as_chunks::<3>().0.iter().all(|face| face[0] == ids[0])); - assert_bounded_query_work(&triangles); - } - - #[test] - fn exactly_welded_fan_has_bounded_query_work() { - let mut triangles = nearly_welded_fan(10_000); - for triangle in &mut triangles { - triangle[0] = DVec2::ZERO; - } - assert_bounded_query_work(&triangles); - } - - #[test] - fn nearly_welded_half_fan_has_bounded_query_work() { - let mut triangles = nearly_welded_fan(20_000); - for (index, triangle) in triangles.iter_mut().enumerate() { - triangle.rotate_left(index % 3); - } - for count in [2_500, 5_000, 10_000] { - assert_bounded_query_work(&triangles[..count]); - } - } - - fn assert_bounded_query_work(triangles: &[[DVec2; 3]]) { - let count = triangles.len(); - let mut order: Vec<_> = (0..count).collect(); - let mut nodes = Vec::new(); - let center = projection_center(triangles); - let root = build(&mut order, 0, triangles, &mut nodes, center); - QUERY_WORK.with(|work| work.set(0)); - for face in 0..count { - assert!(!query(root, face, triangles, &order, &nodes), "overlapping face {face}"); - let work = QUERY_WORK.with(|work| work.get()); - assert!(work <= count * 100, "query work {work} for {count} faces"); - } - println!("query work {} for {count} faces", QUERY_WORK.with(|work| work.get())); - } - - fn agrees_with_all_pairs(triangles: &[[DVec2; 3]]) { - let mut order: Vec<_> = (0..triangles.len()).collect(); - let mut nodes = Vec::new(); - let center = projection_center(triangles); - let root = build(&mut order, 0, triangles, &mut nodes, center); - for face in 0..triangles.len() { - let expected = (face + 1..triangles.len()).any(|other| intersects(&triangles[face], &triangles[other])); - assert_eq!(query(root, face, triangles, &order, &nodes), expected, "face {face}: {:?}", triangles[face]); - } - } - - #[test] - fn supported_planes_preserve_overlaps_and_boundary_contacts() { - let mut fan = nearly_welded_fan(256); - agrees_with_all_pairs(&fan); - fan[37] = fan[201]; - fan[38] = fan[101].map(|p| p * 0.75); - agrees_with_all_pairs(&fan); - for scale in [2.0f64.powi(-40), 1.0, 2.0f64.powi(40)] { - let shifted: Vec<_> = fan.iter().map(|triangle| triangle.map(|p| (p + DVec2::new(4.0, -8.0)) * scale)).collect(); - agrees_with_all_pairs(&shifted); - } - let mut state = 7u64; - let mut coordinate = || { - state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - ((state >> 32) % 65) as f64 - 32.0 - }; - let triangles: Vec<_> = (0..256).map(|_| std::array::from_fn(|_| DVec2::new(coordinate(), coordinate()))).collect(); - agrees_with_all_pairs(&triangles); - } -} From 2d03e80203e8e9453a481223cc094da0dfd345d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:11:29 -0800 Subject: [PATCH 11/31] craft-mesh-ops: packing finds a positive scale far below its first guess pack() bisected at most 40 times down from the largest scale, so a layout whose feasible scale lay below that range (511^2 unit charts at resolution 1054 with padding just above 1) kept a lower bound of 0 and returned an error. It now halves the upper bound until a positive scale fits and refines from there, and still returns the error when no positive scale fits. --- crates/mesh-ops/src/unwrap.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/mesh-ops/src/unwrap.rs b/crates/mesh-ops/src/unwrap.rs index 719c55246b..ee76c6262b 100644 --- a/crates/mesh-ops/src/unwrap.rs +++ b/crates/mesh-ops/src/unwrap.rs @@ -432,9 +432,16 @@ fn pack(sizes: &[DVec2], res: f32, pad: f32) -> Result<(f64, f32, Vec)> { return Ok((0.0, res, out)); } let (mut lo, mut hi) = (0.0f64, (f64::from(res) - 2.0 * pad).max(0.0) / largest); - if hi > 0.0 && place(hi, res, &mut out) { - lo = hi; + // Halve the upper bound until a positive scale fits, so the refinement below starts + // from a feasible lower bound however far below the first guess the answer lies. + while hi > 0.0 { + if place(hi, res, &mut out) { + lo = hi; + break; + } + hi *= 0.5; } + hi = if lo > 0.0 { (2.0 * lo).min((f64::from(res) - 2.0 * pad).max(0.0) / largest) } else { hi }; for _ in 0..40 { if hi - lo <= lo * 1e-4 { break; @@ -524,6 +531,14 @@ mod tests { assert_eq!((offsets[0].x + 4.0) / f64::from(resolution) * 128.0, 4.0); } + #[test] + fn packing_finds_a_small_scale_far_below_the_first_guess() { + let pad = 1.0 + 262_657.0 / 8_388_608.0; + let (scale, _, _) = pack(&vec![DVec2::ONE; 511 * 511], 1054.0, pad as f32).unwrap(); + assert!(scale > 0.0); + assert!(pack(&vec![DVec2::ONE; 600 * 600], 1054.0, pad as f32).is_err()); + } + #[test] fn weld_grid_keeps_distinct_extreme_positions() { let positions = [Vec3::splat(-f32::MAX), Vec3::ZERO, Vec3::splat(f32::MAX)]; From bc1c6256b45847327c2d6c46b917861f052873a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:16:03 -0800 Subject: [PATCH 12/31] craft-mesh-ops: subdivision keeps polygon diagonals on the right child edges subdivided() copied the diagonal flags unchanged while replacing each triangle with four, so wire_edges read the parent's flags as flags of the first children and hid or showed the wrong edges. Each child now keeps the hidden bits of the parent-edge halves it has, and the edges inside the parent are real. --- crates/mesh-ops/src/mesh.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/mesh-ops/src/mesh.rs b/crates/mesh-ops/src/mesh.rs index 77c993d3c6..ad0f4516cb 100644 --- a/crates/mesh-ops/src/mesh.rs +++ b/crates/mesh-ops/src/mesh.rs @@ -401,14 +401,22 @@ impl Mesh { (m.positions.len() - 1) as u32 }) }; - for t in self.indices.as_chunks::<3>().0 { + // Each child keeps the hidden bits of the halves of the parent's edges it has; the edges + // inside the parent are real. + let mut diagonals = Vec::with_capacity(if self.diagonals.is_empty() { 0 } else { self.diagonals.len().saturating_mul(4) }); + for (k, t) in self.indices.as_chunks::<3>().0.iter().enumerate() { if t.iter().any(|&i| i as usize >= self.positions.len()) { continue; } let (a, b, c) = (t[0], t[1], t[2]); let (ab, bc, ca) = (mid(&mut m, a, b), mid(&mut m, b, c), mid(&mut m, c, a)); m.indices.extend_from_slice(&[a, ab, ca, ab, b, bc, ca, bc, c, ab, bc, ca]); + if !self.diagonals.is_empty() { + let h = self.diagonals.get(k).copied().unwrap_or(0); + diagonals.extend_from_slice(&[h & 0b101, h & 0b011, h & 0b110, 0]); + } } + m.diagonals = diagonals; for s in &mut m.submeshes { s.start *= 4; s.count *= 4; @@ -530,6 +538,12 @@ mod tests { a.append(&m); assert_eq!(a.diagonals, vec![0, 0b100, 0b001]); assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); + // Subdividing hides both halves of the diagonal and nothing else: 16 edges less 2. + let sub = m.subdivided(); + assert_eq!(sub.diagonals.len(), sub.triangle_count()); + let edges = &sub.wire_edges()[0]; + assert_eq!(edges.len(), 14); + assert!(edges.iter().all(|&(a, b)| !matches!((a, b), (0, 6) | (2, 6))), "diagonal halves {edges:?}"); } #[test] From f2b9450d82a311436c19735616014cb81ca42538 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 11:29:00 -0800 Subject: [PATCH 13/31] ui-shell: the title bar keeps an item gap between controls, and dropdown lists fit the window TitleBar puts space.gap.item between its leading controls (it used space.gap.row, 5 pt in the compact sizes), and show_fitted lays out the trailing controls at space.gap.item as well. Overlay::dropdown() sets the new Overlay::off_edge: an anchored dropdown stays space.pad.regular inside the window's edges, except where its field reaches nearer the edge. The fit's cap is still a share of the window. A content-sized collection whose rows run past its room ends on the last row that fits whole and scrolls the rest, so a Select list no longer ends part way through a row. The workspace switcher's doc comment says its commands are in the More options menu of the list's header. --- .../ui-contract/src/contract/items/hooks.rs | 20 +++++- .../src/contract/overlay/placement.rs | 18 ++++- .../ui-contract/src/contract/overlay/props.rs | 11 ++- .../ui-patterns/src/patterns/dock/switcher.rs | 6 +- .../tests/it/docking/workspace_dialogs.rs | 32 +++++++++ crates/ui-shell/src/shell/title_bar/bar.rs | 9 +-- crates/ui-shell/tests/it/shell/title_bar.rs | 43 ++++++++++++ .../tests/it/pickers/select_disabled_owner.rs | 3 +- .../tests/it/pickers/select_list.rs | 68 +++++++++++++++++++ 9 files changed, 196 insertions(+), 14 deletions(-) diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index d2d58f3264..8594db4c33 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -1329,9 +1329,27 @@ impl ItemsHooks<'_, '_, C> { // Under a body sized from its content along the height, the rows take up to the room, as a content-sized // collection's do: the body has no room of its own to hand it. Sizing::Fill | Sizing::FillHeight => Vec2::new(wide, if self.from_content.1 || self.capped { height.min(room.y) } else { 0.0 }), - Sizing::Content | Sizing::FillWidth => Vec2::new(wide, height.min(room.y)), + Sizing::Content | Sizing::FillWidth => Vec2::new(wide, self.whole_rows(height, room.y)), } } + + /// `height` within `room`: where the rows run past the room, the height down to the last row that fits whole, so + /// the collection ends on a whole row and scrolls the rest. A room too short for the first row is taken whole. + fn whole_rows(&self, height: f32, room: f32) -> f32 { + let len = self.source.len(); + let Some(layout) = self.layout.as_deref().filter(|_| height > room && len > 0) else { return height.min(room) }; + let rows = room - self.header.height; + let mut fit = 0.0; + // From the top of the content, an inset before the first row included. + for at in 0..len { + let bottom = layout.rect(at, ScrollPos::default()).max.y; + if bottom > rows + 0.5 { + break; + } + fit = bottom; + } + if fit > 0.0 { (fit + self.header.height).min(room) } else { room } + } } /// Whether a body around the collection, as its scope `env` names it, scrolls along the rows' overflow axis too: the diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index 1adfca1b63..896ec8d3a7 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -222,7 +222,21 @@ pub(crate) fn measuring_room( let bounds = screen_for(ctx, env, overlay); let resolved = resolve_anchor(ctx, id, overlay, own, own_to_screen); let anchor = resolved_anchor(ctx, overlay, resolved, bounds, inset, &mut MemoryStage::peek::(ctx, memory_slot(id)).pointer_at); - Some(content_room(overlay, covers, bounds, kept_in(overlay, resolved, bounds, inset), anchor, rtl)) + let kept = off_edge(overlay, kept_in(overlay, resolved, bounds, inset), anchor, inset); + Some(content_room(overlay, covers, bounds, kept, anchor, rtl)) +} + +/// The rect an anchored layer of `overlay` is placed in from the rect `bounds` it is kept in: for a layer that keeps +/// off the edges ([`Overlay::off_edge`]) `bounds` less `inset` on every side, widened to take in the part of its +/// `anchor` inside `bounds`, so a list still lines up with a control nearer the edge than `inset`. `bounds` when the +/// inset leaves no room, and for every other layer. The fit's cap stays a share of `bounds`. +fn off_edge(overlay: &Overlay, bounds: Rect, anchor: Rect, inset: f32) -> Rect { + let shrunk = bounds.shrink(inset); + if !overlay.off_edge || !shrunk.is_positive() { + return bounds; + } + let held = anchor.intersect(bounds); + if held.is_negative() { shrunk } else { shrunk.union(held) } } /// The most a layer's body may take: the fit's share of the safe rect `bounds`, at least as wide as the layer's @@ -280,7 +294,7 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Op let cap = cap(layer.overlay, bounds, anchor); match &layer.overlay.place { Place::Anchored { side, align, flips_across, offset, clear, .. } => { - let kept = layer_bounds(layer, bounds); + let kept = off_edge(layer.overlay, layer_bounds(layer, bounds), anchor, layer.env.tokens.space.pad.regular); let Some(size) = size else { let room = content_room(layer.overlay, covers, bounds, kept, anchor, rtl); return Placed { at: anchor.left_bottom().clamp(kept.min, kept.max), side: None, asked: None, room }; diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index 829e4e6974..73680ef899 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -166,6 +166,9 @@ pub struct Overlay { /// them shown, pressed or raised is on top, and the app's own egui windows stack with it. Unset, a `Rank::Popup` /// stands above every window instead; a collapsed dock column's flyout sets it. pub among_windows: bool, + /// Whether an anchored layer stays `space.pad.regular` inside the room it is kept in, except where its anchor + /// reaches nearer the edge: a dropdown list hung from a control near the window's edge. + pub off_edge: bool, /// Set only by [`Overlay::full_window`]. full_window: bool, } @@ -208,6 +211,7 @@ impl Overlay { continue_move: None, role: LayerRole::default(), among_windows: false, + off_edge: false, full_window: false, } } @@ -248,15 +252,16 @@ impl Overlay { overlay } - /// A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor. It - /// closes when a row is activated or the focus leaves the anchor. The opener's list keys go to the collection - /// [`Overlay::list`] names. + /// A dropdown list: from its content, at least as wide as its anchor and capped, focus stays on the anchor, and + /// `space.pad.regular` off the window's edges ([`Overlay::off_edge`]). It closes when a row is activated or the + /// focus leaves the anchor. The opener's list keys go to the collection [`Overlay::list`] names. pub fn dropdown() -> Overlay { let focus = FocusPolicy::POPUP.trap(false).restore(false).initial(Initial::KeepAnchor); let mut overlay = Overlay::base(Rank::Popup, Overlay::below(), OverlayFit::ContentCapped(DROPDOWN_SHARE), OwnerClass::PassivePopup, focus); overlay.dismiss = Dismiss::new().on_activate(true).focus_left(true); overlay.min_width = MinWidth::Anchor; overlay.popup = PopupKind::Listbox; + overlay.off_edge = true; overlay } diff --git a/crates/ui-patterns/src/patterns/dock/switcher.rs b/crates/ui-patterns/src/patterns/dock/switcher.rs index fc48ecb026..ff58fd9378 100644 --- a/crates/ui-patterns/src/patterns/dock/switcher.rs +++ b/crates/ui-patterns/src/patterns/dock/switcher.rs @@ -34,9 +34,9 @@ impl Outcome for WorkspaceSwitcherOutput { } /// The switcher at the end of an options bar: a small select showing the current workspace's name. Its list has the -/// built-in and saved workspaces, then Reset, New, Delete and Lock Workspace as the `WorkspaceCommands` rows. A row -/// fires its command, which the host takes with its other app commands and runs with `run_workspace`; the host -/// switches with `WorkspaceSet::select`. The switcher edits nothing. +/// built-in and saved workspaces, and the More options button in the list's header opens Reset, New, Delete and Lock +/// Workspace as the `WorkspaceCommands` rows. A row fires its command, which the host takes with its other app +/// commands and runs with `run_workspace`; the host switches with `WorkspaceSet::select`. The switcher edits nothing. #[must_use = "show the switcher with `show`"] #[derive(crate::contract::Pattern)] #[pattern(probe(WorkspaceSwitcher<'static, u32>))] diff --git a/crates/ui-patterns/tests/it/docking/workspace_dialogs.rs b/crates/ui-patterns/tests/it/docking/workspace_dialogs.rs index 44dd0c5b2c..6e13b13e79 100644 --- a/crates/ui-patterns/tests/it/docking/workspace_dialogs.rs +++ b/crates/ui-patterns/tests/it/docking/workspace_dialogs.rs @@ -126,3 +126,35 @@ fn the_switcher_lists_the_apps_command_rows_in_place_of_the_default_ones() { assert_eq!(switcher_rows(None), (true, true), "the default rows"); assert_eq!(switcher_rows(Some(vec![WorkspaceCommands::New.into()])), (false, true), "only the app's rows"); } + +/// A switcher over more workspaces than its list has room for ends its list on a whole row and scrolls the rest, +/// and its header menu button still opens the workspace commands. +#[trial] +fn a_long_switcher_list_ends_on_a_whole_row_and_keeps_its_commands() { + use craft_ui::contract::Role; + for height in [640.0, 700.0, 733.0, 811.0] { + let mut set: WorkspaceSet = WorkspaceSet::new(vec![NamedWorkspace::new("essentials", "Essentials", Workspace::default())]); + for at in 0..40 { + set.save(&format!("Workspace {at}"), Workspace::default(), WorkspaceChrome::default(), WorkspaceKeeps::NONE).unwrap(); + } + let mut fixture = Fixture::new(move |ui| { + let _ = WorkspaceSwitcher::new(&set).show(ui); + }); + fixture.room(Vec2::new(900.0, height)).settle(); + let select = fixture.by_label("Choose a workspace").expect("the switcher"); + fixture.click(&select).settle(); + let list = fixture.by_role(Role::LIST_BOX).first().expect("the switcher's list opens").rect; + let rows: Vec<_> = fixture.by_role(Role::LIST_BOX_OPTION).into_iter().map(|row| row.rect).collect(); + assert!(rows.len() < 41, "the list {list:?} scrolls at {height}"); + // A row cut off by an end of the list reaches past it, or reports only its shown part. The list opens + // scrolled to the current workspace, the last one. + let full = rows.iter().map(|row| row.height()).fold(0.0, f32::max); + for row in rows.iter().filter(|row| row.top() < list.bottom() - 0.5 && row.bottom() > list.top() + 0.5) { + let whole = row.top() >= list.top() - 0.5 && row.bottom() <= list.bottom() + 0.5 && row.height() >= full - 0.5; + assert!(whole, "a row {row:?} is cut off by an end of the list {list:?} in a window {height} high"); + } + let more = fixture.by_label("More options").expect("the list's header menu button"); + fixture.click(&more).settle(); + assert!(shows(&fixture, "New Workspace…"), "the header menu opens the workspace commands at {height}"); + } +} diff --git a/crates/ui-shell/src/shell/title_bar/bar.rs b/crates/ui-shell/src/shell/title_bar/bar.rs index a0b656fe69..ccee0f5d1e 100644 --- a/crates/ui-shell/src/shell/title_bar/bar.rs +++ b/crates/ui-shell/src/shell/title_bar/bar.rs @@ -64,7 +64,8 @@ impl Outcome for TitleBarOutput { /// A double click follows the desktop's setting (GNOME's `action-double-click-titlebar`), and elsewhere /// maximizes or restores. /// -/// An end with no caption buttons or lights keeps the content `space.pad.regular` off the window's edge. +/// An end with no caption buttons or lights keeps the content `space.pad.regular` off the window's edge. The leading +/// controls, and the trailing controls of a fitted bar, stand `space.gap.item` apart. /// /// In full screen the bar shows no captions and reserves no room. The free area is the container's move band: /// pressing and dragging it moves the window, and a double click acts as above. @@ -208,7 +209,7 @@ impl<'a> TitleBar<'a> { .surface(SurfaceKind::Chrome) .pad(Pad::None) .sizing(Sizing::FillWidth) - .body_gap(Gap::Row) + .body_gap(Gap::Item) .layout(BodyLayout::row()) .header(HeaderRegion::new().band(DragBand::Move).inline(true)) .end(EndRegion::new()); @@ -264,9 +265,9 @@ impl<'a> TitleBar<'a> { mut trailing: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'a, ) -> TitleBarOutput { self.props = self.props.end(EndRegion::new().fit(true)); - // The ranked members fit as units of the first row in the end region. + // The ranked members fit as units of the first row in the end region, `space.gap.item` apart. self.trailing(move |ui: &mut Ui, cx: &mut BodyCx<'_>| { - let _ = Row::new().show(ui, |ui, _| trailing(ui, cx)); + let _ = Row::new().gap(Gap::Item).show(ui, |ui, _| trailing(ui, cx)); }) .show(ui, leading) .output diff --git a/crates/ui-shell/tests/it/shell/title_bar.rs b/crates/ui-shell/tests/it/shell/title_bar.rs index 99e66d15b5..47b328775e 100644 --- a/crates/ui-shell/tests/it/shell/title_bar.rs +++ b/crates/ui-shell/tests/it/shell/title_bar.rs @@ -604,6 +604,49 @@ fn fitted(width: f32, direction: craft_i18n::Direction, fitted: bool) -> impl Fn move |label: &str| fixture.by_label(label).map(|node| node.rect) } +/// A fitted bar with a Home button and a menu bar at its start and two buttons at its end puts `space.gap.item` +/// between Home and the first menu title and between the two trailing buttons. +#[trial] +fn a_fitted_bar_keeps_its_controls_an_item_gap_apart() { + use craft_ui::buttons::Button; + use craft_ui::contract::{BodyCx, Show as _}; + use craft_ui::menu::MenuItem; + use craft_ui::menu::bar::{MenuBar, MenuTitle}; + use craft_ui::runtime::env::Env; + let item = Rc::new(Cell::new(0.0f32)); + let seen = Rc::clone(&item); + let mut fixture = Fixture::new(move |ui| { + seen.set(Env::of(ui).tokens.tokens().space.gap.item); + let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] }; + let frame = Frame::Integrated(Captions { family: CaptionFamily::Windows, layout }); + let leading = |ui: &mut Ui, _: &mut BodyCx<'_>| { + Button::new("Home").show(ui); + let titles = ["&File", "&Edit"] + .into_iter() + .map(|name| { + MenuTitle::new(name, |ui| { + MenuItem::new("Row").show(ui); + }) + }) + .collect(); + MenuBar::new("Main menu", titles).show(ui); + }; + let trailing = |ui: &mut Ui, _: &mut BodyCx<'_>| { + Button::new("Community").show(ui); + Button::new("Search").show(ui); + }; + let _ = TitleBar::new().frame(frame).show_fitted(ui, leading, trailing); + }); + fixture.room(vec2(1000.0, 80.0)).settle(); + let item = item.get(); + assert!(item > 0.0, "the theme has an item gap"); + let rect = |label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("{label} is shown")).rect; + let leading = rect("File").left() - rect("Home").right(); + assert!(leading >= item - 0.5, "Home and File stand {leading} apart, less than the item gap {item}"); + let trailing = rect("Search").left() - rect("Community").right(); + assert!(trailing >= item - 0.5, "Community and Search stand {trailing} apart, less than the item gap {item}"); +} + /// The leading button of the fitted bar trial: menus wider than the trailing content. const MENUS: &str = "File Edit Object Type Select Effect View Window Help"; diff --git a/crates/ui-widgets/tests/it/pickers/select_disabled_owner.rs b/crates/ui-widgets/tests/it/pickers/select_disabled_owner.rs index 5a25c1e607..e50ca0761e 100644 --- a/crates/ui-widgets/tests/it/pickers/select_disabled_owner.rs +++ b/crates/ui-widgets/tests/it/pickers/select_disabled_owner.rs @@ -48,7 +48,8 @@ fn held_popup_retires(disabled: &'static str) { fixture.room(Room::Window.size()).settle(); let trigger = *fixture.by_role(Role::COMBO_BOX).first().expect("the Select"); fixture.click(&trigger).settle(); - assert_eq!(fixture.tree().with_role(Role::LIST_BOX_OPTION).len(), 12, "the twelve options are open before the owner is disabled"); + // The list ends on its last whole row, so the window shows the options that fit and scrolls the rest. + assert!(!fixture.tree().with_role(Role::LIST_BOX_OPTION).is_empty(), "the options are open before the owner is disabled"); let option = fixture.by_label("Two").expect("the real second option"); fixture.press(&option); assert!(fixture.ctx().input(|input| input.pointer.primary_down()), "the real option press is still physically held"); diff --git a/crates/ui-widgets/tests/it/pickers/select_list.rs b/crates/ui-widgets/tests/it/pickers/select_list.rs index 0058cc4914..449fa1d247 100644 --- a/crates/ui-widgets/tests/it/pickers/select_list.rs +++ b/crates/ui-widgets/tests/it/pickers/select_list.rs @@ -14,6 +14,7 @@ use craft_ui::testing::input::{key_press, text}; use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, trial}; use egui::{Event, Key, Modifiers, Ui, Vec2}; use std::cell::Cell; +use std::rc::Rc; use std::sync::Arc; /// A select over One to Four. @@ -335,6 +336,73 @@ fn the_wheel_steps_the_open_select_a_line_an_entry_and_commits_when_it_stops() { assert_eq!(*value.borrow(), 4); } +/// What an open list shows: the window, the select's field, the popup, the list, its option rows and +/// `space.pad.regular`. +struct OpenList { + window: egui::Rect, + field: egui::Rect, + popup: egui::Rect, + list: egui::Rect, + rows: Vec, + pad: f32, +} + +/// The open list of a long select in a short window, whose list may be wider than the window. +fn opened_long_list(room: Vec2, list_width: Option) -> OpenList { + use craft_ui::runtime::env::Env; + let pad = Rc::new(Cell::new(0.0f32)); + let seen = Rc::clone(&pad); + let mut fixture = Fixture::new(move |ui| { + seen.set(Env::of(ui).tokens.tokens().space.pad.regular); + let entries: Vec> = (0..60u8).map(|at| Entry::new(at, format!("Item {at}"))).collect(); + let select = Select::new("Pick", Bind::given(0u8), &entries); + let _ = match list_width { + Some(width) => select.list_width(width), + None => select, + } + .show(ui); + }); + fixture.room(room).settle(); + fixture.key(Key::Tab, Modifiers::NONE); + fixture.key(Key::ArrowDown, Modifiers::ALT); + fixture.settle(); + let window = fixture.ctx().content_rect(); + let field = fixture.by_role(Role::COMBO_BOX).first().expect("the select's field").rect; + let list = fixture.by_role(Role::LIST_BOX).first().expect("Alt+Down opens the list").rect; + let rows = fixture.by_role(Role::LIST_BOX_OPTION).into_iter().map(|row| row.rect).collect(); + let layers = craft_ui::testing::snapshot::layer_rects(fixture.ctx()); + let popup = layers.into_iter().find(|layer| layer.contains_rect(list)).expect("the list's popup layer"); + OpenList { window, field, popup, list, rows, pad: pad.get() } +} + +/// A popup that asks to be as wide as the window or wider keeps `space.pad.regular` off the window's edges, except +/// where its field reaches nearer the edge than that. +#[trial] +fn a_long_list_keeps_a_margin_from_the_window_edges() { + for (room, wide) in [(Vec2::new(900.0, 640.0), None), (Vec2::new(900.0, 640.0), Some(2000.0)), (Vec2::new(1000.0, 700.0), Some(1000.0))] { + let OpenList { window, field, popup, pad, .. } = opened_long_list(room, wide); + assert!(pad > 0.0, "the theme has a regular pad"); + let inside = window.shrink(pad).union(field); + assert!(inside.expand(0.5).contains_rect(popup), "the popup {popup:?} in a {room:?} window keeps {pad} off its edges {window:?}"); + if wide.is_some() { + assert!(popup.right() <= window.right() - pad + 0.5, "the wide popup {popup:?} keeps {pad} off the window's end edge {window:?}"); + } + } +} + +/// A list too long for its popup ends on a whole row and scrolls the rest: no row is cut off at its bottom edge. +#[trial] +fn a_long_list_ends_on_a_whole_row() { + for height in [640.0, 700.0, 733.0, 811.0, 917.0] { + let OpenList { list, rows, .. } = opened_long_list(Vec2::new(900.0, height), None); + assert!(rows.len() < 60 || rows.iter().any(|row| row.top() >= list.bottom()), "the list scrolls in a window {height} high"); + for row in rows.iter().filter(|row| row.top() < list.bottom() - 0.5 && row.bottom() > list.top() + 0.5) { + let whole = row.top() >= list.top() - 0.5 && row.bottom() <= list.bottom() + 0.5; + assert!(whole, "a row {row:?} is cut off by an end of the list {list:?} in a window {height} high"); + } + } +} + /// The entry a long select holds. const HELD: u8 = 40; From cecd0b9ca3c171f13ced9280e1a6b81ddf8b77bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 11:49:09 -0800 Subject: [PATCH 14/31] ui-panels: the tool rail replays its grid with tips set and reads each tool's command once The rail's tips were keyed as changing every pass, so a rail with tips ran its whole slot grid in every frame. The grid's key now holds which tools have a tip and a new ToolTips::revision (0 unless the host sets it); a tip's body shows only while the pointer is over the rail, and the grid runs then. When the grid runs, it resolves each visible tool's command once and hands the results to the FlyoutButtons, which used to resolve every tool again in measure and in parts. A slot whose tools are all shown passes its own tools instead of a clone. Adds testing::last_pass_command_reads, which counts command-state reads per pass. --- .../ui-contract/src/runtime/commands/board.rs | 2 + crates/ui-contract/src/runtime/measure.rs | 13 +++ crates/ui-contract/src/testing/mod.rs | 6 +- crates/ui-panels/src/rails/flyout.rs | 20 +++-- crates/ui-panels/src/rails/tool.rs | 48 ++++++++-- crates/ui-panels/src/rails/tool/data.rs | 10 +++ crates/ui-panels/tests/it/rails/mod.rs | 1 + crates/ui-panels/tests/it/rails/work.rs | 90 +++++++++++++++++++ 8 files changed, 171 insertions(+), 19 deletions(-) create mode 100644 crates/ui-panels/tests/it/rails/work.rs diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index d04b9804ba..95b173950a 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -1548,6 +1548,8 @@ pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &Comma /// `command` as `reader` is shown it, noted as its read: the kept resolution while its inputs are unchanged, else a new /// one, kept. fn read(ctx: &Context, reader: Reader, command: &CommandRef) -> Arc { + #[cfg(feature = "testing")] + measure::count_command_read(ctx); // The resolved command carries the chord the keymap shows, kept or made now. crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); let viewport = pass::current_viewport(ctx); diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index ff9a453e7c..6c5b643088 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -420,6 +420,18 @@ pub fn last_pass_resolves(ctx: &Context, what: Resolve) -> u32 { last_totals(ctx, |log| log.resolves[what as usize], 0) } +/// Counts a reader's read of a command's state in this pass, kept or resolved. +#[cfg(feature = "testing")] +pub(crate) fn count_command_read(ctx: &Context) { + totals(ctx, |log| log.command_reads += 1); +} + +/// The reads of command states the readers of the last pass made, kept or resolved. +#[cfg(feature = "testing")] +pub fn last_pass_command_reads(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.command_reads, 0) +} + /// Counts a kept resolution a wake walked to compare its key. #[cfg(feature = "testing")] pub(crate) fn count_wake_walk(ctx: &Context) { @@ -535,6 +547,7 @@ pub(crate) struct Totals { access_builds: u32, tip_texts: u32, resolves: [u32; 3], + command_reads: u32, wake_walks: u32, asks: Vec<(&'static str, u32)>, } diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 42225ed3dd..673b8d4ce3 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -59,9 +59,9 @@ pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves; pub use crate::runtime::measure::{ MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_derived_builds, - last_frame_memo_runs, last_pass_access_builds, last_pass_body_runs as last_pass_measuring_runs, last_pass_derived_builds, last_pass_measure_asks, - last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, last_pass_tip_texts, least_runs as shrink_least_runs, - row_builds, row_measures, run as measuring_run, take_effects, widest_runs, + last_frame_memo_runs, last_pass_access_builds, last_pass_body_runs as last_pass_measuring_runs, last_pass_command_reads, + last_pass_derived_builds, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, + last_pass_tip_texts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs, }; #[cfg(feature = "testing")] pub use crate::runtime::pass_state::unbound_reads as unbound_pass_state_reads; diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index 97aa8e81ad..6218acc49a 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -18,6 +18,7 @@ use crate::style::{ComponentStyle, FocusLook, GlyphRole, StyleColor, StyleCx}; use craft_behavior::overlay::{Align, Side}; use craft_behavior::{CursorIcon, HitLevel, HitPriority, IconId, Metrics, PartKey, PointerButton, PressPhase, Sense, Value}; use egui::{Pos2, Rect, Response, Vec2}; +use std::sync::Arc; #[cfg(feature = "suite")] pub(crate) mod stories; @@ -102,9 +103,9 @@ struct Held(bool); /// What the parts step resolved for the tools this pass. struct Laid { - resolved: Vec>>, + resolved: Vec>>, /// The click command as resolved, when the button has one. - click: Option>, + click: Option>, shown: usize, } @@ -156,6 +157,10 @@ pub struct FlyoutButton<'a, T: Value + 'static> { /// The index of the tool among `tools` whose row wears the target mark while the flyout is open. #[prop(vis = "pub(crate)")] marked_row: Option, + /// The tools' commands as the rail resolved them in this pass, one per tool in order: the button shows these in + /// place of resolving each command again. + #[prop(vis = "pub(crate)")] + resolved: Option<&'a [Option>]>, laid: Option, picked: Option, open: bool, @@ -181,6 +186,7 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> { tips: None, reveal_row: None, marked_row: None, + resolved: None, laid: None, picked: None, open: false, @@ -222,11 +228,11 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> { } fn resolve(&self, cx: &MeasureCx<'_, Self>) -> Laid { - Laid { - resolved: self.tools.iter().map(|tool| cx.resolve_command(tool.command.clone())).collect(), - click: self.click.clone().and_then(|command| cx.resolve_command(command)), - shown: self.shown_at(), - } + let resolved = match self.resolved.filter(|resolved| resolved.len() == self.tools.len()) { + Some(resolved) => resolved.to_vec(), + None => self.tools.iter().map(|tool| cx.resolve_command(tool.command.clone())).collect(), + }; + Laid { resolved, click: self.click.clone().and_then(|command| cx.resolve_command(command)), shown: self.shown_at() } } /// The command the face stands for: the click command when there is one, else the shown tool's. diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index 54d207493a..d166af2cc3 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -14,7 +14,7 @@ use crate::docking::{DockGrid, DockSizes}; use crate::layout::RowAlign; use crate::layout_components::{Row, Stack}; use crate::runtime::access::Name; -use crate::runtime::commands::resolver_in; +use crate::runtime::commands::{ResolvedCommand, resolver_in}; use crate::runtime::env::{AppValues, EnvValue, Label}; use crate::style::{ComponentStyle, GlyphRole, StyleCx, SurfaceKind, TypeRole, UiTokens}; use crate::tabs::TornOff; @@ -22,8 +22,10 @@ use craft_behavior::overlay::Side; use craft_behavior::{IconId, Metrics, NavShape, Proposal, Roving, Sense, Value}; use craft_theme::ControlSize; use egui::{Id, Rect, Response, Ui, Vec2}; +use std::borrow::Cow; use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::sync::Arc; mod data; mod drag; @@ -320,10 +322,27 @@ struct GridProps<'a, T: PlainData> { sent: Outbox<'a, RailEvent>, } -/// The host's tool tips, which the grid reads through a trait object: while the host sets them the grid runs every pass. +/// The host's tool tips, which the grid reads through a trait object, keyed by which of the slots' tools have a tip and +/// by the host's revision of them. #[derive(MemoProps)] -#[memo_props(every_pass = "the host's tips are a trait object, whose answers no key can follow")] -struct HostTips<'a, T>(&'a dyn ToolTips); +struct HostTips<'a, T> { + #[memo_props( + covered_by = "has", + reason = "away from the pointer the grid reads only which tools have a tip; a tip's body shows only while the pointer rests on its button, and the view runs in every pass the pointer is over it" + )] + tips: &'a dyn ToolTips, + /// Whether each tool of the slots, in order, has a tip. + has: Vec, + revision: u64, +} + +impl<'a, T> HostTips<'a, T> { + /// The tips of `tips` for the tools of `slots`. + fn new(tips: &'a dyn ToolTips, slots: &[ToolSlot]) -> Self { + let has = slots.iter().flat_map(|slot| &slot.tools).map(|tool| tips.has(&tool.id)).collect(); + HostTips { tips, has, revision: tips.revision() } + } +} /// What the body of one pass draws from. struct Draw<'a, T: PlainData> { @@ -347,7 +366,7 @@ impl Draw<'_, T> { /// Shows the grid as a memoized view; what the buttons report goes into `events` (nothing on a replay). Returns the /// Edit Toolbar button's id while the rail shows it, and the host's index and rect of each slot button. fn run(&self, ui: &mut Ui, events: &mut Vec>) -> (Option, Vec<(usize, Rect)>) { - let tips = self.tips.map(HostTips); + let tips = self.tips.map(|tips| HostTips::new(tips, self.slots)); let props = GridProps { slots: self.slots, current: self.current, @@ -374,11 +393,13 @@ impl Draw<'_, T> { /// each slot button, around which the rail takes drops. fn grid(props: &mut GridProps<'_, T>, ui: &mut Ui) -> (Option, Vec<(usize, Rect)>) { let GridProps { slots, current, last_used, hidden, editing, columns, opens, captions, tear_off, tips, mark, reveal, .. } = *props; - let tips = tips.map(|tips| tips.0); + let tips = tips.map(|tips| tips.tips); let visible = visible_slots(slots, hidden_in(hidden)); let cells = visible.len() + usize::from(props.edit_label.is_some()); + // Each visible tool's command, resolved once for the pass: the buttons show these and read none again. let resolve = resolver_in(ui); - let enabled = |tool: &RailTool| resolve(tool.command.clone()).is_some_and(|resolved| resolved.enabled); + let commands: Vec>>> = + visible.iter().map(|(_, tools)| tools.iter().map(|tool| resolve(tool.command.clone())).collect()).collect(); let at: Vec = visible.iter().map(|(index, _)| *index).collect(); // The first caption among a group's slots heads the group. let caption_of = |group: &[usize]| { @@ -403,13 +424,22 @@ fn grid(props: &mut GridProps<'_, T>, ui: &mut match visible.get(k) { Some((index, tools)) => { let slot = &slots[*index]; - let owned: Vec> = tools.iter().map(|tool| (*tool).clone()).collect(); + let states = commands.get(k).map_or(&[][..], Vec::as_slice); + let on = |at: usize| states.get(at).and_then(Option::as_ref).is_some_and(|resolved| resolved.enabled); + let enabled = |tool: &RailTool| tools.iter().position(|own| std::ptr::eq(*own, tool)).is_some_and(on); + // The slot's own tools, unless the host hides some of them. + let owned: Cow<'_, [RailTool]> = if tools.len() == slot.tools.len() { + Cow::Borrowed(slot.tools.as_slice()) + } else { + Cow::Owned(tools.iter().map(|tool| (*tool).clone()).collect()) + }; let Some(shown) = shown_tool(current, slot.id, tools, last_used, enabled) else { continue }; let selected = tools.iter().any(|tool| tool.id == *current); let mut button = FlyoutButton::new(&owned, &shown.id) .id_salt(("slot", slot.id)) .selected(selected) - .enabled(tools.iter().any(|tool| enabled(tool))) + .enabled((0..tools.len()).any(on)) + .resolved(states) .opens(opens); if editing { button = button.edit(SlotEdit::new(slot.id, *index, slot.tools.len(), columns == 1)); diff --git a/crates/ui-panels/src/rails/tool/data.rs b/crates/ui-panels/src/rails/tool/data.rs index cb0a1ed593..ede56102da 100644 --- a/crates/ui-panels/src/rails/tool/data.rs +++ b/crates/ui-panels/src/rails/tool/data.rs @@ -74,12 +74,22 @@ impl ToolSlot { /// The tips of a rail's tools: where a tool `has` one, its button (and the flyout's row) shows it in place of the /// command tooltip. +/// +/// The rail's grid replays its last run while the pointer is away from it and its inputs are unchanged. Its key holds +/// which tools `has` a tip and the [`revision`](ToolTips::revision); a tip's body shows only while the pointer rests on +/// a button, and the grid runs in every pass the pointer is over it. pub trait ToolTips { /// Whether `tool` has a tip. fn has(&self, tool: &T) -> bool; /// Shows the tip of `tool`. fn show(&self, tool: &T, ui: &mut Ui); + + /// A number the host changes when a tip's body changes while the tip may show without the pointer over the rail. + /// `0` unless the host sets one. + fn revision(&self) -> u64 { + 0 + } } /// The tool each slot showed last. Plain data the host keeps with its workspace. diff --git a/crates/ui-panels/tests/it/rails/mod.rs b/crates/ui-panels/tests/it/rails/mod.rs index 75f5937b7d..feacf2f095 100644 --- a/crates/ui-panels/tests/it/rails/mod.rs +++ b/crates/ui-panels/tests/it/rails/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod drawer; pub(crate) mod locate; +pub(crate) mod work; use craft_behavior::{GesturePhase, Mixed, PartKey}; use craft_ui::contract::overlay::{PlacementChange, PlacementKind}; diff --git a/crates/ui-panels/tests/it/rails/work.rs b/crates/ui-panels/tests/it/rails/work.rs new file mode 100644 index 0000000000..38e38b60c5 --- /dev/null +++ b/crates/ui-panels/tests/it/rails/work.rs @@ -0,0 +1,90 @@ +//! The work a rail does in a pass: its grid replays while the pointer is away, tips included, and a grid that runs reads +//! each tool's command once. + +use super::{CUT, REDO, UNDO, tools}; +use craft_ui::contract::tooltip::DELAY; +use craft_ui::contract::{Role, Show as _, Tracked}; +use craft_ui::display::Text; +use craft_ui::rails::{LastUsed, ToolRail, ToolSlot, ToolTips}; +use craft_ui::testing::pointer::moved; +use craft_ui::testing::{Fixture, MemoRun, last_pass_command_reads, last_pass_memo_runs, trial}; +use egui::Ui; +use std::cell::Cell; +use std::rc::Rc; + +/// Undo's tip, while `on`. +struct Tips { + on: bool, +} + +impl ToolTips for Tips { + fn has(&self, tool: &u8) -> bool { + self.on && *tool == UNDO + } + + fn show(&self, _: &u8, ui: &mut Ui) { + Text::new("Steps back one edit").show(ui); + } +} + +/// A rail of two slots, Undo and Redo then Cut, with Undo's tip while `on` holds. +fn rig(on: Rc>) -> Fixture { + let slots = Tracked::new(vec![ToolSlot::new(0, tools(&[UNDO, REDO])), ToolSlot::new(1, tools(&[CUT]))]); + let last = Tracked::new(LastUsed::default()); + let mut fixture = Fixture::new(move |ui| { + let tips = Tips { on: on.get() }; + ToolRail::new("Tools", &slots, &UNDO, &last).tips(&tips).show_rail(ui, |_, _| {}); + }); + fixture.settle(); + fixture +} + +/// How the slot grid took part in the last pass: `(ran, replayed)`. +fn grid_runs(fixture: &Fixture) -> (u32, u32) { + let runs = last_pass_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, _)| name.contains("GridProps")); + runs.fold((0, 0), |(ran, replayed), (_, _, run)| match run { + MemoRun::Ran => (ran + 1, replayed), + MemoRun::Replayed => (ran, replayed + 1), + _ => (ran, replayed), + }) +} + +#[trial] +fn a_rail_with_tips_replays_its_grid_while_the_pointer_is_away_and_still_shows_the_tip() { + let on = Rc::new(Cell::new(true)); + let mut fixture = rig(Rc::clone(&on)); + fixture.frame(vec![]); + assert_eq!(grid_runs(&fixture), (0, 1), "with the pointer away and nothing changed, the grid replays"); + + let undo = fixture.by_role(Role::BUTTON).into_iter().next().expect("the Undo slot's button shows"); + fixture.frame(vec![moved(undo.center())]); + fixture.advance(DELAY); + fixture.settle(); + assert!(fixture.texts().iter().any(|run| run.text == "Steps back one edit"), "resting on Undo's button shows its tip"); + + // The grid runs on while the hover it ended winds down, about a second. + fixture.frame(vec![egui::Event::PointerGone]); + fixture.advance(2.0); + fixture.settle(); + fixture.frame(vec![]); + assert_eq!(grid_runs(&fixture), (0, 1), "once the pointer has left, the grid replays again"); + + on.set(false); + fixture.frame(vec![]); + assert_eq!(grid_runs(&fixture), (1, 0), "a change in which tools have a tip runs the grid"); +} + +#[trial] +fn a_grid_that_runs_reads_each_tool_command_once() { + let mut fixture = rig(Rc::new(Cell::new(false))); + let undo = fixture.by_role(Role::BUTTON).into_iter().next().expect("the Undo slot's button shows"); + fixture.frame(vec![moved(undo.center())]); + fixture.frame(vec![moved(undo.center() + egui::vec2(1.0, 0.0))]); + assert_eq!(grid_runs(&fixture).0, 1, "with the pointer over it, the grid runs"); + let reads = last_pass_command_reads(fixture.ctx()); + assert!(reads <= READS, "a pass of the grid reads {reads} command states, at most {READS}"); +} + +/// The command reads of a pass in which the grid runs: each of the 3 tools once, and those of the two buttons' faces. +/// A grid whose buttons resolve each tool again reads 18. +const READS: u32 = 9; From 93006634f43354930eb2cbfa02a6c2fc537a1594 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 12:07:34 -0800 Subject: [PATCH 15/31] dock: part of a collapsed column floats or docks expanded A group or panel taken out of a column collapsed to icons kept the column's collapsed state in its new column. A group dragged out of an icon column by its grip floated as a strip with a flyout: the tab names were cut off and a click on a tab did not switch the panel. A new column, floating or docked, now stays collapsed only when it holds the whole column it came from. When other panels stay behind, the new column is expanded. Groups that join an existing column still keep the source column's state, so their flyout widths are unchanged. An icon dragged out of a collapsed column that keeps other panels now starts a plain group drag, so the float preview and the window rect match the expanded window that the drop makes. --- crates/behavior/src/dock/edit.rs | 12 +++-- crates/behavior/src/dock/groups.rs | 26 +++++++--- crates/behavior/src/dock/inner.rs | 21 ++++---- crates/behavior/tests/dock_apply.rs | 38 ++++++++++---- crates/ui-panels/src/docking/iconic.rs | 19 +++++-- .../ui-patterns/tests/it/docking/columns.rs | 52 ++++++++++++++++++- 6 files changed, 134 insertions(+), 34 deletions(-) diff --git a/crates/behavior/src/dock/edit.rs b/crates/behavior/src/dock/edit.rs index 2184f141dd..a94b3c5554 100644 --- a/crates/behavior/src/dock/edit.rs +++ b/crates/behavior/src/dock/edit.rs @@ -449,8 +449,9 @@ impl Layout

{ return Err(DockError::MissingPanel); } let taken = column.groups.remove(group); + let part = !column.groups.is_empty(); let id = self.drop_if_empty(&place); - return Ok(Moving { id, ..Moving::taken(taken, source) }); + return Ok(Moving { id, part, ..Moving::taken(taken, source) }); }; if let Some(Node::Stack { entries }) = self.node_of_mut(&place) && entries.len() > 1 @@ -478,14 +479,14 @@ impl Layout

{ if columns.is_empty() { self.take_node(&path); } - Ok(Moving { column: taken, id: None }) + Ok(Moving { column: taken, id: None, part: false }) } Some(PanelPlace::Floating { window, .. }) => { if window >= self.floating.len() { return Err(DockError::MissingPanel); } let taken = self.floating.remove(window); - Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id) }) + Ok(Moving { column: Column { width: Some(taken.rect.width()), ..taken.column }, id: Some(taken.id), part: false }) } Some(PanelPlace::Node(_)) | None => Err(DockError::InvalidPlacement), } @@ -500,7 +501,8 @@ impl Layout

{ } /// Insert groups taken by [`Self::take_unit`] (or a new single-panel group). A new column, docked or floating, - /// keeps the moving column's state; groups that join a column take that column's. + /// keeps the moving column's state, expanded when they are part of a collapsed column; groups that join a column + /// take that column's. /// `canvas` is the protected-panel test an outer edge drop narrows by ([`Self::edge_path`]). pub(super) fn insert_moving(&mut self, moving: Moving

, to: Target

, canvas: &dyn Fn(&P) -> bool) -> Result<(), DockError> { let mut moving = moving; @@ -517,7 +519,7 @@ impl Layout

{ Some(id) => id, None => self.fresh_window_id(), }; - let window = Floating::new(id, Column { width: None, ..moving.column }, rect); + let window = Floating::new(id, moving.into_window_column(), rect); let edge = edge.filter(|_| window.column.iconic); self.floating.push(Floating { edge, ..window }); Ok(()) diff --git a/crates/behavior/src/dock/groups.rs b/crates/behavior/src/dock/groups.rs index a05570c53e..4ff36d0f16 100644 --- a/crates/behavior/src/dock/groups.rs +++ b/crates/behavior/src/dock/groups.rs @@ -330,12 +330,14 @@ pub(super) enum Unit { } /// Groups in transit, in a column that carries the state of the column they came from: a new column, docked or -/// floating, keeps that state (an icon group taken out of a collapsed column stays icons), and a column they -/// join keeps its own. +/// floating, keeps that state, except that part of a collapsed column makes an expanded one (the last group of a +/// collapsed column stays icons); a column they join keeps its own. pub(super) struct Moving

{ pub column: Column

, /// The id of a floating window whose last group is in transit, which a new window keeps. pub id: Option, + /// Panels stay in the column the groups left, so a new column made of them is expanded. + pub part: bool, } impl

Moving

{ @@ -344,14 +346,26 @@ impl

Moving

{ Self::taken(group, Column::new(Vec::new())) } - /// `group` taken out of a column whose state is `source` ([`Column::emptied`]). + /// `group` taken out of a column whose state is `source` ([`Column::emptied`]), as all of that column. pub(super) fn taken(group: Group

, source: Column

) -> Self { - Self { column: Column { groups: vec![group], ..source }, id: None } + Self { column: Column { groups: vec![group], ..source }, id: None, part: false } } - /// The column a new dock column gets: the moving column, `width` points wide unless it brings a width. + /// `panel` alone, taken out of a column whose state is `source`, with whether other panels stay in it. + pub(super) fn panel(panel: P, source: (Column

, bool)) -> Self { + let (column, part) = source; + Self { part, ..Self::taken(Group::new(vec![panel], 0), column) } + } + + /// The column a new floating window gets: the moving column, expanded when it is part of a collapsed one. + pub(super) fn into_window_column(self) -> Column

{ + Column { width: None, iconic: self.column.iconic && !self.part, ..self.column } + } + + /// The column a new dock column gets: the moving column, `width` points wide unless it brings a width, and + /// expanded when it is part of a collapsed one. pub(super) fn into_column(self, width: Option) -> Column

{ - Column { width: self.column.width.or(width), ..self.column } + Column { width: self.column.width.or(width), iconic: self.column.iconic && !self.part, ..self.column } } } diff --git a/crates/behavior/src/dock/inner.rs b/crates/behavior/src/dock/inner.rs index b213dd3177..6d652e7e71 100644 --- a/crates/behavior/src/dock/inner.rs +++ b/crates/behavior/src/dock/inner.rs @@ -49,7 +49,7 @@ impl Layout

{ let source = self.source_of(&panel); // A panel the layout does not hold opens in the new window. let entry = self.take(&panel).unwrap_or(StackEntry { panel: panel.clone(), open: true, height: None }); - let moving = Moving { id: lone, ..Moving::taken(Group::new(vec![entry.panel], 0), source) }; + let moving = Moving { id: lone, ..Moving::panel(entry.panel, source) }; self.insert_moving(moving, Target::Float { rect, edge: None }, canvas) } Action::Close { panel } => self.take(&panel).map(|_| ()).ok_or(DockError::MissingPanel), @@ -72,7 +72,7 @@ impl Layout

{ } let entry = StackEntry { panel, open: true, height: None }; if let Some(anchor) = anchor { - self.insert(entry, Column::new(Vec::new()), &anchor, DockPlacement::Tab { before: None }, canvas) + self.insert(entry, (Column::new(Vec::new()), false), &anchor, DockPlacement::Tab { before: None }, canvas) } else if self.root.is_none() { self.root = Some(Node::Tabs { panels: vec![entry.panel], active: 0 }); Ok(()) @@ -89,7 +89,7 @@ impl Layout

{ { return Err(DockError::MissingTarget); } - self.insert(StackEntry { panel, open: true, height: None }, Column::new(Vec::new()), &anchor, placement, canvas) + self.insert(StackEntry { panel, open: true, height: None }, (Column::new(Vec::new()), false), &anchor, placement, canvas) } Action::MoveFloating { panel, rect, edge } => { if !valid_rect(rect) { @@ -142,7 +142,7 @@ impl Layout

{ to => { let source = self.source_of(&panel); let entry = self.take(&panel).ok_or(DockError::MissingPanel)?; - self.insert_moving(Moving::taken(Group::new(vec![entry.panel], 0), source), to, canvas) + self.insert_moving(Moving::panel(entry.panel, source), to, canvas) } }, Action::Restore { panel, location } => { @@ -256,9 +256,11 @@ impl Layout

{ } /// The state a new column made of `panel` keeps: its column's ([`Self::source_column`]), or none for a panel - /// outside a column or absent. - pub(super) fn source_of(&self, panel: &P) -> Column

{ - self.place(panel).map_or_else(|| Column::new(Vec::new()), |place| self.source_column(&place)) + /// outside a column or absent; and whether other panels stay in that column ([`Moving::part`]). + pub(super) fn source_of(&self, panel: &P) -> (Column

, bool) { + let Some(place) = self.place(panel) else { return (Column::new(Vec::new()), false) }; + let part = self.column(&place).is_some_and(|column| column.panels().any(|other| other != panel)); + (self.source_column(&place), part) } /// The accordion entry of `panel` in the docked tree. @@ -327,7 +329,7 @@ impl Layout

{ pub(super) fn insert( &mut self, entry: StackEntry

, - source: Column

, + source: (Column

, bool), anchor: &P, placement: DockPlacement

, canvas: &dyn Fn(&P) -> bool, @@ -338,8 +340,7 @@ impl Layout

{ .filter(|_| !matches!(placement, DockPlacement::Group { .. } | DockPlacement::Column { .. } | DockPlacement::Edge(_))) .map(<[bool]>::to_vec) else { - let moving = Moving::taken(Group::new(vec![entry.panel], 0), source); - return self.insert_moving(moving, Target::At { anchor: anchor.clone(), placement }, canvas); + return self.insert_moving(Moving::panel(entry.panel, source), Target::At { anchor: anchor.clone(), placement }, canvas); }; let root = self.root.as_mut().ok_or(DockError::MissingTarget)?; if let DockPlacement::Split(zone) = placement diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index be5f2b3a8b..347f7da531 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -310,7 +310,7 @@ fn a_floating_windows_edge_is_saved_set_by_collapsed_moves_and_floats_and_cleare assert_eq!(layout.floating[0].edge, None, "collapsing hangs the strip from the edge nearer the window"); let mut moved = columns(); - moved.apply(Action::move_group(3, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap(); + moved.apply(Action::move_column(3, Target::float_with_edge(window(), Some(DockEdge::End)))).unwrap(); let floated = moved.floating.iter().find(|window| window.contains(&3)).unwrap(); assert_eq!(floated.edge, Some(DockEdge::End), "a collapsed column floats at the edge its strip was dropped near"); let mut moved = columns(); @@ -356,10 +356,21 @@ fn a_group_docked_into_a_collapsed_column_keeps_its_width_as_the_flyout_width() layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap(); layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap(); assert_eq!(flyout(&layout, 3), Some(350.0), "a group from another collapsed column keeps its own"); + + let source = Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_width(300.0).with_iconic(true); + let target = Column::new(vec![g(&[7], 0)]).with_iconic(true); + let mut layout = Layout::new( + Some(Node::split(Axis::X, SplitSize::Ratio(0.5), Node::dock(DockEdge::Start, vec![target]), Node::dock(DockEdge::End, vec![source]))), + vec![], + ); + layout.apply(Action::resize_flyout_width(3, Some(350.0))).unwrap(); + layout.apply(Action::move_group(3, Target::at(7, DockPlacement::group(true, None)))).unwrap(); + assert_eq!(flyout(&layout, 3), Some(350.0), "a group from a collapsed column of its own width keeps its flyout width"); } -/// Collapse to icons is a state of every column: a floating window collapses and stays floating; groups leaving a -/// column float in its state; groups joining a column, docked or floating, take that column's state. +/// Collapse to icons is a state of every column: a floating window collapses and stays floating; a whole column +/// leaving floats in its state, and part of a collapsed column floats expanded; groups joining a column, docked or +/// floating, take that column's state. #[test] fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides() { let mut layout = columns(); @@ -369,15 +380,24 @@ fn a_column_keeps_its_collapsed_state_when_it_floats_and_a_joined_column_decides layout.apply(Action::set_iconic(6, false)).unwrap(); assert_eq!(layout.panel_state(&6), PanelState::Front); - for action in [ - Action::move_column(3, Target::float(window())), - Action::move_group(3, Target::float(window())), - Action::move_panel(3, Target::float(window())), - ] { + let mut moved = columns(); + moved.apply(Action::move_column(3, Target::float(window()))).unwrap(); + assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "the whole collapsed column floats as icons"); + for action in [Action::move_group(3, Target::float(window())), Action::move_panel(3, Target::float(window()))] { let mut moved = columns(); moved.apply(action.clone()).unwrap(); - assert!(floats(&moved, 3) && column_of(&moved, 3).iconic, "{action:?} floats as icons"); + assert!(floats(&moved, 3) && !column_of(&moved, 3).iconic, "{action:?} out of a column with another group floats expanded"); + assert!(column_of(&moved, 4).iconic, "the column it left stays collapsed"); + moved.apply(Action::move_group(4, Target::float(window()))).unwrap(); + assert!(floats(&moved, 4) && column_of(&moved, 4).iconic, "the column's last group floats as icons"); } + let mut tabbed = Layout::new(None, vec![Floating::new(102, Column::new(vec![g(&[3, 4, 5], 0)]).with_iconic(true), window())]); + tabbed.apply(Action::move_panel(3, Target::float(window()))).unwrap(); + assert!(!column_of(&tabbed, 3).iconic, "a tab out of a collapsed column's only group floats expanded"); + tabbed.apply(Action::move_panel(5, Target::new_dock(DockEdge::End))).unwrap(); + assert!(!column_of(&tabbed, 5).iconic, "a tab out of a collapsed column docks expanded"); + tabbed.apply(Action::move_panel(4, Target::new_dock(DockEdge::Start))).unwrap(); + assert!(column_of(&tabbed, 4).iconic, "the column's last panel docks as icons"); let mut moved = columns(); moved.apply(Action::move_group(2, Target::float(window()))).unwrap(); assert!(floats(&moved, 2) && !column_of(&moved, 2).iconic, "out of an expanded column it floats expanded"); diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index e53e5e47da..d21986edec 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -7,7 +7,8 @@ use super::dock_column::{ }; use super::group::GripMarks; use super::{ - CardInset, DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, FlyoutHeight, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag, + CardInset, DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, FlyoutHeight, GroupAt, PanelKey, PanelSpec, Splitter, start_group_drag, + start_icon_drag, }; use crate::buttons::{ActiveLook, IconButton}; use crate::contract::overlay::Anchor; @@ -633,6 +634,9 @@ impl Component for IconicColumn<'_, P> { let dragging = |phase: PressPhase| matches!(phase, PressPhase::DragStart { start, .. } if start.button == craft_behavior::PointerButton::Primary); let mut began = false; + // All of the column floats collapsed with its strip under the pointer; part of it floats expanded, as the + // layout makes it. + let panels = self.column.panels().count(); for (group, extent) in &plan.groups { if dragging(cx.part(GRIP.at(*group as u64)).press.phase) && let Some(lead) = self.column.groups.get(*group) @@ -640,7 +644,12 @@ impl Component for IconicColumn<'_, P> { { let shown = lead.active_panel().unwrap_or(anchor); let label = Label::from((self.spec)(shown).label.as_str().to_owned()); - start_icon_drag(cx, DragUnit::Group(anchor.clone()), PanelKey::of(shown), extent.size(), label); + let unit = DragUnit::Group(anchor.clone()); + if lead.panels.len() == panels { + start_icon_drag(cx, unit, PanelKey::of(shown), extent.size(), label); + } else { + start_group_drag(cx, unit, PanelKey::of(shown), None, Some(label)); + } began = true; } } @@ -650,7 +659,11 @@ impl Component for IconicColumn<'_, P> { && let Some(panel) = self.panel(*group, *panel) { let label = Label::from((self.spec)(panel).label.as_str().to_owned()); - start_icon_drag(cx, DragUnit::Panel(panel.clone()), PanelKey::of(panel), cell.size(), label); + if panels == 1 { + start_icon_drag(cx, DragUnit::Panel(panel.clone()), PanelKey::of(panel), cell.size(), label); + } else { + start_group_drag(cx, DragUnit::Panel(panel.clone()), PanelKey::of(panel), None, Some(label)); + } began = true; } } diff --git a/crates/ui-patterns/tests/it/docking/columns.rs b/crates/ui-patterns/tests/it/docking/columns.rs index 7102d58c88..21f73452af 100644 --- a/crates/ui-patterns/tests/it/docking/columns.rs +++ b/crates/ui-patterns/tests/it/docking/columns.rs @@ -12,7 +12,7 @@ use craft_ui::docking::{ use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::env::{Direction, RootEnv}; use craft_ui::testing::{Fixture, pointer, trial}; -use egui::{Pos2, Rect, Ui, Vec2}; +use egui::{Modifiers, Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::sync::Arc; @@ -423,6 +423,56 @@ fn rail_icons_stay_beside_the_expanded_column_and_the_open_panels_icon_collapses assert!(!shown(&fixture, "Alpha body"), "and its panel no longer shows"); } +/// An icon dragged out of a docked column collapsed to icons and released outside the dock area: from a column that +/// keeps other panels it floats expanded, its title row's middle at the pointer and no edge kept; from a column of its +/// own panel alone it floats collapsed at the edge nearer its strip. +#[trial] +fn an_icon_dragged_out_of_a_collapsed_column_floats_expanded_unless_it_is_the_whole_column() { + for groups in [vec![Group::new(vec![10], 0), Group::new(vec![11], 0)], vec![Group::new(vec![10], 0)]] { + let whole = groups.len() == 1; + let side = Column::new(groups).with_iconic(true); + let root = Node::split(Axis::X, SplitSize::Ratio(0.6), Node::tabs(vec![1], 0), Node::dock(DockEdge::End, vec![side])); + let workspace = Rc::new(RefCell::new(Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))))); + let (held, specs) = (Rc::clone(&workspace), Tracked::new(Sides)); + let mut fixture = Fixture::new(move |ui| { + let mut workspace = Arc::clone(&held.borrow()); + let out = DockArea::new("Icon drag dock", Bind::given(Arc::clone(&workspace)), &specs, &mut Sides, DockConfig::default()).show(ui); + for action in out.actions { + drop(Arc::make_mut(&mut workspace).apply(action, false, |_: &u32| Permissions::ALL)); + } + *held.borrow_mut() = workspace; + }); + fixture.room(Vec2::new(900.0, 500.0)).settle(); + let tree = fixture.tree(); + let alpha = fixture + .by_role(Role::BUTTON) + .into_iter() + .find(|button| craft_ui::testing::access::name(tree, button.node) == Some("Alpha")) + .expect("the column shows the Alpha icon") + .rect; + // Released over the canvas with the key that floats. + let outside = Pos2::new(300.0, 250.0); + fixture.frame(vec![pointer::moved(alpha.center())]).frame(vec![pointer::press(alpha.center())]); + for step in 1..=4 { + fixture.frame(vec![pointer::moved(alpha.center() + (outside - alpha.center()) * (step as f32 / 4.0))]); + } + fixture.hold(Modifiers::COMMAND); + fixture.frame(vec![pointer::moved(outside)]).frame(vec![pointer::release(outside)]); + fixture.hold(Modifiers::NONE); + fixture.settle(); + let layout = workspace.borrow().layout().clone(); + let window = layout.floating.iter().find(|window| window.contains(&10)).unwrap_or_else(|| panic!("Alpha floats: {layout:?}")); + assert_eq!(window.column.iconic, whole, "whole column {whole}: {window:?}"); + if whole { + assert!(window.edge.is_some(), "the collapsed window keeps to an edge: {window:?}"); + } else { + assert_eq!(window.edge, None, "the expanded window keeps no edge: {window:?}"); + assert!((window.rect.center().x - outside.x).abs() <= 1.0, "its title row's middle is at the pointer: {window:?}, {outside:?}"); + assert!(end_columns(&layout)[0].iconic, "the column it left stays collapsed"); + } + } +} + /// How tall the flyout of [`UnderWindow`]'s Alpha group measures. const FLYOUT_HEIGHT: f32 = 300.0; From 79ede4382453bbfe4d8ab9bdd0481169338ddb83 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 12:11:57 -0800 Subject: [PATCH 16/31] ui-panels, ui-widgets: a rule parts the tool rail's footer and the toolbar drawer's footer from what scrolls above them The tool rail's footer region had no rule and no gap, so tools that scrolled under it ran into the host's controls. It now has a divider rule and space.gap.inline above its content. The toolbar drawer's stack was sized from its content, so a drawer clipped to the window left an empty band under Restore Defaults while its list was cut short, and the last row touched the controls under it. The stack now fills the drawer, so the footer stands at its foot and the list takes the room between, with a divider rule above the footer. The header takes the control padding at its sides, so the title and hint start where the list's group headings do. Stack::footer_rule adds the rule between a stack's body and its footer. --- crates/ui-panels/src/rails/drawer.rs | 7 +- crates/ui-panels/src/rails/tool.rs | 5 +- crates/ui-panels/tests/it/rails/drawer.rs | 91 +++++++++++++++++++ .../ui-widgets/src/layout_components/mod.rs | 9 ++ 4 files changed, 109 insertions(+), 3 deletions(-) diff --git a/crates/ui-panels/src/rails/drawer.rs b/crates/ui-panels/src/rails/drawer.rs index 82960abf7c..86fe68b6ac 100644 --- a/crates/ui-panels/src/rails/drawer.rs +++ b/crates/ui-panels/src/rails/drawer.rs @@ -6,7 +6,7 @@ use super::words::RailWords; use crate::buttons::{Button, IconButton}; use crate::contract::overlay::{Anchor, Dismiss, Overlay, Place}; use crate::contract::{ - ActivateOn, Bind, CollectionEvent, Gap, ListDrag, NoValue, Outcome, PopupKind, Props as _, SelectMode, Show as _, ShowCollection as _, + ActivateOn, Bind, CollectionEvent, Gap, ListDrag, NoValue, Outcome, Pad, PopupKind, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing, Trigger, clicked, }; use crate::display::{Shade, TargetMark, Text}; @@ -383,7 +383,10 @@ impl ToolbarDrawer<'_, T> { let list_id = ui.scope_id().with("drawer-tools"); // The search field is the stack's header and the list its body; both read the query from the stack's // memory, which lives while the drawer is open. + // The stack fills the drawer, so the footer stands at its foot and the list takes the room between. The + // header's text starts where the list's headings do. Stack::new() + .fill() .gap(Gap::Row) .header(|ui, stack| { Row::new().show(ui, |ui, _| { @@ -407,6 +410,8 @@ impl ToolbarDrawer<'_, T> { below(ui); restore |= clicked(&Button::new(words.drawer_restore.clone()).show(ui)); }) + .footer_rule() + .header_inset(Pad::Control) .show(ui, |ui, stack| { let query = stack.memory::().query.clone(); let mut list = List::::new(words.drawer_tools.clone()) diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index 54d207493a..a4d32edc07 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -129,7 +129,8 @@ type FooterFn<'a> = Box; /// ([`DockGrid::rail`] in the scope's style): it is a button and the control padding wide at one column and a button and the tight gap wider for each further column, /// and the slots fill the rows in reading order. The control padding surrounds the buttons; a slot that ends a group /// leaves `space.gap.inline` after its row; slots within a group sit `space.gap.tight` apart. The Edit Toolbar button -/// follows the last slot; the host's footer stays in view under the slots, which scroll when the room is short under +/// follows the last slot; the host's footer stays in view under the slots, a divider rule and `space.gap.inline` below +/// them, and the slots scroll when the room is short under /// an overlay bar in the end padding that shows only under the pointer (`Scroll::overlay`), or at rest too with /// [`bar_at_rest`](ToolRail::bar_at_rest), and its /// buttons show the rail's glyphs. The rail is exactly as tall as its rows and footer at the width it gets @@ -208,7 +209,7 @@ impl<'a, T: Value + MemoProps + PlainData + 'static> ToolRail<'a, T> { .child_size(ControlSize::Md) .child_glyphs(GlyphRole::ToolRail) .scroll(Scroll::vertical().overlay()) - .footer(FooterRegion::new()); + .footer(FooterRegion::new().rule(true).gap(Gap::Inline)); ToolRail { common: Common::new(), props, diff --git a/crates/ui-panels/tests/it/rails/drawer.rs b/crates/ui-panels/tests/it/rails/drawer.rs index 248e6b8947..8037469230 100644 --- a/crates/ui-panels/tests/it/rails/drawer.rs +++ b/crates/ui-panels/tests/it/rails/drawer.rs @@ -246,3 +246,94 @@ fn the_edit_toolbar_button_takes_the_apps_icon() { fixture.idle(12); assert!(fixture.by_label("Customize").is_some(), "the button keeps its name with another icon"); } + +/// The level lines in `shapes` that lie strictly between `top` and `bottom` and run at least `width` across. +fn level_rules(shapes: &[egui::Shape], top: f32, bottom: f32, width: f32) -> Vec { + shapes + .iter() + .filter_map(|shape| match shape { + egui::Shape::LineSegment { points: [from, to], .. } if (from.y - to.y).abs() < 0.01 && (from.x - to.x).abs() >= width => Some(from.y), + _ => None, + }) + .filter(|&y| y > top && y < bottom) + .collect() +} + +/// A divider rule parts the rail's footer from its tools, with room on both sides of it. +#[trial] +fn a_rule_parts_the_rails_footer_from_its_tools() { + use craft_ui::buttons::Button; + use craft_ui::contract::Show as _; + use craft_ui::rails::{LastUsed, ToolRail}; + let slots = Tracked::new(vec![slot(0, &[UNDO]), slot(1, &[REDO]), slot(2, &[CUT])]); + let last = Tracked::new(LastUsed::default()); + let mut fixture = Fixture::new(move |ui| { + ToolRail::new("Tools", &slots, &UNDO, &last).show_rail(ui, |ui, _| { + Button::new("Swap").show(ui); + }); + }); + fixture.room(Vec2::new(60.0, 400.0)).settle(); + let cut = fixture.by_label("Cut").expect("the rail shows Cut").rect; + let footer = fixture.by_label("Swap").expect("the rail shows its footer").rect; + let shapes = fixture.frame_shapes(); + let rules = level_rules(&shapes, cut.bottom(), footer.top(), cut.width()); + assert_eq!(rules.len(), 1, "one rule lies between the last tool {cut:?} and the footer {footer:?}: {rules:?}"); +} + +/// The drawer `menu`d with one row beside a 48-point rail, listing the Edit tools and then `more` copies of Copy, with +/// "Below" drawn above Restore Defaults. +fn drawer_fixture(more: u8) -> Fixture { + use craft_ui::contract::Show as _; + use craft_ui::display::Text; + use craft_ui::menu::PanelRow; + use craft_ui::rails::{DrawerGroup, ToolbarDrawer}; + use craft_ui::runtime::commands::CommandRef; + use egui::{Pos2, Rect}; + Fixture::new(move |ui| { + let mut tools = vec![tool(UNDO), tool(REDO), tool(CUT)]; + tools.extend((10..10 + more).map(tool)); + let groups = [DrawerGroup::new("Edit", tools)]; + let toolbar = [slot(0, &[UNDO])]; + let rail = Rect::from_min_size(Pos2::ZERO, Vec2::new(48.0, 400.0)); + let menu = vec![PanelRow::Command(CommandRef::from(EditCommands::Copy))]; + ToolbarDrawer::new(rail, &groups, &toolbar, None).menu(menu).show_with(ui, |ui| { + Text::new("Below").show(ui); + }); + }) +} + +/// The drawer's title and hint start where the list's group headings do. +#[trial] +fn the_drawer_title_and_hint_line_up_with_the_headings() { + let mut fixture = drawer_fixture(0); + fixture.room(Vec2::new(480.0, 400.0)).settle(); + let text = |label: &str| fixture.texts().iter().find(|text| text.text == label).unwrap_or_else(|| panic!("the text {label}")).rect; + let (title, hint, heading) = (text("Edit Toolbar"), text("Drag tools to or from the toolbar."), text("Edit")); + assert!((title.left() - heading.left()).abs() <= 1.0, "the title {title:?} starts where the heading {heading:?} does"); + assert!((hint.left() - heading.left()).abs() <= 1.0, "the hint {hint:?} starts where the heading {heading:?} does"); +} + +/// In a drawer too short for its list, a divider rule parts the list from the footer, and the footer stands at the +/// drawer's foot with no more room under Restore Defaults than above the title. +#[trial] +fn a_rule_parts_the_drawers_list_from_its_footer_at_the_drawers_foot() { + use craft_ui::contract::Role; + let mut fixture = drawer_fixture(40); + fixture.room(Vec2::new(480.0, 240.0)).idle(30); + let drawer = fixture.by_role(Role::DIALOG).first().expect("the drawer is open").rect; + let restore = fixture.by_label("Restore Defaults").expect("the Restore Defaults button").rect; + let text = |label: &str| fixture.texts().iter().find(|text| text.text == label).unwrap_or_else(|| panic!("the text {label}")).rect; + let (title, hint, below) = (text("Edit Toolbar"), text("Drag tools to or from the toolbar."), text("Below")); + let row = fixture.by_label("Cut").expect("the Cut row").rect; + assert!( + drawer.right() < row.right() + row.width() / 4.0, + "the drawer {drawer:?} stays about as wide as its list {row:?}: filling it does not stretch it across the room" + ); + let shapes = fixture.frame_shapes(); + let rules = level_rules(&shapes, hint.bottom(), below.top(), drawer.width() / 2.0); + assert_eq!(rules.len(), 1, "one rule lies between the list and the footer {below:?}: {rules:?}"); + assert!( + drawer.bottom() - restore.bottom() <= title.top() - drawer.top() + 1.0, + "the room under Restore Defaults {restore:?} is no more than the room above the title {title:?} in {drawer:?}" + ); +} diff --git a/crates/ui-widgets/src/layout_components/mod.rs b/crates/ui-widgets/src/layout_components/mod.rs index 16087bded7..cf3660f6fc 100644 --- a/crates/ui-widgets/src/layout_components/mod.rs +++ b/crates/ui-widgets/src/layout_components/mod.rs @@ -280,6 +280,15 @@ impl<'a> Stack<'a> { self } + /// A divider rule between the body and the footer, in a band of its own. Set it after [`footer`](Stack::footer). + #[must_use] + pub fn footer_rule(mut self) -> Self { + if let Some(footer) = self.props.footer { + self.props = self.props.footer(footer.rule(true)); + } + self + } + /// The least width of the stack's content from the size role `least`: a stack sized from its content is at least /// that wide (a page's side menu, `LeastWidth::SideMenu`), and wider content still widens it. #[must_use] From 897ce353fc26c6ee6005517d20db1bd8d5c0cb7e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 12:16:21 -0800 Subject: [PATCH 17/31] ui-panels: the rail test audits the grid's replay against a real run --- crates/ui-panels/tests/it/rails/work.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-panels/tests/it/rails/work.rs b/crates/ui-panels/tests/it/rails/work.rs index 38e38b60c5..8ca2ed9106 100644 --- a/crates/ui-panels/tests/it/rails/work.rs +++ b/crates/ui-panels/tests/it/rails/work.rs @@ -7,7 +7,7 @@ use craft_ui::contract::{Role, Show as _, Tracked}; use craft_ui::display::Text; use craft_ui::rails::{LastUsed, ToolRail, ToolSlot, ToolTips}; use craft_ui::testing::pointer::moved; -use craft_ui::testing::{Fixture, MemoRun, last_pass_command_reads, last_pass_memo_runs, trial}; +use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_pass_command_reads, last_pass_memo_runs, trial}; use egui::Ui; use std::cell::Cell; use std::rc::Rc; @@ -69,6 +69,11 @@ fn a_rail_with_tips_replays_its_grid_while_the_pointer_is_away_and_still_shows_t fixture.frame(vec![]); assert_eq!(grid_runs(&fixture), (0, 1), "once the pointer has left, the grid replays again"); + // The audit runs the grid where it would replay and fails on any difference between the two. + audit_replays(fixture.ctx(), true); + fixture.idle(3); + audit_replays(fixture.ctx(), false); + on.set(false); fixture.frame(vec![]); assert_eq!(grid_runs(&fixture), (1, 0), "a change in which tools have a tip runs the grid"); From 26a7f481430dcc3c6a0ab071f69ad8bd4e9bbfe9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 12:24:07 -0800 Subject: [PATCH 18/31] ui-contract: a disabled list's section headings and rows ignore accessibility actions In a disabled list, the heading node of a section row still offered Click, and an accessibility Click or Expand on it activated or opened the section. A Click on an item row of a disabled list selected the row. The heading's Click now follows the list's and the row's enabled state, and the collection takes no access requests on its rows while it is disabled. --- .../ui-contract/src/contract/items/access.rs | 13 +-- crates/ui-widgets/tests/it/list.rs | 86 +++++++++++++++++++ 2 files changed, 94 insertions(+), 5 deletions(-) diff --git a/crates/ui-contract/src/contract/items/access.rs b/crates/ui-contract/src/contract/items/access.rs index 28161d230c..1684490e5c 100644 --- a/crates/ui-contract/src/contract/items/access.rs +++ b/crates/ui-contract/src/contract/items/access.rs @@ -68,7 +68,7 @@ impl ItemsHooks<'_, '_, C> { rect, enabled: enabled && self.source.enabled(at), focusable: false, - clickable: true, + clickable: enabled && self.source.enabled(at), active: false, face: None, label: "", @@ -77,10 +77,10 @@ impl ItemsHooks<'_, '_, C> { access::report_sub(ctx, &decl); } - /// AccessKit requests on an item row's node or on a section row's collection node (`report_section_node`): Focus - /// moves the lead to the row and key focus to the collection; Click also picks an item and activates it when the - /// collection activates on click, or activates a section it does not select. Expand and Collapse open and - /// close rows with children. + /// AccessKit requests on an item row's node or on a section row's collection node (`report_section_node`), while the + /// collection is enabled: Focus moves the lead to the row and key focus to the collection; Click also picks an item and + /// activates it when the collection activates on click, or activates a section it does not select. Expand and + /// Collapse open and close rows with children. pub(super) fn node_by_access( &mut self, comp: &C, @@ -90,6 +90,9 @@ impl ItemsHooks<'_, '_, C> { place: Placement, ) { use craft_behavior::AccessAction; + if !cx.core.resolved.enabled { + return; + } let (_, built) = self.built(layout, place.rect, place.offset); let rows: Vec<(u64, usize)> = built .into_iter() diff --git a/crates/ui-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index e7ed2b4779..66be705625 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -140,6 +140,92 @@ fn accessibility_click_respects_current_toggle_availability() { assert_eq!(seen.borrow().iter().filter(|event| matches!(event, CollectionEvent::Toggle(_))).count(), 1); } +#[trial] +fn accessibility_actions_respect_a_section_headings_availability() { + use craft_behavior::{DisplayOrder, ItemSource}; + use craft_ui::testing::access::Declared; + use craft_ui::testing::focus::AccessActionKind; + use std::borrow::Cow; + use std::cell::Cell; + + const ROWS: [&str; 2] = ["Inks", "Cyan"]; + struct Source { + heading_enabled: bool, + } + impl DisplayOrder for Source { + fn len(&self) -> usize { + ROWS.len() + } + fn key(&self, at: usize) -> usize { + at + } + fn has_children(&self, at: usize) -> bool { + at == 0 + } + fn is_section(&self, at: usize) -> bool { + at == 0 + } + fn section_stop(&self, at: usize) -> bool { + at == 0 + } + fn section_stops_before(&self, at: usize) -> usize { + usize::from(at > 0) + } + fn enabled(&self, at: usize) -> bool { + at != 0 || self.heading_enabled + } + fn text(&self, at: usize) -> Option> { + Some(Cow::Borrowed(ROWS[at])) + } + } + impl ItemSource for Source {} + + let enabled = Rc::new(Cell::new((true, true))); + let gates = enabled.clone(); + let seen = Rc::new(RefCell::new(Vec::new())); + let held = seen.clone(); + let mut fixture = Fixture::new(move |ui| { + let (list_enabled, heading_enabled) = gates.get(); + let source = Source { heading_enabled }; + let out = List::new("Plates").enabled(list_enabled).show_items(ui, &source, &mut |key, _| ListRow::new(ROWS[*key])); + held.borrow_mut().extend(out.events); + }); + let acted = |event: &CollectionEvent| { + matches!( + event, + CollectionEvent::Activate(_) | CollectionEvent::Open(_) | CollectionEvent::Selection { .. } | CollectionEvent::LeadMoved { .. } + ) + }; + for (list_enabled, heading_enabled, denied) in [(false, true, "disabled list"), (true, false, "disabled section")] { + enabled.set((true, true)); + fixture.settle(); + let heading = fixture.by_label("Inks").expect("the heading"); + assert!(fixture.tree().declares_key(heading.node, Declared::Click)); + seen.borrow_mut().clear(); + enabled.set((list_enabled, heading_enabled)); + fixture.access(AccessActionKind::Click, &heading).settle(); + fixture.access(AccessActionKind::Expand, &heading).settle(); + assert!(!seen.borrow().iter().any(acted), "accessibility acted on the heading of a {denied}: {:?}", seen.borrow()); + let heading = fixture.by_label("Inks").expect("disabled heading remains visible to accessibility"); + assert!(!fixture.tree().declares_key(heading.node, Declared::Click), "the heading of a {denied} still offers accessibility Click"); + } + enabled.set((true, true)); + fixture.settle(); + let row = fixture.by_label("Cyan").expect("the row"); + seen.borrow_mut().clear(); + enabled.set((false, true)); + fixture.access(AccessActionKind::Click, &row).settle(); + assert!(!seen.borrow().iter().any(acted), "accessibility acted on a row of a disabled list: {:?}", seen.borrow()); + enabled.set((true, true)); + fixture.settle(); + let heading = fixture.by_label("Inks").expect("the enabled heading"); + seen.borrow_mut().clear(); + fixture.access(AccessActionKind::Click, &heading).settle(); + fixture.access(AccessActionKind::Expand, &heading).settle(); + assert!(seen.borrow().iter().any(|event| matches!(event, CollectionEvent::Activate(0))), "Click activates the enabled heading"); + assert!(seen.borrow().iter().any(|event| matches!(event, CollectionEvent::Open(_))), "Expand opens the enabled heading"); +} + /// The rects of the three rows of a list shown with `rows`. fn row_rects(rows: RowHeight) -> Vec { let mut fixture = Fixture::new(move |ui| { From 8c807a9a040e319ae8612977fee748649f94689a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 12:31:53 -0800 Subject: [PATCH 19/31] ui: wrapped spread rows keep their end edge, check boxes in a field's row keep their labels - A wrapping SpaceBetween row whose children fit on one line now spreads them over its room, with the last child at the end edge and every child on the middle of the line. Once the children take more than one line, each line starts at the start edge as before. The children run in the same child Ui either way, so they keep their ids when the row starts or stops wrapping. - A check box or other control that draws its label after its mark hides that label only when it sits directly in the body of the field that names it. In a row or grid inside the field it shows its own label, as the accessibility tree already names it. - The Color Guide variation grid puts the theme's item gap between its cells. - A tile grid whose group heads are dividers no longer reserves a head row above its first group: the first tiles sit the inset below the top. --- crates/color-ui/src/ui/harmony.rs | 3 +- crates/color-ui/tests/it/panels.rs | 20 +++++ crates/ui-contract/src/contract/label/step.rs | 13 +++- crates/ui-contract/src/layout/body.rs | 78 +++++++++++++++---- .../ui-contract/src/runtime/access/scope.rs | 5 ++ crates/ui-contract/tests/it/layout/body.rs | 40 ++++++++++ crates/ui-widgets/src/tile_grid/grid.rs | 3 +- crates/ui-widgets/src/tile_grid/layout.rs | 30 +++++-- crates/ui-widgets/tests/it/label/field_row.rs | 39 ++++++++++ crates/ui-widgets/tests/it/label/mod.rs | 1 + crates/ui-widgets/tests/it/tile_grid/grid.rs | 32 ++++++++ 11 files changed, 240 insertions(+), 24 deletions(-) create mode 100644 crates/ui-widgets/tests/it/label/field_row.rs diff --git a/crates/color-ui/src/ui/harmony.rs b/crates/color-ui/src/ui/harmony.rs index 254d30f628..f11fa9129b 100644 --- a/crates/color-ui/src/ui/harmony.rs +++ b/crates/color-ui/src/ui/harmony.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use super::picker::{ChannelRow, ChannelRule}; use super::{ColorDisc, DiscHit, DiscLook, DiscRadius}; use crate::harmony::{Guide, GuideOptions, Harmony, Variation}; -use craft_ui::choice::{CellMarks, SwatchTable, SwatchTableOutput}; +use craft_ui::choice::{CellMarks, SwatchSpacing, SwatchTable, SwatchTableOutput}; #[cfg(feature = "suite")] pub(crate) mod stories; @@ -503,6 +503,7 @@ impl<'a> HarmonyPanel<'a> { .multiple(true) .per_row(columns) .span(true) + .spacing(SwatchSpacing::Spaced) .marks(move |&at| CellMarks::default().edge(at % columns == centre)) .selection(Bind::bound(&mut selection)); let SwatchTableOutput { selected, chosen: clicked, .. } = dragging(table, payload.as_ref(), &grid_cells).show_all(ui); diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index ffcc37b8c5..1fe7ce1f9a 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -1257,3 +1257,23 @@ fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() { assert!(shades.left() <= grid.left() + 1.0 && shades.right() < grid.center().x, "Shades {shades:?} starts at the left edge of {grid:?}"); assert!(tints.right() >= grid.right() - 1.0 && tints.left() > grid.center().x, "Tints {tints:?} ends at the right edge of {grid:?}"); } + +/// The Color Guide's variation cells stand apart: each cell's left edge lies right of the cell before it on its row, +/// and each row's top lies below the row above it. +#[trial] +fn the_color_guide_variation_cells_stand_apart() { + let mut fixture = Fixture::new(|ui| { + let (mut state, mut picked) = (HarmonyPanelState::default(), HarmonyPicked::default()); + let _ = HarmonyPanel::new(Bind::bound(&mut state), Bind::bound(&mut picked), RED).show(ui); + }); + fixture.room(COLOR_ROOM).settle(); + let grid = fixture.by_label("Variations").expect("the variations grid"); + let cells: Vec = + fixture.tree().children_of(grid.node).into_iter().filter_map(|key| fixture.target(key)).map(|cell| cell.rect).collect(); + assert!(cells.len() >= 4, "the grid holds its cells: {cells:?}"); + let (first, next) = (cells[0], cells[1]); + assert!((first.center().y - next.center().y).abs() < 0.5, "the first two cells share a row: {cells:?}"); + assert!(next.left() >= first.right() + 1.0, "a gap lies between two cells of a row: {first:?}, {next:?}"); + let below = cells.iter().find(|cell| cell.top() > first.center().y).expect("a second row of cells"); + assert!(below.top() >= first.bottom() + 1.0, "a gap lies between two rows: {first:?}, {below:?}"); +} diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index 91f25fe60a..b34598318c 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -508,13 +508,22 @@ fn wrap_before(ui: &mut Ui, env: &Env, (label, side): (&Label, &SideLabel), cont } } +/// Whether a leaf placed under `env` sits directly in the body of `container`, the container of the innermost label +/// scope, or in no body's flow at all: that scope's label then names the leaf. A leaf in a row, a grid or any other +/// container inside the labeled one is one of the controls the label groups. +fn named_directly(env: &Env, container: Id) -> bool { + env.flow_body.is_none_or(|flow| flow == sub(container, "layout")) +} + /// Shows `child` in the flow of `ui`. A component whose `LABELLED_AFTER` is set and that carries a label shows it /// through the label step, after the control, unless a label scope already names the control (a `Field`, `labelled`; /// a member of a group, a radio, is named by the group and keeps its own text): -/// that scope's label is the visible text, so the control's own is not shown twice. Every other leaf shows as it is. +/// that scope's label is the visible text, so the control's own is not shown twice. A control in a row or grid inside +/// the scope is part of the field's arrangement, as the accessibility tree has it (`ScopeNode::arranged`): the label +/// names the group, and the control shows its own label. Every other leaf shows as it is. pub(crate) fn show_leaf_in_flow(mut child: C, ui: &mut Ui) -> C::Output { let env = Env::of(ui); - let named_by_scope = env.arena.is_none() && scope::in_label(ui.ctx()); + let named_by_scope = env.arena.is_none() && scope::label_container(ui.ctx()).is_some_and(|container| named_directly(&env, container)); let shows = C::LABELLED_AFTER && child.shows_label() && child.common(crate::contract::Internal::new()).label != Label::Empty && !named_by_scope; if !shows { return crate::contract::run::show_leaf(&mut Some(child), ui, (crate::contract::run::ShowAt::Flow, env), None); diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index dd6e424734..1cc1c6362b 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -77,8 +77,9 @@ pub enum RowAlign { /// At the end edge. End, /// Spread over the row: the first child at the start edge, the last at the end edge, and the room left shared - /// equally between the children (a footer's leading slot and its buttons). One child sits at the start edge, and so - /// do the children of a row that wraps. + /// equally between the children (a footer's leading slot and its buttons). One child sits at the start edge. A row + /// that wraps spreads its children the same way while they fit one line; once they take more lines, each line + /// starts at the start edge. SpaceBetween, } @@ -245,11 +246,12 @@ fn open_wraps(ctx: &egui::Context, sizing: bool, id: Id) { } /// Ends the children of the wrapping `Row` body `id`, `room` wide; a measuring run records each child's line and the -/// height of its tallest child. -fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2) { +/// height of its tallest child. A measuring run returns how many children the row placed and the height of its tallest +/// child when every one of them sits on its first line. +fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2) -> Option<(usize, f32)> { let took = pass_state::with::(ctx, |rows| rows.0.remove(&id)).unwrap_or_default(); if !sizing { - return; + return None; } let mut heights: Vec = Vec::new(); for &(line, height) in &took.children { @@ -262,6 +264,7 @@ fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2) { for (i, &(line, _)) in took.children.iter().enumerate() { found(ctx, true, sub(id, ("wrap", i)), room, Vec2::new(line as f32, heights.get(line).copied().unwrap_or_default())); } + (heights.len() <= 1).then(|| (took.children.len(), heights.first().copied().unwrap_or_default())) } /// Whether egui puts the next child `width` wide in `ui`, a wrapping row's block, on a new line (`Layout::next_frame`): @@ -1345,8 +1348,17 @@ impl Spread { /// records the natural width and count, and the leasts (none for a row that fits). The real run, including one a kept /// transcript serves, builds the same cursor from those records, so each child measures in the same room in both. /// Every sweep runs in a child of `ui` with its layout, so the children get the same ids in each. -/// `env` is the row's env, installed for `ui`. -fn run_spread(ui: &mut Ui, env: &Env, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Option) { +/// `env` is the row's env, installed for `ui`. `fits` is the natural width and count of the children of a wrapping row +/// that fit its first line in this pass's measuring run (`one_line_spread`): the real run spreads them from it, with no +/// leasts. +fn run_spread( + ui: &mut Ui, + env: &Env, + (id, fits): (Id, Option), + gap: f32, + rtl: bool, + body: &mut dyn FnMut(&mut Ui) -> R, +) -> (R, Option) { let ctx = ui.ctx().clone(); let layout = child::row_layout(rtl, false); let sweep = |ui: &mut Ui, env: &Env, last: Option, leasts: Vec, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| { @@ -1362,6 +1374,10 @@ fn run_spread(ui: &mut Ui, env: &Env, id: Id, gap: f32, rtl: bool, body: &mut }; let natural = |spread: &Option| spread.as_ref().map(|spread| spread.measured().x); let leasts_id = sub(id, "leasts"); + if let Some(fits) = fits.filter(|_| !measure::active(&ctx)) { + let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, env, Some(fits), Vec::new(), false, body)).0; + return (inner, natural(&spread)); + } if !measure::active(&ctx) { let count = this_pass(&ctx, false, leasts_id).map_or(0, |count| count.x as usize); let leasts = (0..count).map(|i| this_pass(&ctx, false, sub(id, ("least", i))).map_or(0.0, |least| least.x)).collect(); @@ -1982,9 +1998,11 @@ pub(crate) fn run_body_measured( }; // Each layout runs in its own function, so a body nested in bodies keeps only its own layout's frame on the stack. let line = RowIn { id, gap, shared, sizing, rtl }; + let fits = matches!(layout, BodyLayout::Row { wrap: true, align: RowAlign::SpaceBetween }).then(|| one_line_spread(ui, sizing, id)).flatten(); match layout { BodyLayout::Stack => (run_stack(ui, env, &line, body), None), - BodyLayout::Row { wrap: false, align: RowAlign::SpaceBetween } => run_spread_row(ui, env, &line, body), + BodyLayout::Row { wrap: false, align: RowAlign::SpaceBetween } => run_spread_row(ui, env, &line, None, body), + BodyLayout::Row { wrap: true, align: RowAlign::SpaceBetween } if fits.is_some() => run_spread_row(ui, env, &line, fits, body), BodyLayout::Row { wrap: false, align: RowAlign::Start } => (run_start_row(ui, env, &line, body), None), BodyLayout::Row { wrap, align } => run_row(ui, env, &line, (*wrap, *align), body), BodyLayout::Grid { columns, fit, cells } => (run_grid(ui, env, id, (&columns[..], *fit, *cells), gap, body), None), @@ -2023,8 +2041,19 @@ fn run_stack(ui: &mut Ui, env: &Env, at: &RowIn, body: impl FnMut(&mut Ui) -> inner } -/// An unwrapped `Row` that spreads its children over its room. -fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mut Ui) -> R) -> (R, Option) { +/// The natural width and count of the children of the wrapping `SpaceBetween` row `id` in a real run, when this pass's +/// measuring run set two or more of them on its first line and they fit the room `ui` offers: the row then spreads +/// them over its room as an unwrapped row does. `None` in a measuring run, and for a row that wraps. +fn one_line_spread(ui: &Ui, sizing: bool, id: Id) -> Option { + let fits = this_pass(ui.ctx(), sizing, sub(id, "one_line"))?; + let room = ui.available_rect_before_wrap().width(); + // Half a point: less than a pixel shows at any scale the box runs. + (fits.y >= 2.0 && room.is_finite() && fits.x <= room + 0.5).then_some(fits) +} + +/// An unwrapped `Row` that spreads its children over its room, or a wrapping one whose children `fits` one line +/// (`one_line_spread`). +fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, fits: Option, mut body: impl FnMut(&mut Ui) -> R) -> (R, Option) { let ctx = ui.ctx().clone(); let RowIn { id, gap, shared, sizing, rtl } = *at; let (inner, _) = child::block(ui, None, child::row_layout(rtl, false), |ui| { @@ -2037,7 +2066,7 @@ fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&m scoped.flow_body = Some(id); }); let installed = Env::install_for(ui, row.clone()); - let inner = run_spread(ui, &row, id, gap.x, rtl, &mut body); + let inner = run_spread(ui, &row, (id, fits), gap.x, rtl, &mut body); Env::restore(&ctx, installed); record_line(ui, sizing, id, shared, env.first_line); inner @@ -2101,6 +2130,7 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign // Where its least is asked, a wrapping row is as narrow as its widest child at its least: every child on a // line of its own. let block_layout = if wrap && env.least { child::column_layout(rtl) } else { child::row_layout(rtl, wrap) }; + let mut one_line = None; let (inner, took) = child::block(ui, rect, block_layout, |ui| { let row = env.derive_local(|scoped| { scoped.row_room = Some(room.width()); @@ -2118,9 +2148,18 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign if lines { open_wraps(&ctx, sizing, id); } - let inner = if wrap { body(ui) } else { run_shrinking(ui, &row, id, &mut body) }; + let inner = if wrap && align == RowAlign::SpaceBetween { + // In a child, as the spread row runs its children (`run_spread`): they take the same ids whether the real + // run spreads them on one line or wraps them, and keep their state when the row starts or stops wrapping. + let layout = *ui.layout(); + child::block(ui, None, layout, |ui| Env::run_in(ui, row.clone(), &mut body)).0 + } else if wrap { + body(ui) + } else { + run_shrinking(ui, &row, id, &mut body) + }; if lines { - close_wraps(&ctx, sizing, id, room.size()); + one_line = close_wraps(&ctx, sizing, id, room.size()); } Env::restore(&ctx, installed); if !wrap { @@ -2131,5 +2170,18 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign if align != RowAlign::Start { found(&ctx, sizing, id, room.size(), took.size()); } + if wrap && align == RowAlign::SpaceBetween { + // Children that all fit the first line are spread over the row by the real run (`one_line_spread`): their + // width at the gap alone and their count, and the line they sit on, at the middle of the tallest one, as + // `record_line` records an unwrapped row's. A row that wraps records no count and no line, so it wraps again. + let (count, tallest) = one_line.unwrap_or_default(); + found(&ctx, sizing, sub(id, "one_line"), room.size(), Vec2::new(took.width(), count as f32)); + let line = on_line(id, (tallest > 0.0).then_some((tallest / 2.0, tallest)), shared); + let spread_line = match (line.centre, line.height) { + (Some(centre), Some(height)) if one_line.is_some() && height > 0.0 => Vec2::new(centre, height), + _ => Vec2::ZERO, + }; + found(&ctx, sizing, sub(id, "line"), Vec2::new(0.0, shared.unwrap_or(0.0)), spread_line); + } (inner, (align != RowAlign::Start).then(|| took.width())) } diff --git a/crates/ui-contract/src/runtime/access/scope.rs b/crates/ui-contract/src/runtime/access/scope.rs index 16825da699..f1409fc0f9 100644 --- a/crates/ui-contract/src/runtime/access/scope.rs +++ b/crates/ui-contract/src/runtime/access/scope.rs @@ -373,6 +373,11 @@ pub(crate) fn in_label(ctx: &Context) -> bool { pass_state::with::(ctx, |stack| stack.0.iter().any(|scope| matches!(scope.kind, Kind::Label(_)))) } +/// The container of the innermost open label scope. +pub(crate) fn label_container(ctx: &Context) -> Option { + pass_state::with::(ctx, |stack| stack.0.iter().rev().find(|scope| matches!(scope.kind, Kind::Label(_))).map(|scope| scope.container)) +} + /// Records the narrowest width of a control inside the innermost label scope. The first control to report wins. pub(crate) fn record_control_min(ctx: &Context, width: f32) { let container = pass_state::with::(ctx, |stack| { diff --git a/crates/ui-contract/tests/it/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index ec0a5926ba..e1a7d2d0b9 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -597,6 +597,46 @@ fn a_memoized_view_sits_on_the_rows_line() { } } +/// A wrapping `SpaceBetween` row whose children fit on one line spreads them over its room: the first starts at the +/// row's start, the last ends at its end, and the short child sits at the middle of the tall one's line. Too narrow +/// for one line, it wraps the last child onto a second line from the row's start. The children keep their ids when +/// the row starts wrapping. +#[trial] +fn a_wrapping_space_between_row_spreads_children_that_fit_one_line() { + let seen: Rc<[RefCell; 2]> = Rc::new(Default::default()); + let row = Rc::new(Cell::new(Rect::NOTHING)); + let (shown, shown_row) = (Rc::clone(&seen), Rc::clone(&row)); + let mut fixture = Fixture::new(move |ui| { + let layout = BodyLayout::row().wrap(true).align(RowAlign::SpaceBetween); + let panel = Panel::new().layout(layout).sizing(Sizing::FillWidth).id_salt("spread").show(ui, |ui, _| { + for (i, (seen, size)) in shown.iter().zip([ITEM, Vec2::new(40.0, 30.0)]).enumerate() { + Probe::new(seen).size(size).id_salt(i).show(ui); + } + }); + shown_row.set(panel.output.rect); + }); + let mut ids = Vec::new(); + for (width, fits) in [(300.0, true), (70.0, false)] { + fixture.room(Vec2::new(width, 400.0)).settle(); + ids.push(seen.each_ref().map(|seen| seen.borrow().id)); + let rects = || seen.each_ref().map(|seen| seen.borrow().rect); + let ([first, last], row) = (rects(), row.get()); + let dump = format!("width {width}: row {row:?}, first {first:?}, last {last:?}"); + assert!((first.min.x - row.min.x).abs() < SLACK, "the first child starts at the row's start: {dump}"); + if fits { + assert!((last.max.x - row.max.x).abs() < SLACK, "the last child ends at the row's end: {dump}"); + assert!((first.center().y - last.center().y).abs() < SLACK, "the children share one line: {dump}"); + } else { + assert!(last.top() >= first.bottom() - SLACK, "the last child wraps onto a second line: {dump}"); + assert!((last.min.x - row.min.x).abs() < SLACK, "the second line starts at the row's start: {dump}"); + } + let settled = rects(); + fixture.idle(3); + assert_eq!(rects(), settled, "width {width}: the frames that reuse the measurement place the children alike"); + } + assert_eq!(ids[0], ids[1], "the children keep their ids when the row starts wrapping"); +} + /// An unwrapped row in a row sits on the outer row's line by its own line, whatever its alignment: a row that places /// its block from its start, at its end, centred or spread reports its line as its first line alike. #[trial] diff --git a/crates/ui-widgets/src/tile_grid/grid.rs b/crates/ui-widgets/src/tile_grid/grid.rs index 33bd7390aa..09283aa463 100644 --- a/crates/ui-widgets/src/tile_grid/grid.rs +++ b/crates/ui-widgets/src/tile_grid/grid.rs @@ -511,7 +511,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> { /// the picture plus what the tile adds around it in every tiling. fn laid_out(&self, previous: Option, source: &dyn ItemSource, width: f32, item: Option, cx: &StyleCx<'_>) -> GridLayout { let style = GridSizes::of(cx, self.card, self.card_text, self.items.row_height, self.regular_card_padding, self.action_place); - let spacing = style.spacing(self.caption); + let spacing = style.spacing(self.caption).ruled(self.group_heads == GroupHeads::Rule); let around = style.around.get(self.caption, self.detail_line); // A card never outgrows the grid: in a column narrower than a card the card takes the column. let mut side = self.picture_side(&style, item, around).min(width - 2.0 * spacing.inset - around.size().x).max(1.0); @@ -532,6 +532,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> { justified: self.justified, around, group_header: spacing.group_header, + ruled: spacing.ruled, groups: groups.iter().map(|group| (group.start, group.count, group.open)).collect(), tail: (self.tail.len(), tail_height), }); diff --git a/crates/ui-widgets/src/tile_grid/layout.rs b/crates/ui-widgets/src/tile_grid/layout.rs index c0a202ef54..d07b8f91f4 100644 --- a/crates/ui-widgets/src/tile_grid/layout.rs +++ b/crates/ui-widgets/src/tile_grid/layout.rs @@ -369,12 +369,21 @@ pub struct ArrangeSpacing { pub inset: f32, /// A group header's height. pub group_header: f32, + /// The group headers are dividers (`GroupHeads::Rule`): a header that opens the grid draws nothing, so it takes no + /// height and the first tiles keep the inset at the top. + pub ruled: bool, } impl ArrangeSpacing { /// Spacing of `gap` between tiles, `inset` around the content and headers `group_header` high. pub fn new(gap: f32, inset: f32, group_header: f32) -> Self { - ArrangeSpacing { gap, inset, group_header } + ArrangeSpacing { gap, inset, group_header, ruled: false } + } + + /// The spacing with group headers that are dividers when `ruled`. + #[must_use] + pub fn ruled(self, ruled: bool) -> Self { + ArrangeSpacing { ruled, ..self } } } @@ -401,11 +410,12 @@ pub fn aspects_of(source: &dyn ItemSource) -> Vec { /// - `groups` are in display order and cover only the tiles they name; tiles outside every group sit in rows /// without a header. A closed group has its header only. /// - `inset` pads the sides and the bottom, and the top unless a group header opens the grid: that header sits at -/// the top edge. +/// the top edge. A divider header (`ArrangeSpacing::ruled`) that opens the grid takes no height, and the inset pads +/// the top. pub fn arrange(aspects: &[f32], groups: &[TileGroup], width: f32, tiling: Tiling, spacing: ArrangeSpacing, around: Around) -> TileArrangement { let sanitized: Vec = aspects.iter().map(|a| if a.is_finite() && *a > 0.0 { *a } else { 1.0 }).collect(); let n = sanitized.len(); - let ArrangeSpacing { gap, inset, group_header } = spacing; + let ArrangeSpacing { gap, inset, group_header, ruled } = spacing; let content = (width - 2.0 * inset).max(1.0); let mut out = TileArrangement { tiles: vec![Rect::NOTHING; n], ..TileArrangement::default() }; @@ -424,17 +434,21 @@ pub fn arrange(aspects: &[f32], groups: &[TileGroup], width: f32, tiling: } out.starts = spans.iter().map(|span| span.start).collect(); - // A leading group header sits at the top edge, as the old grids put it; tiles that open the grid keep the inset. - let mut y = if segments.first().is_some_and(|(group, _)| group.is_some()) { 0.0 } else { inset }; + // A leading group header sits at the top edge, as the old grids put it; tiles that open the grid keep the inset, + // and so do those under a leading divider, which draws nothing and takes no height. + let leading = segments.first().is_some_and(|(group, _)| group.is_some()); + let mut y = if leading && !ruled { 0.0 } else { inset }; let mut started = false; for (group, range) in segments { + let first = !started; if started { y += gap; } started = true; if let Some(index) = group { - out.headers.push(Rect::from_min_size(pos2(inset, y), vec2(content, group_header))); - y += group_header; + let height = if first && ruled { 0.0 } else { group_header }; + out.headers.push(Rect::from_min_size(pos2(inset, y), vec2(content, height))); + y += height; if !groups[index].open { continue; } @@ -524,6 +538,8 @@ pub(super) struct Recipe { pub(super) around: Around, /// A group header's height. pub(super) group_header: f32, + /// The group headers are dividers. + pub(super) ruled: bool, /// Each group's first tile, count and open state. pub(super) groups: Vec<(usize, usize, bool)>, /// How many tail rows follow, and their height. diff --git a/crates/ui-widgets/tests/it/label/field_row.rs b/crates/ui-widgets/tests/it/label/field_row.rs new file mode 100644 index 0000000000..2c7bdf81b4 --- /dev/null +++ b/crates/ui-widgets/tests/it/label/field_row.rs @@ -0,0 +1,39 @@ +//! Check boxes inside a field: the field's label names the control its body holds directly, and the check boxes of a +//! row inside the field show their own labels. + +use craft_ui::choice::Checkbox; +use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft_ui::form::Field; +use craft_ui::layout_components::Row; +use craft_ui::testing::{Fixture, trial}; +use egui::Vec2; + +const CREATE: &str = "Create"; +const FILLS: &str = "Fills"; +const STROKES: &str = "Strokes"; +const SNAP: &str = "Snap"; + +/// A field holding a row of two labelled check boxes paints the field's label and both check boxes' labels. A field +/// holding one labelled check box directly paints only the field's label, which names it. +#[trial] +fn check_boxes_in_a_row_inside_a_field_show_their_labels() { + let mut fixture = Fixture::new(|ui| { + Field::new(CREATE).id_salt("create").show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + Checkbox::new(Bind::given(true)).label(FILLS).id_salt("fills").show(ui); + Checkbox::new(Bind::given(false)).label(STROKES).id_salt("strokes").show(ui); + }); + }); + Field::new(SNAP).id_salt("snap").show(ui, |ui, _| { + Checkbox::new(Bind::given(true)).label("Snap to grid").id_salt("snap box").show(ui); + }); + }); + fixture.room(Vec2::new(400.0, 300.0)); + fixture.settle(); + let texts = fixture.texts(); + let painted = |text: &str| texts.iter().any(|run| run.text == text); + for text in [CREATE, FILLS, STROKES, SNAP] { + assert!(painted(text), "{text:?} is painted: {texts:?}"); + } + assert!(!painted("Snap to grid"), "the field's label names the check box its body holds directly: {texts:?}"); +} diff --git a/crates/ui-widgets/tests/it/label/mod.rs b/crates/ui-widgets/tests/it/label/mod.rs index 6489253702..04b03a91ad 100644 --- a/crates/ui-widgets/tests/it/label/mod.rs +++ b/crates/ui-widgets/tests/it/label/mod.rs @@ -5,6 +5,7 @@ pub(crate) mod align; pub(crate) mod baseline; pub(crate) mod bracket; pub(crate) mod caption; +pub(crate) mod field_row; pub mod group; pub(crate) mod hit; pub(crate) mod inside; diff --git a/crates/ui-widgets/tests/it/tile_grid/grid.rs b/crates/ui-widgets/tests/it/tile_grid/grid.rs index 28e762da70..4afae8b121 100644 --- a/crates/ui-widgets/tests/it/tile_grid/grid.rs +++ b/crates/ui-widgets/tests/it/tile_grid/grid.rs @@ -56,6 +56,38 @@ fn a_leading_group_header_sits_at_the_top_edge_and_ungrouped_tiles_keep_the_inse assert!((loose.rows[0].top - INSET).abs() < EPS, "tiles that open the grid keep the inset above them"); } +/// A divider header that opens the grid takes no height: the first tiles sit the inset below the top edge. A divider +/// between two groups keeps the header height. +#[craft_ui::testing::trial] +fn a_leading_divider_header_takes_no_height() { + let aspects = [1.0; 6]; + let groups = [TileGroup::new(0usize, 0, 3, "Alpha"), TileGroup::new(1usize, 3, 3, "Beta")]; + let laid = arrange(&aspects, &groups, WIDTH, Tiling::justified(ROW), spacing().ruled(true), Around::default()); + assert!(laid.headers[0].height().abs() < EPS, "the leading divider takes no height: {:?}", laid.headers[0]); + assert!((laid.rows[0].top - INSET).abs() < EPS, "the first tiles keep the inset above them: {:?}", laid.rows[0]); + assert!((laid.headers[1].height() - HEADER).abs() < EPS, "a divider between groups keeps its height: {:?}", laid.headers[1]); +} + +/// In a grid with `GroupHeads::Rule`, the first tile sits as close to the grid's top as in a grid with no groups. +#[craft_ui::testing::trial] +fn a_rule_grid_starts_its_tiles_at_the_top() { + let top = |ruled: bool| { + let mut fixture = Fixture::new(move |ui| { + let keys: Vec = (0..6).collect(); + let source = keyed(&keys, |key: &usize| *key); + let groups = [TileGroup::new(100usize, 0, 3, "Alpha"), TileGroup::new(101usize, 3, 3, "Beta")]; + let grid = TileGrid::new("Library"); + let grid = if ruled { grid.groups(&groups).group_heads(GroupHeads::Rule) } else { grid }; + let _ = grid.show_items(ui, &source, &mut |key, _| Tile::new(format!("Tile {}", key + 1))); + }); + fixture.room(Vec2::new(600.0, 600.0)); + fixture.settle(); + fixture.by_label("Tile 1").expect("the first tile").rect.top() + }; + let (ruled, plain) = (top(true), top(false)); + assert!((ruled - plain).abs() < 0.5, "the first tile of a rule grid sits at {ruled}, of a plain grid at {plain}"); +} + /// Under `GroupHeads::Rule` a head is a divider: it paints no title, a click on it reports no group event, and a group /// declared closed still shows its tiles; the group's title stays the heading's name. #[craft_ui::testing::trial] From 063b7295e5aa00cd467bcb30efe0b74be890bdc9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 13:04:58 -0800 Subject: [PATCH 20/31] ui: a wrapping spread row on one line keeps to its container's wrap width A wrapping SpaceBetween row whose children fit one line was spread over the whole room its container offered, while the same row wraps its lines at the container's paragraph line length (a wrap width set on a content-sized container). A row that fills a stack whose least width is wider than its wrap width put its last child at the stack's end instead of at the wrap width. The rect the row wraps in is now one helper, wrap_rect. The one-line check compares the children with that rect's width, and the spread row places them in that rect. A row with no narrower wrap width still spreads over its room. --- crates/ui-contract/src/layout/body.rs | 36 +++++++++------- .../tests/it/layout/stack_widths.rs | 43 ++++++++++++++++++- 2 files changed, 63 insertions(+), 16 deletions(-) diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 1cc1c6362b..a5ed448344 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -1998,7 +1998,8 @@ pub(crate) fn run_body_measured( }; // Each layout runs in its own function, so a body nested in bodies keeps only its own layout's frame on the stack. let line = RowIn { id, gap, shared, sizing, rtl }; - let fits = matches!(layout, BodyLayout::Row { wrap: true, align: RowAlign::SpaceBetween }).then(|| one_line_spread(ui, sizing, id)).flatten(); + let fits = + matches!(layout, BodyLayout::Row { wrap: true, align: RowAlign::SpaceBetween }).then(|| one_line_spread(ui, env, sizing, id)).flatten(); match layout { BodyLayout::Stack => (run_stack(ui, env, &line, body), None), BodyLayout::Row { wrap: false, align: RowAlign::SpaceBetween } => run_spread_row(ui, env, &line, None, body), @@ -2041,22 +2042,34 @@ fn run_stack(ui: &mut Ui, env: &Env, at: &RowIn, body: impl FnMut(&mut Ui) -> inner } +/// The rect a wrapping `Start` or `SpaceBetween` row lays its lines in, when its container sets a line length for +/// paragraphs (`Scoped::measure`, a dialog's) narrower than the room `ui` offers: the row wraps at that length, as the +/// paragraphs beside it do, so a dialog sized from its content stays as wide as its text and a row of radios that +/// would not fit there takes a second line instead of widening the dialog. A room unbounded at its end edge (a +/// measuring run's) is cut from its start edge. `None` where the row takes the room `ui` offers. +fn wrap_rect(ui: &Ui, env: &Env, rtl: bool) -> Option { + let room = ui.available_rect_before_wrap(); + env.measure.filter(|measure| *measure < room.width() && (!rtl || room.right().is_finite())).map(|measure| Flow::new(room, rtl).span(0.0, measure)) +} + /// The natural width and count of the children of the wrapping `SpaceBetween` row `id` in a real run, when this pass's -/// measuring run set two or more of them on its first line and they fit the room `ui` offers: the row then spreads -/// them over its room as an unwrapped row does. `None` in a measuring run, and for a row that wraps. -fn one_line_spread(ui: &Ui, sizing: bool, id: Id) -> Option { +/// measuring run set two or more of them on its first line and they fit the rect the row wraps in (`wrap_rect`): the +/// row then spreads them over that rect as an unwrapped row does over its room. `None` in a measuring run, and for a +/// row that wraps. +fn one_line_spread(ui: &Ui, env: &Env, sizing: bool, id: Id) -> Option { let fits = this_pass(ui.ctx(), sizing, sub(id, "one_line"))?; - let room = ui.available_rect_before_wrap().width(); + let room = wrap_rect(ui, env, env.direction.is_rtl()).unwrap_or_else(|| ui.available_rect_before_wrap()).width(); // Half a point: less than a pixel shows at any scale the box runs. (fits.y >= 2.0 && room.is_finite() && fits.x <= room + 0.5).then_some(fits) } /// An unwrapped `Row` that spreads its children over its room, or a wrapping one whose children `fits` one line -/// (`one_line_spread`). +/// (`one_line_spread`), spread over the rect it wraps in (`wrap_rect`). fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, fits: Option, mut body: impl FnMut(&mut Ui) -> R) -> (R, Option) { let ctx = ui.ctx().clone(); let RowIn { id, gap, shared, sizing, rtl } = *at; - let (inner, _) = child::block(ui, None, child::row_layout(rtl, false), |ui| { + let rect = fits.and_then(|_| wrap_rect(ui, env, rtl)); + let (inner, _) = child::block(ui, rect, child::row_layout(rtl, false), |ui| { let line = on_line(id, row_line(&ctx, sizing, id, shared), shared); let row = env.derive_local(|scoped| { scoped.grid = Some(id); @@ -2102,14 +2115,7 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign let RowIn { id, shared, sizing, rtl, .. } = *at; let room = ui.available_rect_before_wrap(); let rect = match align { - // A wrapping row wraps at the line length its container sets for paragraphs (a dialog's), as the paragraphs - // beside it do: a dialog sized from its content stays as wide as its text, and a row of radios that would not - // fit there takes a second line instead of widening the dialog. A room unbounded at its end edge (a measuring - // run's) is cut from its start edge. - RowAlign::Start | RowAlign::SpaceBetween if wrap => env - .measure - .filter(|measure| *measure < room.width() && (!rtl || room.right().is_finite())) - .map(|measure| Flow::new(room, rtl).span(0.0, measure)), + RowAlign::Start | RowAlign::SpaceBetween if wrap => wrap_rect(ui, env, rtl), RowAlign::Start | RowAlign::SpaceBetween => None, RowAlign::Center | RowAlign::End => { let last = this_pass(&ctx, sizing, id); diff --git a/crates/ui-widgets/tests/it/layout/stack_widths.rs b/crates/ui-widgets/tests/it/layout/stack_widths.rs index f3dd67968f..1a08d56071 100644 --- a/crates/ui-widgets/tests/it/layout/stack_widths.rs +++ b/crates/ui-widgets/tests/it/layout/stack_widths.rs @@ -5,7 +5,9 @@ use craft_ui::buttons::Button; use craft_ui::choice::{Radio, RadioGroup}; -use craft_ui::contract::{Bind, FieldLayout, Gap, LeastWidth, Pad, Props as _, Scroll, Show as _, ShowContainer as _, SideLabel, Sizing, WrapWidth}; +use craft_ui::contract::{ + Bind, FieldLayout, Gap, LeastWidth, Pad, Props as _, RowAlign, Scroll, Show as _, ShowContainer as _, SideLabel, Sizing, WrapWidth, +}; use craft_ui::display::Text; use craft_ui::layout_components::{Row, Stack}; use craft_ui::testing::{Fixture, trial}; @@ -191,6 +193,45 @@ fn labelled_radios_in_a_wrapping_row_break_onto_a_new_line() { assert!(starts >= 2, "a radio that wraps starts its line at the row's start edge: {starts} radios do"); } +/// A wrapping `SpaceBetween` row that fills a stack its least width makes wider than its wrap width, and whose children +/// fit one line, spreads them over the wrap width, the line length it wraps them at. Without a wrap width it spreads +/// them over the whole stack. +#[trial] +fn a_spread_wrapping_row_keeps_to_the_stacks_wrap_width() { + use craft_ui::runtime::env::Env; + let shown = |wrap_width: bool| { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING, Rect::NOTHING, 0.0))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let (first, last, wrap) = (Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING), Cell::new(0.0)); + let stack = Stack::new().least_width(LeastWidth::WideDialog); + let stack = if wrap_width { stack.wrap_width(WrapWidth::Dialog) } else { stack }; + let shown = stack.show(ui, |ui, _| { + wrap.set(WrapWidth::Dialog.points(Env::of(ui).tokens.tokens())); + Row::new().wrap(true).align(RowAlign::SpaceBetween).sizing(Sizing::FillWidth).show(ui, |ui, _| { + first.set(Button::new("Home").id_salt("home").show(ui).rect); + last.set(Button::new("Next").id_salt("next").show(ui).rect); + }); + }); + if !ui.is_sizing_pass() { + out.set((shown.output.rect, first.get(), last.get(), wrap.get())); + } + }); + fixture.room(Vec2::new(1600.0, 600.0)).settle(); + seen.get() + }; + let (stack, first, last, wrap) = shown(true); + let dump = format!("stack {stack:?}, first {first:?}, last {last:?}, wrap width {wrap}"); + assert!(stack.width() > wrap + 1.0, "the least width makes the stack wider than its wrap width: {dump}"); + assert!((first.center().y - last.center().y).abs() < 1.0, "the children share one line: {dump}"); + assert!(last.max.x <= first.min.x + wrap + 0.5, "the last child ends within the wrap width: {dump}"); + assert!(last.max.x > first.min.x + wrap - 0.5, "the last child ends at the wrap width's end: {dump}"); + let (stack, first, last, _) = shown(false); + let dump = format!("stack {stack:?}, first {first:?}, last {last:?}"); + assert!((first.center().y - last.center().y).abs() < 1.0, "without a wrap width the children share one line: {dump}"); + assert!((last.max.x - stack.max.x).abs() < 0.5, "without a wrap width the last child ends at the stack's end: {dump}"); +} + /// A body that scrolls keeps the bar's lane clear: a child that fills the width stops where the bar starts, not under it /// (a Print page's buttons ran under the settings column's bar). #[trial] From b74d5e7efcc17b69355c8649b173a69e20cd0dbb Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:10:53 +0100 Subject: [PATCH 21/31] ui-contract: a ruled footer that draws nothing takes no divider ToolRail always installs a ruled footer region. Hosts that pass an empty footer closure were left with a divider under the last tool and a sliver of empty room. Skip the rule band and its size when the footer painted nothing. --- crates/ui-contract/src/contract/body/hooks.rs | 4 ++-- crates/ui-contract/src/contract/body/regions.rs | 2 +- crates/ui-panels/src/rails/tool.rs | 2 +- crates/ui-panels/tests/it/rails/drawer.rs | 16 ++++++++++++++++ 4 files changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 6287e64633..dd1a64502c 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -1850,10 +1850,10 @@ impl BodyHooks<'_> { if took.x > 0.0 { took.x += offset + 2.0 * inset; } + // A footer that drew nothing takes no band, gap or rule: a rule over nothing would part the body from empty room. if took.y > 0.0 { - took.y += lead + inset; + took.y += lead + inset + self.rules.footer; } - took.y += self.rules.footer; if slot.is_none() { self.footer_size = Some(took); } diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index a7e1fefeaa..d3b73ff6a0 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -553,7 +553,7 @@ impl<'b> BodyHooks<'b> { } else { header }; - let footer_rule = (self.rules.footer > 0.0).then(|| { + let footer_rule = (self.rules.footer > 0.0 && (sizes.footer.y > 0.0 || footer_in_body(props))).then(|| { // A footer across the container rules the whole width; one beside or in the end region rules its own. let x = if full { footer.x_range() } else { inner.x_range() }; let w = self.rules.footer; diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index a4d32edc07..e90452e93f 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -130,7 +130,7 @@ type FooterFn<'a> = Box; /// and the slots fill the rows in reading order. The control padding surrounds the buttons; a slot that ends a group /// leaves `space.gap.inline` after its row; slots within a group sit `space.gap.tight` apart. The Edit Toolbar button /// follows the last slot; the host's footer stays in view under the slots, a divider rule and `space.gap.inline` below -/// them, and the slots scroll when the room is short under +/// them when that footer draws content, and the slots scroll when the room is short under /// an overlay bar in the end padding that shows only under the pointer (`Scroll::overlay`), or at rest too with /// [`bar_at_rest`](ToolRail::bar_at_rest), and its /// buttons show the rail's glyphs. The rail is exactly as tall as its rows and footer at the width it gets diff --git a/crates/ui-panels/tests/it/rails/drawer.rs b/crates/ui-panels/tests/it/rails/drawer.rs index 8037469230..f1c094e71c 100644 --- a/crates/ui-panels/tests/it/rails/drawer.rs +++ b/crates/ui-panels/tests/it/rails/drawer.rs @@ -337,3 +337,19 @@ fn a_rule_parts_the_drawers_list_from_its_footer_at_the_drawers_foot() { "the room under Restore Defaults {restore:?} is no more than the room above the title {title:?} in {drawer:?}" ); } + +/// A rail whose host draws no footer shows no rule under its last tool. +#[trial] +fn a_rail_without_a_footer_shows_no_rule_under_its_tools() { + use craft_ui::rails::{LastUsed, ToolRail}; + let slots = Tracked::new(vec![slot(0, &[UNDO]), slot(1, &[REDO]), slot(2, &[CUT])]); + let last = Tracked::new(LastUsed::default()); + let mut fixture = Fixture::new(move |ui| { + ToolRail::new("Tools", &slots, &UNDO, &last).show_rail(ui, |_, _| {}); + }); + fixture.room(Vec2::new(60.0, 400.0)).settle(); + let cut = fixture.by_label("Cut").expect("the rail shows Cut").rect; + let shapes = fixture.frame_shapes(); + let rules = level_rules(&shapes, cut.bottom(), f32::MAX, cut.width()); + assert!(rules.is_empty(), "no rule lies under the last tool {cut:?} of a rail with no footer: {rules:?}"); +} From cc3172c60645a77c6eafd555f920d29c31f76fb3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 13:22:26 -0800 Subject: [PATCH 22/31] ui: a wrapping spread row on one line sets its children on an unwrapped row's line A wrapping SpaceBetween row whose children fit one line recorded its line at the middle of its tallest child. When the real run spread the children, a child whose line lies above its middle (a nested row whose line is its first button's, beside a column of two buttons) sat its line on that middle and reached below the row's measured height, over the next sibling. The measuring run now records what each child takes about a line, as an unwrapped row's children do, and the row records that line and its height. The measuring block takes that height when the real run may spread the children, so the container measures the row as tall as it shows. --- crates/ui-contract/src/layout/body.rs | 51 +++++++++++++------ .../tests/it/layout/stack_widths.rs | 38 ++++++++++++++ 2 files changed, 73 insertions(+), 16 deletions(-) diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index a5ed448344..b15ac50b43 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -229,6 +229,9 @@ pub(crate) struct WrapRows(IdMap); struct WrapTook { /// Each child placed so far: its line, counted from the row's first, and its height. children: Vec<(usize, f32)>, + /// What the children took about a line, as an unwrapped row's children do (`RowLines`): the line a real run that + /// spreads them on one line sets them on. + line: LineTook, /// The top of the last child's slot. top: Option, /// In a real run, each child's line and that line's height in this pass's measuring run, while every child so far @@ -246,9 +249,9 @@ fn open_wraps(ctx: &egui::Context, sizing: bool, id: Id) { } /// Ends the children of the wrapping `Row` body `id`, `room` wide; a measuring run records each child's line and the -/// height of its tallest child. A measuring run returns how many children the row placed and the height of its tallest -/// child when every one of them sits on its first line. -fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2) -> Option<(usize, f32)> { +/// height of its tallest child. A measuring run returns how many children the row placed and what they took about a +/// line when every one of them sits on its first line. +fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2) -> Option<(usize, LineTook)> { let took = pass_state::with::(ctx, |rows| rows.0.remove(&id)).unwrap_or_default(); if !sizing { return None; @@ -264,7 +267,7 @@ fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2) -> Option< for (i, &(line, _)) in took.children.iter().enumerate() { found(ctx, true, sub(id, ("wrap", i)), room, Vec2::new(line as f32, heights.get(line).copied().unwrap_or_default())); } - (heights.len() <= 1).then(|| (took.children.len(), heights.first().copied().unwrap_or_default())) + (heights.len() <= 1).then_some((took.children.len(), took.line)) } /// Whether egui puts the next child `width` wide in `ui`, a wrapping row's block, on a new line (`Layout::next_frame`): @@ -276,10 +279,11 @@ fn wraps(ui: &Ui, width: f32) -> bool { } /// Counts the next child of `size` placed in `ui`, the block of the wrapping `Row` body that places the children under -/// `env`, on its line: the line egui sets it on, or a line another allocation started. Returns the height of that line +/// `env`, on its line: the line egui sets it on, or a line another allocation started. `first` is how far below its +/// top the child's first line's centre lies, as a child of an unwrapped row reports it. Returns the height of that line /// in this pass's measuring run while each child so far went on the line it went on there; `None` outside a wrapping /// row, in a measuring run, and once the lines differ. -fn wrap_line(ui: &Ui, env: &Env, size: Vec2) -> Option { +fn wrap_line(ui: &Ui, env: &Env, size: Vec2, first: Option) -> Option { let body = env.flow_body.filter(|_| ui.layout().main_wrap)?; let (starts, top) = (wraps(ui, size.x), ui.cursor().top()); pass_state::with::(ui.ctx(), |rows| { @@ -291,6 +295,7 @@ fn wrap_line(ui: &Ui, env: &Env, size: Vec2) -> Option { }; let i = took.children.len(); took.children.push((line, size.y)); + took.line.add(first, size.y); let planned = took.planned.as_ref().and_then(|planned| planned.get(i)).filter(|(at, _)| *at == line).map(|(_, height)| *height); if planned.is_none() { took.planned = None; @@ -1480,7 +1485,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, env: &Env, size: Vec2, child: InFlow) - let centre = bracket.and_then(|(_, centre)| centre).or_else(|| line.and_then(|line| line.centre)); let above = centre.zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); // A child of a wrapping row takes the height of its line; a one-line child sits at its middle. - let wrapped = if line.is_none() { wrap_line(ui, env, size) } else { None }; + let wrapped = if line.is_none() { wrap_line(ui, env, size, child.first) } else { None }; let height = line.and_then(|line| line.height).or(wrapped); let slot = Vec2::new(size.x, height.map_or(above + size.y, |height| height.max(above + size.y))); let (rect, in_cell) = take_in_flow(ui, env, slot); @@ -2166,6 +2171,14 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign }; if lines { one_line = close_wraps(&ctx, sizing, id, room.size()); + // Children that the real run may spread on one line sit on the line they take there, as an unwrapped + // row's do: the block takes that line's height, which may be more than its tallest child's (a check box + // with a detail line under its label sits its first line on the line). + let spread = one_line.filter(|(count, _)| align == RowAlign::SpaceBetween && *count >= 2); + if let Some(line) = spread.and_then(|(_, took)| spread_line(id, took, shared)) { + let top = ui.max_rect().top(); + alloc::reach_down_to(ui, top + line.y); + } } Env::restore(&ctx, installed); if !wrap { @@ -2178,16 +2191,22 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign } if wrap && align == RowAlign::SpaceBetween { // Children that all fit the first line are spread over the row by the real run (`one_line_spread`): their - // width at the gap alone and their count, and the line they sit on, at the middle of the tallest one, as - // `record_line` records an unwrapped row's. A row that wraps records no count and no line, so it wraps again. - let (count, tallest) = one_line.unwrap_or_default(); + // width at the gap alone and their count, and the line they sit on (`spread_line`), as `record_line` records + // an unwrapped row's. A row that wraps records no count and no line, so it wraps again. + let count = one_line.map_or(0, |(count, _)| count); found(&ctx, sizing, sub(id, "one_line"), room.size(), Vec2::new(took.width(), count as f32)); - let line = on_line(id, (tallest > 0.0).then_some((tallest / 2.0, tallest)), shared); - let spread_line = match (line.centre, line.height) { - (Some(centre), Some(height)) if one_line.is_some() && height > 0.0 => Vec2::new(centre, height), - _ => Vec2::ZERO, - }; - found(&ctx, sizing, sub(id, "line"), Vec2::new(0.0, shared.unwrap_or(0.0)), spread_line); + let line = one_line.and_then(|(_, took)| spread_line(id, took, shared)).unwrap_or(Vec2::ZERO); + found(&ctx, sizing, sub(id, "line"), Vec2::new(0.0, shared.unwrap_or(0.0)), line); } (inner, (align != RowAlign::Start).then(|| took.width())) } + +/// The line the children of the wrapping `SpaceBetween` row `id` sit on when they `took` one line, with the line +/// `shared` it shares with its container's inline header or end region: how far below the row's top the line's centre +/// lies, and the row's height once every child sits on it, as `record_line` finds an unwrapped row's. `None` when the +/// line has no height. +fn spread_line(id: Id, took: LineTook, shared: Option) -> Option { + let own = (took.height() > 0.0).then(|| (took.centre.unwrap_or(0.0), took.height())); + let line = on_line(id, own, shared); + line.centre.zip(line.height).filter(|(_, height)| *height > 0.0).map(|(centre, height)| Vec2::new(centre, height)) +} diff --git a/crates/ui-widgets/tests/it/layout/stack_widths.rs b/crates/ui-widgets/tests/it/layout/stack_widths.rs index 1a08d56071..1b7bacffaf 100644 --- a/crates/ui-widgets/tests/it/layout/stack_widths.rs +++ b/crates/ui-widgets/tests/it/layout/stack_widths.rs @@ -232,6 +232,44 @@ fn a_spread_wrapping_row_keeps_to_the_stacks_wrap_width() { assert!((last.max.x - stack.max.x).abs() < 0.5, "without a wrap width the last child ends at the stack's end: {dump}"); } +/// A wrapping `SpaceBetween` row whose children fit one line sets them on the line an unwrapped row sets them on, and +/// takes that line's height: a nested row whose line is its first button's, above a column of two buttons beside it, +/// stays inside the row and clear of the button below it. +#[trial] +fn a_spread_wrapping_row_keeps_a_child_whose_line_is_above_its_middle_inside_it() { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING, Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let (row, nested, next, below) = (Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING)); + let _ = Stack::new().gap(Gap::None).show(ui, |ui, _| { + let shown = Row::new().wrap(true).align(RowAlign::SpaceBetween).show(ui, |ui, _| { + let shown = Row::new().show(ui, |ui, _| { + let _ = Button::new("Home").id_salt("home").show(ui); + let _ = Stack::new().show(ui, |ui, _| { + let _ = Button::new("Up").id_salt("up").show(ui); + let _ = Button::new("Down").id_salt("down").show(ui); + }); + }); + nested.set(shown.output.rect); + next.set(Button::new("Next").id_salt("next").show(ui).rect); + }); + row.set(shown.output.rect); + below.set(Button::new("Below").id_salt("below").show(ui).rect); + }); + if !ui.is_sizing_pass() { + out.set((row.get(), nested.get(), next.get(), below.get())); + } + }); + fixture.room(Vec2::new(800.0, 600.0)).settle(); + let (row, nested, next, below) = seen.get(); + let dump = format!("row {row:?}, nested row {nested:?}, next {next:?}, below {below:?}"); + assert!(nested.height() > next.height() * 1.5, "the nested row is two buttons tall: {dump}"); + assert!(next.min.x > nested.max.x, "the children share one line: {dump}"); + assert!(nested.max.y <= row.max.y + 0.5, "the nested row stays inside the row: {dump}"); + assert!(nested.max.y <= below.min.y + 0.5, "the nested row stays clear of the button below: {dump}"); + assert!((next.center().y - (nested.min.y + next.height() / 2.0)).abs() < 1.0, "the button sits on the nested row's line: {dump}"); +} + /// A body that scrolls keeps the bar's lane clear: a child that fills the width stops where the bar starts, not under it /// (a Print page's buttons ran under the settings column's bar). #[trial] From 706df36b99eb0e432a6695e000316677b6bfba33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 13:00:36 -0800 Subject: [PATCH 23/31] ui-contract: a disabled node offers no Expand, Collapse, context menu, step, value or custom action A disabled section heading with children still offered Expand while closed and Collapse while open, and so did any other disabled node that reported an expanded state, on a component's own node and on a sub-node. A disabled node with a value still offered SetValue, Increment and Decrement, a disabled sub-node that steps something offered Increment and Decrement, a disabled node kept its custom actions, and a disabled component with a context menu trigger offered ShowContextMenu. These actions now follow the node's enabled state. The node still reports its expanded state and its value. Fixture::by_label now looks for a disabled node with the name before it falls back to the first node that carries the text, so a disabled value control is still found by its label instead of the field that holds it. --- crates/ui-contract/src/runtime/access/emit.rs | 21 +-- crates/ui-contract/src/testing/fixture.rs | 11 +- .../tests/it/access/disabled_actions.rs | 126 ++++++++++++++++++ crates/ui-contract/tests/it/access/mod.rs | 1 + crates/ui-widgets/tests/it/list.rs | 71 ++++++++++ 5 files changed, 215 insertions(+), 15 deletions(-) create mode 100644 crates/ui-contract/tests/it/access/disabled_actions.rs diff --git a/crates/ui-contract/src/runtime/access/emit.rs b/crates/ui-contract/src/runtime/access/emit.rs index c117a209c0..22993795e0 100644 --- a/crates/ui-contract/src/runtime/access/emit.rs +++ b/crates/ui-contract/src/runtime/access/emit.rs @@ -126,7 +126,7 @@ fn named(name: &Name, label: &str, fallbacks: &[Option<&str>]) -> Named { /// The expanded state of a node: an explicit value, else open when `OPEN` or `EXPANDED` is shown this pass. A /// component that can be open and is closed says so with `Access::expanded`; a node with no state is not -/// expandable, so `Expand` and `Collapse` are declared only where the state exists. +/// expandable, so `Expand` and `Collapse` are declared only where the state exists and the node is enabled. fn expanded_of(flags: Flags, explicit: Option) -> Option { explicit.or_else(|| flags.intersects(Flags::OPEN | Flags::EXPANDED).then_some(true)) } @@ -160,7 +160,8 @@ fn write_position(spec: &mut NodeSpec, position: Option, level: Opt } } -/// The actions the interaction and the numeric facts declare. +/// The actions the interaction and the numeric facts declare. Called after `write_states`: a disabled node offers no +/// context menu and no value action. fn declare_actions( spec: &mut NodeSpec, focusable: bool, @@ -169,15 +170,15 @@ fn declare_actions( numeric: Option<&Numeric>, variable_steps: Option<(bool, bool)>, ) { - // A read-only value offers no action that would change it. - let numeric = numeric.filter(|_| !spec.read_only); + // A read-only or disabled value offers no action that would change it. + let numeric = numeric.filter(|_| !spec.read_only && !spec.disabled); if focusable { spec.actions.push(NodeAction::Focus); } if clickable { spec.actions.push(NodeAction::Click); } - if context_menu { + if context_menu && !spec.disabled { spec.actions.push(NodeAction::ContextMenu); } if let Some(numeric) = numeric { @@ -213,7 +214,11 @@ fn declare_scroll_actions(spec: &mut NodeSpec, (vertical, horizontal): (bool, bo } } +/// The custom actions of a node, none while it is disabled. Called after `write_states`. fn custom_actions(spec: &mut NodeSpec, actions: &[(i32, Label)]) { + if spec.disabled { + return; + } spec.custom_actions = actions.iter().map(|(id, label)| (*id, label.as_str().to_owned())).collect(); } @@ -317,7 +322,7 @@ pub(crate) fn report(ctx: &Context, own: &Own<'_>) { write_states(&mut spec, own.flags, own.selected, own.enabled, own.read_only); spec.ltr_axis = own.ltr_axis; spec.busy |= access.busy; - if let Some(expanded) = expanded { + if let Some(expanded) = expanded.filter(|_| own.enabled) { spec.actions.push(if expanded { NodeAction::Collapse } else { NodeAction::Expand }); } declare_actions(&mut spec, own.focusable, own.clickable, own.context_menu, numeric, access.variable_steps); @@ -408,7 +413,7 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) { spec.url = node.url.clone(); spec.has_popup = node.has_popup; spec.current = node.current || flags.contains(Flags::CURRENT); - if let Some(expanded) = expanded { + if let Some(expanded) = expanded.filter(|_| decl.enabled) { spec.actions.push(if expanded { NodeAction::Collapse } else { NodeAction::Expand }); } write_position(&mut spec, node.position, node.level); @@ -417,7 +422,7 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) { spec.sortable = node.sortable; write_states(&mut spec, flags, None, decl.enabled, false); declare_actions(&mut spec, decl.focusable, decl.clickable, false, numeric, None); - if node.steps && numeric.is_none() { + if node.steps && numeric.is_none() && decl.enabled { spec.actions.extend([NodeAction::Increment, NodeAction::Decrement]); } custom_actions(&mut spec, &node.custom_actions); diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index 4b407b1277..f662509a07 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -608,21 +608,18 @@ impl Fixture { /// The node named `label`: the interactive node whose name resolves to it (its own, or the node that labels it /// through `labelled_by`) and that labels no other node, so a field's control comes before its caption link; - /// else the first node that carries the text. + /// else such a node that is disabled; else the first node that carries the text. pub fn by_label(&self, label: &str) -> Option { let tree = &self.tree; let reported: HashSet = tree.keys().into_iter().collect(); let labels: HashSet = reported.iter().flat_map(|key| tree.labelled_by_key(*key)).collect(); let ordered = self.in_tree_order(&reported); + let named = |key: NodeKey| super::access::name(tree, key) == Some(label) && tree.role_of(key) != Some(Role::LABEL) && !labels.contains(&key); let node = ordered .iter() .copied() - .find(|key| { - super::access::name(tree, *key) == Some(label) - && tree.role_of(*key) != Some(Role::LABEL) - && !labels.contains(key) - && super::access::is_interactive(tree, *key) - }) + .find(|key| named(*key) && super::access::is_interactive(tree, *key)) + .or_else(|| ordered.iter().copied().find(|key| named(*key) && tree.is_disabled_key(*key))) .or_else(|| ordered.iter().copied().find(|key| tree.name_of(*key) == Some(label)))?; self.target(node) } diff --git a/crates/ui-contract/tests/it/access/disabled_actions.rs b/crates/ui-contract/tests/it/access/disabled_actions.rs new file mode 100644 index 0000000000..72a139fc3f --- /dev/null +++ b/crates/ui-contract/tests/it/access/disabled_actions.rs @@ -0,0 +1,126 @@ +//! A disabled node offers no action that would act on it: no Expand or Collapse, no context menu, no value step and no +//! custom action, on a component's own node and on its sub-nodes, while it still reports its state. + +use craft_behavior::PartKey; +use craft_ui::contract::{Access, Common, Component, Cx, MeasureCx, Name, Numeric, Overlays as _, Props as _, Role, Show as _, Trigger}; +use craft_ui::style::StyleCx; +use craft_ui::testing::access::Declared; +use craft_ui::testing::{Fixture, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::{Id, Vec2}; +use std::cell::Cell; +use std::rc::Rc; + +const SECTION: PartKey = PartKey::new("section"); +const KNOB: PartKey = PartKey::new("knob"); +const NUDGE: PartKey = PartKey::new("nudge"); + +/// A closed disclosure button with a custom action and a context menu, and three sub-nodes: an open heading, a stepped +/// knob and a part that steps something with no number and serves a custom action. +#[derive(craft_ui::contract::Component)] +struct Fold { + #[common] + common: Common, +} + +impl Component for Fold { + const ROLE: Role = Role::BUTTON; + type Style = PlainStyle; + type Output = egui::Response; + + fn style(_: &StyleCx<'_>, _: FoldStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(120.0, 30.0) + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.expanded(false).custom_action(1, "Reset".into()); + let section = access.node(SECTION, Role::HEADING).expanded(true); + section.name = Name::Text("Section".to_owned()); + let knob = access.node(KNOB, Role::SLIDER); + knob.name = Name::Text("Knob".to_owned()); + knob.numeric = Some(Numeric::new(3.0, 0.0..=10.0).step(1.0)); + let nudge = access.node(NUDGE, Role::BUTTON).steps().custom_action(2, "Center".into()); + nudge.name = Name::Text("Nudge".to_owned()); + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + cx.popup("menu").trigger(Trigger::Context, cx); + } + + fn finish(self, cx: Cx<'_, Self>) -> egui::Response { + cx.response.clone() + } +} + +/// A stepped value in the middle of its range. +#[derive(craft_ui::contract::Component)] +struct Dial { + #[common] + common: Common, +} + +impl Component for Dial { + const ROLE: Role = Role::SLIDER; + type Style = PlainStyle; + type Output = egui::Response; + + fn style(_: &StyleCx<'_>, _: DialStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(120.0, 30.0) + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.numeric(Numeric::new(5.0, 0.0..=10.0).step(1.0)); + } + + fn finish(self, cx: Cx<'_, Self>) -> egui::Response { + cx.response.clone() + } +} + +#[trial] +fn a_disabled_node_offers_no_action_and_keeps_its_state() { + let enabled = Rc::new(Cell::new(true)); + let fold = Rc::new(Cell::new(Id::NULL)); + let (gate, shown) = (enabled.clone(), fold.clone()); + let mut fixture = Fixture::new(move |ui| { + shown.set(Fold { common: Common::new() }.label("Fold").enabled(gate.get()).show(ui).id); + Dial { common: Common::new() }.label("Dial").enabled(gate.get()).show(ui); + }); + for on in [true, false] { + enabled.set(on); + fixture.settle(); + let tree = fixture.tree(); + let own = fixture.by_label("Fold").expect("the disclosure"); + let dial = fixture.by_label("Dial").expect("the value"); + let part = |key: PartKey| fixture.part(fold.get(), key).expect("the part's node"); + let (section, knob, nudge) = (part(SECTION), part(KNOB), part(NUDGE)); + assert_eq!(tree.expanded_of(own.node), Some(false), "the disclosure reports it is closed (enabled: {on})"); + assert_eq!(tree.expanded_of(section.node), Some(true), "the heading reports it is open (enabled: {on})"); + let offers = [ + (own.node, Declared::Expand, "the disclosure's Expand"), + (own.node, Declared::Custom, "the disclosure's custom action"), + (own.node, Declared::ContextMenu, "the disclosure's context menu"), + (section.node, Declared::Collapse, "the heading's Collapse"), + (knob.node, Declared::SetValue, "the knob's SetValue"), + (knob.node, Declared::Increment, "the knob's Increment"), + (knob.node, Declared::Decrement, "the knob's Decrement"), + (nudge.node, Declared::Increment, "the nudge's Increment"), + (nudge.node, Declared::Decrement, "the nudge's Decrement"), + (nudge.node, Declared::Custom, "the nudge's custom action"), + (dial.node, Declared::SetValue, "the dial's SetValue"), + (dial.node, Declared::Increment, "the dial's Increment"), + (dial.node, Declared::Decrement, "the dial's Decrement"), + ]; + for (node, action, what) in offers { + assert_eq!(tree.declares_key(node, action), on, "{what} is offered only while enabled (enabled: {on})"); + } + } +} diff --git a/crates/ui-contract/tests/it/access/mod.rs b/crates/ui-contract/tests/it/access/mod.rs index 91b1a25461..59c581eb0a 100644 --- a/crates/ui-contract/tests/it/access/mod.rs +++ b/crates/ui-contract/tests/it/access/mod.rs @@ -2,6 +2,7 @@ pub(crate) mod bounds; pub(crate) mod controls; +pub(crate) mod disabled_actions; pub(crate) mod face_record; pub(crate) mod face_state; pub(crate) mod focus; diff --git a/crates/ui-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index e7ed2b4779..de5a4a7f92 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -2304,3 +2304,74 @@ fn tight_thumbnail_rows_stand_lower_and_indent_less() { assert!(tight_height < roomy_height, "the tight row ({tight_height}) is lower than the roomy one ({roomy_height})"); assert!(0.0 < tight_indent && tight_indent < roomy_indent, "a level indents less ({tight_indent}) than an icon slot ({roomy_indent})"); } + +/// A section heading with children offers Expand while closed and Collapse while open, and neither while its list or +/// its own row is disabled. +#[trial] +fn a_disabled_section_heading_offers_no_expand_or_collapse() { + use craft_behavior::{DisplayOrder, ItemSource}; + use craft_ui::testing::access::Declared; + use std::borrow::Cow; + use std::cell::Cell; + + const ROWS: [&str; 2] = ["Inks", "Cyan"]; + struct Source { + heading_enabled: bool, + open: bool, + } + impl DisplayOrder for Source { + fn len(&self) -> usize { + if self.open { ROWS.len() } else { 1 } + } + fn key(&self, at: usize) -> usize { + at + } + fn has_children(&self, at: usize) -> bool { + at == 0 + } + fn open(&self, at: usize) -> bool { + at == 0 && self.open + } + fn is_section(&self, at: usize) -> bool { + at == 0 + } + fn section_stop(&self, at: usize) -> bool { + at == 0 + } + fn section_stops_before(&self, at: usize) -> usize { + usize::from(at > 0) + } + fn enabled(&self, at: usize) -> bool { + at != 0 || self.heading_enabled + } + fn text(&self, at: usize) -> Option> { + Some(Cow::Borrowed(ROWS[at])) + } + } + impl ItemSource for Source {} + + let state = Rc::new(Cell::new((true, true, false))); + let shown = state.clone(); + let mut fixture = Fixture::new(move |ui| { + let (list_enabled, heading_enabled, open) = shown.get(); + let source = Source { heading_enabled, open }; + let _ = List::new("Plates").enabled(list_enabled).show_items(ui, &source, &mut |key, _| ListRow::new(ROWS[*key])); + }); + for (open, offered, other) in [(false, Declared::Expand, Declared::Collapse), (true, Declared::Collapse, Declared::Expand)] { + state.set((true, true, open)); + fixture.settle(); + let heading = fixture.by_label("Inks").expect("the heading"); + assert_eq!(fixture.tree().expanded_of(heading.node), Some(open), "the heading reports its open state"); + assert!(fixture.tree().declares_key(heading.node, offered), "an enabled heading offers {offered:?} (open: {open})"); + assert!(!fixture.tree().declares_key(heading.node, other), "an enabled heading offers no {other:?} (open: {open})"); + for (list_enabled, heading_enabled, denied) in [(false, true, "disabled list"), (true, false, "disabled section")] { + state.set((list_enabled, heading_enabled, open)); + fixture.settle(); + let heading = fixture.by_label("Inks").expect("a disabled heading stays in the accessibility tree"); + assert_eq!(fixture.tree().expanded_of(heading.node), Some(open), "the heading of a {denied} still reports its open state"); + for action in [Declared::Expand, Declared::Collapse] { + assert!(!fixture.tree().declares_key(heading.node, action), "the heading of a {denied} still offers {action:?} (open: {open})"); + } + } + } +} From 3a8c25c711821a9e8d50b0369dfa38e509501003 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 13:37:18 -0800 Subject: [PATCH 24/31] ui-panels: the drawer footer test rejects Restore Defaults below the drawer The footer-room check alone passed when Restore Defaults extended past the drawer's bottom edge, since the clearance was then negative. The test now also requires the clearance to be at least -1 point. --- crates/ui-panels/tests/it/rails/drawer.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-panels/tests/it/rails/drawer.rs b/crates/ui-panels/tests/it/rails/drawer.rs index f1c094e71c..57b2fa76f4 100644 --- a/crates/ui-panels/tests/it/rails/drawer.rs +++ b/crates/ui-panels/tests/it/rails/drawer.rs @@ -332,6 +332,7 @@ fn a_rule_parts_the_drawers_list_from_its_footer_at_the_drawers_foot() { let shapes = fixture.frame_shapes(); let rules = level_rules(&shapes, hint.bottom(), below.top(), drawer.width() / 2.0); assert_eq!(rules.len(), 1, "one rule lies between the list and the footer {below:?}: {rules:?}"); + assert!(drawer.bottom() - restore.bottom() >= -1.0, "Restore Defaults {restore:?} stays inside the drawer {drawer:?}"); assert!( drawer.bottom() - restore.bottom() <= title.top() - drawer.top() + 1.0, "the room under Restore Defaults {restore:?} is no more than the room above the title {title:?} in {drawer:?}" From 61d99fa43634dcf795054af170f784582df96ad3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 14:36:22 -0800 Subject: [PATCH 25/31] ui-contract: an accessibility request that acts on a disabled node reaches no component route_access sent Expand, Collapse, ShowContextMenu, Increment, Decrement, SetValue, ReplaceSelectedText and custom actions on to the owner of a disabled node, so a disabled component opened its menu or context menu, took a step or a value, or ran a custom action. Each registered node now records whether it is enabled, and route_access drops these requests and Click on a disabled node before it moves focus. Focus, the scroll requests and a text selection still reach the owner. --- .../ui-contract/src/contract/steps/report.rs | 3 + crates/ui-contract/src/runtime/access/emit.rs | 9 + crates/ui-contract/src/runtime/access/text.rs | 3 + crates/ui-contract/src/runtime/egui/input.rs | 18 ++ crates/ui-contract/src/runtime/keys.rs | 4 +- crates/ui-contract/src/runtime/keys/nodes.rs | 13 +- crates/ui-contract/src/runtime/keys/route.rs | 6 +- .../tests/it/runtime/disabled_requests.rs | 272 ++++++++++++++++++ crates/ui-contract/tests/it/runtime/mod.rs | 1 + 9 files changed, 326 insertions(+), 3 deletions(-) create mode 100644 crates/ui-contract/tests/it/runtime/disabled_requests.rs diff --git a/crates/ui-contract/src/contract/steps/report.rs b/crates/ui-contract/src/contract/steps/report.rs index 5a7b1873fc..38515ccabd 100644 --- a/crates/ui-contract/src/contract/steps/report.rs +++ b/crates/ui-contract/src/contract/steps/report.rs @@ -236,6 +236,9 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> } if let Some(folded) = &folded { keys::register_node(ctx, id, folded.inner, None, focusable); + if !resolved.enabled { + keys::register_disabled(ctx, id); + } } let editor_record = || { let widget = core.editor.as_ref()?.widget; diff --git a/crates/ui-contract/src/runtime/access/emit.rs b/crates/ui-contract/src/runtime/access/emit.rs index c117a209c0..eb5a585dd1 100644 --- a/crates/ui-contract/src/runtime/access/emit.rs +++ b/crates/ui-contract/src/runtime/access/emit.rs @@ -346,6 +346,9 @@ pub(crate) fn report(ctx: &Context, own: &Own<'_>) { ); keys::register_node(ctx, own.id, own.id, None, own.focusable); keys::register_expanded(ctx, own.id, expanded, own.toggle); + if !own.enabled { + keys::register_disabled(ctx, own.id); + } scope::register( ctx, scope::ScopeNode { @@ -383,6 +386,9 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) { }, ); keys::register_node(ctx, id, decl.owner, Some(node.part), false); + if !decl.enabled { + keys::register_disabled(ctx, id); + } return; } let face_name = decl.face.as_ref().map(|face| face.name); @@ -440,6 +446,9 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) { ); keys::register_node(ctx, id, decl.owner, Some(node.part), decl.focusable); keys::register_expanded(ctx, id, expanded, None); + if !decl.enabled { + keys::register_disabled(ctx, id); + } if decl.active { adapter::set_focus(ctx, id); } diff --git a/crates/ui-contract/src/runtime/access/text.rs b/crates/ui-contract/src/runtime/access/text.rs index 46d255a9aa..428c3ae2d4 100644 --- a/crates/ui-contract/src/runtime/access/text.rs +++ b/crates/ui-contract/src/runtime/access/text.rs @@ -114,6 +114,9 @@ pub(crate) fn report_text(ctx: &Context, owner: Id, facts: &TextFacts, unit: Opt ); let index = u64::try_from(entries.len()).ok(); keys::register_node(ctx, id, owner, Some(PartRef { key: RUN, index }), false); + if facts.disabled { + keys::register_disabled(ctx, id); + } entries.push(Entry { node: adapter::node_key(id), line: line_at, bytes: run.bytes.clone(), text: text.to_owned() }); } } diff --git a/crates/ui-contract/src/runtime/egui/input.rs b/crates/ui-contract/src/runtime/egui/input.rs index 2f26c1d500..049701d614 100644 --- a/crates/ui-contract/src/runtime/egui/input.rs +++ b/crates/ui-contract/src/runtime/egui/input.rs @@ -275,6 +275,24 @@ impl Action { matches!(self.0.action, A::ScrollIntoView | A::ScrollUp | A::ScrollDown | A::ScrollLeft | A::ScrollRight | A::SetScrollOffset) } + /// Whether the request acts on its node: activates, opens or closes it, shows its context menu, steps or sets its + /// value, edits its text or runs one of its custom actions. A disabled node takes none of these. + pub(crate) fn acts(&self) -> bool { + use accesskit::Action as A; + matches!( + self.0.action, + A::Click + | A::Expand + | A::Collapse + | A::ShowContextMenu + | A::Increment + | A::Decrement + | A::SetValue + | A::ReplaceSelectedText + | A::CustomAction + ) + } + /// The request as an `Intent::Access` payload for the sub-node `part`. pub(crate) fn request(&self, part: Option) -> craft_behavior::AccessRequest { craft_behavior::AccessRequest::new(self.0.action, part, self.0.data.clone()) diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index c4a14baddf..ceb9750c6d 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -46,7 +46,7 @@ pub(crate) use intents::{ take_cancel, take_every_escape, take_window_cancel, }; pub use intents::{with_canvas_window_intents, with_window_intents}; -pub(crate) use nodes::{redirect_node, register_expanded, register_node}; +pub(crate) use nodes::{redirect_node, register_disabled, register_expanded, register_node}; pub(crate) use route::{ activated_member, begin, focus_in_modal_dialog, layout_of, note_fired, owner_at, pasted, pasted_text, queue_edit, routed_to, take_shortcuts, }; @@ -286,6 +286,8 @@ struct Node { owner: Id, part: Option, focusable: bool, + /// The node is enabled this pass: a request that acts on a disabled node reaches no one. + enabled: bool, /// The node's expanded state this pass, `None` when it has none. expanded: Option, /// The part of the owner that opens the popup whose state the node reports, when that part has no node of its own: diff --git a/crates/ui-contract/src/runtime/keys/nodes.rs b/crates/ui-contract/src/runtime/keys/nodes.rs index 74de801402..c1a5547f12 100644 --- a/crates/ui-contract/src/runtime/keys/nodes.rs +++ b/crates/ui-contract/src/runtime/keys/nodes.rs @@ -37,6 +37,17 @@ pub(crate) fn register_expanded(ctx: &Context, node: Id, expanded: Option, }); } +/// Marks the node registered by `register_node` as disabled: a request that would act on it (`Action::acts`) reaches +/// no one, while Focus, the scroll requests and a text selection still go to its owner. +pub(crate) fn register_disabled(ctx: &Context, node: Id) { + crate::runtime::replay::journal(ctx, || node, |ctx, &node| register_disabled(ctx, node)); + current(ctx, |stage| { + if let Some(entry) = stage.nodes.get_mut(&node_key(node)) { + entry.enabled = false; + } + }); +} + /// Registers an AccessKit node so a request that targets it reaches `owner`. pub(crate) fn register_node(ctx: &Context, node: Id, owner: Id, part: Option, focusable: bool) { crate::runtime::replay::journal( @@ -46,6 +57,6 @@ pub(crate) fn register_node(ctx: &Context, node: Id, owner: Id, part: Option Option { Some(Nudge { direction, mods: press.mods, held: press.held.clone() }) } -/// Routes an AccessKit action request to the owner of its target node, whatever the focus (9.2 rule 2). +/// Routes an AccessKit action request to the owner of its target node, whatever the focus (9.2 rule 2). A request +/// that acts on a disabled node is dropped before it moves focus. fn route_access(ctx: &Context, request: &Action, nodes: &HashMap, routed: &mut HashMap, Routed>, activated: &mut IdMap) { let Some(node) = nodes.get(&request.node()).copied() else { return }; + if !node.enabled && request.acts() { + return; + } let owner = Some(node.owner); // A request that only scrolls (a screen reader's Scroll Into View) shows the node and leaves focus where it is. if node.focusable && !request.scrolls() { diff --git a/crates/ui-contract/tests/it/runtime/disabled_requests.rs b/crates/ui-contract/tests/it/runtime/disabled_requests.rs new file mode 100644 index 0000000000..cb767dd943 --- /dev/null +++ b/crates/ui-contract/tests/it/runtime/disabled_requests.rs @@ -0,0 +1,272 @@ +//! An AccessKit request that would act on a disabled node does not reach its component: no Expand, Collapse, Click, +//! context menu, step, value or custom action, on the component's own node or on its sub-nodes. The same requests on +//! an enabled component do. + +use craft_behavior::{AccessAction, AccessData, Input, PartKey, Sense}; +use craft_ui::contract::{ + Access, Common, Component, Cx, Focus as _, MeasureCx, Name, Numeric, Overlays as _, PartsCx, Pointer as _, Props as _, Role, Show as _, Trigger, +}; +use craft_ui::runtime::focus::KeyUse; +use craft_ui::style::StyleCx; +use craft_ui::testing::{Fixture, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::accesskit::{ActionRequest, NodeId, TreeId}; +use egui::{Event, Id, Rect, Vec2, pos2}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +const CHEVRON: PartKey = PartKey::new("chevron"); +const SECTION: PartKey = PartKey::new("section"); +const KNOB: PartKey = PartKey::new("knob"); +const NUDGE: PartKey = PartKey::new("nudge"); + +/// What reached the components in their latest run. +#[derive(Default)] +struct Seen { + menu_open: Cell, + context_open: Cell, + activations: Cell, + moves: Cell, + values: RefCell>, + requests: RefCell>, + opener: Cell>, + dial: Cell>, +} + +impl Seen { + fn requested(&self, action: AccessAction) -> bool { + self.requests.borrow().contains(&action) + } +} + +/// A button whose chevron part, with no node of its own, opens a menu, with a context menu, a custom action and three +/// sub-nodes: an open heading, a stepped knob and a part that steps something with no number. +#[derive(craft_ui::contract::Component)] +struct Opener { + #[common] + common: Common, + seen: Rc, +} + +impl Component for Opener { + const ROLE: Role = Role::BUTTON; + type Style = PlainStyle; + type Output = egui::Response; + + fn style(_: &StyleCx<'_>, _: OpenerStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(160.0, 30.0) + } + + fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { + let chevron = Rect::from_min_max(pos2(rect.max.x - 30.0, rect.min.y), rect.max); + cx.part(CHEVRON, chevron).sense(Sense::CLICK).toggles("menu"); + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.custom_action(1, "Reset".into()); + let section = access.node(SECTION, Role::HEADING).expanded(true); + section.name = Name::Text("Section".to_owned()); + let knob = access.node(KNOB, Role::SLIDER); + knob.name = Name::Text("Knob".to_owned()); + knob.numeric = Some(Numeric::new(3.0, 0.0..=10.0).step(1.0)); + let nudge = access.node(NUDGE, Role::BUTTON).steps(); + nudge.name = Name::Text("Nudge".to_owned()); + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + cx.popup("context").trigger(Trigger::Context, cx); + self.seen.menu_open.set(cx.popup("menu").is_open(cx)); + self.seen.context_open.set(cx.popup("context").is_open(cx)); + if cx.activation().is_some() { + self.seen.activations.set(self.seen.activations.get() + 1); + } + if let Some(value) = cx.intents().take_set_value_at(KNOB) { + self.seen.values.borrow_mut().push(value); + } + while let Some(request) = cx.intents().take_access() { + self.seen.requests.borrow_mut().push(request.action); + } + } + + fn finish(self, cx: Cx<'_, Self>) -> egui::Response { + cx.response.clone() + } +} + +/// A stepped value in the middle of its range that takes the moves and values routed to it. +#[derive(craft_ui::contract::Component)] +struct Dial { + #[common] + common: Common, + seen: Rc, +} + +impl Component for Dial { + const ROLE: Role = Role::SLIDER; + type Style = PlainStyle; + type Output = egui::Response; + + fn keys(&self) -> KeyUse { + KeyUse::of(Input::Pointer).with_moves() + } + + fn style(_: &StyleCx<'_>, _: DialStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(120.0, 30.0) + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.numeric(Numeric::new(5.0, 0.0..=10.0).step(1.0)); + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + while cx.intents().take_move().is_some() { + self.seen.moves.set(self.seen.moves.get() + 1); + } + if let Some(value) = cx.intents().take_set_value() { + self.seen.values.borrow_mut().push(value); + } + } + + fn finish(self, cx: Cx<'_, Self>) -> egui::Response { + cx.response.clone() + } +} + +/// The node a request targets. +#[derive(Clone, Copy)] +enum Aim { + Opener, + Dial, + Part(PartKey), +} + +/// One request and how the components show that it reached them. +struct Case { + what: &'static str, + aim: Aim, + action: AccessAction, + data: Option, + reached: fn(&Seen) -> bool, +} + +/// Shows the two components, enabled or not, sends the request of `case` and returns what reached them. +fn send(case: &Case, enabled: bool) -> Rc { + let seen = Rc::new(Seen::default()); + let shown = seen.clone(); + let mut fixture = Fixture::new(move |ui| { + let opener = Opener { common: Common::new(), seen: shown.clone() }.label("Opener").enabled(enabled).show(ui); + shown.opener.set(Some(opener.id)); + let dial = Dial { common: Common::new(), seen: shown.clone() }.label("Dial").enabled(enabled).show(ui); + shown.dial.set(Some(dial.id)); + }); + fixture.settle(); + let opener = seen.opener.get().expect("the opener ran"); + let node = match case.aim { + Aim::Opener => opener.accesskit_id(), + Aim::Dial => seen.dial.get().expect("the dial ran").accesskit_id(), + Aim::Part(part) => NodeId(fixture.part(opener, part).expect("the part's node").node.raw()), + }; + let request = ActionRequest { action: case.action, target_tree: TreeId::ROOT, target_node: node, data: case.data.clone() }; + fixture.frame(vec![Event::AccessKitActionRequest(request)]).settle(); + seen +} + +#[trial] +fn a_disabled_component_takes_no_access_request_that_acts_on_it() { + let cases = [ + Case { + what: "Expand on the component opens its menu", + aim: Aim::Opener, + action: AccessAction::Expand, + data: None, + reached: |seen| seen.menu_open.get(), + }, + Case { + what: "ShowContextMenu on the component opens its context menu", + aim: Aim::Opener, + action: AccessAction::ShowContextMenu, + data: None, + reached: |seen| seen.context_open.get(), + }, + Case { + what: "Click on the component activates it", + aim: Aim::Opener, + action: AccessAction::Click, + data: None, + reached: |seen| seen.activations.get() > 0, + }, + Case { + what: "a custom action on the component reaches it", + aim: Aim::Opener, + action: AccessAction::CustomAction, + data: Some(AccessData::CustomAction(1)), + reached: |seen| seen.requested(AccessAction::CustomAction), + }, + Case { + what: "a text SetValue on the component reaches it", + aim: Aim::Opener, + action: AccessAction::SetValue, + data: Some(AccessData::Value("Typed".into())), + reached: |seen| seen.requested(AccessAction::SetValue), + }, + Case { + what: "Increment on the value steps it", + aim: Aim::Dial, + action: AccessAction::Increment, + data: None, + reached: |seen| seen.moves.get() > 0, + }, + Case { + what: "SetValue on the value sets it", + aim: Aim::Dial, + action: AccessAction::SetValue, + data: Some(AccessData::NumericValue(8.0)), + reached: |seen| !seen.values.borrow().is_empty(), + }, + Case { + what: "Collapse on the heading reaches the component", + aim: Aim::Part(SECTION), + action: AccessAction::Collapse, + data: None, + reached: |seen| seen.requested(AccessAction::Collapse), + }, + Case { + what: "Click on the heading reaches the component", + aim: Aim::Part(SECTION), + action: AccessAction::Click, + data: None, + reached: |seen| seen.requested(AccessAction::Click), + }, + Case { + what: "Increment on the nudge reaches the component", + aim: Aim::Part(NUDGE), + action: AccessAction::Increment, + data: None, + reached: |seen| seen.requested(AccessAction::Increment), + }, + Case { + what: "SetValue on the knob sets it", + aim: Aim::Part(KNOB), + action: AccessAction::SetValue, + data: Some(AccessData::NumericValue(8.0)), + reached: |seen| !seen.values.borrow().is_empty(), + }, + ]; + let mut wrong = Vec::new(); + for case in &cases { + for enabled in [true, false] { + if (case.reached)(&send(case, enabled)) != enabled { + wrong.push(format!("{} (enabled: {enabled})", case.what)); + } + } + } + assert!(wrong.is_empty(), "each request reaches the components only while they are enabled: {wrong:#?}"); +} diff --git a/crates/ui-contract/tests/it/runtime/mod.rs b/crates/ui-contract/tests/it/runtime/mod.rs index 9b4a733b42..c30407d52b 100644 --- a/crates/ui-contract/tests/it/runtime/mod.rs +++ b/crates/ui-contract/tests/it/runtime/mod.rs @@ -6,6 +6,7 @@ pub(crate) mod clipboard; pub(crate) mod control_click; pub(crate) mod cursor; pub(crate) mod derived; +pub(crate) mod disabled_requests; pub(crate) mod elapsed; pub(crate) mod env; pub(crate) mod fingers; From 8f3dd38f0270ee2de8e881a05ab4a5c40a9fbcf8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 15:17:26 -0800 Subject: [PATCH 26/31] theme: the built-in themes load without searching them for reference cycles The first call to builtins() parsed the twelve embedded theme files with format::parse, which resolves every layer of each theme in both modes to look for reference cycles. That took 23.8 ms (median of 15, release build) once per process, the first time an app reads a theme. builtins() now parses the files with format::parse_builtin, which skips the cycle search: 0.25 ms. A new test runs the full format::parse on every embedded file, so a built-in with a cycle still fails the tests, and another counts the cycle searches while loading (12 before, 0 now). --- crates/theme/src/builtins.rs | 37 +++++++++++++++++++++++++++++--- crates/theme/src/format/mod.rs | 3 +++ crates/theme/src/format/parse.rs | 19 ++++++++++++++++ 3 files changed, 56 insertions(+), 3 deletions(-) diff --git a/crates/theme/src/builtins.rs b/crates/theme/src/builtins.rs index 9c5edd0c2a..e038897b69 100644 --- a/crates/theme/src/builtins.rs +++ b/crates/theme/src/builtins.rs @@ -23,12 +23,16 @@ pub(super) const SOURCES: [(&str, &str); 12] = [ ("vectorcraft-modern-medium", include_str!("../themes/vectorcraft-modern-medium.json")), ]; +static BUILTINS: LazyLock> = LazyLock::new(load); + +/// Parses every embedded file, without the search for reference cycles that +/// `every_builtin_passes_the_full_check` runs on each of them. // An invalid embedded file is a build defect that the built-in tests catch. #[allow(clippy::panic)] -static BUILTINS: LazyLock> = LazyLock::new(|| { +fn load() -> Vec { SOURCES .iter() - .map(|(name, text)| match format::parse(text.as_bytes()) { + .map(|(name, text)| match format::parse_builtin(text.as_bytes()) { Ok(file) => file.theme, Err(errors) => { let list: Vec = errors.0.iter().map(ToString::to_string).collect(); @@ -36,7 +40,7 @@ static BUILTINS: LazyLock> = LazyLock::new(|| { } }) .collect() -}); +} /// The built-in themes, in picker order. Panics if an embedded file is invalid, which the /// built-in tests rule out. @@ -50,3 +54,30 @@ pub fn builtins() -> &'static [ThemeDef] { pub(super) fn suite_default() -> &'static ThemeDef { builtins().iter().find(|t| t.id.as_str() == SUITE_DEFAULT).expect("SUITE_DEFAULT is a built-in") } + +#[cfg(test)] +mod tests { + use super::*; + + /// Every embedded file passes the full check of a theme file, the reference cycles included. + #[test] + fn every_builtin_passes_the_full_check() { + for (name, text) in SOURCES { + if let Err(errors) = format::parse(text.as_bytes()) { + panic!("{name}.json: {errors:?}"); + } + } + } + + /// Loading the built-ins parses each file once and does not search it for reference cycles. + #[test] + fn loading_the_builtins_does_not_search_for_reference_cycles() { + format::CYCLE_SEARCHES.set(0); + let themes = load(); + assert_eq!(themes.len(), SOURCES.len()); + assert_eq!(format::CYCLE_SEARCHES.get(), 0, "cycle searches while loading the built-ins"); + // A file read with the full check is searched. + assert!(format::parse(SOURCES[0].1.as_bytes()).is_ok()); + assert_eq!(format::CYCLE_SEARCHES.get(), 1); + } +} diff --git a/crates/theme/src/format/mod.rs b/crates/theme/src/format/mod.rs index 729099f079..cded6fea39 100644 --- a/crates/theme/src/format/mod.rs +++ b/crates/theme/src/format/mod.rs @@ -17,7 +17,10 @@ mod sizes; mod validate; mod write; +#[cfg(test)] +pub(crate) use parse::CYCLE_SEARCHES; pub use parse::parse; +pub(crate) use parse::parse_builtin; /// Reads an app's size overrides: [`AppSizes::parse`](crate::AppSizes::parse). pub fn parse_app_sizes(bytes: &[u8]) -> Result { diff --git a/crates/theme/src/format/parse.rs b/crates/theme/src/format/parse.rs index f0e6dde89a..30a65c8c9d 100644 --- a/crates/theme/src/format/parse.rs +++ b/crates/theme/src/format/parse.rs @@ -21,6 +21,22 @@ use crate::{AppId, IconPackId, ThemeId}; /// kept for [`write`](super::write). Every field error is reported, not /// only the first. pub fn parse(bytes: &[u8]) -> Result { + parse_with(bytes, true) +} + +/// [`parse`] without the search for reference cycles, for the built-in themes. The built-in tests +/// run [`parse`] on each of them. +pub(crate) fn parse_builtin(bytes: &[u8]) -> Result { + parse_with(bytes, false) +} + +#[cfg(test)] +thread_local! { + /// How many times this thread searched a parsed theme for reference cycles. + pub(crate) static CYCLE_SEARCHES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +fn parse_with(bytes: &[u8], find_cycles: bool) -> Result { let stop = |path: &[&str], kind| Err(FormatErrors(vec![FormatError { path: path.iter().map(|s| (*s).to_owned()).collect(), kind }])); if bytes.len() > MAX_THEME_BYTES { return stop(&[], ErrorKind::TooLarge { len: bytes.len() }); @@ -46,7 +62,10 @@ pub fn parse(bytes: &[u8]) -> Result { let mut p = Parser::new(); let theme = p.theme(&raw); match theme { + Some(theme) if p.errors.is_empty() && !find_cycles => Ok(ThemeFile { theme, raw }), Some(theme) if p.errors.is_empty() => { + #[cfg(test)] + CYCLE_SEARCHES.set(CYCLE_SEARCHES.get() + 1); let cycles = theme.reference_errors(); if cycles.is_empty() { Ok(ThemeFile { theme, raw }) } else { Err(FormatErrors(cycles)) } } From 7892ab1318cd0366e06f187647f08c42feee07aa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 15:19:09 -0800 Subject: [PATCH 27/31] ui-contract: a disabled text part also disables its owner's node for routed requests report_text marked the owner's AccessKit node disabled for a disabled text part but left the owner's routing entry enabled, so ReplaceSelectedText, Click or a custom action on that node still reached an enabled component. The owner's entry is now marked disabled with the text part. --- crates/ui-contract/src/runtime/access/text.rs | 4 + .../tests/it/runtime/disabled_requests.rs | 89 ++++++++++++++++++- 2 files changed, 91 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/runtime/access/text.rs b/crates/ui-contract/src/runtime/access/text.rs index 428c3ae2d4..fbb7007a1e 100644 --- a/crates/ui-contract/src/runtime/access/text.rs +++ b/crates/ui-contract/src/runtime/access/text.rs @@ -137,6 +137,10 @@ pub(crate) fn report_text(ctx: &Context, owner: Id, facts: &TextFacts, unit: Opt } }); adapter::write_text(ctx, owner, &TextNode { value: value.as_deref(), editable: facts.editable, disabled: facts.disabled, selection }); + // The owner's node, registered with its common facts, is disabled with the text part it stands for. + if facts.disabled { + keys::register_disabled(ctx, owner); + } Service::::run(ctx, |tables| tables.0.insert(owner, entries)); } diff --git a/crates/ui-contract/tests/it/runtime/disabled_requests.rs b/crates/ui-contract/tests/it/runtime/disabled_requests.rs index cb767dd943..6c82b70c78 100644 --- a/crates/ui-contract/tests/it/runtime/disabled_requests.rs +++ b/crates/ui-contract/tests/it/runtime/disabled_requests.rs @@ -2,10 +2,12 @@ //! context menu, step, value or custom action, on the component's own node or on its sub-nodes. The same requests on //! an enabled component do. -use craft_behavior::{AccessAction, AccessData, Input, PartKey, Sense}; +use craft_behavior::{AccessAction, AccessData, Input, PartKey, PlainText, Sense}; use craft_ui::contract::{ - Access, Common, Component, Cx, Focus as _, MeasureCx, Name, Numeric, Overlays as _, PartsCx, Pointer as _, Props as _, Role, Show as _, Trigger, + Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, Numeric, Overlays as _, PartsCx, + Pointer as _, Props as _, Role, Show as _, Trigger, }; +use craft_ui::primitives::{TextKey, TextOptions}; use craft_ui::runtime::focus::KeyUse; use craft_ui::style::StyleCx; use craft_ui::testing::{Fixture, trial}; @@ -19,6 +21,7 @@ const CHEVRON: PartKey = PartKey::new("chevron"); const SECTION: PartKey = PartKey::new("section"); const KNOB: PartKey = PartKey::new("knob"); const NUDGE: PartKey = PartKey::new("nudge"); +const TEXT: PartKey = PartKey::new("text"); /// What reached the components in their latest run. #[derive(Default)] @@ -270,3 +273,85 @@ fn a_disabled_component_takes_no_access_request_that_acts_on_it() { } assert!(wrong.is_empty(), "each request reaches the components only while they are enabled: {wrong:#?}"); } + +/// An enabled field over a string whose text part is enabled or not, recording the access requests that reach it. +#[derive(craft_ui::contract::Component)] +struct Field<'a> { + #[common] + common: Common, + value: Bind<'a, String>, + text_enabled: bool, + requests: Rc>>, +} + +impl Component for Field<'_> { + const ROLE: Role = Role::TEXT_INPUT; + const INPUT: Input = Input::Text; + type Style = PlainStyle; + type Output = EditResponse; + + fn style(_: &StyleCx<'_>, _: FieldStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn sense(&self) -> Sense { + Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(120.0, 24.0) + } + + fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { + let options = TextOptions { enabled: self.text_enabled, ..TextOptions::default() }; + let (shown, rect) = (cx.value().cloned().unwrap_or_default(), cx.content_rect); + cx.text(TextKey::::new(TEXT), rect, &PlainText, &shown, &options); + } + + fn bind(&mut self) -> Option> { + Some(self.value.reborrow()) + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + while let Some(request) = cx.intents().take_access() { + self.requests.borrow_mut().push(request.action); + } + } + + fn finish(self, cx: Cx<'_, Self>) -> EditResponse { + cx.edit_response() + } +} + +/// Shows the field with its text part enabled or not, sends `action` to the field's node and returns the access +/// requests that reached the field and its value. +fn send_to_field(text_enabled: bool, action: AccessAction, data: AccessData) -> (Vec, String) { + let value = Rc::new(RefCell::new(String::from("Kept"))); + let requests = Rc::new(RefCell::new(Vec::new())); + let id = Rc::new(Cell::new(Id::NULL)); + let (held, taken, seen) = (value.clone(), requests.clone(), id.clone()); + let mut fixture = Fixture::new(move |ui| { + let mut text = held.borrow_mut(); + let field = Field { common: Common::new(), value: Bind::bound(&mut *text), text_enabled, requests: taken.clone() }; + seen.set(field.label("Field").show(ui).response.id); + }); + fixture.settle(); + requests.borrow_mut().clear(); + let request = ActionRequest { action, target_tree: TreeId::ROOT, target_node: id.get().accesskit_id(), data: Some(data) }; + fixture.frame(vec![Event::AccessKitActionRequest(request)]).settle(); + let reached = requests.borrow().clone(); + let value = value.borrow().clone(); + (reached, value) +} + +/// The node of an enabled field stands for its text part and is disabled with it: a request that acts on the node +/// reaches the field, or sets its value, only while the text part is enabled. +#[trial] +fn a_disabled_text_part_disables_its_owners_node_for_requests_that_act_on_it() { + let replace = |enabled| send_to_field(enabled, AccessAction::ReplaceSelectedText, AccessData::Value("Typed".into())).0; + assert!(replace(true).contains(&AccessAction::ReplaceSelectedText), "an enabled text part takes ReplaceSelectedText"); + assert!(replace(false).is_empty(), "a disabled text part takes no ReplaceSelectedText"); + let set = |enabled| send_to_field(enabled, AccessAction::SetValue, AccessData::Value("Typed".into())).1; + assert_eq!(set(true), "Typed", "an enabled text part takes the value"); + assert_eq!(set(false), "Kept", "a disabled text part keeps its value"); +} From ef5313acecc5ae11c9c9487569abe66f3c5decff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 15:25:18 -0800 Subject: [PATCH 28/31] ui: a wrapping spread row wraps content that takes a second line and reports its spread line A wrapping SpaceBetween row counted only its craft children when deciding whether its content fits one line. A direct egui allocation that wrapped onto a second line left the count unchanged, so the real run spread the row and the allocation ran past the row's end edge. The row now also compares how far its content reaches below its top with its tallest child. When the row spreads its children on one line, its measuring run now reports the line they sit on as the row's first line, as an unwrapped row does, instead of the first child's own first line. A parent row then places the spread children on its own line. --- crates/ui-contract/src/layout/body.rs | 47 +++++++++++++++--- crates/ui-contract/tests/it/layout/body.rs | 55 ++++++++++++++++++++++ 2 files changed, 95 insertions(+), 7 deletions(-) diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 9833c2a256..6a197510c9 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -260,8 +260,10 @@ fn open_wraps(ctx: &egui::Context, sizing: bool, id: Id) { /// Ends the children of the wrapping `Row` body `id`, `room` wide; a measuring run records each child's line and the /// height of its tallest child. A measuring run returns how many children the row placed and what they took about a -/// line when every one of them sits on its first line. -fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2) -> Option<(usize, LineTook)> { +/// line when every one of them sits on its first line and the row's `content`, how far below its top everything in it +/// reaches (direct egui allocations included), is no taller than its tallest child: egui sets anything it wraps below +/// the first line. +fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2, content: f32) -> Option<(usize, LineTook)> { let took = pass_state::with::(ctx, |rows| rows.0.remove(&id)).unwrap_or_default(); if !sizing { return None; @@ -277,7 +279,8 @@ fn close_wraps(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2) -> Option< for (i, &(line, _)) in took.children.iter().enumerate() { found(ctx, true, sub(id, ("wrap", i)), room, Vec2::new(line as f32, heights.get(line).copied().unwrap_or_default())); } - (heights.len() <= 1).then_some((took.children.len(), took.line)) + let first = heights.first().copied().unwrap_or_default(); + (heights.len() <= 1 && content <= first + ONE_LINE_SLACK).then_some((took.children.len(), took.line)) } /// Whether egui puts the next child `width` wide in `ui`, a wrapping row's block, on a new line (`Layout::next_frame`): @@ -2158,6 +2161,10 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign // line of its own. let block_layout = if wrap && env.least { child::column_layout(rtl) } else { child::row_layout(rtl, wrap) }; let mut one_line = None; + // The children of a wrapping `SpaceBetween` row report their first line to the row, which reports the line they + // sit on when the real run spreads them on one line, and the first child's otherwise. + let spreads = lines && align == RowAlign::SpaceBetween; + let first_target = env.first_line.filter(|_| spreads && sizing).map(|target| (target, sub(id, "first_line"))); let (inner, took) = child::block(ui, rect, block_layout, |ui| { let row = env.derive_local(|scoped| { scoped.row_room = Some(room.width()); @@ -2166,6 +2173,9 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign if line.is_some() { scoped.first_line = None; } + if let Some((_, own)) = first_target { + scoped.first_line = Some(own); + } // A leaf wider than a whole line takes the line, never below its least, as in a stack. if wrap { scoped.shrink = Some(Shrink::Fit); @@ -2175,26 +2185,49 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign if lines { open_wraps(&ctx, sizing, id); } + if let Some((_, own)) = first_target { + open_first_lines(&ctx, &[own]); + } + // How far below the row's top its content reaches, direct egui allocations included, which the children's + // lines (`close_wraps`) do not count. + let mut content = 0.0; let inner = if wrap && align == RowAlign::SpaceBetween { // In a child, as the spread row runs its children (`run_spread`): they take the same ids whether the real // run spreads them on one line or wraps them, and keep their state when the row starts or stops wrapping. let layout = *ui.layout(); - child::block(ui, None, layout, |ui| Env::run_in(ui, row.clone(), &mut body)).0 + child::block(ui, None, layout, |ui| { + let top = ui.max_rect().top(); + let inner = Env::run_in(ui, row.clone(), &mut body); + content = (ui.min_rect().bottom() - top).max(0.0); + inner + }) + .0 } else if wrap { body(ui) } else { run_shrinking(ui, &row, id, &mut body) }; if lines { - one_line = close_wraps(&ctx, sizing, id, room.size()); + one_line = close_wraps(&ctx, sizing, id, room.size(), content); // Children that the real run may spread on one line sit on the line they take there, as an unwrapped // row's do: the block takes that line's height, which may be more than its tallest child's (a check box // with a detail line under its label sits its first line on the line). let spread = one_line.filter(|(count, _)| align == RowAlign::SpaceBetween && *count >= 2); - if let Some(line) = spread.and_then(|(_, took)| spread_line(id, took, shared)) { - let top = ui.max_rect().top(); + let top = ui.max_rect().top(); + let line = spread.and_then(|(_, took)| spread_line(id, took, shared)); + if let Some(line) = line { alloc::reach_down_to(ui, top + line.y); } + // The row's first line is the line the real run spreads its children on, as `record_line` reports an + // unwrapped row's, else the first child's. + if let Some((target, own)) = first_target { + let child = close_first_line(&ctx, own); + if let Some(line) = line { + report_first_line(&ctx, target, Some(top + line.x)); + } else if let Some(at) = child { + report_first_line(&ctx, target, at); + } + } } Env::restore(&ctx, installed); if !wrap { diff --git a/crates/ui-contract/tests/it/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index e1a7d2d0b9..bf447c58cf 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -637,6 +637,61 @@ fn a_wrapping_space_between_row_spreads_children_that_fit_one_line() { assert_eq!(ids[0], ids[1], "the children keep their ids when the row starts wrapping"); } +/// A wrapping `SpaceBetween` row whose children fit one line but whose direct egui allocation after them wraps onto a +/// second line wraps: the allocation stays inside the row instead of running past its end. +#[trial] +fn a_spread_wrapping_row_wraps_a_direct_allocation_that_takes_a_second_line() { + let seen: Rc<[RefCell; 2]> = Rc::new(Default::default()); + let rects = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let (shown, shown_rects) = (Rc::clone(&seen), Rc::clone(&rects)); + let mut fixture = Fixture::new(move |ui| { + let layout = BodyLayout::row().wrap(true).align(RowAlign::SpaceBetween); + let direct = Cell::new(Rect::NOTHING); + let panel = Panel::new().layout(layout).sizing(Sizing::FillWidth).id_salt("spread").show(ui, |ui, _| { + for (i, seen) in shown.iter().enumerate() { + Probe::new(seen).size(Vec2::new(20.0, 10.0)).id_salt(i).show(ui); + } + direct.set(ui.allocate_exact_size(Vec2::new(60.0, 10.0), egui::Sense::hover()).0); + }); + shown_rects.set((panel.output.rect, direct.get())); + }); + fixture.room(Vec2::new(100.0, 400.0)).settle(); + let (row, direct) = rects.get(); + let first = seen[0].borrow().rect; + let dump = format!("row {row:?}, first {first:?}, direct {direct:?}"); + assert!(direct.max.x <= row.max.x + SLACK, "the direct allocation ends inside the row: {dump}"); + assert!(direct.top() >= first.bottom() - SLACK, "the direct allocation wraps onto a second line: {dump}"); +} + +/// A wrapping `SpaceBetween` row that spreads children of different heights on one line, in an unwrapped row beside a +/// taller block, reports the line its children sit on as its first line: its children sit on the outer row's line. +#[trial] +fn a_spread_wrapping_row_reports_its_spread_line_as_its_first_line() { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING, Rect::NOTHING))); + let shown = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + Panel::new().layout(BodyLayout::row()).id_salt("outer").show(ui, |ui, _| { + let tall = Block::new(Vec2::new(20.0, 50.0)).show(ui).rect; + let layout = BodyLayout::row().wrap(true).align(RowAlign::SpaceBetween); + let inner = Panel::new().layout(layout).id_salt("inner").show(ui, |ui, _| { + let short = Block::new(ITEM).show(ui).rect; + let big = Block::new(Vec2::new(40.0, 30.0)).show(ui).rect; + (short, big) + }); + if !is_measuring(ui.ctx()) { + let (short, big) = inner.inner.unwrap_or((Rect::NOTHING, Rect::NOTHING)); + shown.set((tall, short, big)); + } + }); + }); + fixture.room(Vec2::splat(400.0)).settle(); + let (tall, short, big) = seen.get(); + let dump = format!("tall {tall:?}, short {short:?}, big {big:?}"); + assert!(short.height() > 0.0 && big.height() > 0.0, "the inner row showed its blocks: {dump}"); + assert!((short.center().y - big.center().y).abs() < SLACK, "the inner row's blocks share one line: {dump}"); + assert!((short.center().y - tall.center().y).abs() < SLACK, "the inner row's line is the outer row's line: {dump}"); +} + /// An unwrapped row in a row sits on the outer row's line by its own line, whatever its alignment: a row that places /// its block from its start, at its end, centred or spread reports its line as its first line alike. #[trial] From 5c251dac391bf024d296bed96579505f61d70687 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 15:42:38 -0800 Subject: [PATCH 29/31] ui-contract: a disabled text part shown through PaintUi::inner disables the owner's node The owner's node stands for an inner component's focus stop and sends the requests it receives to that component. Its routing entry was disabled only with the owner, so ReplaceSelectedText or SetValue on an enabled owner still reached an inner field whose text part was disabled. The inner component now tells the owner's report whether it, or its text part, is disabled, and the owner's entry is disabled with it. --- .../ui-contract/src/contract/steps/report.rs | 17 +++-- crates/ui-contract/src/runtime/access/fold.rs | 3 + .../tests/it/runtime/disabled_requests.rs | 69 ++++++++++++++++++- 3 files changed, 81 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/report.rs b/crates/ui-contract/src/contract/steps/report.rs index 38515ccabd..122ad273d4 100644 --- a/crates/ui-contract/src/contract/steps/report.rs +++ b/crates/ui-contract/src/contract/steps/report.rs @@ -220,11 +220,17 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> toggle, ltr_axis: resolved.ltr_axis, }; + let editor_record = || { + let widget = core.editor.as_ref()?.widget; + pass_state::with::(ctx, |records| records.0.remove(&widget)) + }; + let text_facts = core.text_access.take().or_else(editor_record); if let Some(owner) = inner_of { // Shown as the owner's control: the owner's node is the one node, and stands for this root's key focus. access::hide(ctx, id); scope::leave(ctx, id); - access::fold::offer(ctx, owner, access::fold::Folded { inner: id, value: access.value.clone() }); + let disabled = !resolved.enabled || text_facts.as_ref().is_some_and(|facts| facts.disabled); + access::fold::offer(ctx, owner, access::fold::Folded { inner: id, value: access.value.clone(), disabled }); if flags.contains(Flags::FOCUSED) { access::set_focus(ctx, owner); } @@ -236,15 +242,12 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> } if let Some(folded) = &folded { keys::register_node(ctx, id, folded.inner, None, focusable); - if !resolved.enabled { + // Disabled with the inner component it stands for, or with that component's text part. + if !resolved.enabled || folded.disabled { keys::register_disabled(ctx, id); } } - let editor_record = || { - let widget = core.editor.as_ref()?.widget; - pass_state::with::(ctx, |records| records.0.remove(&widget)) - }; - if let Some(facts) = core.text_access.take().or_else(editor_record) { + if let Some(facts) = text_facts { crate::runtime::access::text::report_text(ctx, id, &facts, access.unit.as_deref(), access.value.as_deref()); } else if let Some(editor) = &core.editor { crate::runtime::access::text::fold_editor(ctx, editor.widget, id); diff --git a/crates/ui-contract/src/runtime/access/fold.rs b/crates/ui-contract/src/runtime/access/fold.rs index 7bf1ced4b7..e09e47ffa0 100644 --- a/crates/ui-contract/src/runtime/access/fold.rs +++ b/crates/ui-contract/src/runtime/access/fold.rs @@ -18,6 +18,9 @@ pub(crate) struct Folded { pub inner: Id, /// The inner component's value text. pub value: Option, + /// The inner component, or the text part it shows, is disabled: a request that acts on the owner's node reaches + /// no one. + pub disabled: bool, } fn owner_slot(inner: Id) -> Id { diff --git a/crates/ui-contract/tests/it/runtime/disabled_requests.rs b/crates/ui-contract/tests/it/runtime/disabled_requests.rs index 6c82b70c78..cd42831c65 100644 --- a/crates/ui-contract/tests/it/runtime/disabled_requests.rs +++ b/crates/ui-contract/tests/it/runtime/disabled_requests.rs @@ -4,7 +4,7 @@ use craft_behavior::{AccessAction, AccessData, Input, PartKey, PlainText, Sense}; use craft_ui::contract::{ - Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, Numeric, Overlays as _, PartsCx, + Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, Numeric, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Role, Show as _, Trigger, }; use craft_ui::primitives::{TextKey, TextOptions}; @@ -355,3 +355,70 @@ fn a_disabled_text_part_disables_its_owners_node_for_requests_that_act_on_it() { assert_eq!(set(true), "Typed", "an enabled text part takes the value"); assert_eq!(set(false), "Kept", "a disabled text part keeps its value"); } + +/// An enabled component that shows the field as its own control (`PaintUi::inner`). +#[derive(craft_ui::contract::Component)] +struct Wrapper { + #[common] + common: Common, + value: Rc>, + text_enabled: bool, + requests: Rc>>, +} + +impl Component for Wrapper { + const ROLE: Role = Role::TEXT_INPUT; + type Style = PlainStyle; + type Output = egui::Response; + + fn style(_: &StyleCx<'_>, _: WrapperStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(120.0, 24.0) + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let mut text = self.value.borrow_mut(); + let field = Field { common: Common::new(), value: Bind::bound(&mut *text), text_enabled: self.text_enabled, requests: self.requests.clone() }; + ui.inner("field", cx.rect, field.label("Field")); + } + + fn finish(self, cx: Cx<'_, Self>) -> egui::Response { + cx.response.clone() + } +} + +/// Shows the wrapper with its inner field's text part enabled or not, sends `action` to the wrapper's node and returns +/// the access requests that reached the inner field and its value. +fn send_to_wrapper(text_enabled: bool, action: AccessAction, data: AccessData) -> (Vec, String) { + let value = Rc::new(RefCell::new(String::from("Kept"))); + let requests = Rc::new(RefCell::new(Vec::new())); + let id = Rc::new(Cell::new(Id::NULL)); + let (held, taken, seen) = (value.clone(), requests.clone(), id.clone()); + let mut fixture = Fixture::new(move |ui| { + let wrapper = Wrapper { common: Common::new(), value: held.clone(), text_enabled, requests: taken.clone() }; + seen.set(wrapper.label("Wrapper").show(ui).id); + }); + fixture.settle(); + requests.borrow_mut().clear(); + let request = ActionRequest { action, target_tree: TreeId::ROOT, target_node: id.get().accesskit_id(), data: Some(data) }; + fixture.frame(vec![Event::AccessKitActionRequest(request)]).settle(); + let reached = requests.borrow().clone(); + let value = value.borrow().clone(); + (reached, value) +} + +/// The node of a component that shows a field through `PaintUi::inner` stands for the field's text part and is +/// disabled with it: a request that acts on the node reaches the field, or sets its value, only while the text part +/// is enabled. +#[trial] +fn a_disabled_inner_text_part_disables_the_wrappers_node_for_requests_that_act_on_it() { + let replace = |enabled| send_to_wrapper(enabled, AccessAction::ReplaceSelectedText, AccessData::Value("Typed".into())).0; + assert!(replace(true).contains(&AccessAction::ReplaceSelectedText), "an enabled inner text part takes ReplaceSelectedText"); + assert!(replace(false).is_empty(), "a disabled inner text part takes no ReplaceSelectedText"); + let set = |enabled| send_to_wrapper(enabled, AccessAction::SetValue, AccessData::Value("Typed".into())).1; + assert_eq!(set(true), "Typed", "an enabled inner text part takes the value"); + assert_eq!(set(false), "Kept", "a disabled inner text part keeps its value"); +} From fb32cbef253747a2dd758a5137e54a5f28957a8b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 16:05:07 -0800 Subject: [PATCH 30/31] ui-contract: a disabled inner component disables every owner of a nested PaintUi::inner An owner that shows a component through PaintUi::inner offered its own owner a Folded record built only from its own enabled state and its text part, so an inner component's disabled state stopped one level up. With two inner levels over a disabled text part, the outermost node stayed enabled and a request that acts on it reached the intermediate component. The record now also carries the disabled state the owner received from its own inner component. --- .../ui-contract/src/contract/steps/report.rs | 4 +- .../tests/it/runtime/disabled_requests.rs | 71 ++++++++++++++++++- 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/report.rs b/crates/ui-contract/src/contract/steps/report.rs index 122ad273d4..e56923a07c 100644 --- a/crates/ui-contract/src/contract/steps/report.rs +++ b/crates/ui-contract/src/contract/steps/report.rs @@ -229,7 +229,9 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> // Shown as the owner's control: the owner's node is the one node, and stands for this root's key focus. access::hide(ctx, id); scope::leave(ctx, id); - let disabled = !resolved.enabled || text_facts.as_ref().is_some_and(|facts| facts.disabled); + // Disabled with its own inner component as well, so the state reaches every owner of a nested `inner`. + let disabled = + !resolved.enabled || folded.as_ref().is_some_and(|folded| folded.disabled) || text_facts.as_ref().is_some_and(|facts| facts.disabled); access::fold::offer(ctx, owner, access::fold::Folded { inner: id, value: access.value.clone(), disabled }); if flags.contains(Flags::FOCUSED) { access::set_focus(ctx, owner); diff --git a/crates/ui-contract/tests/it/runtime/disabled_requests.rs b/crates/ui-contract/tests/it/runtime/disabled_requests.rs index cd42831c65..3820681304 100644 --- a/crates/ui-contract/tests/it/runtime/disabled_requests.rs +++ b/crates/ui-contract/tests/it/runtime/disabled_requests.rs @@ -356,7 +356,8 @@ fn a_disabled_text_part_disables_its_owners_node_for_requests_that_act_on_it() { assert_eq!(set(false), "Kept", "a disabled text part keeps its value"); } -/// An enabled component that shows the field as its own control (`PaintUi::inner`). +/// An enabled component that shows the field as its own control (`PaintUi::inner`), recording the access requests +/// that reach it. #[derive(craft_ui::contract::Component)] struct Wrapper { #[common] @@ -385,6 +386,12 @@ impl Component for Wrapper { ui.inner("field", cx.rect, field.label("Field")); } + fn update(&mut self, cx: &mut Cx<'_, Self>) { + while let Some(request) = cx.intents().take_access() { + self.requests.borrow_mut().push(request.action); + } + } + fn finish(self, cx: Cx<'_, Self>) -> egui::Response { cx.response.clone() } @@ -422,3 +429,65 @@ fn a_disabled_inner_text_part_disables_the_wrappers_node_for_requests_that_act_o assert_eq!(set(true), "Typed", "an enabled inner text part takes the value"); assert_eq!(set(false), "Kept", "a disabled inner text part keeps its value"); } + +/// An enabled component that shows the wrapper as its own control (`PaintUi::inner`), so the field is nested two +/// owners deep. +#[derive(craft_ui::contract::Component)] +struct Outer { + #[common] + common: Common, + value: Rc>, + text_enabled: bool, + requests: Rc>>, +} + +impl Component for Outer { + const ROLE: Role = Role::TEXT_INPUT; + type Style = PlainStyle; + type Output = egui::Response; + + fn style(_: &StyleCx<'_>, _: OuterStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(120.0, 24.0) + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let wrapper = Wrapper { common: Common::new(), value: self.value.clone(), text_enabled: self.text_enabled, requests: self.requests.clone() }; + ui.inner("wrapper", cx.rect, wrapper.label("Wrapper")); + } + + fn finish(self, cx: Cx<'_, Self>) -> egui::Response { + cx.response.clone() + } +} + +/// Shows the outer component with the nested field's text part enabled or not, sends `action` to the outer node and +/// returns the access requests that reached the wrapper or the field. +fn send_to_outer(text_enabled: bool, action: AccessAction, data: AccessData) -> Vec { + let value = Rc::new(RefCell::new(String::from("Kept"))); + let requests = Rc::new(RefCell::new(Vec::new())); + let id = Rc::new(Cell::new(Id::NULL)); + let (taken, seen) = (requests.clone(), id.clone()); + let mut fixture = Fixture::new(move |ui| { + let outer = Outer { common: Common::new(), value: value.clone(), text_enabled, requests: taken.clone() }; + seen.set(outer.label("Outer").show(ui).id); + }); + fixture.settle(); + requests.borrow_mut().clear(); + let request = ActionRequest { action, target_tree: TreeId::ROOT, target_node: id.get().accesskit_id(), data: Some(data) }; + fixture.frame(vec![Event::AccessKitActionRequest(request)]).settle(); + requests.borrow().clone() +} + +/// A disabled text part two `PaintUi::inner` owners deep disables the outermost node too: the intermediate owner +/// passes its inner component's disabled state on to its own owner, so a request that acts on the outer node reaches +/// the wrapper only while the text part is enabled. +#[trial] +fn a_disabled_text_part_nested_two_owners_deep_disables_the_outer_node() { + let replace = |enabled| send_to_outer(enabled, AccessAction::ReplaceSelectedText, AccessData::Value("Typed".into())); + assert!(replace(true).contains(&AccessAction::ReplaceSelectedText), "an enabled nested text part takes ReplaceSelectedText"); + assert!(replace(false).is_empty(), "a disabled nested text part takes no ReplaceSelectedText"); +} From 598d489936dfee2b4d735db3ae0cd4982188c823 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 15:22:08 -0800 Subject: [PATCH 31/31] craft-captions: TTML tag parsing tests count byte reads instead of timing the parse `many_unmatched_lt_is_fast` asserted that a parse of 256,000 `<` and one `>` took under 2 s, and `unclosed_angle_brackets_are_escaped_in_one_pass` asserted under 5 s for 200,000 `<`. On a loaded machine the first took 2.01 s and failed, and 0.10 s when run again. The TTML writer's tag parser now reads the caption text through a small `Reader` type in a child module of `ttml.rs`. Its only accessors are `byte(index)` and `suffix(start)`, an iterator that reads each byte through `byte`. In test builds `byte` counts its calls. `parse_tag` and `QuoteCache::next` take a `Reader` in place of a `&[u8]`, and the tag name is built from the bytes as they are read. Parsing behavior and output do not change. The two unit tests write each text at 50,000 and 100,000 characters and assert at most three byte reads per character of text, and that twice the text costs less than three times as many reads. With a search for `>` after every `<` put back in `parse_tag` through `suffix` or through repeated `byte` calls, both fail at the first assertion: 5,000,050,000 byte reads in a text of 100,000, and 5,000,250,000 in a text of 100,001. The same search written against the slice (`bytes.get(i..)`) does not compile, because `Reader` has no `get` method and its field is private. The count covers only reads through `Reader`. `inline` still holds the caption text as a `&str`, and a search over it is not counted: with `rest[1..].find('>')` added to the check for `<` in `inline`, `many_unmatched_angle_brackets_before_one_gt_are_read_once` passes. A change that hands the parser the raw slice again, through a new accessor or parameter, is not counted either. The integration test keeps its output check as `many_unmatched_lt_stay_text`. --- crates/captions/src/ttml.rs | 111 ++++++++++++++---- .../captions/tests/it/ttml_literal_angle.rs | 5 +- 2 files changed, 93 insertions(+), 23 deletions(-) diff --git a/crates/captions/src/ttml.rs b/crates/captions/src/ttml.rs index 78db4763b3..07c2fd9cb1 100644 --- a/crates/captions/src/ttml.rs +++ b/crates/captions/src/ttml.rs @@ -113,6 +113,57 @@ fn time_expr(t: Tick, rate: Option) -> String { } } +/// The caption text as the tag parser sees it: one byte at a time, counted in tests. +mod reader { + #[cfg(test)] + thread_local! { + /// Calls to [`Reader::byte`] on this thread (tests: the tag parser's work is linear in the text). + pub(super) static READS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// The bytes of a caption text, read only through [`Reader::byte`]. + #[derive(Clone, Copy)] + pub(super) struct Reader<'a> { + bytes: &'a [u8], + } + + impl<'a> Reader<'a> { + pub(super) fn new(bytes: &'a [u8]) -> Self { + Self { bytes } + } + + /// The byte at `index`, or `None` past the end. + pub(super) fn byte(self, index: usize) -> Option { + #[cfg(test)] + READS.with(|r| r.set(r.get().saturating_add(1))); + self.bytes.get(index).copied() + } + + /// The bytes from `start` to the end, each read through [`Reader::byte`]. + pub(super) fn suffix(self, start: usize) -> Suffix<'a> { + Suffix { reader: self, next: start } + } + } + + /// Iterator returned by [`Reader::suffix`]. + pub(super) struct Suffix<'a> { + reader: Reader<'a>, + next: usize, + } + + impl Iterator for Suffix<'_> { + type Item = u8; + + fn next(&mut self) -> Option { + let c = self.reader.byte(self.next)?; + self.next = self.next.saturating_add(1); + Some(c) + } + } +} + +use reader::Reader; + /// Memoised "next occurrence of a quote byte" searches, so unterminated quotes are not rescanned. #[derive(Default)] struct QuoteCache { @@ -121,7 +172,7 @@ struct QuoteCache { impl QuoteCache { /// Index of the next `quote` byte at or after `from`. - fn next(&mut self, bytes: &[u8], quote: u8, from: usize) -> Option { + fn next(&mut self, bytes: Reader<'_>, quote: u8, from: usize) -> Option { let slot = usize::from(quote == b'\''); if let Some((searched, result)) = self.found[slot] && searched <= from @@ -129,7 +180,7 @@ impl QuoteCache { { return result; } - let result = bytes.get(from..).and_then(|t| t.iter().position(|&c| c == quote)).map(|i| from + i); + let result = bytes.suffix(from).position(|c| c == quote).map(|i| from + i); self.found[slot] = Some((from, result)); result } @@ -139,42 +190,42 @@ impl QuoteCache { /// letters/digits starting with a letter immediately after, then whitespace-separated /// `name="value"` / `name='value'` attributes, optional `/` before `>`. A `>` inside a quoted /// value does not end the tag. Returns `(index after '>', closing, lowercase name)`; the name is empty for a self-closing tag. -fn parse_tag(bytes: &[u8], start: usize, cache: &mut QuoteCache) -> Option<(usize, bool, String)> { +fn parse_tag(bytes: Reader<'_>, start: usize, cache: &mut QuoteCache) -> Option<(usize, bool, String)> { let mut i = start + 1; - let closing = bytes.get(i) == Some(&b'/'); + let closing = bytes.byte(i) == Some(b'/'); if closing { i += 1; } - let name_start = i; - if !bytes.get(i)?.is_ascii_alphabetic() { + if !bytes.byte(i)?.is_ascii_alphabetic() { return None; } - while bytes.get(i).is_some_and(u8::is_ascii_alphanumeric) { + let mut name = String::new(); + while let Some(c) = bytes.byte(i).filter(u8::is_ascii_alphanumeric) { + name.push(char::from(c.to_ascii_lowercase())); i += 1; } - let name = String::from_utf8_lossy(bytes.get(name_start..i)?).to_ascii_lowercase(); loop { let ws_start = i; - while bytes.get(i).is_some_and(u8::is_ascii_whitespace) { + while bytes.byte(i).is_some_and(|c| c.is_ascii_whitespace()) { i += 1; } - match bytes.get(i)? { + match bytes.byte(i)? { b'>' => return Some((i + 1, closing, name)), // self-closing: no markup - b'/' if !closing && bytes.get(i + 1) == Some(&b'>') => return Some((i + 2, closing, String::new())), + b'/' if !closing && bytes.byte(i + 1) == Some(b'>') => return Some((i + 2, closing, String::new())), _ => {} } if i == ws_start { return None; } let key_start = i; - while bytes.get(i).is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b':' | b'_')) { + while bytes.byte(i).is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b':' | b'_')) { i += 1; } - if i == key_start || bytes.get(i) != Some(&b'=') { + if i == key_start || bytes.byte(i) != Some(b'=') { return None; } - let quote = *bytes.get(i + 1)?; + let quote = bytes.byte(i + 1)?; if quote != b'"' && quote != b'\'' { return None; } @@ -204,10 +255,11 @@ fn inline(text: &str) -> String { }; let mut rest = text; let mut cache = QuoteCache::default(); + let bytes = Reader::new(text.as_bytes()); while !rest.is_empty() { // Only a well-formed tag is markup; "1 < 2 and 3 > 2" and "ad" are text. if rest.starts_with('<') - && let Some((end, closing, name)) = parse_tag(text.as_bytes(), text.len() - rest.len(), &mut cache) + && let Some((end, closing, name)) = parse_tag(bytes, text.len() - rest.len(), &mut cache) { let attr = match name.as_str() { "i" => Some("tts:fontStyle=\"italic\""), @@ -1171,15 +1223,34 @@ mod tests { assert_eq!(out, "x"); } + /// `inline(text)` and the number of bytes the tag parser read for it. + fn inline_cost(text: &str) -> (String, usize) { + reader::READS.with(|r| r.set(0)); + let out = inline(text); + (out, reader::READS.with(std::cell::Cell::get)) + } + + /// The tag parser reads each byte of `text` a bounded number of times, and twice the text costs about twice the work. + fn assert_linear(make: impl Fn(usize) -> String, escaped: impl Fn(usize) -> String) { + let (out, small) = inline_cost(&make(50_000)); + assert_eq!(out, escaped(50_000)); + let text = make(100_000); + let (out, large) = inline_cost(&text); + assert_eq!(out, escaped(100_000)); + assert!(large <= 3 * text.len(), "{large} byte reads in a text of {}", text.len()); + assert!(large < 3 * small, "twice the text, {small} then {large} byte reads"); + } + #[test] fn unclosed_angle_brackets_are_escaped_in_one_pass() { // Every `<` used to search the rest of the text for a `>`, which made this quadratic. - let text = "<".repeat(200_000); - let started = std::time::Instant::now(); - let out = inline(&text); - assert_eq!(out, "<".repeat(200_000)); - assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + assert_linear(|n| "<".repeat(n), |n| "<".repeat(n)); // A tag before the unclosed tail is still markup; the tail stays literal text. assert_eq!(inline("a 1 < 2"), "a 1 < 2"); } + + #[test] + fn many_unmatched_angle_brackets_before_one_gt_are_read_once() { + assert_linear(|n| format!("{}>", "<".repeat(n)), |n| format!("{}>", "<".repeat(n))); + } } diff --git a/crates/captions/tests/it/ttml_literal_angle.rs b/crates/captions/tests/it/ttml_literal_angle.rs index 0e48439013..f2a98abb61 100644 --- a/crates/captions/tests/it/ttml_literal_angle.rs +++ b/crates/captions/tests/it/ttml_literal_angle.rs @@ -66,11 +66,10 @@ fn whitespace_after_lt_is_literal_text() { } } +/// The work for this text is checked in `ttml.rs`'s `many_unmatched_angle_brackets_before_one_gt_are_read_once`. #[test] -fn many_unmatched_lt_is_fast() { +fn many_unmatched_lt_stay_text() { let input = format!("{}>", "<".repeat(256_000)); - let start = std::time::Instant::now(); let text = export(&input, Format::Ttml); - assert!(start.elapsed() < std::time::Duration::from_secs(2), "took {:?}", start.elapsed()); assert!(text.contains(&format!("{}>", "<".repeat(256_000)))); }