From 06ac6c8931e9dc07025ebc9952d80d92f9b6f53d Mon Sep 17 00:00:00 2001 From: Justin John Date: Mon, 2 Nov 2026 20:30:57 +0530 Subject: [PATCH 01/14] Path cache: skip untouched paths, cover channels and alpha images, cap memory Follow-up to #133's review notes. - The cache key now covers the owner layer's and texture set's channels, and each path's brush alpha image, so changing them repaints instead of reusing stale pixels. - The cache keeps a snapshot after each path and the tiles each path painted. An unchanged path above an edit reuses its tiles when the edit didn't reach them; removing a path reuses the paths above it. - Snapshots stay within 256 MB, oldest dropped first, keeping the one below the path being edited so live edits start there. - Path repaints ignore the quick mask: a path paints only from what it stores. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/painting.rs | 8 + crates/engine/src/path_tool.rs | 304 ++++++++++++++++++++++++++------ crates/engine/src/quick_mask.rs | 4 +- crates/engine/src/session.rs | 5 +- 4 files changed, 265 insertions(+), 56 deletions(-) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index de132ffd..3c90af84 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -141,6 +141,8 @@ impl Session { let ts = self.ts(); let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024)); let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? }; + // PathCache reuses a path's tiles only if painting one tile reads no other. + debug_assert!(!(self.painting_paths && pickup.is_some()), "path repaints never pick up"); if pickup.is_some() { // Clone and smudge read the composite: bring it up to date first. self.update(); @@ -402,6 +404,9 @@ impl Session { self.doc = st.before; return Ok(()); } + if self.painting_paths { + self.path_tiles.extend(st.canvas.dirty.iter().copied()); + } let gbuf = self.caches.get(st.ts).map(|c| c.gbuf.clone()); let mesh = self.mesh.clone(); let mut staging = std::mem::take(&mut st.staging); @@ -502,6 +507,9 @@ impl Session { pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> { let size = (canvas.alpha.width(), canvas.alpha.height()); let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; + if self.painting_paths { + self.path_tiles.extend(canvas.dirty.iter().copied()); + } if self.quick_mask.editing { self.commit_quick_mask(ts, size, src(self.tool.brush.opacity)); return Ok(()); diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 0b2903e0..6629c944 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -7,13 +7,16 @@ //! (`path.edit`, live while the points, brush or material change) or removed (`path.remove`). use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use texturecraft_compose::ImageRes; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape}; use texturecraft_geom::OrbitCamera; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; +use texturecraft_texel::{TILE_AREA, TileImage}; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; use crate::session::{StackTarget, Tool}; @@ -22,6 +25,9 @@ use crate::{EngineError, Result, Session, cmd}; /// Control points kept at most. pub const MAX_PATH_POINTS: usize = 4096; +/// Bytes of tiles the path cache's snapshots may hold (plus the edited path's); the oldest go +/// first. +const CACHE_BYTES: usize = 256 << 20; /// Curve sampling step in viewport pixels (3D view) and texture units (2D view). const STEP_PX: f32 = 2.0; const STEP_UV: f32 = 0.001; @@ -58,17 +64,74 @@ impl PathState { } } -/// A path sublayer's pixels after painting its first paths (`below`), with the mesh and -/// texture size they were painted for. +/// Mesh id, texture size, owner layer channels, texture set channels. +type CacheKey = (u64, Option<(u32, u32)>, Vec, Vec); +/// A path sublayer's images: its mask (`None`) and each channel. +type Snap = BTreeMap, TileImage>; +/// A stored path and the brush alpha image it was painted with. +type Painted = (PathShape, Option>); + +/// A path sublayer as last painted for `key`: its paths, its images after each path +/// (`snaps[k]` after the first k; tiles are shared, so a snapshot costs only the tiles that +/// path changed; None once [`evict`]ed) and the tiles each path painted. #[derive(Clone)] -// shortcut: the key doesn't cover image resources a path's brush alpha reads; replacing one -// leaves cached paths with the old alpha until a path below the edited one changes. pub(crate) struct PathCache { eid: LayerId, - key: (u64, Option<(u32, u32)>), - below: Vec, - mask: Option, - layers: Vec<((LayerId, Channel), texturecraft_texel::TileImage)>, + key: CacheKey, + shapes: Vec, + snaps: Vec>, + tiles: Vec>, +} + +/// Drop the snapshots past `budget` bytes, oldest first, so adding a path and editing recent +/// ones stay cheap, but keep snapshot `edited` (below the path being edited, so its next live +/// repaint starts there). Snapshot k holds at most path k-1's tiles in each image; the first +/// (empty) and the last (the live pixels) cost nothing. +fn evict(snaps: &mut [Option], tiles: &[BTreeSet<(u32, u32)>], budget: usize, edited: usize) { + let mut bytes = 0; + for k in (1..snaps.len().saturating_sub(1)).rev().filter(|&k| k != edited) { + if let Some(snap) = &snaps[k] { + bytes += tiles[k - 1].len() * snap.values().map(|i| TILE_AREA * i.comps() * 2).sum::(); + if bytes > budget { + snaps[k] = None; + } + } + } +} + +fn same_handle(a: Option<&Arc>, b: Option<&Arc>) -> bool { + match (a, b) { + (Some(x), Some(y)) => Arc::ptr_eq(x, y), + (x, y) => x.is_none() && y.is_none(), + } +} + +fn same_path(a: &Painted, b: &Painted) -> bool { + a.0 == b.0 && same_handle(a.1.as_ref(), b.1.as_ref()) +} + +/// Whether `a` and `b` hold the same tiles at `tiles`, by shared handle (painting a tile always +/// gives it a new one); a missing image reads as empty. +fn same_tiles(a: &Snap, b: &Snap, tiles: &BTreeSet<(u32, u32)>) -> bool { + a.keys().chain(b.keys()).all(|k| { + let (x, y) = (a.get(k), b.get(k)); + let dims = |i: &TileImage| (i.width(), i.height(), i.comps()); + x.zip(y).is_none_or(|(x, y)| dims(x) == dims(y)) + && tiles.iter().all(|&(tx, ty)| same_handle(x.and_then(|i| i.tile_handle(tx, ty)), y.and_then(|i| i.tile_handle(tx, ty)))) + }) +} + +/// Copy `from`'s tiles at `tiles` into `to`. +fn copy_tiles(to: &mut Snap, from: &Snap, tiles: &BTreeSet<(u32, u32)>) { + for (k, src) in from { + to.entry(*k).or_insert_with(|| TileImage::new(src.width(), src.height(), src.comps())); + } + for (k, dst) in to.iter_mut() { + let src = from.get(k); + for &(x, y) in tiles { + dst.set_tile(x, y, src.and_then(|i| i.tile_handle(x, y)).cloned()); + } + } } /// What a stored path is painted with ([`PathShape::paint`]). @@ -197,7 +260,7 @@ fn remove_path(s: &mut Session, p: &Value) -> Result { { shapes.remove(index); } - s.render_paths(eid, index) + s.render_paths(eid) })?; if s.tool.path.editing.is_some_and(|(e, _)| e == eid) { s.stop_path_edit(); @@ -359,32 +422,43 @@ impl Session { }, _ => return Err(EngineError::Other(format!("{} is not a path sublayer", eid.0))), }; - let mut out = self.render_paths(eid, index)?.get(index).cloned().unwrap_or_else(|| json!({})); + let mut out = self.render_paths(eid)?.get(index).cloned().unwrap_or_else(|| json!({})); out["effect"] = json!(eid.0); out["index"] = json!(index); Ok(out) } - /// Repaint path sublayer `eid` from its stored paths, bottom to top, where paths before - /// `from` are unchanged: their pixels come from [`PathCache`] when it holds them, and are - /// cached for the next repaint otherwise, so editing a path repaints it and the paths above - /// only. Runs inside the caller's undo step. Returns each painted path's report (null for - /// the cached ones). - fn render_paths(&mut self, eid: LayerId, from: usize) -> Result> { + /// Repaint path sublayer `eid` from its stored paths, bottom to top. From [`PathCache`]: the + /// paths before the first changed one keep their pixels, and an unchanged path above it + /// whose tiles the change didn't reach keeps its painted tiles; the rest repaint. Runs + /// inside the caller's undo step. Returns each painted path's report (null for the cached + /// ones). + fn render_paths(&mut self, eid: LayerId) -> Result> { let shapes = self.paths(eid).ok_or_else(|| EngineError::Other(format!("{} is not a path sublayer", eid.0)))?.to_vec(); - let key = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size)); - self.doc.pixels.masks.remove(&eid); - self.doc.pixels.layers.retain(|(id, _), _| *id != eid); - let start = match &self.path_cache { - Some(c) if c.eid == eid && c.key == key && c.below.len() <= from && shapes.get(..c.below.len()) == Some(&c.below[..]) => { - if let Some(m) = &c.mask { - self.doc.pixels.masks.insert(eid, m.clone()); - } - self.doc.pixels.layers.extend(c.layers.iter().cloned()); - c.below.len() - } - _ => 0, - }; + let images = &self.images; + let alpha = |sh: &PathShape| read_paint(sh).ok().and_then(|p| p.brush.alpha_image).and_then(|n| images.get(&n).cloned()); + let new: Vec = shapes + .into_iter() + .map(|sh| { + let a = alpha(&sh); + (sh, a) + }) + .collect(); + let project = &self.doc.project; + let owner = project.effect(eid).and_then(|(o, _)| project.layer(o).ok()).map(|l| l.channels.keys().copied().collect()).unwrap_or_default(); + let set = project.texture_set(self.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let key: CacheKey = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size), owner, set); + let old = self.path_cache.take().filter(|c| c.eid == eid && c.key == key); + let (prefix, suffix) = old.as_ref().map_or((0, 0), |c| { + let p = c.shapes.iter().zip(&new).take_while(|(a, b)| same_path(a, b)).count(); + (p, c.shapes[p..].iter().rev().zip(new[p..].iter().rev()).take_while(|(a, b)| same_path(a, b)).count()) + }); + // Start from the last snapshot kept at or below the first changed path (the first one, + // empty, is always kept). + let start = old.as_ref().map_or(0, |c| (0..=prefix).rev().find(|&k| c.snaps[k].is_some()).unwrap_or(0)); + let mut snaps = old.as_ref().map_or_else(|| vec![Some(Snap::new())], |c| c.snaps[..=start].to_vec()); + let mut tiles = old.as_ref().map_or_else(Vec::new, |c| c.tiles[..start].to_vec()); + let mut state = snaps[start].clone().unwrap_or_default(); // Each path goes through the regular stroke and fill code with its own settings; their // own history entries are dropped (the caller records one step). let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing); @@ -395,13 +469,22 @@ impl Session { self.painting_paths = true; let mut out = vec![Value::Null; start]; let mut result = Ok(()); - for i in start..=shapes.len() { - if i == from.min(shapes.len()) && i > start { - let pixels = &self.doc.pixels; - let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect(); - self.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers }); + for (j, (sh, _)) in new.iter().enumerate().skip(start) { + // Painting is per tile: over the same tiles, an unchanged path paints the same. + let o = if j < prefix { Some(j) } else { (j >= new.len() - suffix).then(|| j + old.as_ref().map_or(0, |c| c.shapes.len()) - new.len()) }; + if let (Some(c), Some(o)) = (&old, o) + && let (Some(below), Some(after)) = (&c.snaps[o], &c.snaps[o + 1]) + && same_tiles(&state, below, &c.tiles[o]) + { + copy_tiles(&mut state, after, &c.tiles[o]); + tiles.push(c.tiles[o].clone()); + snaps.push(Some(state.clone())); + evict(&mut snaps, &tiles, CACHE_BYTES, prefix); + out.push(Value::Null); + continue; } - let Some(sh) = shapes.get(i) else { break }; + self.put_snap(eid, &state); + self.path_tiles.clear(); match self.paint_shape(sh) { Ok(v) => out.push(v), Err(e) => { @@ -409,13 +492,39 @@ impl Session { break; } } + state = self.take_snap(eid); + tiles.push(std::mem::take(&mut self.path_tiles)); + snaps.push(Some(state.clone())); + evict(&mut snaps, &tiles, CACHE_BYTES, prefix); } + self.put_snap(eid, &state); self.painting_paths = false; (self.tool, self.camera, self.target, self.quick_mask.editing) = saved; (self.undo, self.redo) = history; + if result.is_ok() { + self.path_cache = Some(PathCache { eid, key, shapes: new, snaps, tiles }); + } result.map(|_| out) } + fn take_snap(&self, eid: LayerId) -> Snap { + let p = &self.doc.pixels; + let mask = p.masks.get(&eid).map(|m| (None, m.clone())); + mask.into_iter().chain(p.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, c), img)| (Some(*c), img.clone()))).collect() + } + + fn put_snap(&mut self, eid: LayerId, snap: &Snap) { + let p = &mut self.doc.pixels; + p.masks.remove(&eid); + p.layers.retain(|(id, _), _| *id != eid); + for (k, img) in snap { + match k { + None => p.masks.insert(eid, img.clone()), + Some(c) => p.layers.insert((eid, *c), img.clone()), + }; + } + } + fn paint_shape(&mut self, shape: &PathShape) -> Result { let paint = read_paint(shape)?; self.tool.brush = paint.brush; @@ -493,7 +602,7 @@ impl Session { #[cfg(test)] mod tests { - use serde_json::json; + use serde_json::{Value, json}; use crate::{Session, execute}; @@ -504,29 +613,118 @@ mod tests { v } - #[test] - fn cached_repaint_matches_a_full_repaint() { - let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + /// A session with horizontal UV paths at `rows` (one path sublayer) on a 512 texture. + fn with_paths(rows: &[f32]) -> (Session, texturecraft_core::LayerId) { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 512).unwrap(); s.update(); execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); let mut eid = 0; - for v in [0.2, 0.5, 0.8] { - let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v + 0.05]], "commit": true})).unwrap(); + for v in rows { + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v]], "commit": true})).unwrap(); eid = r["committed"]["effect"].as_u64().unwrap(); } - let eid = texturecraft_core::LayerId(eid); - // Live edits of the middle path reuse the bottom path's pixels. - execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); - for v in [0.4, 0.45] { - execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); - } - assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1)); - let r = s.render_paths(eid, 1).unwrap(); - assert!(r[0].is_null() && !r[1].is_null(), "the bottom path came from the cache: {r:?}"); - let cached = pixels(&s, eid); + (s, texturecraft_core::LayerId(eid)) + } + + /// Move path `index` to row `v` (a live edit) and check the result against painting every + /// path. Returns which paths were repainted. + fn edit_row(s: &mut Session, eid: texturecraft_core::LayerId, index: usize, v: f32) -> Vec { + execute(s, "path.edit", &json!({"effect": eid.0, "index": index})).unwrap(); + let before = s.path_cache.clone(); + execute(s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); + let cached = pixels(s, eid); + s.path_cache = before; + let painted = s.render_paths(eid).unwrap().iter().map(|r| !r.is_null()).collect(); + assert_eq!(cached, pixels(s, eid)); s.path_cache = None; - s.render_paths(eid, 0).unwrap(); - assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); + s.render_paths(eid).unwrap(); + assert_eq!(cached, pixels(s, eid), "same pixels as painting every path"); assert!(!cached.is_empty()); + s.stop_path_edit(); + painted + } + + #[test] + fn cached_repaint_matches_a_full_repaint() { + // Rows 0.2, 0.45 and 0.8 of 512 texels are in different 64-texel tile rows. + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + assert_eq!(edit_row(&mut s, eid, 1, 0.47), [false, true, false], "only the edited path repaints"); + assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false, false], "paths above keep their tiles"); + assert_eq!(edit_row(&mut s, eid, 0, 0.79), [true, false, true], "a path over the change repaints"); + } + + #[test] + fn removing_a_path_keeps_the_paths_above() { + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + let before = s.path_cache.clone(); + execute(&mut s, "path.remove", &json!({"effect": eid.0, "index": 0})).unwrap(); + let cached = pixels(&s, eid); + s.path_cache = before; + assert!(s.render_paths(eid).unwrap().iter().all(Value::is_null), "both paths above came from the cache"); + s.path_cache = None; + s.render_paths(eid).unwrap(); + assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); + } + + #[test] + fn replacing_the_brush_alpha_image_repaints() { + let (mut s, eid) = with_paths(&[0.2]); + let img = |v: f32| std::sync::Arc::new(texturecraft_compose::ImageRes { width: 2, height: 2, rgba: vec![[v; 4]; 4], srgb: false }); + s.images.insert("a".into(), img(1.0)); + execute(&mut s, "tool.brush", &json!({"alpha": {"image": "a"}})).unwrap(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.8], [0.9, 0.8]], "commit": true})).unwrap(); + s.render_paths(eid).unwrap(); + s.images.insert("a".into(), img(0.5)); + let r = s.render_paths(eid).unwrap(); + assert!(r[0].is_null() && !r[1].is_null(), "only the path using the image repaints: {r:?}"); + } + + #[test] + fn snapshots_stay_within_the_budget() { + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + let c = s.path_cache.as_mut().unwrap(); + super::evict(&mut c.snaps, &c.tiles, usize::MAX, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4); + super::evict(&mut c.snaps, &c.tiles, 0, 0); + assert!(c.snaps[0].is_some() && c.snaps[3].is_some() && c.snaps[1..3].iter().all(Option::is_none), "only the free ones stay"); + // Appending still paints the new path alone. + let shape = s.paths(eid).unwrap()[0].clone(); + if let Some(texturecraft_core::Effect { kind: texturecraft_core::EffectKind::Path(v), .. }) = s.doc.project.effect_mut(eid) { + v.push(shape); + } + let r = s.render_paths(eid).unwrap(); + assert_eq!(r.iter().map(|x| !x.is_null()).collect::>(), [false, false, false, true]); + // Editing above evicted snapshots repaints from the bottom and matches a full repaint. + let c = s.path_cache.as_mut().unwrap(); + super::evict(&mut c.snaps, &c.tiles, 0, 0); + assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); + // That edit kept the snapshot below path 3 within a zero budget: its next frame starts there. + let c = s.path_cache.as_mut().unwrap(); + super::evict(&mut c.snaps, &c.tiles, 0, 2); + assert!(c.snaps[2].is_some() && c.snaps[1].is_none()); + assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, true], "path 4 lost its snapshot too"); + } + + #[test] + fn the_quick_mask_does_not_clip_paths() { + let (mut s, eid) = with_paths(&[0.2, 0.8]); + let plain = pixels(&s, eid); + s.quick_mask.enabled = true; + s.path_cache = None; + s.render_paths(eid).unwrap(); + assert_eq!(plain, pixels(&s, eid)); + } + + #[test] + fn owner_channel_change_skips_the_cache() { + let (mut s, eid) = with_paths(&[0.3, 0.7]); + s.render_paths(eid).unwrap(); + let owner = s.doc.project.effect(eid).unwrap().0; + let layer = s.doc.project.layer_mut(owner).unwrap(); + let ch = *layer.channels.keys().next().unwrap(); + layer.channels.remove(&ch); + let r = s.render_paths(eid).unwrap(); + assert!(!r[0].is_null(), "the bottom path was repainted: {r:?}"); + assert!(!s.doc.pixels.layers.contains_key(&(eid, ch)), "no pixels left in the removed channel"); } } diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index 304ab3c9..f407a9ef 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -86,10 +86,10 @@ impl Session { } /// What limits a paint stroke on `ts`: the mask and whether it is inverted (None when the - /// quick mask is off or being edited). + /// quick mask is off or being edited, and for paths, which repaint from what they store). pub(crate) fn stroke_limit(&self, ts: usize, size: (u32, u32)) -> Option<(TileImage, bool)> { let q = &self.quick_mask; - (q.enabled && !q.editing).then(|| (self.quick_mask_image(ts, size), q.inverted)) + (q.enabled && !q.editing && !self.painting_paths).then(|| (self.quick_mask_image(ts, size), q.inverted)) } /// Commit a stroke into the quick mask of `ts`. diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index e9909635..7b49d8e2 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -346,8 +346,10 @@ pub struct Session { pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). pub(crate) painting_paths: bool, - /// Pixels of the paths below the one being edited, so live edits skip repainting them. + /// A path sublayer as last painted, so a repaint skips the paths an edit didn't reach. pub(crate) path_cache: Option, + /// Tiles painted since `render_paths` cleared it (the footprint of one path). + pub(crate) path_tiles: std::collections::BTreeSet<(u32, u32)>, pub path: Option, pub modified: bool, /// Bumps on every document change. @@ -402,6 +404,7 @@ impl Session { quick_mask: Default::default(), painting_paths: false, path_cache: None, + path_tiles: Default::default(), path: None, modified: false, revision: 1, From 83e13fb6c083d0dc5969869ed508f2789d71c6e6 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Wed, 4 Nov 2026 23:43:30 -0500 Subject: [PATCH 02/14] fix(geom): Mesh::validate refuses non-finite normals and absurd UVs validate checked positions were finite but not normals or UVs. A UV like 1e30 saturates the integer texel maths in ImageRes::sample, the colour bake and the path tracer, and x0 + 1 then overflows (a panic in debug builds, a wrapped lookup in release). UVs must now be finite and within +-1e6 (UDIM layouts stop at 10 columns); normals must be finite. Co-Authored-By: Claude Sonnet 5.5 --- crates/geom/src/mesh.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 95d66b4e..1d92dc8b 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -47,6 +47,9 @@ pub struct Mesh { /// Hard cap on mesh size accepted from files (triangles). pub const MAX_TRIANGLES: usize = 20_000_000; +/// Largest UV coordinate a mesh may carry (UDIM tiles stop at 10 columns; this is far beyond any +/// real layout). Texel lookups turn UVs into integers, which a UV like 1e30 would overflow. +pub const MAX_UV: f32 = 1.0e6; impl Mesh { pub fn triangle_count(&self) -> usize { @@ -145,6 +148,12 @@ impl Mesh { if self.positions.iter().any(|p| !p.is_finite()) { return Err(GeomError::Invalid("mesh has non-finite positions".into())); } + if self.normals.iter().any(|n| !n.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite normals".into())); + } + if self.uvs.iter().any(|uv| !uv.is_finite() || uv.x.abs() > MAX_UV || uv.y.abs() > MAX_UV) { + return Err(GeomError::Invalid(format!("mesh has non-finite UVs or UVs beyond ±{MAX_UV}"))); + } for s in &self.submeshes { if s.start as usize + s.count as usize > self.indices.len() || s.material >= self.materials.len().max(1) { return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); @@ -443,6 +452,26 @@ mod tests { assert!(m.validate().is_err()); } + #[test] + fn validate_refuses_non_finite_normals_and_absurd_uvs() { + assert!(quad().validate().is_ok()); + for bad in [f32::NAN, f32::INFINITY, -f32::INFINITY, 1.0e30, -2.0e6] { + let mut m = quad(); + m.uvs[1].x = bad; + assert!(m.validate().is_err(), "uv {bad}"); + let mut m = quad(); + m.uvs[2].y = bad; + assert!(m.validate().is_err(), "uv {bad}"); + } + let mut m = quad(); + m.normals[0].z = f32::NAN; + assert!(m.validate().is_err()); + // Large but real UDIM-style layouts stay valid. + let mut m = quad(); + m.uvs[0] = Vec2::new(1009.5, 0.5); + assert!(m.validate().is_ok()); + } + #[test] fn append_offsets_indices_and_materials() { let mut a = quad(); From da53dc8a8c37ca21d8b3c5fe2c1c4efc8558c37a Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 6 Nov 2026 07:29:11 -0500 Subject: [PATCH 03/14] fix(#253): texel lookups at huge finite UVs no longer overflow MAX_UV (1e6) does not protect the 32-bit lookup in the path tracer (1e6 * 4096 saturates i32, then +dx overflows), and sample()/base_color() add 1 to a saturated i64. UVs also come from places other than mesh attributes. Lookups now saturate/64-bit and refuse non-finite coordinates after scaling. Co-Authored-By: Claude Sonnet 5.5 --- crates/bake/src/map/source.rs | 27 +++++++++++++++++++++++---- crates/compose/src/store.rs | 28 +++++++++++++++++++++++++++- crates/render/src/trace.rs | 29 +++++++++++++++++++++++++---- 3 files changed, 75 insertions(+), 9 deletions(-) diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index 0e1f9164..27b50ffe 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -117,10 +117,15 @@ fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { Vec4::new(srgb_to_linear(color(0)), srgb_to_linear(color(1)), srgb_to_linear(color(2)), color(3)) }; let (fx, fy) = (uv.x * width as f32 - 0.5, uv.y * height as f32 - 0.5); - let (x0, y0) = (fx.floor(), fy.floor()); - let (tx, ty) = (fx - x0, fy - y0); - let (x, y) = (x0 as i64, y0 as i64); - texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty) + if fx.is_finite() && fy.is_finite() { + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - x0, fy - y0); + let (x, y) = (x0 as i64, y0 as i64); + let (x1, y1) = (x.saturating_add(1), y.saturating_add(1)); + texel(x, y).lerp(texel(x1, y), tx).lerp(texel(x, y1).lerp(texel(x1, y1), tx), ty) + } else { + Vec4::ONE + } }; let color = sampled_color * material.factor; Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w) @@ -133,3 +138,17 @@ fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { let next = keys.len() as u32; *keys.entry(base).or_insert(next) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn base_color_sampling_survives_huge_finite_uvs() { + let material = BaseColor { factor: Vec4::ONE, width: 2, height: 2, texels: vec![[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]] }; + for uv in [Vec2::new(1.0e30, 0.5), Vec2::new(0.5, -1.0e30), Vec2::splat(f32::MAX), Vec2::splat(1.0e6)] { + let c = base_color(&material, uv); + assert!(c.is_finite(), "{uv}: {c}"); + } + } +} diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index 1370c0c0..1dc801b5 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -85,9 +85,17 @@ impl ImageRes { } let fx = u * self.width as f32 - 0.5; let fy = v * self.height as f32 - 0.5; + if !fx.is_finite() || !fy.is_finite() { + return [0.0; 4]; + } let (x0, y0) = (fx.floor() as i64, fy.floor() as i64); let (tx, ty) = (fx - fx.floor(), fy - fy.floor()); - let (a, b, c, d) = (self.texel(x0, y0), self.texel(x0 + 1, y0), self.texel(x0, y0 + 1), self.texel(x0 + 1, y0 + 1)); + let (a, b, c, d) = ( + self.texel(x0, y0), + self.texel(x0.saturating_add(1), y0), + self.texel(x0, y0.saturating_add(1)), + self.texel(x0.saturating_add(1), y0.saturating_add(1)), + ); let mut out = [0.0; 4]; for k in 0..4 { let top = a[k] + (b[k] - a[k]) * tx; @@ -97,3 +105,21 @@ impl ImageRes { out } } + +#[cfg(test)] +mod tests { + use super::*; + + fn checker() -> ImageRes { + ImageRes { width: 2, height: 2, rgba: vec![[0.0; 4], [1.0; 4], [1.0; 4], [0.0; 4]], srgb: false } + } + + #[test] + fn sampling_at_huge_finite_coordinates_does_not_overflow() { + let img = checker(); + for (u, v) in [(1.0e30, 0.5), (0.5, -1.0e30), (f32::MAX, f32::MAX), (1.0e6, -1.0e6)] { + let s = img.sample(u, v); + assert!(s.iter().all(|c| c.is_finite() && (0.0..=1.0).contains(c)), "({u}, {v}) -> {s:?}"); + } + } +} diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index a823a031..39b51d1d 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -537,10 +537,7 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3 let set = scene.tri_set.get(tri as usize).and_then(|s| scene.sets.get(*s)); // The composite texel at offset (dx, dy) from the hit. - let texel = |s: &TraceSet, dx: i32, dy: i32| { - let (w, h) = (s.composite.resolution.max(1) as i32, s.composite.height.max(1) as i32); - (((uv.x * w as f32).floor() as i32 + dx).rem_euclid(w) as u32, ((uv.y * h as f32).floor() as i32 + dy).rem_euclid(h) as u32) - }; + let texel = |s: &TraceSet, dx: i32, dy: i32| wrapped_texel(uv, (s.composite.resolution, s.composite.height), dx, dy); let ch = |c: Channel, dx: i32, dy: i32| -> [f32; 3] { let Some(s) = set else { return c.default_value() }; let (x, y) = texel(s, dx, dy); @@ -1042,8 +1039,32 @@ fn trace(scene: &TraceScene, mut o: Vec3, mut d: Vec3, settings: &TraceSettings, Some(Sample { radiance: if l.is_finite() { l } else { Vec3::ZERO }, albedo, normal, depth }) } +/// The texel of a `size` image at `uv` (wrapping), offset by `(dx, dy)`. 64-bit so a far-off UV +/// times a wide image can't overflow the offset (in 32 bits a UV of 1e6 on an image 4096 wide saturated, and the offset then overflowed). +fn wrapped_texel(uv: Vec2, size: (u32, u32), dx: i32, dy: i32) -> (u32, u32) { + let (w, h) = (i64::from(size.0.max(1)), i64::from(size.1.max(1))); + let at = |t: f32, n: i64, d: i32| ((t * n as f32).floor() as i64).saturating_add(i64::from(d)).rem_euclid(n) as u32; + (at(uv.x, w, dx), at(uv.y, h, dy)) +} + #[cfg(test)] mod tests { + #[test] + fn texel_lookup_survives_far_off_uvs() { + use super::wrapped_texel; + use texturecraft_geom::glam::Vec2; + // Inside the image, and offsets wrap around the edges. + assert_eq!(wrapped_texel(Vec2::new(0.25, 0.75), (4, 4), 0, 0), (1, 3)); + assert_eq!(wrapped_texel(Vec2::new(0.0, 0.99), (4, 4), -1, 1), (3, 0)); + // 1e6 (the largest UV a mesh may carry) times 8192 texels is past i32::MAX; 1e30 saturates. + for uv in [1.0e6, -1.0e6, 1.0e30, f32::MAX] { + for (dx, dy) in [(1, 1), (-1, -1), (0, 0)] { + let (x, y) = wrapped_texel(Vec2::new(uv, uv), (8192, 8192), dx, dy); + assert!(x < 8192 && y < 8192, "{uv}: ({x}, {y})"); + } + } + } + use super::*; use texturecraft_geom::primitives; From 88e0eb1ba5417f931bcde44efa08978bc9f234ff Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:40:16 -0500 Subject: [PATCH 04/14] fix(#253): clamp the height sample position so x0 + 1 can't overflow A huge finite UV saturates the cast to isize (32-bit on wasm32), and x0 + 1 then overflowed (a panic in debug). Past one texel outside, every lookup clamps to the same edge texel, so clamping the position first changes no result. Co-Authored-By: Claude Sonnet 5.5 --- crates/render/src/displace.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index f2e2b19a..d40c9b73 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -117,6 +117,10 @@ impl Heights { if !(fx.is_finite() && fy.is_finite()) { return 0.0; } + // Past one texel outside, every lookup clamps to the same edge texel, so clamping the + // position first changes no result but keeps `x0 + 1` far from overflowing: a huge finite + // UV saturates the `as isize` cast, and isize is 32 bits on wasm32. + let (fx, fy) = (fx.clamp(-1.0, self.w as f32), fy.clamp(-1.0, self.h as f32)); let (x0, y0) = (fx.floor(), fy.floor()); let (tx, ty) = (fx - x0, fy - y0); let (x0, y0) = (x0 as isize, y0 as isize); @@ -144,6 +148,21 @@ mod tests { TraceSet { material: 0, composite, height_strength: strength } } + #[test] + fn sampling_at_huge_or_far_uvs_clamps_to_the_edge_without_overflow() { + let heights = Heights { w: 2, h: 2, data: vec![1.0, 2.0, 3.0, 4.0] }; + // x0 + 1 used to overflow for these (the cast to isize saturates at isize::MAX). + for far in [1.0e30_f32, -1.0e30, f32::MAX, f32::MIN, 1.0e10] { + assert!(heights.sample(Vec2::new(far, far)).is_finite()); + } + assert_eq!(heights.sample(Vec2::new(1.0e30, 1.0e30)), 4.0); + assert_eq!(heights.sample(Vec2::new(-1.0e30, -1.0e30)), 1.0); + assert_eq!(heights.sample(Vec2::new(1.0e30, -1.0e30)), 2.0); + assert_eq!(heights.sample(Vec2::new(f32::NAN, 0.5)), 0.0); + // In range, bilinear is unchanged: the centre of the 2 x 2 is the mean. + assert!((heights.sample(Vec2::new(0.5, 0.5)) - 2.5).abs() < 1e-6); + } + #[test] fn uniform_height_lifts_the_dense_plane_along_its_normal() { let plane = primitives::plane(2.0, 1); From a5ba5eb719646208cfc270dc0963076e9e807ed2 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:24:10 -0500 Subject: [PATCH 05/14] docs(#253): doc comments for the touched functions and the new tests Co-Authored-By: Claude Sonnet 5.5 --- crates/bake/src/map/source.rs | 3 +++ crates/compose/src/store.rs | 2 ++ crates/geom/src/mesh.rs | 1 + crates/render/src/displace.rs | 1 + crates/render/src/trace.rs | 3 +++ 5 files changed, 10 insertions(+) diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index 27b50ffe..7f2e7e32 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -106,6 +106,8 @@ impl<'a> Source<'a> { } } +/// The material's base colour at `uv` (bilinear, wrapping), sRGB RGBA times its factor; white +/// where there is no texture or the UV is not finite. fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { let sampled_color = if material.texels.is_empty() || !uv.is_finite() { Vec4::ONE @@ -143,6 +145,7 @@ fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { mod tests { use super::*; + /// Sampling at huge but finite UVs returns a finite colour instead of overflowing. #[test] fn base_color_sampling_survives_huge_finite_uvs() { let material = BaseColor { factor: Vec4::ONE, width: 2, height: 2, texels: vec![[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]] }; diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index 1dc801b5..d8461f50 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -110,10 +110,12 @@ impl ImageRes { mod tests { use super::*; + /// A 2 x 2 black and white checker image for the sampling test. fn checker() -> ImageRes { ImageRes { width: 2, height: 2, rgba: vec![[0.0; 4], [1.0; 4], [1.0; 4], [0.0; 4]], srgb: false } } + /// Sampling at huge finite coordinates stays finite and within 0..=1 instead of overflowing. #[test] fn sampling_at_huge_finite_coordinates_does_not_overflow() { let img = checker(); diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 1d92dc8b..64c8b1e5 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -452,6 +452,7 @@ mod tests { assert!(m.validate().is_err()); } + /// Validation rejects non-finite normals and non-finite or beyond-limit UVs, but accepts UDIM-style UVs. #[test] fn validate_refuses_non_finite_normals_and_absurd_uvs() { assert!(quad().validate().is_ok()); diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index d40c9b73..abd71692 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -148,6 +148,7 @@ mod tests { TraceSet { material: 0, composite, height_strength: strength } } + /// Far-off UVs clamp to the nearest edge texel without overflow; NaN gives 0 and in-range sampling is unchanged. #[test] fn sampling_at_huge_or_far_uvs_clamps_to_the_edge_without_overflow() { let heights = Heights { w: 2, h: 2, data: vec![1.0, 2.0, 3.0, 4.0] }; diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index 39b51d1d..1ea49e22 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -514,6 +514,8 @@ fn rnm(base: Vec3, detail: Vec3) -> Vec3 { (t * t.dot(u) - u * t.z).normalize_or(Vec3::Z) } +/// Builds the shading surface at a ray hit: interpolated geometry, normal and tangent frame, and the +/// set's channel values (base colour, roughness, metallic, coat and so on) at the hit's UV. fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f32) -> Option { let m = &scene.mesh; let i = tri as usize * 3; @@ -1049,6 +1051,7 @@ fn wrapped_texel(uv: Vec2, size: (u32, u32), dx: i32, dy: i32) -> (u32, u32) { #[cfg(test)] mod tests { + /// `wrapped_texel` wraps offsets at the edges and stays inside the image for far-off UVs. #[test] fn texel_lookup_survives_far_off_uvs() { use super::wrapped_texel; From 57c6179179b46bbbfddd4deb26143042681cbb79 Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 01:18:50 -0500 Subject: [PATCH 06/14] Show a notice when an autosave fails The worker reports its result to the app. A failure, including a worker that cannot start, shows one dismissible notice with the path and the reason, recorded in the Log, until a later autosave works. --- crates/ui-egui/src/autosave_notice.rs | 75 +++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 22 +++++--- crates/ui-egui/tests/autosave_notice.rs | 46 +++++++++++++++ 3 files changed, 136 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/autosave_notice.rs create mode 100644 crates/ui-egui/tests/autosave_notice.rs diff --git a/crates/ui-egui/src/autosave_notice.rs b/crates/ui-egui/src/autosave_notice.rs new file mode 100644 index 00000000..cc37af56 --- /dev/null +++ b/crates/ui-egui/src/autosave_notice.rs @@ -0,0 +1,75 @@ +//! Tells the user when an autosave fails: the worker reports back, and one notice stays until a later +//! autosave works, so a missing backup is not mistaken for a saved one. + +use std::path::PathBuf; +use std::sync::mpsc::{Receiver, Sender, channel}; + +use crate::TextureCraftApp; +use crate::i18n::trf; + +/// How one autosave ended. +struct Outcome { + path: PathBuf, + result: Result<(), String>, +} + +pub(crate) struct AutosaveNotice { + sender: Sender, + receiver: Receiver, + /// The failure the user was last told about; cleared by an autosave that works. + shown: Option, +} + +impl Default for AutosaveNotice { + fn default() -> Self { + let (sender, receiver) = channel(); + Self { sender, receiver, shown: None } + } +} + +/// Sends one autosave's result to the app, from any thread. +pub(crate) struct Reporter { + sender: Sender, + context: egui::Context, +} + +impl Reporter { + pub(crate) fn report(self, path: PathBuf, result: Result<(), String>) { + match &result { + Ok(()) => log::info!("autosaved {}", path.display()), + Err(error) => log::warn!("autosave to {} failed: {error}", path.display()), + } + + // A closed channel means the app is gone, so there is nobody left to tell + if self.sender.send(Outcome { path, result }).is_ok() { + self.context.request_repaint(); + } + } +} + +impl AutosaveNotice { + pub(crate) fn reporter(&self, context: &egui::Context) -> Reporter { + Reporter { sender: self.sender.clone(), context: context.clone() } + } +} + +/// Take in finished autosaves. A failure is announced once, however often it repeats. +pub(crate) fn poll(app: &mut TextureCraftApp) { + while let Ok(Outcome { path, result }) = app.autosave_notice.receiver.try_recv() { + let message = result.err().map(|error| trf("Autosave to {path} failed: {error}", &[("path", &path.display()), ("error", &error)])); + if message == app.autosave_notice.shown { + continue; + } + + if let Some(old) = app.autosave_notice.shown.take() { + app.toasts.retain(|toast| toast.text != old); + } + + if let Some(message) = &message { + app.session.log.error("Autosave", message.clone()); + app.toast_sticky(message.clone()); + } + + app.autosave_notice.shown = message; + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 401581e8..313cca82 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -10,6 +10,8 @@ mod anchor_properties; mod angle_dial; mod ask; +#[cfg(not(target_arch = "wasm32"))] +mod autosave_notice; mod bake_job; pub mod bake_mode; mod bake_preset; @@ -357,6 +359,8 @@ pub struct TextureCraftApp { /// When the next autosave is due (seconds of app time; desktop only). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] next_autosave: f64, + #[cfg(not(target_arch = "wasm32"))] + autosave_notice: autosave_notice::AutosaveNotice, /// The brightness and accent the style was last built for. styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. @@ -493,6 +497,8 @@ impl TextureCraftApp { fired_clipboard: Vec::new(), last_time: 0.0, next_autosave, + #[cfg(not(target_arch = "wasm32"))] + autosave_notice: Default::default(), styled: None, focused: true, #[cfg(not(target_arch = "wasm32"))] @@ -1033,7 +1039,7 @@ impl TextureCraftApp { /// Every `prefs.autosave_minutes`, write a modified project to the autosave folder (encoded /// and written on a worker thread; the project data is shared copy-on-write). #[cfg(not(target_arch = "wasm32"))] - fn autosave(&mut self, now: f64) { + fn autosave(&mut self, ctx: &egui::Context, now: f64) { let period = autosave_period_seconds(self.ui.prefs.autosave_minutes); // The clock starts at the first unsaved change @@ -1058,19 +1064,19 @@ impl TextureCraftApp { texturecraft_engine::core::PROJECT_EXT )); let snapshot = self.session.project_snapshot(); + let reporter = self.autosave_notice.reporter(ctx); + let spawn_reporter = self.autosave_notice.reporter(ctx); + let target = path.clone(); let spawned = std::thread::Builder::new().name("texturecraft-autosave".into()).spawn(move || { let result = std::fs::create_dir_all(&dir).map_err(|e| e.to_string()).and_then(|_| reservation.save(&path, &snapshot).map_err(|error| error.to_string())); drop(snapshot); drop(reservation); - match result { - Ok(()) => log::info!("autosaved {}", path.display()), - Err(e) => log::warn!("autosave to {} failed: {e}", path.display()), - } + reporter.report(path, result); }); if let Err(e) = spawned { - log::warn!("could not start autosave: {e}"); + spawn_reporter.report(target, Err(e.to_string())); } } } @@ -1213,7 +1219,9 @@ impl eframe::App for TextureCraftApp { ctx.set_zoom_factor(scale); } #[cfg(not(target_arch = "wasm32"))] - self.autosave(now); + self.autosave(ctx, now); + #[cfg(not(target_arch = "wasm32"))] + autosave_notice::poll(self); i18n::set_language(&self.ui.prefs.language); #[cfg(target_arch = "wasm32")] { diff --git a/crates/ui-egui/tests/autosave_notice.rs b/crates/ui-egui/tests/autosave_notice.rs new file mode 100644 index 00000000..d5786734 --- /dev/null +++ b/crates/ui-egui/tests/autosave_notice.rs @@ -0,0 +1,46 @@ +//! A failed autosave is announced in the interface. This is its own test binary because the data +//! folder it breaks is fixed once for the whole process. + +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; + +fn notices(harness: &Harness<'_, TextureCraftApp>) -> usize { + harness.state().toasts.iter().filter(|toast| toast.text.contains("autosave-notice")).count() +} + +/// Run frames until `done`, giving the autosave worker real time to finish. +fn run_until(harness: &mut Harness<'_, TextureCraftApp>, done: impl Fn(&Harness<'_, TextureCraftApp>) -> bool) { + let started = Instant::now(); + while !done(harness) { + assert!(started.elapsed() < Duration::from_secs(60), "the autosave did not report"); + harness.step(); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +fn a_failing_autosave_is_announced_once_until_it_works_again() { + let root = std::env::temp_dir().join(format!("tc-autosave-notice-{}", std::process::id())); + // A file where the data folder should be, so the autosave folder cannot be created + std::fs::write(&root, b"not a folder").unwrap(); + texturecraft_ui_egui::set_data_root(root.clone()); + + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + // Each frame is longer than the shortest autosave period, so every frame is due + let mut harness = Harness::builder().with_step_dt(61.0).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.autosave_minutes = 1; + harness.state_mut().session.modified = true; + + run_until(&mut harness, |harness| notices(harness) > 0); + for _ in 0..20 { + harness.step(); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(notices(&harness), 1, "the same failure is not announced again"); + + std::fs::remove_file(&root).unwrap(); + run_until(&mut harness, |harness| notices(harness) == 0); + let _ = std::fs::remove_dir_all(&root); +} From d9b1d58d6c0040ceb9ac4c5fe344822de7f64104 Mon Sep 17 00:00:00 2001 From: Morion Date: Thu, 26 Nov 2026 12:16:22 -0500 Subject: [PATCH 07/14] Report an autosave before releasing its reservation, and fix its notice test A later autosave could start once the reservation was dropped and report first, so an earlier success then cleared its failure. The test now installs the headless runtime the framework needs, counts only the autosave's own notice, and reads it in English. --- crates/ui-egui/src/lib.rs | 3 ++- crates/ui-egui/tests/autosave_notice.rs | 12 ++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3ffaaffe..f2cda0c4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1074,9 +1074,10 @@ impl TextureCraftApp { let result = std::fs::create_dir_all(&dir).map_err(|e| e.to_string()).and_then(|_| reservation.save(&path, &snapshot).map_err(|error| error.to_string())); drop(snapshot); - drop(reservation); + // Report while the reservation still holds off the next autosave, so results arrive in the order of the attempts reporter.report(path, result); + drop(reservation); }); if let Err(e) = spawned { spawn_reporter.report(target, Err(e.to_string())); diff --git a/crates/ui-egui/tests/autosave_notice.rs b/crates/ui-egui/tests/autosave_notice.rs index d5786734..703c13e9 100644 --- a/crates/ui-egui/tests/autosave_notice.rs +++ b/crates/ui-egui/tests/autosave_notice.rs @@ -7,7 +7,8 @@ use egui_kittest::Harness; use texturecraft_ui_egui::TextureCraftApp; fn notices(harness: &Harness<'_, TextureCraftApp>) -> usize { - harness.state().toasts.iter().filter(|toast| toast.text.contains("autosave-notice")).count() + // Other loaders name the broken data folder too: only the autosave's own notice counts + harness.state().toasts.iter().filter(|toast| toast.text.starts_with("Autosave to ") && toast.text.contains("autosave-notice")).count() } /// Run frames until `done`, giving the autosave worker real time to finish. @@ -29,7 +30,14 @@ fn a_failing_autosave_is_announced_once_until_it_works_again() { let session = texturecraft_engine::sample_session(128, 32).unwrap(); // Each frame is longer than the shortest autosave period, so every frame is due - let mut harness = Harness::builder().with_step_dt(61.0).build_eframe(|context| TextureCraftApp::new(context, session)); + let mut harness = Harness::builder() + .with_step_dt(61.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + // The notice is matched by its English text, whatever the system's language + harness.state_mut().ui.prefs.language = "en".into(); + // One frame applies the language before any autosave reports + harness.step(); harness.state_mut().ui.prefs.autosave_minutes = 1; harness.state_mut().session.modified = true; From 0ec4775ef63ad89f6eccfc84947c2391eceefbf1 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:30:56 -0500 Subject: [PATCH 08/14] fix(path-cache): charge each snapshot for the tile buffers it alone keeps alive evict charged snapshot k for path k-1's tiles only, but snapshot k holds every pixel after k paths and shares tile handles with the others. After an older snapshot was evicted, a newer one could retain a whole older generation (full fill, one-tile stroke, full fill, one-tile stroke) and the 256 MiB cap was exceeded. Walk newest to oldest and charge only handles not already held by the live pixels, the edited snapshot or a kept newer snapshot. Also drop the debug_assert from non-test code. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/painting.rs | 2 - crates/engine/src/path_tool.rs | 103 +++++++++++++++++++++++++++------ 2 files changed, 84 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 3c90af84..dd0013b2 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -141,8 +141,6 @@ impl Session { let ts = self.ts(); let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024)); let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? }; - // PathCache reuses a path's tiles only if painting one tile reads no other. - debug_assert!(!(self.painting_paths && pickup.is_some()), "path repaints never pick up"); if pickup.is_some() { // Clone and smudge read the composite: bring it up to date first. self.update(); diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 6629c944..b73dd661 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -16,7 +16,7 @@ use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackgrou use texturecraft_geom::OrbitCamera; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; -use texturecraft_texel::{TILE_AREA, TileImage}; +use texturecraft_texel::TileImage; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; use crate::session::{StackTarget, Tool}; @@ -83,18 +83,48 @@ pub(crate) struct PathCache { tiles: Vec>, } +/// The identities of the tile buffers `snap` holds, added to `seen`; returns the bytes of those +/// not already there. +fn charge(snap: &Snap, seen: &mut BTreeSet) -> usize { + let mut bytes = 0; + for img in snap.values() { + for ty in 0..img.tiles_y() { + for tx in 0..img.tiles_x() { + if let Some(t) = img.tile_handle(tx, ty) + && seen.insert(Arc::as_ptr(t) as usize) + { + bytes += t.len() * 2; + } + } + } + } + bytes +} + /// Drop the snapshots past `budget` bytes, oldest first, so adding a path and editing recent /// ones stay cheap, but keep snapshot `edited` (below the path being edited, so its next live -/// repaint starts there). Snapshot k holds at most path k-1's tiles in each image; the first -/// (empty) and the last (the live pixels) cost nothing. -fn evict(snaps: &mut [Option], tiles: &[BTreeSet<(u32, u32)>], budget: usize, edited: usize) { +/// repaint starts there). Tiles are shared between snapshots and with the live pixels (the last +/// snapshot) and snapshot k holds every tile as it was after k paths, so each snapshot, newest +/// first, is charged for the tile buffers no live pixels, kept newer snapshot or `edited` already +/// hold: what freeing it would release at most. The first (empty) and the last cost nothing. +fn evict(snaps: &mut [Option], budget: usize, edited: usize) { + let mut seen = BTreeSet::new(); + for k in [snaps.len().saturating_sub(1), edited] { + if let Some(Some(snap)) = snaps.get(k) { + charge(snap, &mut seen); + } + } let mut bytes = 0; for k in (1..snaps.len().saturating_sub(1)).rev().filter(|&k| k != edited) { - if let Some(snap) = &snaps[k] { - bytes += tiles[k - 1].len() * snap.values().map(|i| TILE_AREA * i.comps() * 2).sum::(); - if bytes > budget { - snaps[k] = None; - } + let Some(Some(snap)) = snaps.get(k) else { continue }; + // Count into a copy: an evicted snapshot's tiles are not retained by it any more. + let mut with = seen.clone(); + let cost = charge(snap, &mut with); + if bytes + cost > budget { + snaps[k] = None; + } else { + bytes += cost; + seen = with; } } } @@ -479,7 +509,7 @@ impl Session { copy_tiles(&mut state, after, &c.tiles[o]); tiles.push(c.tiles[o].clone()); snaps.push(Some(state.clone())); - evict(&mut snaps, &tiles, CACHE_BYTES, prefix); + evict(&mut snaps, CACHE_BYTES, prefix); out.push(Value::Null); continue; } @@ -495,7 +525,7 @@ impl Session { state = self.take_snap(eid); tiles.push(std::mem::take(&mut self.path_tiles)); snaps.push(Some(state.clone())); - evict(&mut snaps, &tiles, CACHE_BYTES, prefix); + evict(&mut snaps, CACHE_BYTES, prefix); } self.put_snap(eid, &state); self.painting_paths = false; @@ -683,10 +713,15 @@ mod tests { fn snapshots_stay_within_the_budget() { let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, usize::MAX, 0); + super::evict(&mut c.snaps, usize::MAX, 0); assert_eq!(c.snaps.iter().flatten().count(), 4); - super::evict(&mut c.snaps, &c.tiles, 0, 0); - assert!(c.snaps[0].is_some() && c.snaps[3].is_some() && c.snaps[1..3].iter().all(Option::is_none), "only the free ones stay"); + // The paths are on different tiles, so keeping every snapshot costs nothing beyond the live + // pixels: even a zero budget keeps them. + super::evict(&mut c.snaps, 0, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels are free"); + // Drop them by hand to test the repaint from the bottom. + c.snaps[1] = None; + c.snaps[2] = None; // Appending still paints the new path alone. let shape = s.paths(eid).unwrap()[0].clone(); if let Some(texturecraft_core::Effect { kind: texturecraft_core::EffectKind::Path(v), .. }) = s.doc.project.effect_mut(eid) { @@ -696,13 +731,43 @@ mod tests { assert_eq!(r.iter().map(|x| !x.is_null()).collect::>(), [false, false, false, true]); // Editing above evicted snapshots repaints from the bottom and matches a full repaint. let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, 0, 0); + assert!(c.snaps[1].is_none() && c.snaps[2].is_none()); assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); - // That edit kept the snapshot below path 3 within a zero budget: its next frame starts there. + // That edit kept the snapshot below path 3 within a zero budget: its next frame starts + // there, and the snapshots above it that cost nothing keep their paths unrepainted. let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, 0, 2); - assert!(c.snaps[2].is_some() && c.snaps[1].is_none()); - assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, true], "path 4 lost its snapshot too"); + super::evict(&mut c.snaps, 0, 2); + assert!(c.snaps[2].is_some()); + assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, false], "only the edited path repaints"); + } + + /// `prev` with the tiles in `at` replaced by new handles (what painting a path does). + fn painted(prev: &super::Snap, at: &[(u32, u32)]) -> super::Snap { + let mut next = prev.clone(); + for img in next.values_mut() { + for &(x, y) in at { + img.set_tile(x, y, Some(std::sync::Arc::new(vec![1u16; texturecraft_texel::TILE_AREA * 4]))); + } + } + next + } + + #[test] + fn the_budget_counts_the_tiles_an_old_snapshot_keeps_alive() { + let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + // A full-texture fill, a one-tile stroke, another full fill, another one-tile stroke. + let s1 = painted(&empty, &all); + let s2 = painted(&s1, &[(0, 0)]); + let s3 = painted(&s2, &all); + let s4 = painted(&s3, &[(0, 0)]); + let mut snaps = vec![Some(empty), Some(s1), Some(s2), Some(s3), Some(s4)]; + // Snapshot 3 is the edited one. Snapshot 2 alone holds 15 tiles of the first fill that + // neither the live image nor snapshot 3 has: that is over a budget of 8 tiles. + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + super::evict(&mut snaps, 8 * tile_bytes, 3); + assert!(snaps[3].is_some(), "the edited snapshot stays"); + assert!(snaps[2].is_none(), "snapshot 2 keeps the first fill alive, over the budget"); } #[test] From 14f02e5fe79d333f9d115ee3dc0c90c0ba633206 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:17:44 -0500 Subject: [PATCH 09/14] test(path-cache): a snapshot is charged only for tiles no kept snapshot shares Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/path_tool.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index b73dd661..bd4c9715 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -770,6 +770,33 @@ mod tests { assert!(snaps[2].is_none(), "snapshot 2 keeps the first fill alive, over the budget"); } + #[test] + fn a_snapshot_is_charged_only_for_what_no_kept_snapshot_shares() { + let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + // Two full fills then a one-tile stroke (the live pixels). Snapshot 2 shares 15 tiles with + // the live pixels and owns one; snapshot 1 owns the whole first fill: 16 tiles. + let s1 = painted(&empty, &all); + let s2 = painted(&s1, &all); + let s3 = painted(&s2, &[(0, 0)]); + let fresh = || vec![Some(empty.clone()), Some(s1.clone()), Some(s2.clone()), Some(s3.clone())]; + let kept = |snaps: &[Option]| snaps.iter().map(Option::is_some).collect::>(); + let mut snaps = fresh(); + super::evict(&mut snaps, usize::MAX, 0); + assert_eq!(kept(&snaps), [true; 4]); + let mut snaps = fresh(); + super::evict(&mut snaps, tile_bytes, 0); + assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile, snapshot 1 sixteen"); + let mut snaps = fresh(); + super::evict(&mut snaps, 0, 0); + assert_eq!(kept(&snaps), [true, false, false, true], "snapshot 2 owns one tile, over a zero budget"); + // Keeping snapshot 1 (edited) makes snapshot 2 free of the tiles they share, not of its own. + let mut snaps = fresh(); + super::evict(&mut snaps, 0, 1); + assert_eq!(kept(&snaps), [true, true, false, true]); + } + #[test] fn the_quick_mask_does_not_clip_paths() { let (mut s, eid) = with_paths(&[0.2, 0.8]); From 589eb4c76432db8b350ec4c8e8c56f0f956833e8 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:29:26 -0500 Subject: [PATCH 10/14] test(path-cache): a filled path above an edit keeps its tiles from the cache Covers the footprint recorded by commit_fill; emptying it left every other test green. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/path_tool.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index bd4c9715..785c779d 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -683,6 +683,15 @@ mod tests { assert_eq!(edit_row(&mut s, eid, 0, 0.79), [true, false, true], "a path over the change repaints"); } + #[test] + fn a_filled_path_above_an_edit_keeps_its_tiles() { + // The stroke at row 0.2 is edited; the closed, filled path above it lies in other tiles. + let (mut s, eid) = with_paths(&[0.2]); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.7], [0.5, 0.7], [0.5, 0.9], [0.1, 0.9]], "closed": true, "fill": true, "commit": true})) + .unwrap(); + assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false], "the fill above comes from the cache, with its pixels"); + } + #[test] fn removing_a_path_keeps_the_paths_above() { let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); From f28d4d8b6439208fa721536be0023853841ad3d4 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:30:56 -0500 Subject: [PATCH 11/14] fix(paths): count each snapshot's tile table against the path cache budget Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/path_tool.rs | 58 ++++++++++++++++++++++++++-------- crates/texel/src/tile.rs | 11 +++++++ 2 files changed, 56 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 5efc1215..15455941 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -173,11 +173,15 @@ pub(crate) struct PathCache { tiles: Vec>, } -/// The identities of the tile buffers `snap` holds, added to `seen`; returns the bytes of those -/// not already there. +/// The identities of the tile buffers and tile tables `snap` holds, added to `seen`; returns the +/// bytes of those not already there. A table (one pointer per tile slot) is shared by clones until +/// one writes, so a snapshot that diverged from the live image holds its own. fn charge(snap: &Snap, seen: &mut BTreeSet) -> usize { let mut bytes = 0; for img in snap.values() { + if seen.insert(img.table_id()) { + bytes += img.table_bytes(); + } for ty in 0..img.tiles_y() { for tx in 0..img.tiles_x() { if let Some(t) = img.tile_handle(tx, ty) @@ -239,7 +243,9 @@ impl EvictPacer { /// A snapshot was appended after a path that painted `tiles` tile positions of `state`'s images. fn appended(&mut self, snaps: &mut [Option], edited: usize, state: &Snap, tiles: usize) { let tile_bytes: usize = state.values().map(|image| texturecraft_texel::TILE_AREA * image.comps() * 2).sum(); - self.held = self.held.saturating_add(tiles.saturating_mul(tile_bytes)); + // The new snapshot may also own a table per image (a write after the clone copies it). + let table_bytes: usize = state.values().map(TileImage::table_bytes).sum(); + self.held = self.held.saturating_add(tiles.saturating_mul(tile_bytes)).saturating_add(table_bytes); if self.held > CACHE_BYTES { self.held = evict(snaps, CACHE_BYTES, edited); } @@ -1475,10 +1481,11 @@ mod tests { let c = s.path_cache.as_mut().unwrap(); super::evict(&mut c.snaps, usize::MAX, 0); assert_eq!(c.snaps.iter().flatten().count(), 4); - // The paths are on different tiles, so keeping every snapshot costs nothing beyond the live - // pixels: even a zero budget keeps them. - super::evict(&mut c.snaps, 0, 0); - assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels are free"); + // The paths are on different tiles, so a snapshot costs nothing beyond its own tile table + // (the tiles are all shared with the live pixels): a budget of two tables keeps them. + let table: usize = c.snaps[1].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum(); + super::evict(&mut c.snaps, 2 * table, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels cost only their tables"); // Drop them by hand to test the repaint from the bottom. c.snaps[1] = None; c.snaps[2] = None; @@ -1493,10 +1500,11 @@ mod tests { let c = s.path_cache.as_mut().unwrap(); assert!(c.snaps[1].is_none() && c.snaps[2].is_none()); assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); - // That edit kept the snapshot below path 3 within a zero budget: its next frame starts - // there, and the snapshots above it that cost nothing keep their paths unrepainted. + // That edit kept the snapshot below path 3 within a one-table budget: its next frame starts + // there, and the snapshots above it that cost only a table keep their paths unrepainted. let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, 0, 2); + let table: usize = c.snaps[2].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum(); + super::evict(&mut c.snaps, table, 2); assert!(c.snaps[2].is_some()); assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, false], "only the edited path repaints"); } @@ -1533,6 +1541,7 @@ mod tests { #[test] fn appending_paths_scans_the_snapshots_only_when_the_budget_may_be_passed() { let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; let mut snaps = vec![Some(empty.clone()), Some(painted(&empty, &[(0, 0)]))]; let mut pacer = super::EvictPacer::start(&mut snaps, 0); @@ -1540,7 +1549,7 @@ mod tests { // A few small paths add up to an estimate without a scan (a scan would reset it to the exact 0). for n in 1..=3 { pacer.appended(&mut snaps, 0, &empty, 1); - assert_eq!(pacer.held, n * tile_bytes, "after {n} paths"); + assert_eq!(pacer.held, n * (tile_bytes + table), "after {n} paths"); } // Past the budget the estimate gives way to an exact scan. pacer.appended(&mut snaps, 0, &empty, super::CACHE_BYTES / tile_bytes + 1); @@ -1552,6 +1561,7 @@ mod tests { let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); // Two full fills then a one-tile stroke (the live pixels). Snapshot 2 shares 15 tiles with // the live pixels and owns one; snapshot 1 owns the whole first fill: 16 tiles. let s1 = painted(&empty, &all); @@ -1563,8 +1573,8 @@ mod tests { super::evict(&mut snaps, usize::MAX, 0); assert_eq!(kept(&snaps), [true; 4]); let mut snaps = fresh(); - super::evict(&mut snaps, tile_bytes, 0); - assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile, snapshot 1 sixteen"); + super::evict(&mut snaps, tile_bytes + table, 0); + assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile and a table, snapshot 1 sixteen"); let mut snaps = fresh(); super::evict(&mut snaps, 0, 0); assert_eq!(kept(&snaps), [true, false, false, true], "snapshot 2 owns one tile, over a zero budget"); @@ -1574,6 +1584,28 @@ mod tests { assert_eq!(kept(&snaps), [true, true, false, true]); } + #[test] + fn the_tile_table_of_a_diverged_snapshot_counts_once_against_the_budget() { + // Big image: the table (one slot per tile position) outweighs a one-tile stroke. + let empty: super::Snap = [(Some(texturecraft_core::Channel::Roughness), texturecraft_texel::TileImage::new(8192, 8192, 4))].into(); + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); + assert!(table >= 128 * 128 * 8, "table {table}"); + let s1 = painted(&empty, &[(0, 0)]); + let s2 = painted(&s1, &[(1, 0)]); + let s3 = painted(&s2, &[(2, 0)]); + let live = painted(&s3, &[(3, 0)]); + let mut seen = std::collections::BTreeSet::new(); + // Alone, a diverged snapshot holds its own table; charged again with the same table, it is free. + let first = super::charge(&s2, &mut seen); + assert!(first >= table, "charged {first}"); + assert_eq!(super::charge(&s2, &mut seen), 0); + // Tiles alone (8 KiB each) would fit this budget; with tables only one snapshot does. + let tile_only = texturecraft_texel::TILE_AREA * 4 * 2; + let mut snaps = vec![Some(empty.clone()), Some(s1), Some(s2), Some(s3), Some(live)]; + super::evict(&mut snaps, 3 * tile_only, 0); + assert!(snaps.iter().filter(|s| s.is_some()).count() < 5, "tables must evict snapshots"); + } + #[test] fn the_quick_mask_does_not_clip_paths() { let (mut s, eid) = with_paths(&[0.2, 0.8]); diff --git a/crates/texel/src/tile.rs b/crates/texel/src/tile.rs index 31e30349..81c96ac7 100644 --- a/crates/texel/src/tile.rs +++ b/crates/texel/src/tile.rs @@ -62,6 +62,17 @@ impl TileImage { self.tile_index(tx, ty).and_then(|i| self.tiles.get(i)).and_then(Option::as_ref) } + /// Identity of the shared tile table: clones share it until one of them writes, so two images + /// with the same id hold one allocation (for memory accounting). + pub fn table_id(&self) -> usize { + Arc::as_ptr(&self.tiles) as usize + } + + /// Bytes of the tile table itself (one slot per tile position), not counting the tiles. + pub fn table_bytes(&self) -> usize { + self.tiles.len().saturating_mul(std::mem::size_of::>()) + } + /// Replace a tile wholesale (None frees it). pub fn set_tile(&mut self, tx: u32, ty: u32, data: Option) { let len = TILE_AREA * self.comps; From 95345879f01c44e19fc1b42c37a8d59a076b0c23 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:47:34 +0000 Subject: [PATCH 12/14] Properties: slider tracks stay put when a value gains a sign or digits The value column was as wide as the widest number on show, so dragging a slider below zero moved every track in the panel. It now reserves the widest value each track can reach, up to a cap so a huge range keeps its tracks, and never narrows while the pointer is held. --- .../ui-egui/src/property_sheet/axis_rows.rs | 8 +- .../src/property_sheet/factor_slider.rs | 13 ++- crates/ui-egui/src/property_sheet/mod.rs | 3 + .../src/property_sheet/property_sheet.rs | 45 ++++++++- crates/ui-egui/src/property_sheet/slider.rs | 18 +++- .../src/property_sheet/stacked_rows.rs | 6 +- crates/ui-egui/src/property_sheet/tests.rs | 91 +++++++++++++++++++ 7 files changed, 170 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index c74a956a..7edf54b9 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -5,7 +5,7 @@ use std::ops::RangeInclusive; use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::row::SECTION_CAPTION_CENTER; -use super::slider::{DIAL_AIR, DIAL_RADIUS, KNOB_RADIUS}; +use super::slider::{DIAL_AIR, DIAL_RADIUS, KNOB_RADIUS, shown_value}; use super::switch_control::PILL_SIZE; use super::track::Track; use super::{BLOCK_MARGIN, PropertySheet, SMALL_TEXT_SIZE, StackSlider, TEXT_SIZE}; @@ -168,7 +168,11 @@ impl PropertySheet<'_> { } let dragged = self.track(id, slider.label, &track, slider.value, &slider.range); - let typed = self.value_field(id, slider.label, center_y, *slider.value, &slider.typed, slider.decimals, slider.suffix); + + // The column fits what the track reaches; a typed value past it widens the column while it is on show + self.measure_track_values(&slider.range, |end| shown_value(end, slider.decimals, slider.suffix)); + let shown = shown_value(*slider.value, slider.decimals, slider.suffix); + let typed = self.column_value_field(id, &slider.label, center_y, &shown, slider.suffix, *slider.value, &slider.typed, slider.decimals); *edit = Self::apply_typed(slider.value, typed, dragged); y += STACK_CAPTION_LINE + STACK_PART_LINE + STACK_GAP; } diff --git a/crates/ui-egui/src/property_sheet/factor_slider.rs b/crates/ui-egui/src/property_sheet/factor_slider.rs index eddf9f72..d789e802 100644 --- a/crates/ui-egui/src/property_sheet/factor_slider.rs +++ b/crates/ui-egui/src/property_sheet/factor_slider.rs @@ -6,20 +6,29 @@ use super::PropertySheet; use super::slider::{KNOB_RADIUS, kept_in}; use super::track::Track; +/// Decimals a factor reads with +const FACTOR_DECIMALS: usize = 2; + impl PropertySheet<'_> { /// A factor (×1.50) on a track `doublings` halvings or doublings each way from ×1 (marked by the zero tick); a typed value may go past the track's ends, within `typed`. `Some(merge)` when it changed pub(crate) fn factor_slider(&mut self, label: &str, factor: &mut f32, doublings: f32, typed: RangeInclusive) -> Option { let (control, center_y) = self.row(label); let id = self.next_id(); + let track = Track { start: control.left() + KNOB_RADIUS, end: self.track_end(), center_y, zero: Some(0.0), ramp: false }; let track_range = -doublings..=doublings; let mut along = kept_in(factor.max(f32::MIN_POSITIVE).log2(), &track_range); + let dragged = self.track(id, label, &track, &mut along, &track_range); if dragged.is_some() { *factor = along.exp2(); } - let shown = format!("×{:.2}", *factor); - let entered = self.column_value_field(id, &label, center_y, &shown, "", *factor, &typed, 2); + + let show = |factor: f32| format!("×{factor:.FACTOR_DECIMALS$}"); + self.measure_track_values(&track_range, |end| show(end.exp2())); + let shown = show(*factor); + + let entered = self.column_value_field(id, &label, center_y, &shown, "", *factor, &typed, FACTOR_DECIMALS); Self::apply_typed(factor, entered, dragged) } } diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 3a0b341d..6184cbb4 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -122,6 +122,9 @@ const LOOSE_LABEL_AIR: f32 = 2.0; /// The narrowest value column at a slider's right end const VALUE_MIN_WIDTH: f32 = 26.0; +/// The most the value column reserves for values not on show yet, so a huge range leaves the tracks their length +const TRACK_VALUE_RESERVE_MAX: f32 = 72.0; + /// Air between a slider track's end and the value column, room for the knob and a gap const TRACK_TO_VALUE: f32 = 14.0; diff --git a/crates/ui-egui/src/property_sheet/property_sheet.rs b/crates/ui-egui/src/property_sheet/property_sheet.rs index e1e5b1b6..61b0649c 100644 --- a/crates/ui-egui/src/property_sheet/property_sheet.rs +++ b/crates/ui-egui/src/property_sheet/property_sheet.rs @@ -1,8 +1,10 @@ +use std::ops::RangeInclusive; + use egui::{Color32, FontId, Id, Rect, Ui, pos2, vec2}; use super::{ - CONTROL_HEIGHT, LABEL_COLUMN_MIN, LABEL_TO_CONTROL, SIDE_PADDING_POINTS, TEXT_SIZE, TRACK_TO_VALUE, VALUE_MIN_WIDTH, open_card::OpenCard, section_tabs, - sheet_measure::SheetMeasure, + CONTROL_HEIGHT, LABEL_COLUMN_MIN, LABEL_TO_CONTROL, SIDE_PADDING_POINTS, TEXT_SIZE, TRACK_TO_VALUE, TRACK_VALUE_RESERVE_MAX, VALUE_MIN_WIDTH, + open_card::OpenCard, section_tabs, sheet_measure::SheetMeasure, }; use crate::theme::{Tokens, semibold}; @@ -29,6 +31,9 @@ pub(crate) struct PropertySheet<'u> { pub(super) held: bool, /// Sub-headers so far in the current folding section: a later one takes air above it pub(super) sub_headers: usize, + + /// The value font's widest digit, found on first use + pub(super) widest_digit: Option, } impl<'u> PropertySheet<'u> { @@ -36,8 +41,10 @@ impl<'u> PropertySheet<'u> { pub(crate) fn show(ui: &'u mut Ui, id_salt: impl egui::AsIdSalt, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { let id = ui.make_persistent_id(id_salt); let used = ui.memory_mut(|memory| memory.caches.cache::().get(&id).copied()).unwrap_or_default(); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); let rect = ui.available_rect_before_wrap(); + let mut sheet = PropertySheet { tokens: Tokens::get(ui.ctx()), id, @@ -56,8 +63,10 @@ impl<'u> PropertySheet<'u> { info: None, held: false, sub_headers: 0, + widest_digit: None, ui, }; + let result = body(&mut sheet); sheet.close_card(); if !sheet.sections.is_empty() { @@ -66,7 +75,13 @@ impl<'u> PropertySheet<'u> { } // Refresh visible sheets so measurements of closed sheets expire - let seen = sheet.seen; + let mut seen = sheet.seen; + + // A held pointer may be dragging a track: the value column only narrows once it is released + if sheet.ui.input(|input| input.pointer.any_down()) { + seen.value_width = seen.value_width.max(used.value_width); + } + sheet.ui.memory_mut(|memory| memory.caches.cache::().set(id, seen)); if seen != used { sheet.ui.ctx().request_discard("Properties columns changed"); @@ -91,6 +106,30 @@ impl<'u> PropertySheet<'u> { self.seen.value_width = self.seen.value_width.max(width); } + /// Widens the value column for the widest value a track over `range` can read, as `show` writes it, so a drag moves no track + pub(super) fn measure_track_values(&mut self, range: &RangeInclusive, show: impl Fn(f32) -> String) { + let widest_digit = self.widest_digit(); + for end in [*range.start(), *range.end()] { + let shown: String = show(end).chars().map(|character| if character.is_ascii_digit() { widest_digit } else { character }).collect(); + let width = self.text_width(&shown, semibold(TEXT_SIZE)).min(TRACK_VALUE_RESERVE_MAX); + self.seen.value_width = self.seen.value_width.max(width); + } + } + + /// Digits differ in width, so a value between a track's ends can be wider than either end + fn widest_digit(&mut self) -> char { + if let Some(digit) = self.widest_digit { + return digit; + } + + let widest = ('0'..='9') + .map(|digit| (digit, self.text_width(&digit.to_string(), semibold(TEXT_SIZE)))) + .max_by(|one, other| one.1.total_cmp(&other.1)) + .map_or('0', |(digit, _)| digit); + self.widest_digit = Some(widest); + widest + } + pub(super) fn text_width(&self, text: &str, font: FontId) -> f32 { self.ui.painter().layout_no_wrap(text.to_owned(), font, Color32::WHITE).size().x } diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 3697880b..a68ddcab 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -130,7 +130,9 @@ impl PropertySheet<'_> { self.paint_dial(pos2(dial_x, center_y), *degrees); - let shown = if plus { format!("{:+.0}°", *degrees) } else { format!("{:.0}°", *degrees) }; + let show = |angle: f32| if plus { format!("{angle:+.0}°") } else { format!("{angle:.0}°") }; + self.measure_track_values(&range, show); + let shown = show(*degrees); let typed = self.column_value_field(id, &name, center_y, &shown, "°", *degrees, &range, 0); Self::apply_typed(degrees, typed, dragged) } @@ -255,7 +257,7 @@ impl PropertySheet<'_> { edit } - /// The value at the row's end, answering as `label`'s value; a click turns it into a field, which returns the typed value when done + /// The value at the row's end of a track over `range`, answering as `label`'s value; a click turns it into a field, which returns the typed value when done #[allow(clippy::too_many_arguments)] pub(super) fn value_field( &mut self, @@ -267,11 +269,12 @@ impl PropertySheet<'_> { decimals: usize, suffix: &str, ) -> Option { - let shown = format!("{}{suffix}", shown_number(value, decimals)); + self.measure_track_values(range, |end| shown_value(end, decimals, suffix)); + let shown = shown_value(value, decimals, suffix); self.column_value_field(id, &label, center_y, &shown, suffix, value, range, decimals) } - /// [`Self::value_field`] reading `shown`: the panel's value column grows to fit it + /// [`Self::value_field`] reading `shown`: the panel's value column grows to fit it. A caller with a track measures its range first #[allow(clippy::too_many_arguments)] pub(super) fn column_value_field( &mut self, @@ -303,7 +306,7 @@ impl PropertySheet<'_> { decimals: usize, suffix: &str, ) -> Option { - let shown = format!("{}{suffix}", shown_number(value, decimals)); + let shown = shown_value(value, decimals, suffix); self.value_text_field(id, ValueText { label: &label, right, width, center_y, shown: &shown, suffix }, value, range, decimals) } @@ -363,3 +366,8 @@ impl PropertySheet<'_> { pub(super) fn kept_in(value: f32, range: &RangeInclusive) -> f32 { value.max(*range.start()).min(*range.end()) } + +/// `value` as a slider's end reads it +pub(super) fn shown_value(value: f32, decimals: usize, suffix: &str) -> String { + format!("{}{suffix}", shown_number(value, decimals)) +} diff --git a/crates/ui-egui/src/property_sheet/stacked_rows.rs b/crates/ui-egui/src/property_sheet/stacked_rows.rs index d7934290..6b961630 100644 --- a/crates/ui-egui/src/property_sheet/stacked_rows.rs +++ b/crates/ui-egui/src/property_sheet/stacked_rows.rs @@ -187,13 +187,14 @@ impl PropertySheet<'_> { info: None, held: self.held, sub_headers: self.sub_headers, + widest_digit: self.widest_digit, ui: &mut child, }; let result = body(&mut sheet); - let PropertySheet { named, seen, card, air_at, drawn_bottom, empty, sections, held, sub_headers, scope, band_scope, .. } = sheet; + let PropertySheet { named, seen, card, air_at, drawn_bottom, empty, sections, held, sub_headers, scope, band_scope, widest_digit, .. } = sheet; (self.named, self.seen, self.card, self.air_at, self.drawn_bottom, self.empty, self.sections) = (named, seen, card, air_at, drawn_bottom, empty, sections); - (self.held, self.sub_headers, self.scope, self.band_scope) = (held, sub_headers, scope, band_scope); + (self.held, self.sub_headers, self.scope, self.band_scope, self.widest_digit) = (held, sub_headers, scope, band_scope, widest_digit); let bottom = child.min_rect().bottom().max(top); let region = Rect::from_min_max(pos2(self.left, top), pos2(self.right, bottom)); @@ -305,6 +306,7 @@ impl PropertySheet<'_> { info: None, held: false, sub_headers: 0, + widest_digit: self.widest_digit, ui: &mut second_ui, }; let second_response = second_sheet.dropdown_button(second, &name(second_value), None::); diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 28b126c4..917449ed 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -1017,6 +1017,97 @@ fn a_ramps_value_ends_on_the_linked_tiling_value() { assert_eq!(ramp.right(), tiling.right(), "the ramp's value ends at {}, Tiling's at {}", ramp.right(), tiling.right()); } +/// The row types whose values share a panel's value column +#[derive(Clone, Copy, Debug)] +enum ValueRow { + Signed, + Angle, + Factor, + Captioned, + Unbounded, +} + +/// One row on a sheet of its own, so no other row's value holds the column open +fn value_row(ui: &mut egui::Ui, (row, value): &mut (ValueRow, f32)) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "value row", |sheet| match row { + ValueRow::Signed => { + sheet.signed_slider("Value", value, -1.0..=1.0, 2); + } + ValueRow::Angle => { + sheet.relative_angle("Value", value, -180.0..=180.0); + } + ValueRow::Factor => { + sheet.factor_slider("Value", value, 4.0, 0.0..=2000.0); + } + ValueRow::Captioned => { + sheet.picture_sliders(&swatch(Color32::from_gray(128)), &mut [super::StackSlider::whole("Value", value, -1000.0..=1000.0)]); + } + ValueRow::Unbounded => { + sheet.slider("Value", value, 0.0..=f32::MAX, 2); + } + }); + }); +} + +fn value_row_track(harness: &Harness<'_, (ValueRow, f32)>) -> Rect { + harness.get_by_role_and_label(egui::Role::Slider, "Value").rect() +} + +/// A value gaining a minus sign or digits moves no track (the value column followed the widest number on show) +#[test] +fn tracks_stay_put_as_their_values_gain_a_sign_and_digits() { + let rows = [ + (ValueRow::Signed, [0.0, -0.88, 0.88, -1.0]), + (ValueRow::Angle, [0.0, -88.0, 88.0, -180.0]), + (ValueRow::Factor, [1.0, 16.0, 0.1, 8.0]), + (ValueRow::Captioned, [0.0, -888.0, 888.0, -1000.0]), + ]; + for (row, [first, rest @ ..]) in rows { + let mut harness = builder(Brightness::MediumDark).build_ui_state(value_row, (row, first)); + harness.run_steps(3); + let before = value_row_track(&harness); + + for value in rest { + harness.state_mut().1 = value; + harness.run_steps(3); + assert_eq!(value_row_track(&harness), before, "the {row:?} track moved at {value}"); + } + } +} + +/// A range far past anything readable reserves only so much, and its track still ends in the panel's right half +#[test] +fn a_huge_range_leaves_its_track_its_length() { + let mut harness = builder(Brightness::MediumDark).build_ui_state(value_row, (ValueRow::Unbounded, 1.0)); + harness.run_steps(3); + + // The end, not the width: a squeezed track turns inside out and still reads as wide + let track = value_row_track(&harness); + assert!(track.right() > PANEL_WIDTH / 2.0, "the track ends at {}", track.right()); +} + +/// Dragging back from a value past the track's ends narrows the column only once the drag ends +#[test] +fn a_drag_from_a_typed_value_moves_no_track_until_release() { + let mut harness = builder(Brightness::MediumDark).build_ui_state(value_row, (ValueRow::Factor, 1000.0)); + harness.run_steps(3); + let before = value_row_track(&harness); + + harness.drag_at(before.center()); + + // Past egui's longest click, the press becomes a drag + harness.run_steps(5); + assert!(harness.state().1 < 1000.0, "the press moved no value"); + assert_eq!(value_row_track(&harness), before, "the track moved under the drag"); + + harness.drop_at(before.center()); + harness.run_steps(3); + assert!(value_row_track(&harness).right() > before.right(), "the column stayed wide after the release"); +} + #[test] fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() { let context = egui::Context::default(); From 29cc9738039c207aab8138c472c6d9d19cf9b559 Mon Sep 17 00:00:00 2001 From: Morion Date: Sun, 29 Nov 2026 11:57:38 -0500 Subject: [PATCH 13/14] Announce the autosave failure notice to screen readers --- crates/ui-egui/src/autosave_notice.rs | 5 +++++ crates/ui-egui/tests/autosave_notice.rs | 19 +++++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/autosave_notice.rs b/crates/ui-egui/src/autosave_notice.rs index cc37af56..5ca18157 100644 --- a/crates/ui-egui/src/autosave_notice.rs +++ b/crates/ui-egui/src/autosave_notice.rs @@ -68,6 +68,11 @@ pub(crate) fn poll(app: &mut TextureCraftApp) { if let Some(message) = &message { app.session.log.error("Autosave", message.clone()); app.toast_sticky(message.clone()); + + // The user's focus is elsewhere, so a screen reader hears the notice only as a live region + if let Some(toast) = app.toasts.last_mut() { + toast.announce = true; + } } app.autosave_notice.shown = message; diff --git a/crates/ui-egui/tests/autosave_notice.rs b/crates/ui-egui/tests/autosave_notice.rs index 703c13e9..5b735a38 100644 --- a/crates/ui-egui/tests/autosave_notice.rs +++ b/crates/ui-egui/tests/autosave_notice.rs @@ -1,11 +1,23 @@ //! A failed autosave is announced in the interface. This is its own test binary because the data //! folder it breaks is fixed once for the whole process. +use std::path::PathBuf; use std::time::{Duration, Instant}; +use egui::accesskit::Live; use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_ui_egui::TextureCraftApp; +/// Removes the test's folder, also when an assertion fails +struct TempFolder(PathBuf); + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + fn notices(harness: &Harness<'_, TextureCraftApp>) -> usize { // Other loaders name the broken data folder too: only the autosave's own notice counts harness.state().toasts.iter().filter(|toast| toast.text.starts_with("Autosave to ") && toast.text.contains("autosave-notice")).count() @@ -23,7 +35,9 @@ fn run_until(harness: &mut Harness<'_, TextureCraftApp>, done: impl Fn(&Harness< #[test] fn a_failing_autosave_is_announced_once_until_it_works_again() { - let root = std::env::temp_dir().join(format!("tc-autosave-notice-{}", std::process::id())); + let folder = TempFolder(std::env::temp_dir().join(format!("tc-autosave-notice-{}", std::process::id()))); + std::fs::create_dir_all(&folder.0).unwrap(); + let root = folder.0.join("data"); // A file where the data folder should be, so the autosave folder cannot be created std::fs::write(&root, b"not a folder").unwrap(); texturecraft_ui_egui::set_data_root(root.clone()); @@ -47,8 +61,9 @@ fn a_failing_autosave_is_announced_once_until_it_works_again() { std::thread::sleep(Duration::from_millis(10)); } assert_eq!(notices(&harness), 1, "the same failure is not announced again"); + let announced = harness.query_all_by_label_contains("Autosave to ").any(|node| node.accesskit_node().live() == Live::Polite); + assert!(announced, "the notice is a live region, so a screen reader reads it"); std::fs::remove_file(&root).unwrap(); run_until(&mut harness, |harness| notices(harness) == 0); - let _ = std::fs::remove_dir_all(&root); } From 5600be65561d9bc38cf6c0fe6df910c2cdbd346f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 13:48:49 -0500 Subject: [PATCH 14/14] Use craft-nightly for nightly profile self-isolation and security fence (#911) --- Cargo.lock | 9 + Cargo.toml | 2 + apps/texturecraft/Cargo.toml | 2 + apps/texturecraft/src/build_flavor.rs | 32 +- apps/texturecraft/src/launch_profile.rs | 255 +++------ apps/texturecraft/src/main.rs | 40 +- apps/texturecraft/src/profile_root.rs | 668 ++++++------------------ 7 files changed, 277 insertions(+), 731 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 01e17558..2c2a5d6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1324,6 +1324,14 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -5949,6 +5957,7 @@ dependencies = [ "craft-host", "craft-image-codecs", "craft-menu", + "craft-nightly", "craft-update", "eframe", "egui", diff --git a/Cargo.toml b/Cargo.toml index bb398c92..2a15ba96 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -89,6 +89,8 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # The theme mode the app hands the runtime (crates/ui-egui/src/framework.rs). craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +# Nightly profile isolation, launch protocol, and security fence (apps/texturecraft). +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/apps/texturecraft/Cargo.toml b/apps/texturecraft/Cargo.toml index ab29d036..c9be2510 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -25,6 +25,8 @@ log = { workspace = true } rfd = { workspace = true } # Pass the selected window backend to the title bar and UI runtime craft-host = { workspace = true } +# Nightly profile isolation, launch protocol, and security fence. +craft-nightly = { workspace = true } # Reads the saved System title bar setting before the window opens (eframe's settings format). ron = "0.12" diff --git a/apps/texturecraft/src/build_flavor.rs b/apps/texturecraft/src/build_flavor.rs index 294f1e19..9330b7d8 100644 --- a/apps/texturecraft/src/build_flavor.rs +++ b/apps/texturecraft/src/build_flavor.rs @@ -1,14 +1,9 @@ //! The build-time channel, which is distinct from a launch selector: no runtime environment can //! promote a stable build into the Nightly one. -use crate::launch_profile::Profile; use std::ffi::OsString; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BuildFlavor { - Stable, - NightlyV1, -} +pub use craft_nightly::BuildFlavor; /// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`). pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; @@ -17,15 +12,6 @@ pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor /// workspace version (`build.rs` bakes it so both flavors read it the same way). pub const BUILT_VERSION: &str = env!("TEXTURECRAFT_VERSION"); -/// A nightly build starts only with its profile, and a stable build only without one. -pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { - match (flavor, profile.is_nightly()) { - (BuildFlavor::NightlyV1, false) => Err("Open TextureCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable TextureCraft build; nightly-v1 requires the nightly build".into()), - _ => Ok(()), - } -} - /// A refused nightly start explains itself in a native dialog: a release Windows build has no /// console, and a Dock launch on macOS has none either. pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { @@ -58,22 +44,6 @@ mod tests { assert!(!needs_native_error(BuildFlavor::Stable, false)); } - #[test] - fn nightly_build_without_a_profile_is_refused_before_startup() { - let started = std::cell::Cell::new(false); - let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); - assert!(result.unwrap_err().contains("ArtCraft Launcher")); - assert!(!started.get()); - } - - #[test] - fn stable_and_nightly_flavors_accept_only_their_own_profile() { - let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); - assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); - assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); - assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); - } - #[test] fn the_nightly_version_line_is_exact_and_says_its_channel() { let nightly = version(BuildFlavor::NightlyV1); diff --git a/apps/texturecraft/src/launch_profile.rs b/apps/texturecraft/src/launch_profile.rs index 84f5061f..9e29c559 100644 --- a/apps/texturecraft/src/launch_profile.rs +++ b/apps/texturecraft/src/launch_profile.rs @@ -1,126 +1,30 @@ -//! The Launcher's nightly-v1 bootstrap, selected before logging, updates, fonts or saved state. -//! Stable launches keep their arguments and directory policy unchanged, and no environment is -//! mutated: the profile is a value this process reads, not a variable it exports. +//! The Launcher's nightly-v1 bootstrap and direct-launch self-isolation, backed by `craft-nightly`. +//! +//! Selected before logging, updates, fonts or saved state. Stable launches keep their arguments and +//! directory policy unchanged, and no environment is mutated: the profile is a value this process +//! reads, not a variable it exports. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; -pub const VERSION: &str = "nightly-v1"; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), -} - -impl Profile { - pub fn is_nightly(&self) -> bool { - matches!(self, Self::NightlyV1(_)) - } - - pub fn root(&self) -> Option<&Path> { - match self { - Self::Stable => None, - Self::NightlyV1(root) => Some(root), - } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub struct Launch { - pub profile: Profile, - pub args: Vec, -} - -static PROFILE: OnceLock = OnceLock::new(); +pub use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions}; pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().unwrap_or(&Profile::Stable) } -pub fn install(profile: Profile) -> Result<(), String> { - PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) -} - -/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is a -/// file, even when it looks like a profile flag. No filesystem or startup hook runs here. -pub fn parse(args: Vec) -> Result { - let mut selector = None; - let mut root = None; - let mut other = Vec::new(); - let mut files = Vec::new(); - let mut iter = args.iter(); - let mut delimiter = false; - while let Some(arg) = iter.next() { - if arg == "--" { - delimiter = true; - files.extend(iter.cloned()); - break; - } - if arg == "--launch-profile" || arg == "--profile-root" { - let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; - if slot.is_some() { - return Err("the profile selector and root must each occur exactly once".into()); - } - let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; - if value.to_string_lossy().starts_with("--") { - return Err("the profile selector/root needs a value".into()); - } - *slot = Some(value.clone()); - } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { - return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); - } else { - other.push(arg.clone()); - } - } - match (selector, root) { - (None, None) => Ok(Launch { profile: Profile::Stable, args }), - (Some(version), Some(root)) if version == VERSION => { - if !delimiter || !other.is_empty() { - return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); - } - let root = PathBuf::from(root); - if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { - return Err("the nightly profile root must be absolute and contain no parent traversal".into()); - } - Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) - } - (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), - _ => Err("--launch-profile and --profile-root must be supplied together".into()), - } -} - -/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), -/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never -/// validated or touched, and `-- --version` stays a file name. -pub fn version_query(args: &[OsString]) -> bool { - let Some((last, pair)) = args.split_last() else { return false }; - if last != "--version" && last != "-V" { - return false; - } - let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); - matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) -} - -/// Validation finishes before the caller's first startup effect. Stable never calls the nightly -/// root validator, so its old directory resolution stays unchanged. -pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { - if let Profile::NightlyV1(root) = &launch.profile { - launch.profile = Profile::NightlyV1(validate(root)?); - } - Ok(launch) -} - -/// Resolve the selected private root before the caller's first startup effect. -pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable) +/// Parse startup arguments for `flavor`, validate and prepare the isolated nightly profile root +/// (self-isolating into `craft_nightly::canonical_profile_root("texturecraft")` on direct nightly +/// launches, or using the explicit `--launch-profile nightly-v1 --profile-root ` pair), and +/// install the resolved [`Profile`] into the process-wide `OnceLock`. +pub fn prepare(flavor: BuildFlavor, args: Vec) -> Result { + let spec = crate::profile_root::spec(); + craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::new()) } #[cfg(test)] mod tests { use super::*; - use std::cell::Cell; + use std::path::PathBuf; fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() @@ -130,88 +34,93 @@ mod tests { if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) - } - #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { + fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() { + let spec = crate::profile_root::spec(); for argv in [args(&[]), args(&["model.glb"]), args(&["--gpu", "nvidia"]), args(&["--", "--launch-profile", "model.glb"])] { - let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); - assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + let launch = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); } + + let nightly_flags = args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]); + let err = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, nightly_flags, &StartupOptions::new()).unwrap_err(); + assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild)); } #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "model with spaces.glb"])); - let launch = parse(argv).unwrap(); + fn direct_nightly_launch_self_isolates_to_canonical_root_and_preserves_args() { + let spec = crate::profile_root::spec(); + let expected_root = craft_nightly::canonical_profile_root(crate::profile_root::APP_ID).expect("canonical profile root"); + let argv = args(&["model.glb", "--gpu", "nvidia"]); + + let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert!(launch.profile.is_nightly()); + assert_eq!(launch.passthrough_args, argv); + assert!(!launch.is_version_query()); + } + + #[test] + fn explicit_launcher_flags_override_canonical_root_and_preserve_files() { + let spec = crate::profile_root::spec(); + let argv = args(&[ + craft_nightly::LAUNCH_PROFILE_FLAG, + craft_nightly::NIGHTLY_V1_CONTRACT, + craft_nightly::PROFILE_ROOT_FLAG, + absolute(), + "--", + "--profile-root", + "model with spaces.glb", + ]); + + let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap(); assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "model with spaces.glb"])); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "model with spaces.glb"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + fn invalid_profile_arguments_are_refused() { + let spec = crate::profile_root::spec(); for argv in [ - args(&["--launch-profile", VERSION]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT]), args(&["--profile-root", absolute()]), args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root=/nightly-data/profiles/texturecraft", "--"]), + args(&[ + "--launch-profile", + craft_nightly::NIGHTLY_V1_CONTRACT, + "--launch-profile", + craft_nightly::NIGHTLY_V1_CONTRACT, + "--profile-root", + absolute(), + "--", + ]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]), + args(&["--gpu", "nvidia", "--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]), ] { - assert!(parse(argv.clone()).is_err(), "{argv:?}"); + assert!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).is_err(), "{argv:?}"); } } #[test] - fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { - let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; - let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + fn version_queries_are_recognized_plain_and_via_launcher() { + let spec = crate::profile_root::spec(); for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); - } - } - for argv in [ - args(&["--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), - args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), - args(&["--launch-profile", VERSION, "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), - ] { - assert!(!version_query(&argv), "{argv:?}"); - } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); - } + let plain = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap(); + assert!(plain.is_version_query(), "plain {flag}"); - #[test] - fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { - let reached = Cell::new(false); - let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); - assert!(result.is_err()); - assert!(!reached.get()); - } + let launcher = craft_nightly::parse_startup( + BuildFlavor::NightlyV1, + &spec, + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), flag]), + &StartupOptions::new(), + ) + .unwrap(); + assert!(launcher.is_version_query(), "launcher {flag}"); + } - #[test] - fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { - let checked = PathBuf::from(absolute()).join("checked"); - let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); - assert_eq!(launch.profile.root(), Some(checked.as_path())); - assert!(launch.profile.is_nightly()); + let file_named_version = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--", "--version"]), &StartupOptions::new()).unwrap(); + assert!(!file_named_version.is_version_query()); } } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 678c0a8c..0255487b 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -291,33 +291,31 @@ fn report_launch_profile_error(error: &str) { } } -/// Select the immutable launch profile before any startup service or side effect, and answer the -/// Launcher's version queries before root validation, logging, IPC or a window. `None` means the -/// launch is already answered and the process returns. +/// Select the immutable launch profile before any startup service or side effect, and answer +/// version queries before root validation, logging, IPC or a window. `None` means the launch is +/// already answered and the process returns. fn prepare_launch() -> Option> { let argv: Vec = std::env::args_os().skip(1).collect(); - // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --version`: both are answered here, with nothing but standard output written. - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + // Plain `--version` / `-V` is answered immediately with nothing but standard output written, + // even in a minimal environment without home/data variables. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); + return None; + } + let early = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + // Launcher's `--launch-profile nightly-v1 --profile-root --version`: `craft-nightly` + // skips root validation and profile installation for version queries. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() { use std::io::Write as _; let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); return None; } - let early = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - initialize_nightly_process_identity().map_err(|error| error.to_string())?; - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())) - }) - .unwrap_or_else(|error| { - report_launch_profile_error(&error); - std::process::exit(2) - }); let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }; - if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) { + if let Err(error) = initialize_nightly_process_identity().map_err(|error| error.to_string()).and_then(|()| os_window::select_identity(identity)) { report_launch_profile_error(&error); std::process::exit(2); } @@ -326,7 +324,7 @@ fn prepare_launch() -> Option> { texturecraft_ui_egui::set_data_root(root.clone()); texturecraft_ui_egui::os_window::set_display_version(build_flavor::BUILT_VERSION.to_owned()); } - Some(early.args) + Some(early.passthrough_args) } /// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value diff --git a/apps/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs index db10fdae..7ab39c60 100644 --- a/apps/texturecraft/src/profile_root.rs +++ b/apps/texturecraft/src/profile_root.rs @@ -1,567 +1,223 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! App-owned nightly profile specification backed by `craft-nightly`. //! -//! A Nightly profile has to hold *all* of its user state: eframe's `app.ron`/`ui.json`, the error -//! log, session logs, autosave copies, smart materials, layouts, templates, brush and export -//! presets. Anything that resolves to a stable folder would read and prune Stable's files, so the -//! root is refused when it overlaps one of them, when an entry inside it is an alias that leaves it, -//! or when it is not writable. +//! A Nightly profile holds *all* of its user state: eframe's `app.ron`/`ui.json`, the error log, +//! session logs, autosave copies, smart materials, layouts, templates, brush and export presets. +//! `craft-nightly` enforces the security fence, symlink/hardlink checks, `0o700` hardening, and +//! writability probe using the TextureCraft-specific boundaries declared here. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; +use std::path::PathBuf; -/// The folder names the launch checks use for this app in each platform's location. +use craft_nightly::AppProfileSpec; + +/// Canonical lowercase app identifier used for the default nightly profile path. +pub const APP_ID: &str = "texturecraft"; +/// Human-readable application name and stable folder name. const BRAND: &str = "TextureCraft"; -/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). -const STABLE_ID: &str = "ai.storyteller.texturecraft"; -/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). Inside that -/// sandbox `FLATPAK_ID` is always set, so this exact id is the one a Nightly native launch accepts. -const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; /// eframe lowercases its folder name on Linux (`file_storage.rs`), so Stable's real settings folder /// is `$XDG_DATA_HOME/texturecraft`, not the capitalised `TextureCraft` the app is called. const LINUX_STORAGE_BRAND: &str = "texturecraft"; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, -} - -impl Platform { - fn current() -> Result { - match std::env::consts::OS { - "windows" => Ok(Self::Windows), - "linux" => Ok(Self::Linux), - "macos" => Ok(Self::Mac), - _ => Err("nightly-v1 is not defined for this operating system".into()), - } - } - - fn ignores_case(self) -> bool { - self != Self::Linux - } -} - -fn absolute(path: PathBuf, label: &str) -> Result { - if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { - return Err(format!("{label} must be absolute and contain no parent traversal")); - } - Ok(path) -} - -fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { - let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; - absolute(PathBuf::from(value), key) -} - -fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { - match env(key).filter(|v| !v.is_empty()) { - Some(value) => absolute(PathBuf::from(value), key), - None => Ok(required_base(env, "HOME")?.join(fallback)), - } -} - -/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor -/// is not a missing directory that may be replaced or followed later. -fn canonical_future(path: &Path) -> Result { - let mut parent = path; - let mut missing = Vec::new(); - loop { - match std::fs::symlink_metadata(parent) { - Ok(_) => break, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string()); - parent = parent.parent().ok_or("the profile root has no existing ancestor")?; - } - Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), - } - } - let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; - for part in missing.into_iter().rev() { - resolved.push(part); - } - Ok(resolved) -} - -/// Whether one path is the other or contains it (in either direction), compared component by -/// component and folded the way the platform's filesystem folds names. `TextureCraft2` is not -/// inside `TextureCraft`. -fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { - let parts = |p: &Path| { - p.components() - .map(|c| { - let value = c.as_os_str().to_string_lossy().into_owned(); - if platform.ignores_case() { value.to_lowercase() } else { value } - }) - .collect::>() - }; - let (a, b) = (parts(a), parts(b)); - a.starts_with(&b) || b.starts_with(&a) -} - -/// The running install: never let the profile live inside it (it would be replaced or removed by -/// the next update). -fn installation_boundary(platform: Platform, exe: &Path) -> Result { - let parent = exe.parent().ok_or("cannot establish the installation boundary")?; - if platform == Platform::Mac { - // A profile in Resources is still inside the versioned bundle, not beside MacOS. - if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { - return Ok(bundle.to_path_buf()); - } - } - Ok(parent.to_path_buf()) -} - -/// The default data folder, `Documents/TextureCraft`, as the app's own resolver builds it -/// (`crate::data_folder("")`): `USERPROFILE` on Windows and `HOME` elsewhere, then `Documents`. -fn default_data_folder(platform: Platform, env: &impl Fn(&str) -> Option) -> Result { - let home = match platform { - Platform::Windows => required_base(env, "USERPROFILE")?, - _ => required_base(env, "HOME")?, - }; - Ok(home.join("Documents").join(BRAND)) -} - -fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { - let mut roots = match platform { - Platform::Windows => { - // eframe's settings folder (`%APPDATA%\TextureCraft`), its local counterpart, and the MSI's - // per-machine and any per-user install folders. A custom install folder is covered by the - // executable's own folder below. - let mut roots = ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join(BRAND))).collect::, _>>()?; - roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join(BRAND)); - for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { - if let Some(base) = env(key).filter(|v| !v.is_empty()) { - roots.push(absolute(PathBuf::from(base), key)?.join(BRAND)); - } - } - roots - } - Platform::Linux => { - // The four XDG roots carry eframe's settings, caches and state under the app's name. - let mut roots = - [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] - .into_iter() - .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join(BRAND))) - .collect::, _>>()?; - // eframe's own folder for this app on Linux, which is what holds Stable's `app.ron`, - // `ui.json` and `errors.log`: it folds the name, so it is the lowercase one. - roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(LINUX_STORAGE_BRAND)); - roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); - // The stable Flatpak keeps its own per-app data folder. - roots.push(required_base(env, "HOME")?.join(format!(".var/app/{STABLE_ID}"))); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; - let library = home.join("Library"); - vec![ - library.join("Application Support").join(BRAND), - library.join("Caches").join(BRAND), - library.join("Caches").join(STABLE_ID), - library.join("Preferences").join(BRAND), - library.join("Preferences").join(format!("{STABLE_ID}.plist")), - library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")), - home.join("Applications").join(format!("{BRAND}.app")), - PathBuf::from("/Applications").join(format!("{BRAND}.app")), - ] - } - }; - // The user's own documents folder is Stable's default data folder on every platform; a profile - // there would share autosaves, smart materials and presets with it. - roots.push(default_data_folder(platform, env)?); - roots.push(installation_boundary(platform, exe)?); - roots.into_iter().map(|p| canonical_future(&p)).collect() -} - -/// An entry inside the profile must resolve inside it, so a link planted there cannot point -/// Nightly's writes at another app's files. -fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { - let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let entry = chosen.join(name); - let metadata = std::fs::symlink_metadata(&entry).map_err(|e| format!("cannot inspect the nightly {label}: {e}"))?; - if !metadata.is_dir() { - return Err(format!("the nightly {label} must be a directory inside its selected profile")); - } - let child = canonical_future(&entry)?; - if child == chosen || !child.starts_with(&chosen) { - return Err(format!("the nightly {label} must stay inside its selected profile")); - } - Ok(child) -} +/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). +const STABLE_ID: &str = "ai.storyteller.texturecraft"; +/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). +const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; /// Known folder-only entries directly inside a Nightly profile. -const PROFILE_FOLDERS: [&str; 10] = ["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"]; +const PROFILE_FOLDERS: &[&str] = &["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"]; -/// Every existing entry directly in the profile (autosave, logs, library and so on) must resolve -/// inside it. -fn entries_stay_inside(root: &Path) -> Result<(), String> { - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), - }; - for entry in entries { - let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - let path = entry.path(); - let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - // Settings and session state are ordinary files, not directories. Keep the existing - // directory-boundary check for folders (including the known folder-only entries). - let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); - if metadata.is_file() && !folder_only { - private_regular_file(&path, &metadata)?; - } else { - private_subdirectory(root, entry.file_name(), "profile entry")?; - } - } - Ok(()) +/// Build TextureCraft's `craft_nightly::AppProfileSpec` from the current process environment. +pub fn spec() -> AppProfileSpec { + spec_with_env(|key| std::env::var_os(key)) } -/// Persisted files must have their own ordinary file identity, not an alias to other data. -fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt as _; - if metadata.nlink() != 1 { - return Err("the nightly profile file must not be shared".into()); - } +/// Build TextureCraft's `craft_nightly::AppProfileSpec` using a custom environment lookup. +pub fn spec_with_env(env: impl Fn(&str) -> Option) -> AppProfileSpec { + AppProfileSpec { + app_id: APP_ID, + display_name: BRAND, + stable_dir_names: &[BRAND, LINUX_STORAGE_BRAND], + stable_package_id: STABLE_ID, + nightly_package_id: NIGHTLY_ID, + profile_root_env: None, + forbidden_env_vars: &[], + portable_markers: &[], + folder_only_entries: PROFILE_FOLDERS, + extra_forbidden_roots: extra_forbidden_roots(&env), } - #[cfg(windows)] - { - use winsafe::{HFILE, co}; - let (file, _) = HFILE::CreateFile( - path.to_str().ok_or("the nightly profile file path is not textual")?, - co::GENERIC::default(), - Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), - None, - co::DISPOSITION::OPEN_EXISTING, - co::FILE_ATTRIBUTE::NORMAL, - Some(co::FILE_FLAG::OPEN_REPARSE_POINT), - None, - None, - ) - .map_err(|e| e.to_string())?; - let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; - if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) { - return Err("the nightly profile file must not be an alias or directory".into()); - } - if info.nNumberOfLinks != 1 { - return Err("the nightly profile file must not be shared".into()); - } - } - let _ = (path, metadata); - Ok(()) } -/// The app's writable probe: create a file exclusively in the profile and remove it again. -pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { - let probe = dir.join("exclusive-write-probe"); - let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; - drop(file); - std::fs::remove_file(probe) +fn non_empty_abs_env(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key).filter(|v| !v.is_empty())?; + let path = PathBuf::from(value); + path.is_absolute().then_some(path) } -/// Refuse a stable folder, the running install or an alias, create a missing root with owner-only -/// access where the platform has it, and return the resolved root to use. -pub fn validate( - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) -} +/// Platform-specific stable data and install roots beyond the OS config/data/cache dirs that +/// `craft-nightly` already fences from `stable_dir_names` and `stable_package_id`. +fn extra_forbidden_roots(env: &impl Fn(&str) -> Option) -> Vec { + let mut roots = Vec::new(); -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - absolute(root.to_path_buf(), "the nightly profile root")?; - // A native package must not carry another app's Flatpak namespace, and the Nightly bundle must - // be able to start inside its own sandbox, where the runtime always sets `FLATPAK_ID`. Its - // `~/.var/app/` sandbox is separate from stable's, so only other ids are refused. - if platform != Platform::Windows - && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) - && id != NIGHTLY_ID + // The user's own Documents folder is Stable's default data folder on every platform; a profile + // there would share autosaves, smart materials and presets with it. + #[cfg(target_os = "windows")] + if let Some(home) = non_empty_abs_env(env, "USERPROFILE") { + roots.push(home.join("Documents").join(BRAND)); + } + #[cfg(not(target_os = "windows"))] + if let Some(home) = non_empty_abs_env(env, "HOME") { + roots.push(home.join("Documents").join(BRAND)); + } + + #[cfg(target_os = "windows")] { - return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into()); + if let Some(local) = non_empty_abs_env(env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join(BRAND)); + } + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs_env(env, key) { + roots.push(base.join(BRAND)); + } + } } - let chosen = canonical_future(root)?; - let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; - let forbidden = forbidden_roots(platform, &env, &exe)?; - if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { - return Err("the nightly root must not overlap stable data or an installation".into()); - } - // Existing aliases under the profile must not redirect any of its folders elsewhere. - entries_stay_inside(&chosen)?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] + + #[cfg(target_os = "linux")] { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); + roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); + if let Some(home) = non_empty_abs_env(env, "HOME") { + roots.push(home.join(format!(".var/app/{STABLE_ID}"))); + } } - create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; - let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; - if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { - return Err("the nightly profile changed while it was being validated".into()); + + #[cfg(target_os = "macos")] + { + if let Some(home) = non_empty_abs_env(env, "HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences").join(format!("{STABLE_ID}.plist"))); + roots.push(library.join("Saved Application State").join(format!("{STABLE_ID}.savedState"))); + roots.push(home.join("Applications").join(format!("{BRAND}.app"))); + } + roots.push(PathBuf::from("/Applications").join(format!("{BRAND}.app"))); } - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) + + roots } #[cfg(test)] mod tests { use super::*; + use craft_nightly::{ProfileError, validate_and_prepare_root}; use std::collections::BTreeMap; + use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, + struct TempDir { + path: PathBuf, } - impl Fixture { - fn new() -> Self { + impl TempDir { + fn new(label: &str) -> Self { static NEXT: AtomicU64 = AtomicU64::new(0); - let root = loop { - let candidate = - std::env::temp_dir().join(format!("texturecraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir()); + let path = loop { + let candidate = base.join(format!("texturecraft-profile-spec-{label}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); match std::fs::create_dir(&candidate) { - Ok(()) => break std::fs::canonicalize(candidate).unwrap(), + Ok(()) => break candidate, Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(error) => panic!("cannot create owned fixture: {error}"), } }; - let home = root.join("home"); - let exe = root.join("install/texturecraft"); - std::fs::create_dir_all(&home).unwrap(); - std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); - std::fs::write(&exe, b"fixture executable, never run").unwrap(); - let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] - .into_iter() - .map(|(key, value)| (key.into(), value.into_os_string())) - .collect(); - Self { root, env, exe } + Self { path } } - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable) - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) - } - - fn profile(&self, name: &str) -> PathBuf { - self.root.join("profiles").join(name) + fn path(&self) -> &Path { + &self.path } } - impl Drop for Fixture { + impl Drop for TempDir { fn drop(&mut self) { - // Only the directory this fixture created is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); + let _ = std::fs::remove_dir_all(&self.path); } } #[test] - fn a_fresh_private_profile_is_created_and_returned_resolved() { - let fixture = Fixture::new(); - let profile = fixture.profile("nightly"); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - assert_eq!(fixture.check(platform, &profile).unwrap(), profile); - assert!(profile.is_dir()); - std::fs::remove_dir_all(&profile).ok(); + fn spec_declares_texturecraft_ids_folders_and_extra_forbidden_roots() { + let tmp = TempDir::new("spec"); + let home = tmp.path().join("home"); + let mut env = BTreeMap::new(); + env.insert("HOME", home.clone().into_os_string()); + env.insert("USERPROFILE", home.clone().into_os_string()); + env.insert("LOCALAPPDATA", tmp.path().join("local").into_os_string()); + env.insert("ProgramFiles", tmp.path().join("Program Files").into_os_string()); + + let spec = spec_with_env(|key| env.get(key).cloned()); + assert_eq!(spec.app_id, "texturecraft"); + assert_eq!(spec.display_name, "TextureCraft"); + assert_eq!(spec.stable_dir_names, &["TextureCraft", "texturecraft"]); + assert_eq!(spec.stable_package_id, "ai.storyteller.texturecraft"); + assert_eq!(spec.nightly_package_id, "ai.storyteller.texturecraft.nightly"); + assert_eq!(spec.profile_root_env, None); + assert!(spec.forbidden_env_vars.is_empty()); + assert!(spec.portable_markers.is_empty()); + assert_eq!(spec.folder_only_entries, PROFILE_FOLDERS); + assert!(spec.extra_forbidden_roots.contains(&home.join("Documents").join(BRAND))); + + #[cfg(target_os = "linux")] + { + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/usr/bin/texturecraft"))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/opt/texturecraft"))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!(".var/app/{STABLE_ID}")))); + } + #[cfg(target_os = "macos")] + { + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Preferences/{STABLE_ID}.plist")))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Saved Application State/{STABLE_ID}.savedState")))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Applications/{BRAND}.app")))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(format!("/Applications/{BRAND}.app")))); + } + #[cfg(target_os = "windows")] + { + assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("local/Programs/ArtCraft").join(BRAND))); + assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("Program Files").join(BRAND))); } } #[test] - fn every_stable_data_folder_of_each_platform_is_refused_before_any_probe() { - let fixture = Fixture::new(); - let home = fixture.home(); - let candidates: Vec<(Platform, PathBuf)> = vec![ - (Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join(BRAND)), - (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join(BRAND)), - (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft").join(BRAND)), - (Platform::Windows, home.join("Documents").join(BRAND)), - (Platform::Linux, home.join(".config").join(BRAND)), - (Platform::Linux, home.join(".local/share").join(BRAND)), - (Platform::Linux, home.join(".local/share").join(LINUX_STORAGE_BRAND)), - (Platform::Linux, home.join(".cache").join(BRAND)), - (Platform::Linux, home.join(".local/state").join(BRAND)), - (Platform::Linux, home.join("Documents").join(BRAND)), - (Platform::Linux, PathBuf::from("/usr/bin/texturecraft")), - (Platform::Linux, PathBuf::from("/opt/texturecraft")), - (Platform::Linux, home.join(format!(".var/app/{STABLE_ID}"))), - (Platform::Mac, home.join("Library/Application Support").join(BRAND)), - (Platform::Mac, home.join("Library/Caches").join(BRAND)), - (Platform::Mac, home.join("Library/Preferences").join(format!("{STABLE_ID}.plist"))), - (Platform::Mac, home.join("Library/Saved Application State").join(format!("{STABLE_ID}.savedState"))), - (Platform::Mac, home.join("Documents").join(BRAND)), - (Platform::Mac, PathBuf::from(format!("/Applications/{BRAND}.app"))), - ]; - for (platform, stable) in candidates { - for candidate in [stable.clone(), stable.join("nested nightly")] { - let probed = std::cell::Cell::new(false); - let result = validate_for( - platform, - &candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "{platform:?} accepted {}", candidate.display()); - assert!(!probed.get(), "a refused root must not be probed: {}", candidate.display()); - } + fn nightly_profile_reopens_and_enforces_folder_only_entries() { + let tmp = TempDir::new("reopen"); + let private = tmp.path().join("nightly-profile"); + let spec = spec_with_env(|_| None); + + let canonical = validate_and_prepare_root(&private, &spec).expect("fresh private profile"); + assert_eq!(canonical, private); + for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(private.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + std::fs::create_dir(private.join(name)).unwrap(); + } + + assert_eq!(validate_and_prepare_root(&private, &spec).expect("reopen populated profile"), private); + assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data"); + + for name in PROFILE_FOLDERS { + let path = private.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); } } #[test] - fn the_running_install_is_fenced_on_every_platform() { - let fixture = Fixture::new(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - let inside = fixture.exe.parent().unwrap().join("profile"); - assert!(fixture.check(platform, &inside).is_err(), "{platform:?} let the profile inside the install"); - } - } + fn documents_data_folder_is_refused() { + let tmp = TempDir::new("documents"); + let home = tmp.path().join("home"); + let documents_stable = home.join("Documents").join(BRAND); + let spec = spec_with_env(|key| matches!(key, "HOME" | "USERPROFILE").then(|| home.clone().into_os_string())); - #[test] - fn lookalike_names_are_not_overlaps_but_case_folding_is() { - let fixture = Fixture::new(); - let documents = fixture.home().join("Documents"); - assert!(fixture.check(Platform::Linux, &documents.join("TextureCraft2")).is_ok(), "a neighbor with a suffix is a different folder"); - assert!(fixture.check(Platform::Linux, &documents.join("texturecraft")).is_ok(), "Linux folds names exactly"); - for platform in [Platform::Windows, Platform::Mac] { - assert!(fixture.check(platform, &documents.join("texturecraft")).is_err(), "{platform:?} must fold case"); - } - } - - #[test] - fn relative_parent_traversal_and_empty_roots_are_refused() { - let fixture = Fixture::new(); - for root in [PathBuf::from("relative/profile"), PathBuf::from("/nightly/../stable"), PathBuf::from("")] { - assert!(fixture.check(Platform::Linux, &root).is_err(), "{}", root.display()); - } - } - - #[test] - fn only_the_nightly_flatpak_may_start_with_its_own_id() { - let fixture = Fixture::new(); - let profile = fixture.profile("flatpak"); - assert!(fixture.check(Platform::Linux, &profile).is_ok()); - std::fs::remove_dir_all(&profile).ok(); - let check_with = |id: &str, candidate: &Path| { - let id = OsString::from(id); - validate_for( - Platform::Linux, - candidate, - |key| if key == "FLATPAK_ID" { Some(id.clone()) } else { fixture.get(key) }, - Some(&fixture.exe), - ensure_writable, - ) - }; - // Stable's id, its window id and an unrelated app's id are all refusals. - for id in [STABLE_ID, "ai.storyteller.texturecraft.nightly-v1", "org.example.other"] { - assert!(check_with(id, &profile).is_err(), "{id} was accepted"); - } - // The Nightly bundle's own id is the sandbox the Nightly package runs in: accepted, with the - // profile its wrapper names inside it (`${XDG_DATA_HOME}/TextureCraft-Nightly`). - let sandbox = fixture.home().join(format!(".var/app/{NIGHTLY_ID}")); - let sandboxed = sandbox.join(".local/share/TextureCraft-Nightly"); - assert_eq!(check_with(NIGHTLY_ID, &sandboxed).expect("the Nightly Flatpak may start"), sandboxed); - std::fs::remove_dir_all(&sandbox).ok(); - } - - #[test] - #[cfg(unix)] - fn an_entry_that_leaves_the_profile_is_refused() { - let fixture = Fixture::new(); - let profile = fixture.profile("aliased"); - let outside = fixture.root.join("somewhere else"); - std::fs::create_dir_all(&profile).unwrap(); - std::fs::create_dir_all(&outside).unwrap(); - std::os::unix::fs::symlink(&outside, profile.join("autosave")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_err(), "a link out of the profile must be refused"); - // A dangling link is not a missing folder that may be created. - std::fs::remove_file(profile.join("autosave")).unwrap(); - std::os::unix::fs::symlink(profile.join("missing"), profile.join("logs")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_err()); - std::fs::remove_file(profile.join("logs")).unwrap(); - // A plain folder inside it is fine. - std::fs::create_dir(profile.join("autosave")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_ok()); - } - - #[test] - fn a_failed_write_probe_never_falls_back_to_stable() { - let fixture = Fixture::new(); - let profile = fixture.profile("read only"); - let reached = std::cell::Cell::new(false); - let result = validate_for( - Platform::Linux, - &profile, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - reached.set(true); - Err(std::io::Error::other("read-only filesystem")) - }, - ); - assert!(result.is_err()); - assert!(reached.get()); - assert!(result.unwrap_err().contains("not writable")); - // The app must not then use the stable folder: it simply refuses to start. - assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err()); - } - - #[test] - fn nightly_profile_reopens_after_saving_settings_and_session_state() { - let fixture = Fixture::new(); - for platform in [Platform::Mac, Platform::Linux, Platform::Windows] { - let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); - assert_eq!(fixture.check(platform, &private).unwrap(), private); - for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] { - std::fs::write(private.join(name), b"saved profile data").unwrap(); - } - for name in PROFILE_FOLDERS { - std::fs::create_dir(private.join(name)).unwrap(); - } - assert_eq!(fixture.check(platform, &private).unwrap(), private); - assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data"); - for name in PROFILE_FOLDERS { - let path = private.join(name); - std::fs::remove_dir(&path).unwrap(); - std::fs::write(&path, b"not a directory").unwrap(); - assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); - std::fs::remove_file(&path).unwrap(); - std::fs::create_dir(&path).unwrap(); - } - } - } - - #[test] - #[cfg(unix)] - fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() { - let fixture = Fixture::new(); - let real = fixture.root.join("real profiles"); - std::fs::create_dir_all(&real).unwrap(); - let link = fixture.root.join("linked"); - std::os::unix::fs::symlink(&real, &link).unwrap(); - // A link to a private folder is fine, and the resolved root is what the app uses. - let resolved = fixture.check(Platform::Linux, &link.join("nightly")).unwrap(); - assert_eq!(resolved, real.join("nightly")); + assert!(matches!(validate_and_prepare_root(&documents_stable, &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); + assert!(matches!(validate_and_prepare_root(&documents_stable.join("nested"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); } }