From 5b0fbec41677dc5af9701e68de03272348546b84 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 02:55:01 -0800 Subject: [PATCH 01/32] Retype: glyphs drawn alike in several fonts count as one outline in near matching Near matching compared a shape with the 256 glyphs closest to it in proportion, over every indexed face. Faces that draw the same glyphs (Noto families sharing their Latin dots, copies of a font under other names) each took places among the 256, and when glyphs tied, which of them kept a place depended on an unstable selection. A simplified period, turned with its line, ranks near the 240th place among the faces craft-fonts supplies, so each face loaded after them pushed some fonts' periods out: with four copies of Source Sans 3 loaded, Source Sans 3's period was no longer compared and Retype left the period of "no." an outline. In a full vectorcraft-engine test run the test fonts that other tests load into the shared font database did this to turned_near_matched_round_glyphs_keep_the_line_turn. Each indexed glyph now carries a hash of its outline. Ranking groups the glyphs drawn alike into one outline, keeps the 256 closest outlines with every glyph of each, and breaks ties by index order. A group is fitted once and its poses go to each of its glyphs, so the comparisons spent do not grow with the number of faces that draw the outline. docs/mcp.md describes the limit as 256 outlines. --- crates/text/src/retype.rs | 168 ++++++++++++++++++++++++++++++-------- docs/mcp.md | 4 +- 2 files changed, 138 insertions(+), 34 deletions(-) diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index deeebbd519..b020a3827f 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -79,7 +79,8 @@ pub const MAX_NEAR_KEYS: usize = 1024; const NEAR_WORK: u64 = 2_000_000_000; /// Point comparisons near matching makes for one shape, at most. const NEAR_SHAPE_WORK: u64 = 50_000_000; -/// Glyphs one shape is near matched against, at most: those closest to it in proportion. +/// Outlines one shape is near matched against, at most: those closest to it in proportion, each +/// with every glyph drawn as it is. const NEAR_FITS: usize = 256; /// Contours [`clusters`] reads, at most: past it, none. const MAX_CLUSTER_CONTOURS: usize = 1024; @@ -173,6 +174,8 @@ struct Entry { sig: Signature, /// The glyph's outline in font units, for the whole-outline check. outline: BezPath, + /// [`outline_hash`] of `outline`: glyphs drawn alike hash alike. + drawn: u64, /// Whether the glyph was indexed for its exact key: only these take part in exact matching, /// and the ones indexed only for near matching ([`RetypeIndex::near_matches`]) do not. exact: bool, @@ -285,7 +288,7 @@ impl RetypeIndex { if keys.contains(&key) { let outline = drawn.unwrap_or_else(|| db.outline_uncached(face, gid)); if let Some(sig) = signatures(&outline, false).into_iter().next() { - entries.push(Entry { face: fi, gid, ch, sig, outline, exact: true }); + entries.push(Entry { face: fi, gid, ch, sig, drawn: outline_hash(&outline), outline, exact: true }); } continue; } @@ -308,7 +311,7 @@ impl RetypeIndex { break 'faces; } if let Some(sig) = signatures(&outline, false).into_iter().next() { - entries.push(Entry { face: fi, gid, ch, sig, outline, exact: false }); + entries.push(Entry { face: fi, gid, ch, sig, drawn: outline_hash(&outline), outline, exact: false }); } } } @@ -496,11 +499,12 @@ impl RetypeIndex { /// shape need not be built as the glyph is. Upright ones first, then the closest; the other /// turns a glyph fits in (at most 7) are kept in [`GlyphMatch::alts`]; at most /// [`MAX_CANDIDATES`] for each face. Empty for a tolerance of 0 or less, and for shapes of more - /// than 8 contours. A shape is compared with at most the 256 glyphs closest to it in proportion - /// (the spread-to-length ratio, and the share of the length each contour has), closest first, - /// in at most 50 million point comparisons, and the index's calls make at most 2 billion in - /// all (ranking a glyph by proportion counts as one per contour and one more); once they are - /// spent, the glyphs not yet ranked or compared are left out. + /// than 8 contours. A shape is compared with the glyphs of at most the 256 outlines closest to + /// it in proportion (the spread-to-length ratio, and the share of the length each contour has), + /// closest first; glyphs drawn alike, in several faces or in one, are one outline and are fitted + /// once. A shape takes at most 50 million point comparisons, and the index's calls make at most + /// 2 billion in all (ranking a glyph by proportion counts as one per contour and one more); once + /// they are spent, the glyphs not yet ranked or compared are left out. pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec { // NaN too. if tolerance.is_nan() || tolerance <= 0.0 { @@ -529,20 +533,33 @@ impl RetypeIndex { } }; let near = self.ranked_near(&s, &mut work); + // The glyph fitted last and its poses: the glyphs drawn alike after it take them. + let mut last: Option<(&Entry, Option)> = None; for (_, e) in near { - if work == 0 { - break; - } let Some(face) = self.faces.get(e.face) else { continue }; - let fits = near_fit(&e.sig, &s, tolerance, &mut work); - let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol)); - let Some(flat) = flat.as_ref() else { break }; - // Every turn the glyph fits the shape at, nearest upright first: the first is its - // pose, the others its alternatives (a glyph that looks alike turned). - let mut poses = - fits.into_iter().filter(|f| f.1 <= tolerance).filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r))).take(MAX_NEAR_POSES); - let Some((pose, residual)) = poses.next() else { continue }; - let rest: Vec<(Pose, f64)> = poses.collect(); + let alike = last.as_ref().filter(|(l, _)| drawn_alike(l, e)).map(|(_, p)| p.clone()); + let posed = match alike { + Some(p) => p, + None => { + if work == 0 { + break; + } + let fits = near_fit(&e.sig, &s, tolerance, &mut work); + let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol)); + let Some(flat) = flat.as_ref() else { break }; + // Every turn the glyph fits the shape at, nearest upright first: the first is its + // pose, the others its alternatives (a glyph that looks alike turned). + let mut poses = fits + .into_iter() + .filter(|f| f.1 <= tolerance) + .filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r))) + .take(MAX_NEAR_POSES); + let p = poses.next().map(|(pose, residual)| (pose, residual, poses.collect())); + last = Some((e, p.clone())); + p + } + }; + let Some((pose, residual, rest)) = posed else { continue }; let m = GlyphMatch { face: face.clone(), gid: e.gid, @@ -568,11 +585,13 @@ impl RetypeIndex { out.into_iter().map(|(_, m)| m).collect() } - /// The glyphs of as many contours as near-matching shape `s` that are closest to it in - /// proportion, at most [`NEAR_FITS`], closest first: their spread-to-length ratio, and the - /// share of the length each contour has, longest first. Ranking a glyph takes one comparison - /// per contour, and one more, from `work`; once it is spent, the glyphs not yet ranked are - /// left out. + /// The glyphs of as many contours as near-matching shape `s` whose outlines are among the + /// [`NEAR_FITS`] outlines closest to it in proportion, closest first: their spread-to-length + /// ratio, and the share of the length each contour has, longest first. Glyphs drawn alike (one + /// outline in several faces, or in several glyphs of one face) are one outline and come + /// together, in index order, so copies of a font do not crowd out the glyphs of the faces they + /// copy; outlines as close come in index order. Ranking a glyph takes one comparison per + /// contour, and one more, from `work`; once it is spent, the glyphs not yet ranked are left out. fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); @@ -595,24 +614,40 @@ impl RetypeIndex { if d.is_finite() { d } else { f64::INFINITY } }; let cost = s.contours as u64 + 1; - let mut near: Vec<(f64, &Entry)> = vec![]; - for e in list.iter().skip(start).filter_map(|i| self.entries.get(*i)).take_while(|e| e.sig.invariant <= hi) { + // Each outline with its distance and its glyphs, in the order they are ranked; the list + // is sorted by invariant and then by index, so each outline's first glyph is its lowest. + let mut outlines: Vec<(f64, Vec<(usize, &Entry)>)> = vec![]; + let mut by_drawn: HashMap> = HashMap::new(); + for (i, e) in list.iter().skip(start).filter_map(|i| Some((*i, self.entries.get(*i)?))).take_while(|(_, e)| e.sig.invariant <= hi) { let Some(left) = work.checked_sub(cost) else { break }; *work = left; - near.push((apart(e), e)); + let same = by_drawn.entry(e.drawn).or_default(); + let found = same.iter().copied().find(|k| outlines.get(*k).and_then(|o| o.1.first()).is_some_and(|(_, f)| drawn_alike(f, e))); + match found.and_then(|k| outlines.get_mut(k)) { + Some(o) => o.1.push((i, e)), + None => { + same.push(outlines.len()); + outlines.push((apart(e), vec![(i, e)])); + } + } } - if near.len() > NEAR_FITS { - near.select_nth_unstable_by(NEAR_FITS, |a, b| a.0.total_cmp(&b.0)); - near.truncate(NEAR_FITS); + let first = |o: &(f64, Vec<(usize, &Entry)>)| o.1.first().map_or(usize::MAX, |(i, _)| *i); + let order = |a: &(f64, Vec<(usize, &Entry)>), b: &(f64, Vec<(usize, &Entry)>)| a.0.total_cmp(&b.0).then(first(a).cmp(&first(b))); + if outlines.len() > NEAR_FITS { + outlines.select_nth_unstable_by(NEAR_FITS, order); + outlines.truncate(NEAR_FITS); } - near.sort_by(|a, b| a.0.total_cmp(&b.0)); - near + outlines.sort_by(order); + outlines.into_iter().flat_map(|(d, glyphs)| glyphs.into_iter().map(move |(_, e)| (d, e))).collect() } } /// Turns of one glyph [`RetypeIndex::near_matches`] keeps, at most: its pose and its alternatives. const MAX_NEAR_POSES: usize = 8; +/// A near-matched glyph's pose and leftover distance, and its other poses, each with its own. +type NearPoses = (Pose, f64, Vec<(Pose, f64)>); + /// `out` (each match with its face's index) without the matches past the first /// [`MAX_CANDIDATES`] of each face, so faces drawn alike (copies of one font under other names) /// do not crowd out the glyphs of the faces after them. @@ -625,6 +660,38 @@ fn keep_per_face(out: &mut Vec<(usize, GlyphMatch)>) { }); } +/// Whether glyphs `a` and `b` are drawn alike: the same outline in font units. +fn drawn_alike(a: &Entry, b: &Entry) -> bool { + a.drawn == b.drawn && a.outline == b.outline +} + +/// A hash of `outline`'s elements and points: outlines drawn alike hash alike. +fn outline_hash(outline: &BezPath) -> u64 { + // FNV-1a, as `key_and_count`; a rare clash only compares two outlines in full. + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + let mut add = |v: u64| { + for b in v.to_le_bytes() { + h ^= u64::from(b); + h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + }; + for el in outline.elements() { + let (tag, pts) = match *el { + PathEl::MoveTo(p) => (0, [p, p, p]), + PathEl::LineTo(p) => (1, [p, p, p]), + PathEl::QuadTo(a, b) => (2, [a, b, b]), + PathEl::CurveTo(a, b, c) => (3, [a, b, c]), + PathEl::ClosePath => (4, [Point::ZERO; 3]), + }; + add(tag); + for p in pts { + add(p.x.to_bits()); + add(p.y.to_bits()); + } + } + h +} + /// Entry `e`'s pose on near-matching shape `s` at scaled turn `z`, when its whole outline, so /// placed, lies within `tol` of the shape's (`flat`). fn near_pose(e: &Entry, s: &Signature, z: (f64, f64), flat: &Flat, tol: f64) -> Option { @@ -2106,6 +2173,41 @@ mod tests { assert!(found.len() > MAX_CANDIDATES && has_every_period(&found), "near: {} matches", found.len()); } + #[test] + fn glyphs_drawn_alike_in_many_faces_are_all_near_matched() { + // Source Sans 3 Regular first, then 40 copies of it under other names: each face has nine + // glyphs close to a period in proportion, 369 in all, more than the 256 near matching + // compares a shape with, but nine outlines. + let db = FontDb::with_font_dirs(vec![]); + let source = db.face("Source Sans 3", "Regular").unwrap(); + let mut faces = vec![source.clone()]; + for i in 0..40 { + let family = format!("Alike {i} Sans"); + db.add_font(crate::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("Alike{i}Sans-Regular"))).unwrap()); + faces.push(db.face(&family, "Regular").unwrap()); + } + let gid = source.mapped_chars().iter().find(|(c, _)| *c == '.').map(|(_, g)| *g).unwrap(); + // Turned a half turn, as a line of type set upside down. + let period = + Affine::translate((300.0, 200.0)) * Affine::rotate(std::f64::consts::PI) * Affine::scale(0.04) * db.outline_uncached(&source, gid); + let simple = simplified(&period, 0.05); + let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]); + let found = index.near_matches(&simple, 0.02); + for f in &faces { + assert!(found.iter().any(|m| m.ch == '.' && m.face.id() == f.id()), "{}: no period among {} matches", f.family, found.len()); + } + // Each outline is fitted once, however many faces draw it: past ranking the copies' glyphs + // (two comparisons each, for one contour), the comparisons spent are those of Source Sans 3 + // alone. + let alone = RetypeIndex::build_near(&db, [source], &BTreeSet::new(), &[near_key(&simple).unwrap()]); + let alone_found = alone.near_matches(&simple, 0.02); + assert_eq!(found.len(), alone_found.len() * faces.len()); + let mut all = u64::MAX; + let ranked = alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).len() as u64; + let spent = |ix: &RetypeIndex| NEAR_WORK - ix.near_work.load(Ordering::Acquire); + assert_eq!(spent(&index), spent(&alone) + 40 * ranked * 2); + } + #[test] fn a_face_past_its_near_share_keeps_the_glyphs_closest_to_the_shapes() { // One glyph of the face is indexed for near matching: the one closest to a simplified o, diff --git a/docs/mcp.md b/docs/mcp.md index a9e9d9649a..fdf4720f1c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13420,7 +13420,9 @@ glyphs may become separate objects that paint the overlap twice. When the split shortest runs is checked, then the other complete splits in order, up to 32 splits per shape for exact matches and 32 for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups, 512 contours or 65,536 path elements is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are -matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at +matched whole only. Near matching compares a shape with the glyphs of at most the 256 outlines closest to it in +proportion; glyphs drawn alike (copies of one font under other names, or one outline under several characters) are one +outline and are fitted once. It takes at most 50 million point comparisons per shape and 2 billion per command, ranking a glyph by proportion counting as one comparison per contour and one more; past them, the glyphs not yet ranked or compared are left out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that From 3e0a3f6cc71937c307863fb14b6c04b067ea11ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 04:14:24 -0800 Subject: [PATCH 02/32] Retype: outline comparisons in near matching count toward its work limit Near matching groups the glyphs drawn alike by a hash of their outline and compares each glyph's outline with the outlines in its hash bucket. Those comparisons were not counted toward the work limit, and the hash is not collision-resistant: a font with many glyphs whose outlines hash alike made each new glyph compare with every outline before it, so the work grew with the square of the glyph count. Each comparison now takes one unit per element of the glyph's outline from the work limit, and a glyph is compared with at most 4 outlines of one hash; past them, it is an outline of its own. docs/mcp.md describes the new count. The engine test helper lines_in_family took the line's face from RetypeIndex::matches, which keeps the first 16 matches over every face. When other tests had loaded more than 16 copies of Source Sans 3 that draw the i alike, the family the test asked for could fall past them, and the helper would use another face, without its kerning, so a_word_space_after_a_glyph_kerned_toward_it_is_kept_past_the_glyphs_measured could fail in a full engine run with craft-fonts. The helper now reads all_matches, as Retype does. --- crates/engine/src/cmd/retype_tests.rs | 5 +- crates/text/src/retype.rs | 85 +++++++++++++++++++++++---- docs/mcp.md | 3 +- 3 files changed, 78 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 5f89bc1284..f5deb6b600 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1926,11 +1926,12 @@ fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec = vec![]; for pc in &pieces { - let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect(); + let cands: Vec<_> = index.all_matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect(); if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) { lines.extend(super::new_line(pc, &cands, 0.0)); } diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index b020a3827f..c000cce127 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -82,6 +82,9 @@ const NEAR_SHAPE_WORK: u64 = 50_000_000; /// Outlines one shape is near matched against, at most: those closest to it in proportion, each /// with every glyph drawn as it is. const NEAR_FITS: usize = 256; +/// Outlines with one [`outline_hash`] that near matching compares a glyph's outline with, at most: +/// past them, a glyph whose outline hashes alike is an outline of its own. +const MAX_HASH_CLASHES: usize = 4; /// Contours [`clusters`] reads, at most: past it, none. const MAX_CLUSTER_CONTOURS: usize = 1024; @@ -503,8 +506,9 @@ impl RetypeIndex { /// it in proportion (the spread-to-length ratio, and the share of the length each contour has), /// closest first; glyphs drawn alike, in several faces or in one, are one outline and are fitted /// once. A shape takes at most 50 million point comparisons, and the index's calls make at most - /// 2 billion in all (ranking a glyph by proportion counts as one per contour and one more); once - /// they are spent, the glyphs not yet ranked or compared are left out. + /// 2 billion in all (ranking a glyph by proportion counts as one per contour and one more, and + /// comparing its outline with one of at most 4 others with the same hash as one per element of + /// its outline); once they are spent, the glyphs not yet ranked or compared are left out. pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec { // NaN too. if tolerance.is_nan() || tolerance <= 0.0 { @@ -591,7 +595,9 @@ impl RetypeIndex { /// outline in several faces, or in several glyphs of one face) are one outline and come /// together, in index order, so copies of a font do not crowd out the glyphs of the faces they /// copy; outlines as close come in index order. Ranking a glyph takes one comparison per - /// contour, and one more, from `work`; once it is spent, the glyphs not yet ranked are left out. + /// contour, and one more, from `work`, and comparing its outline with one that hashes alike (at + /// most [`MAX_HASH_CLASHES`] of them) one per element of its outline; once it is spent, the + /// glyphs not yet ranked are left out. fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); @@ -622,11 +628,32 @@ impl RetypeIndex { let Some(left) = work.checked_sub(cost) else { break }; *work = left; let same = by_drawn.entry(e.drawn).or_default(); - let found = same.iter().copied().find(|k| outlines.get(*k).and_then(|o| o.1.first()).is_some_and(|(_, f)| drawn_alike(f, e))); + // Each outline that hashes alike is compared with this one in full, one comparison per + // element of its outline. + let compare = e.outline.elements().len() as u64; + let (mut found, mut spent) = (None, false); + for k in same.iter().copied() { + let Some(left) = work.checked_sub(compare) else { + spent = true; + break; + }; + *work = left; + if outlines.get(k).and_then(|o| o.1.first()).is_some_and(|(_, f)| drawn_alike(f, e)) { + found = Some(k); + break; + } + } + if spent { + break; + } match found.and_then(|k| outlines.get_mut(k)) { Some(o) => o.1.push((i, e)), None => { - same.push(outlines.len()); + // Past MAX_HASH_CLASHES outlines that hash alike, the others are not compared: + // each is an outline of its own. + if same.len() < MAX_HASH_CLASHES { + same.push(outlines.len()); + } outlines.push((apart(e), vec![(i, e)])); } } @@ -2197,15 +2224,46 @@ mod tests { assert!(found.iter().any(|m| m.ch == '.' && m.face.id() == f.id()), "{}: no period among {} matches", f.family, found.len()); } // Each outline is fitted once, however many faces draw it: past ranking the copies' glyphs - // (two comparisons each, for one contour), the comparisons spent are those of Source Sans 3 - // alone. + // (two comparisons each, for one contour, and one per element of the outline for comparing + // it with Source Sans 3's), the comparisons spent are those of Source Sans 3 alone. let alone = RetypeIndex::build_near(&db, [source], &BTreeSet::new(), &[near_key(&simple).unwrap()]); let alone_found = alone.near_matches(&simple, 0.02); assert_eq!(found.len(), alone_found.len() * faces.len()); let mut all = u64::MAX; - let ranked = alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).len() as u64; + let ranked: u64 = + alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).iter().map(|(_, e)| 2 + e.outline.elements().len() as u64).sum(); let spent = |ix: &RetypeIndex| NEAR_WORK - ix.near_work.load(Ordering::Acquire); - assert_eq!(spent(&index), spent(&alone) + 40 * ranked * 2); + assert_eq!(spent(&index), spent(&alone) + 40 * ranked); + } + + #[test] + fn outlines_whose_hashes_clash_are_compared_within_the_work_budget() { + // 5,000 glyphs of one square each, moved apart, all given the same outline hash: each is + // compared with at most MAX_HASH_CLASHES of the others, and each comparison is charged. + let square = |i: usize| Affine::translate((i as f64, 0.0)) * kurbo::Rect::new(0.0, 0.0, 100.0, 100.0).to_path(0.1); + let n = 5_000; + let entries: Vec = (0..n) + .map(|i| Entry { face: 0, gid: i as u32, ch: 'a', sig: signature(&square(i)).unwrap(), outline: square(i), drawn: 7, exact: false }) + .collect(); + let elements = square(0).elements().len() as u64; + let s = signature(&square(0)).unwrap(); + let cost = s.contours as u64 + 1; + let mut buckets = HashMap::new(); + buckets.insert(s.contours, (0..n).collect::>()); + let index = RetypeIndex { faces: vec![], entries, buckets, by_glyph: HashMap::new(), near_work: AtomicU64::new(NEAR_WORK) }; + let mut work = u64::MAX; + let ranked = index.ranked_near(&s, &mut work); + assert_eq!(ranked.len(), NEAR_FITS, "each square is an outline of its own"); + let compared: u64 = (0..n as u64).map(|i| i.min(MAX_HASH_CLASHES as u64)).sum(); + assert_eq!(u64::MAX - work, n as u64 * cost + compared * elements); + // With too little work left for the comparisons, ranking stops where it runs out. + let mut work = n as u64 * cost / 4; + let short = index.ranked_near(&s, &mut work); + assert!(short.len() < NEAR_FITS, "{} ranked", short.len()); + assert!(work < cost + elements, "{work} left"); + // Near matching the shape spends at most one shape's allowance and returns. + index.near_matches(&square(0), 0.02); + assert!(NEAR_WORK - index.near_work.load(Ordering::Acquire) <= NEAR_SHAPE_WORK); } #[test] @@ -2479,9 +2537,12 @@ mod tests { let index = RetypeIndex::build_near(db, [face], &BTreeSet::new(), &[near_key(&shape).unwrap()]); let s = near_signature(&shape).unwrap(); let mut all = u64::MAX; - let ranked = index.ranked_near(&s, &mut all).len(); - assert!(ranked >= 1, "the o is ranked"); - assert_eq!(u64::MAX - all, ranked as u64 * 3, "each glyph of two contours takes three"); + let ranked = index.ranked_near(&s, &mut all); + assert!(!ranked.is_empty(), "the o is ranked"); + // The Greek omicron is drawn as the o: it is also compared with the o's outline. + let compared = |i: usize, e: &Entry| if ranked[..i].iter().any(|(_, f)| f.drawn == e.drawn) { e.outline.elements().len() as u64 } else { 0 }; + let spent: u64 = ranked.iter().enumerate().map(|(i, (_, e))| 3 + compared(i, e)).sum(); + assert_eq!(u64::MAX - all, spent, "each glyph of two contours takes three, and one per element for each comparison"); // Enough to rank one glyph of two contours and nothing more. let mut work = 4; assert_eq!(index.ranked_near(&s, &mut work).len(), 1); diff --git a/docs/mcp.md b/docs/mcp.md index fdf4720f1c..93c53b4eeb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13424,7 +13424,8 @@ matched whole only. Near matching compares a shape with the glyphs of at most th proportion; glyphs drawn alike (copies of one font under other names, or one outline under several characters) are one outline and are fitted once. It takes at most 50 million point comparisons per shape and 2 billion per command, ranking a glyph by proportion counting as one -comparison per contour and one more; past them, the glyphs not yet ranked or compared are left out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in +comparison per contour and one more, and comparing its outline with one of at most 4 others that hash alike counting +as one per element of its outline; past them, the glyphs not yet ranked or compared are left out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that limit are not looked up. At most 262,144 glyphs are drawn to check whether they could near match, and at most 32,768 are indexed for it, each face taking an equal share of both; of a face's glyphs, those closest to the selected shapes From bf562e37170495327dfbc34d57b7cba92e2b0409 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:27:38 -0800 Subject: [PATCH 03/32] Retype: near matching reuses poses by outline group without comparing again ranked_near now returns each glyph's outline group with it, and near_matches reuses the last fitted poses when the group matches instead of comparing the two outlines again. The outline comparisons all happen in ranked_near, where each one is charged to the shape's allowance, so the 50 million and 2 billion limits cover them. A new test counts the outline comparisons near_matches makes beyond ranking. --- crates/text/src/retype.rs | 57 +++++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 11 deletions(-) diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index c000cce127..f27fc5e561 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -537,11 +537,12 @@ impl RetypeIndex { } }; let near = self.ranked_near(&s, &mut work); - // The glyph fitted last and its poses: the glyphs drawn alike after it take them. - let mut last: Option<(&Entry, Option)> = None; - for (_, e) in near { + // The outline fitted last and its poses: the glyphs drawn alike after it take them, with no + // second comparison of their outlines. + let mut last: Option<(usize, Option)> = None; + for (_, outline, e) in near { let Some(face) = self.faces.get(e.face) else { continue }; - let alike = last.as_ref().filter(|(l, _)| drawn_alike(l, e)).map(|(_, p)| p.clone()); + let alike = last.as_ref().filter(|(l, _)| *l == outline).map(|(_, p)| p.clone()); let posed = match alike { Some(p) => p, None => { @@ -559,7 +560,7 @@ impl RetypeIndex { .filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r))) .take(MAX_NEAR_POSES); let p = poses.next().map(|(pose, residual)| (pose, residual, poses.collect())); - last = Some((e, p.clone())); + last = Some((outline, p.clone())); p } }; @@ -597,8 +598,9 @@ impl RetypeIndex { /// copy; outlines as close come in index order. Ranking a glyph takes one comparison per /// contour, and one more, from `work`, and comparing its outline with one that hashes alike (at /// most [`MAX_HASH_CLASHES`] of them) one per element of its outline; once it is spent, the - /// glyphs not yet ranked are left out. - fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { + /// glyphs not yet ranked are left out. Each glyph comes with its distance and the number of + /// its outline in the list, the same for every glyph drawn alike. + fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, usize, &Entry)> { let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK); @@ -665,7 +667,7 @@ impl RetypeIndex { outlines.truncate(NEAR_FITS); } outlines.sort_by(order); - outlines.into_iter().flat_map(|(d, glyphs)| glyphs.into_iter().map(move |(_, e)| (d, e))).collect() + outlines.into_iter().enumerate().flat_map(|(k, (d, glyphs))| glyphs.into_iter().map(move |(_, e)| (d, k, e))).collect() } } @@ -689,6 +691,8 @@ fn keep_per_face(out: &mut Vec<(usize, GlyphMatch)>) { /// Whether glyphs `a` and `b` are drawn alike: the same outline in font units. fn drawn_alike(a: &Entry, b: &Entry) -> bool { + #[cfg(test)] + OUTLINES_COMPARED.set(OUTLINES_COMPARED.get() + 1); a.drawn == b.drawn && a.outline == b.outline } @@ -1818,6 +1822,8 @@ fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize] thread_local! { /// How many readings [`signatures`] tried on this thread, kept or not. static READINGS_TRIED: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many outline comparisons [`drawn_alike`] made on this thread. + static OUTLINES_COMPARED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// The first reading of `path` (for tests). @@ -2231,11 +2237,39 @@ mod tests { assert_eq!(found.len(), alone_found.len() * faces.len()); let mut all = u64::MAX; let ranked: u64 = - alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).iter().map(|(_, e)| 2 + e.outline.elements().len() as u64).sum(); + alone.ranked_near(&near_signature(&simple).unwrap(), &mut all).iter().map(|(_, _, e)| 2 + e.outline.elements().len() as u64).sum(); let spent = |ix: &RetypeIndex| NEAR_WORK - ix.near_work.load(Ordering::Acquire); assert_eq!(spent(&index), spent(&alone) + 40 * ranked); } + #[test] + fn glyphs_drawn_alike_are_not_compared_again_after_ranking() { + // Source Sans 3 Regular and 30 copies of it: ranking compares each copy's outlines with + // the first face's and charges every comparison; fitting reuses the poses by outline and + // compares no outline again. + let db = FontDb::with_font_dirs(vec![]); + let source = db.face("Source Sans 3", "Regular").unwrap(); + let mut faces = vec![source.clone()]; + for i in 0..30 { + let family = format!("Again {i} Sans"); + db.add_font(crate::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &format!("Again{i}Sans-Regular"))).unwrap()); + faces.push(db.face(&family, "Regular").unwrap()); + } + let gid = source.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap(); + let shape = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * db.outline_uncached(&source, gid); + let simple = simplified(&shape, 0.05); + let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]); + OUTLINES_COMPARED.set(0); + let mut all = u64::MAX; + let ranked = index.ranked_near(&near_signature(&simple).unwrap(), &mut all); + let in_ranking = OUTLINES_COMPARED.get(); + assert!(ranked.len() > faces.len(), "{} ranked", ranked.len()); + OUTLINES_COMPARED.set(0); + let found = index.near_matches(&simple, 0.02); + assert!(found.iter().any(|m| m.ch == 'o'), "no o among {} matches", found.len()); + assert_eq!(OUTLINES_COMPARED.get(), in_ranking, "outlines compared outside the charged ranking"); + } + #[test] fn outlines_whose_hashes_clash_are_compared_within_the_work_budget() { // 5,000 glyphs of one square each, moved apart, all given the same outline hash: each is @@ -2540,8 +2574,9 @@ mod tests { let ranked = index.ranked_near(&s, &mut all); assert!(!ranked.is_empty(), "the o is ranked"); // The Greek omicron is drawn as the o: it is also compared with the o's outline. - let compared = |i: usize, e: &Entry| if ranked[..i].iter().any(|(_, f)| f.drawn == e.drawn) { e.outline.elements().len() as u64 } else { 0 }; - let spent: u64 = ranked.iter().enumerate().map(|(i, (_, e))| 3 + compared(i, e)).sum(); + let compared = + |i: usize, e: &Entry| if ranked[..i].iter().any(|(_, _, f)| f.drawn == e.drawn) { e.outline.elements().len() as u64 } else { 0 }; + let spent: u64 = ranked.iter().enumerate().map(|(i, (_, _, e))| 3 + compared(i, e)).sum(); assert_eq!(u64::MAX - all, spent, "each glyph of two contours takes three, and one per element for each comparison"); // Enough to rank one glyph of two contours and nothing more. let mut work = 4; From 42a7b9ea08530f8c8f79166c852f3a0a704da990 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:05:41 -0800 Subject: [PATCH 04/32] Tests: check default swatches, nightly ids and panel places by behavior default_swatches_parse no longer reads swatch.rs as text: it checks that no default swatch outside the black and white ones falls back to black or white. The nightly id test compares the window id with the package id and id_for instead of echoing string literals. The library panel and Tab panel tests compare a panel's place with the saved place and the canvas instead of literal coordinates. --- crates/color/src/swatch.rs | 20 +++++++++++++------ crates/ui-egui/src/os_window.rs | 6 +++--- .../ui-egui/src/panels/library_panel/tests.rs | 6 ++++-- crates/ui-egui/src/panels/tabs/tests.rs | 4 +++- 4 files changed, 24 insertions(+), 12 deletions(-) diff --git a/crates/color/src/swatch.rs b/crates/color/src/swatch.rs index 12ae31220a..7b64d91d1b 100644 --- a/crates/color/src/swatch.rs +++ b/crates/color/src/swatch.rs @@ -187,12 +187,20 @@ mod tests { #[test] fn default_swatches_parse() { // `solid`/`grad` fall back to black or white on a bad literal instead of panicking; make sure - // none falls back. - let src = include_str!("swatch.rs"); - let hexes: Vec<&str> = src.split('"').filter(|t| t.starts_with('#') && t.len() == 7).collect(); - assert!(hexes.len() > 30); - for h in hexes { - assert!(Color::from_hex(h).is_some(), "{h}"); + // none falls back: only the swatches named for black or white carry those colors. + let (s, g) = default_swatches(Model::Rgb); + let all: Vec<&Swatch> = s.iter().chain(g.iter().flat_map(|g| &g.swatches)).collect(); + assert!(all.len() > 30); + for w in all { + let colors: Vec = match &w.paint { + Paint::Solid { color, .. } => vec![*color], + Paint::Gradient(gp) => gp.gradient.stops.iter().map(|st| st.color).collect(), + _ => vec![], + }; + for c in colors { + let fallback = c == Color::BLACK || c == Color::WHITE; + assert!(!fallback || w.name.contains("White") || w.name.contains("Black"), "{} fell back to {c:?}", w.name); + } } } } diff --git a/crates/ui-egui/src/os_window.rs b/crates/ui-egui/src/os_window.rs index 00ce8344e7..493dccbb92 100644 --- a/crates/ui-egui/src/os_window.rs +++ b/crates/ui-egui/src/os_window.rs @@ -119,9 +119,9 @@ mod tests { #[test] fn the_two_nightly_ids_are_the_contract_ones() { // The package and bundle identity ends in `.nightly`; the window and AUMID in `.nightly-v1`. - assert_eq!(NIGHTLY_PACKAGE_ID, "ai.storyteller.vectorcraft.nightly"); - assert_eq!(NIGHTLY_APP_ID, "ai.storyteller.vectorcraft.nightly-v1"); - assert_ne!(NIGHTLY_PACKAGE_ID, NIGHTLY_APP_ID); + assert_eq!(id_for(LaunchIdentity::NightlyV1), NIGHTLY_APP_ID); + assert!(NIGHTLY_PACKAGE_ID.ends_with(".nightly"), "{NIGHTLY_PACKAGE_ID}"); + assert_eq!(NIGHTLY_APP_ID.strip_suffix("-v1"), Some(NIGHTLY_PACKAGE_ID), "the window id is the package id plus -v1"); } #[test] diff --git a/crates/ui-egui/src/panels/library_panel/tests.rs b/crates/ui-egui/src/panels/library_panel/tests.rs index a08ea664f8..c6682d264c 100644 --- a/crates/ui-egui/src/panels/library_panel/tests.rs +++ b/crates/ui-egui/src/panels/library_panel/tests.rs @@ -486,13 +486,14 @@ fn persistent_panels_reopen_at_startup_with_their_settings() { assert_eq!((r["persistent"].as_bool(), r["view"].as_str(), r["showFind"].as_bool()), (Some(true), Some("largeList"), Some(false))); app.run("ui.libraryPanel", json!({"panel": brand, "persistent": true})).unwrap(); app.run("window.panel.float", json!({"panel": pastels, "x": 40, "y": 90})).unwrap(); + let saved = docking(&app).floating.iter().find(|g| g.contains(&pastels)).unwrap().rect; // A persistent panel reopens even when it was closed. app.run("window.panel.close", json!({"panel": brand})).unwrap(); let next = restarted(&app); assert!(is_open(&next.ui, &pastels) && is_open(&next.ui, &brand), "{}", next.ui.status); assert!(!is_open(&next.ui, &brights), "a panel that isn't persistent closed with the app"); let group = docking(&next).floating.iter().find(|g| g.contains(&pastels)).unwrap(); - assert_eq!(group.rect.min, Pos2::new(40.0, 90.0), "where it was"); + assert_eq!(group.rect.min, saved.min, "where it was"); let s = settings(&next.ui, "swatches", "pastels").unwrap(); assert_eq!((s.view, s.hide_find, s.persistent), (Some(View::LargeList), true, true)); let (_, id) = parse(&brand).unwrap(); @@ -711,11 +712,12 @@ fn previous_and_next_show_the_neighbouring_library_in_the_same_panel() { let first = panel_of(app.run("window.swatchLibrary", json!({"library": "pastels"})).unwrap()); app.run("window.panel.float", json!({"panel": first, "x": 50, "y": 60})).unwrap(); app.run("ui.libraryPanel", json!({"panel": first, "persistent": true, "view": "smallList"})).unwrap(); + let saved = docking(&app).floating.iter().find(|g| g.contains(&first)).unwrap().rect; step::(&mut app, "pastels", 1); let next = panel_id("swatches", SWATCH_IDS[5]); assert!(!is_open(&app.ui, &first) && is_open(&app.ui, &next), "{}", app.ui.status); let group = docking(&app).floating.iter().find(|g| g.contains(&next)).unwrap(); - assert_eq!((group.panels().count(), group.rect.min), (1, Pos2::new(50.0, 60.0)), "in its place"); + assert_eq!((group.panels().count(), group.rect.min), (1, saved.min), "in its place"); let s = settings(&app.ui, "swatches", SWATCH_IDS[5]).unwrap(); assert_eq!((s.view, s.persistent), (Some(View::SmallList), true), "the panel keeps its settings"); assert!(settings(&app.ui, "swatches", "pastels").is_none()); diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index 7aacaaf1f8..52ea6ea9ec 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -1088,6 +1088,8 @@ fn above_text_puts_the_panel_at_the_top_when_below_the_text_does_not_fit() { } let (node, _, span) = current(&app).unwrap(); above_text(&mut app, &node, span).unwrap(); - assert_eq!(tabs_rect(&app).min.y, 0.0, "view centered at y {center_y}"); + // Neither above the text (off the window) nor below it (inside the canvas): at the window's top. + let (top, canvas) = (tabs_rect(&app).min.y, app.canvas_view().unwrap().rect); + assert!(top >= 0.0 && top < canvas.top(), "view centered at y {center_y}: panel top {top}, canvas {canvas:?}"); } } From 7e1fe2afadba08c16f10080d0bd63ed3d03bba6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:27:41 -0800 Subject: [PATCH 05/32] Tests: check the nightly id against packaging and the panel at the window top The nightly id test now also reads the published package id from packaging/macos/nightly_plist.py and nightly-lib.sh, and the Position Panel Above Text test requires the panel top to equal the window top. --- crates/ui-egui/src/os_window.rs | 5 +++++ crates/ui-egui/src/panels/tabs/tests.rs | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/os_window.rs b/crates/ui-egui/src/os_window.rs index 493dccbb92..8d25c6e7d2 100644 --- a/crates/ui-egui/src/os_window.rs +++ b/crates/ui-egui/src/os_window.rs @@ -122,6 +122,11 @@ mod tests { assert_eq!(id_for(LaunchIdentity::NightlyV1), NIGHTLY_APP_ID); assert!(NIGHTLY_PACKAGE_ID.ends_with(".nightly"), "{NIGHTLY_PACKAGE_ID}"); assert_eq!(NIGHTLY_APP_ID.strip_suffix("-v1"), Some(NIGHTLY_PACKAGE_ID), "the window id is the package id plus -v1"); + // The packaging publishes the same package id. + let plist = include_str!("../../../packaging/macos/nightly_plist.py"); + assert!(plist.contains(&format!("IDENTIFIER = \"{NIGHTLY_PACKAGE_ID}\"")), "nightly_plist.py"); + let lib = include_str!("../../../packaging/macos/nightly-lib.sh"); + assert!(lib.contains(&format!("MAC_NIGHTLY_ID='{NIGHTLY_PACKAGE_ID}'")), "nightly-lib.sh"); } #[test] diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index 52ea6ea9ec..a30cf7b559 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -1090,6 +1090,7 @@ fn above_text_puts_the_panel_at_the_top_when_below_the_text_does_not_fit() { above_text(&mut app, &node, span).unwrap(); // Neither above the text (off the window) nor below it (inside the canvas): at the window's top. let (top, canvas) = (tabs_rect(&app).min.y, app.canvas_view().unwrap().rect); - assert!(top >= 0.0 && top < canvas.top(), "view centered at y {center_y}: panel top {top}, canvas {canvas:?}"); + assert!(canvas.top() > 0.0, "canvas {canvas:?}"); + assert_eq!(top, 0.0, "view centered at y {center_y}: panel top {top}, canvas {canvas:?}"); } } From 7330cf12d8e3c734e5051553a129fd3d50bdfce0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 02:43:37 -0800 Subject: [PATCH 06/32] Tests: declare the packaging files the nightly-ids test reads The nightly-ids test in os_window.rs reads packaging/macos/nightly_plist.py and packaging/macos/nightly-lib.sh. List both under the crate's [package.metadata.craft] reads so test selection reruns it when they change. --- crates/ui-egui/Cargo.toml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index fa9d95b172..49fad8d56f 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -113,4 +113,9 @@ toml = "1" # The files of other crates that this crate's tests read, for CI's test selection. [package.metadata.craft] -reads = ["crates/engine/src/cmd/addons/cutting/banner.rs", "crates/plugins/tests/fixtures/desaturate.wasm"] +reads = [ + "crates/engine/src/cmd/addons/cutting/banner.rs", + "crates/plugins/tests/fixtures/desaturate.wasm", + "packaging/macos/nightly-lib.sh", + "packaging/macos/nightly_plist.py", +] From d73142fbd2bd388ef50d1f4249ef4e2834b69679 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 03:39:16 -0800 Subject: [PATCH 07/32] Tests: read the active nightly id assignment in either quote style The nightly-ids test now reads the last uncommented IDENTIFIER and MAC_NIGHTLY_ID assignment and accepts single or double quotes, so a commented-out old line no longer satisfies it. --- crates/ui-egui/src/os_window.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/os_window.rs b/crates/ui-egui/src/os_window.rs index 8d25c6e7d2..72575b951f 100644 --- a/crates/ui-egui/src/os_window.rs +++ b/crates/ui-egui/src/os_window.rs @@ -124,9 +124,29 @@ mod tests { assert_eq!(NIGHTLY_APP_ID.strip_suffix("-v1"), Some(NIGHTLY_PACKAGE_ID), "the window id is the package id plus -v1"); // The packaging publishes the same package id. let plist = include_str!("../../../packaging/macos/nightly_plist.py"); - assert!(plist.contains(&format!("IDENTIFIER = \"{NIGHTLY_PACKAGE_ID}\"")), "nightly_plist.py"); + assert_eq!(assigned(plist, "IDENTIFIER"), Some(NIGHTLY_PACKAGE_ID), "nightly_plist.py"); let lib = include_str!("../../../packaging/macos/nightly-lib.sh"); - assert!(lib.contains(&format!("MAC_NIGHTLY_ID='{NIGHTLY_PACKAGE_ID}'")), "nightly-lib.sh"); + assert_eq!(assigned(lib, "MAC_NIGHTLY_ID"), Some(NIGHTLY_PACKAGE_ID), "nightly-lib.sh"); + } + + /// The value of the last uncommented top-level `name = value` or `name=value` line, with one pair of + /// single or double quotes removed. + fn assigned<'a>(source: &'a str, name: &str) -> Option<&'a str> { + source + .lines() + .filter_map(|line| { + let rest = line.strip_prefix(name)?.trim_start().strip_prefix('=')?.trim(); + let unquoted = ['\'', '"'].iter().find_map(|q| rest.strip_prefix(*q)?.strip_suffix(*q)); + Some(unquoted.unwrap_or(rest)) + }) + .next_back() + } + + #[test] + fn assigned_reads_the_active_line_in_either_quote_style() { + assert_eq!(assigned("# ID='old'\nID=\"new\"\n", "ID"), Some("new")); + assert_eq!(assigned("ID = 'a'\n", "ID"), Some("a")); + assert_eq!(assigned("IDX='a'\n", "ID"), None); } #[test] From 4c8e40c19166258459aa7a53e9d91008d9c19bf1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 04:18:47 -0800 Subject: [PATCH 08/32] Tests: ignore a trailing comment after the nightly id assignment The packaging check's `assigned` helper now drops a `#` comment that follows the value, quoted or bare, so `IDENTIFIER = "x" # bundle ID` still reads as `x`. --- crates/ui-egui/src/os_window.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/os_window.rs b/crates/ui-egui/src/os_window.rs index 72575b951f..49f7190275 100644 --- a/crates/ui-egui/src/os_window.rs +++ b/crates/ui-egui/src/os_window.rs @@ -130,14 +130,20 @@ mod tests { } /// The value of the last uncommented top-level `name = value` or `name=value` line, with one pair of - /// single or double quotes removed. + /// single or double quotes removed and a trailing `#` comment after the value ignored. fn assigned<'a>(source: &'a str, name: &str) -> Option<&'a str> { source .lines() .filter_map(|line| { let rest = line.strip_prefix(name)?.trim_start().strip_prefix('=')?.trim(); - let unquoted = ['\'', '"'].iter().find_map(|q| rest.strip_prefix(*q)?.strip_suffix(*q)); - Some(unquoted.unwrap_or(rest)) + let quoted = ['\'', '"'].iter().find_map(|q| { + let inner = rest.strip_prefix(*q)?; + let end = inner.find(*q)?; + let after = inner[end + 1..].trim(); + (after.is_empty() || after.starts_with('#')).then(|| &inner[..end]) + }); + let bare = rest.split_once(" #").map_or(rest, |(value, _)| value.trim_end()); + Some(quoted.unwrap_or(bare)) }) .next_back() } @@ -147,6 +153,9 @@ mod tests { assert_eq!(assigned("# ID='old'\nID=\"new\"\n", "ID"), Some("new")); assert_eq!(assigned("ID = 'a'\n", "ID"), Some("a")); assert_eq!(assigned("IDX='a'\n", "ID"), None); + assert_eq!(assigned("ID = 'a' # bundle ID\n", "ID"), Some("a")); + assert_eq!(assigned("ID=\"a\" # bundle ID\n", "ID"), Some("a")); + assert_eq!(assigned("ID=a # bundle ID\n", "ID"), Some("a")); } #[test] From 7307781c1dfdf45176d4f756c3c6ca0bbea937fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 06:15:20 -0800 Subject: [PATCH 09/32] Tests: a # glued to the closing quote is no shell comment In nightly-lib.sh, MAC_NIGHTLY_ID='x'#y assigns x#y, so the helper now treats a # right after the closing quote as a comment only for the Python file. Both readings have a case in assigned_reads_the_active_line_in_either_quote_style. --- crates/ui-egui/src/os_window.rs | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/os_window.rs b/crates/ui-egui/src/os_window.rs index 49f7190275..2c4abd98cd 100644 --- a/crates/ui-egui/src/os_window.rs +++ b/crates/ui-egui/src/os_window.rs @@ -124,14 +124,15 @@ mod tests { assert_eq!(NIGHTLY_APP_ID.strip_suffix("-v1"), Some(NIGHTLY_PACKAGE_ID), "the window id is the package id plus -v1"); // The packaging publishes the same package id. let plist = include_str!("../../../packaging/macos/nightly_plist.py"); - assert_eq!(assigned(plist, "IDENTIFIER"), Some(NIGHTLY_PACKAGE_ID), "nightly_plist.py"); + assert_eq!(assigned(plist, "IDENTIFIER", false), Some(NIGHTLY_PACKAGE_ID), "nightly_plist.py"); let lib = include_str!("../../../packaging/macos/nightly-lib.sh"); - assert_eq!(assigned(lib, "MAC_NIGHTLY_ID"), Some(NIGHTLY_PACKAGE_ID), "nightly-lib.sh"); + assert_eq!(assigned(lib, "MAC_NIGHTLY_ID", true), Some(NIGHTLY_PACKAGE_ID), "nightly-lib.sh"); } /// The value of the last uncommented top-level `name = value` or `name=value` line, with one pair of - /// single or double quotes removed and a trailing `#` comment after the value ignored. - fn assigned<'a>(source: &'a str, name: &str) -> Option<&'a str> { + /// single or double quotes removed and a trailing `#` comment after the value ignored. With `shell`, a `#` + /// after a closing quote starts a comment only when whitespace comes before it; Python needs no whitespace. + fn assigned<'a>(source: &'a str, name: &str, shell: bool) -> Option<&'a str> { source .lines() .filter_map(|line| { @@ -139,8 +140,9 @@ mod tests { let quoted = ['\'', '"'].iter().find_map(|q| { let inner = rest.strip_prefix(*q)?; let end = inner.find(*q)?; - let after = inner[end + 1..].trim(); - (after.is_empty() || after.starts_with('#')).then(|| &inner[..end]) + let after = &inner[end + 1..]; + let comment = (!shell || after.starts_with(char::is_whitespace)) && after.trim_start().starts_with('#'); + (after.trim().is_empty() || comment).then(|| &inner[..end]) }); let bare = rest.split_once(" #").map_or(rest, |(value, _)| value.trim_end()); Some(quoted.unwrap_or(bare)) @@ -150,12 +152,17 @@ mod tests { #[test] fn assigned_reads_the_active_line_in_either_quote_style() { - assert_eq!(assigned("# ID='old'\nID=\"new\"\n", "ID"), Some("new")); - assert_eq!(assigned("ID = 'a'\n", "ID"), Some("a")); - assert_eq!(assigned("IDX='a'\n", "ID"), None); - assert_eq!(assigned("ID = 'a' # bundle ID\n", "ID"), Some("a")); - assert_eq!(assigned("ID=\"a\" # bundle ID\n", "ID"), Some("a")); - assert_eq!(assigned("ID=a # bundle ID\n", "ID"), Some("a")); + for shell in [false, true] { + assert_eq!(assigned("# ID='old'\nID=\"new\"\n", "ID", shell), Some("new")); + assert_eq!(assigned("ID = 'a'\n", "ID", shell), Some("a")); + assert_eq!(assigned("IDX='a'\n", "ID", shell), None); + assert_eq!(assigned("ID = 'a' # bundle ID\n", "ID", shell), Some("a")); + assert_eq!(assigned("ID=\"a\" # bundle ID\n", "ID", shell), Some("a")); + assert_eq!(assigned("ID=a # bundle ID\n", "ID", shell), Some("a")); + } + // In Python a `#` right after the closing quote starts a comment; in a shell it is part of the word. + assert_eq!(assigned("ID='a'#b\n", "ID", false), Some("a")); + assert_eq!(assigned("ID='a'#b\n", "ID", true), Some("'a'#b")); } #[test] From 454e134152662bcf0ecb0f47babff2da161750ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:11:36 -0800 Subject: [PATCH 10/32] xtask: test-lint follows each loading path, keeps || table checks and skips name-only suffix checks - never-run: follow every file that loads a module up to its crate root and combine the gates along each path; a module that no root loads any more is treated as compiled out. Deleted parents and base `#[path]` loaders now select unchanged children, and the base comparison matches tests by line so same-named tests in other inline modules stay apart. - cfgs_over: skip sibling attributes such as `#[test_case(1; "one")]` before looking for the item body. - census: a helper behind `&&` on the left of `||` no longer hides the whole-table check on the right. - reads-source: an `ends_with(".rs")` check counts only when it selects from a listing or the file's test code reads a file. - docs: unchanged-line hits fail the command when a changed parent takes away a test's last CI route. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 593 ++++++++++++++++++++++++++++++++++++----- 2 files changed, 525 insertions(+), 70 deletions(-) diff --git a/docs/development.md b/docs/development.md index c833a400e8..278aa77454 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` keeps out of every CI test build (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, and an environment variable that no CI leg sets. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` keeps out of every CI test build (`never-run`). It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, and an environment variable that no CI leg sets. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, except a `never-run` test in an unchanged file whose last CI route a changed `mod` declaration or `cfg` in a file that loads it takes away. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 5384b51e4c..52186558be 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -79,7 +79,7 @@ //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the //! workspace by crate and rule, and does not fail. -use std::cell::OnceCell; +use std::cell::{OnceCell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::Path; use std::process::Command; @@ -295,31 +295,55 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let crates: BTreeSet = changed.keys().map(|p| crate_of(p)).chain([TESTKIT.to_owned()]).collect(); let helper_files: Vec = files.iter().filter(|p| crates.contains(&crate_of(p))).cloned().collect(); let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); - // Files under the module of a changed file: a `cfg` added to their `mod` declaration can turn - // their tests off without a change to them. + // Deleted files do not appear in `changed`, but a deleted root or parent may have been the + // last file that loaded a child. `--no-renames` lists the old path of a moved file as deleted. + let deleted: BTreeSet = + git(root, &["-c", "core.quotepath=off", "diff", "--no-renames", "--name-only", "-z", "--diff-filter=D", &base, "--", "*.rs"])? + .split('\0') + .filter(|p| !p.is_empty() && is_scanned(p)) + .map(str::to_owned) + .collect(); + // Files under the module of a changed or deleted file: a `cfg` added to their `mod` + // declaration can turn their tests off without a change to them. let module_dirs: Vec = present .iter() + .chain(&deleted) .map(|p| { let (dir, file) = p.rsplit_once('/').unwrap_or(("", p)); if ["mod.rs", "lib.rs", "main.rs"].contains(&file) { format!("{dir}/") } else { format!("{}/", p.trim_end_matches(".rs")) } }) .collect(); - let below: Vec = - files.iter().filter(|p| !changed.contains_key(*p) && module_dirs.iter().any(|d| p.starts_with(d.as_str()))).cloned().collect(); + // The gates the parent declarations gave at the base: a parent edit counts against a child's + // test only when the test ran in CI before it. Each parent is read from the base once, hit or + // miss. + let base_reads: RefCell>> = RefCell::default(); + let read_base = |p: &str| { + if let Some(s) = base_reads.borrow().get(p) { + return s.clone(); + } + let s = git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE); + base_reads.borrow_mut().insert(p.to_owned(), s.clone()); + s + }; + let loaders = base_path_loads(&present.iter().chain(&deleted).cloned().collect::>(), &read_base); + let below = unchanged_children(&files, &changed, &module_dirs, &loaders); let gated: Vec = present.iter().chain(&below).cloned().collect(); let gates = module_gates(&gated, &|p| read_small(root, p)); - let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); + let base_gates = module_gates_from(&gated, &read_base, &loaders); + // A changed or deleted file that loaded a child at the base may have stopped loading it, which + // the head's gates do not show; the base comparison below still drops a test that was already + // off. + let base_parent_changed = + |p: &str| base_gates.get(p).is_some_and(|g| g.sources.iter().any(|(parent, _)| changed.contains_key(parent) || deleted.contains(parent))); + let path_index = OnceCell::new(); + let module_cfgs = head_cfgs(&gated, &gates, &base_gates, &|p| path_names(&path_index, &files, &|f| read_small(root, f), p)); let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; - // The gates the parent declarations gave at the base: a parent edit counts against a child's - // test only when the test ran in CI before it. - let read_base = |p: &str| git(root, &["show", &format!("{base}:{p}")]).ok().filter(|s| s.len() as u64 <= MAX_FILE); - let base_cfgs = module_gates(&gated, &read_base).into_iter().map(|(p, g)| (p, g.preds)).collect(); + let base_cfgs = base_gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); let base_ctx = Ctx { helpers: ctx.helpers.clone(), ci_env: ctx.ci_env.clone(), module_cfgs: base_cfgs }; - let newly_off = - |path: &str, src: &str, hit: &Hit| !lint_file(path, src, &base_ctx).iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test); + let newly_off = |path: &str, src: &str, hit: &Hit| off_since(&lint_file(path, src, &base_ctx), hit); let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { - let parent_changed = gate_changed(gates.get(&path), &changed); + let parent_changed = gate_changed(gates.get(&path), &changed) || base_parent_changed(&path); for hit in lint_file(&path, &src, &ctx) { if touches(&hit, changed.get(&path).and_then(Option::as_ref)) || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) @@ -330,13 +354,101 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } } } - for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed)) { + for path in below.iter().filter(|p| gate_changed(gates.get(*p), &changed) || base_parent_changed(p)) { let Some(src) = read_small(root, path) else { continue }; counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); } finish(&counted, older, present.len(), &base) } +/// The head's `cfg` predicates for each of `paths`. A module file that reached a crate root at the +/// base and reaches none now ([`Gates::dead`]) is compiled into no target, so it gets the +/// predicate `any()`, which never holds, unless `elsewhere` says a `#[path]` attribute in some +/// other file may still load it. +fn head_cfgs( + paths: &[String], + head: &HashMap, + base: &HashMap, + elsewhere: &dyn Fn(&str) -> bool, +) -> HashMap> { + paths + .iter() + .filter_map(|p| { + let was_live = base.get(p).is_some_and(|b| !b.dead && !b.sources.is_empty()); + let now_dead = head.get(p).is_none_or(|g| g.dead) && module_parent(p).is_some(); + if was_live && now_dead && !elsewhere(p) { + Some((p.clone(), vec!["any()".to_owned()])) + } else { + head.get(p).map(|g| (p.clone(), g.preds.clone())) + } + }) + .collect() +} + +/// Whether any of `files`, read through `read`, has a `#[path]` declaration that resolves to `p`. +fn path_names(index: &OnceCell>>, files: &[String], read: &dyn Fn(&str) -> Option, p: &str) -> bool { + index + .get_or_init(|| { + let mut names: HashMap> = HashMap::new(); + for f in files { + if let Some(s) = read(f) { + for load in path_loads(&s, f) { + names.entry(load.path).or_default().insert(f.clone()); + } + } + } + names + }) + .get(p) + .is_some_and(|parents| parents.iter().any(|f| f != p)) +} + +/// The `#[path]` declarations reachable from `paths` at the base, through at most 16 levels. +/// Each file is read at most once through `read`. +fn base_path_loads(paths: &[String], read: &dyn Fn(&str) -> Option) -> Vec { + let mut pending = paths.to_vec(); + let mut seen = HashSet::new(); + let mut loaders = vec![]; + for _ in 0..16 { + if pending.is_empty() { + break; + } + for p in std::mem::take(&mut pending) { + if !seen.insert(p.clone()) { + continue; + } + if let Some(s) = read(&p) { + let loads = path_loads(&s, &p); + pending.extend(loads.iter().map(|l| l.path.clone())); + loaders.extend(loads); + } + } + } + loaders +} + +/// The unchanged files whose tests a changed or deleted file can turn off: those under one of +/// `module_dirs`, and those a `#[path]` declaration in `loaders` loaded at the base. +fn unchanged_children( + files: &[String], + changed: &BTreeMap>>, + module_dirs: &[String], + loaders: &[PathLoad], +) -> Vec { + files + .iter() + .filter(|p| !changed.contains_key(*p) && (module_dirs.iter().any(|d| p.starts_with(d.as_str())) || loaders.iter().any(|l| l.path == **p))) + .cloned() + .collect() +} + +/// Whether `hit` is a `never-run` test that `base`, the hits of the same source under the base's +/// gates, does not report. Both lints read the same source, so the test's line tells same-named +/// tests in different inline modules apart. +fn off_since(base: &[Hit], hit: &Hit) -> bool { + !base.iter().any(|h| h.rule == Rule::NeverRun && h.test == hit.test && h.line == hit.line) +} + /// The command line: `--all`, `--base `. #[derive(Debug, Default, PartialEq)] struct Options { @@ -1465,7 +1577,7 @@ fn census(v: &View, helpers: &HashSet) -> Vec { /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions /// nested deeper than 64 operators are not judged. An operand that calls one of `helpers` (asserting /// helpers called in the condition) is not a presence check, and a weak right side of an `||` does -/// not count when the left side calls one, since the left side always runs. +/// not count when the left side always calls one ([`always_calls`]). fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool) { let or = top_level_at(cond, "||").first().copied(); if depth > 64 || !cond.contains(".all(") { @@ -1477,7 +1589,7 @@ fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool if s.contains(".all(") { census_condition(s, depth + 1, helpers) } else { (weak_predicate(s) && !calls_any(s, helpers), false) } }; let (l, r) = (side(&cond[..at]), side(&cond[at + 2..])); - let r = if or.is_some() && calls_any(&cond[..at], helpers) { (false, false) } else { r }; + let r = if or.is_some() && always_calls(&cond[..at], helpers, depth) { (false, false) } else { r }; if or.is_none() { (l.0 && r.0, l.1 || r.1) } else if l == (true, true) || r == (true, true) { @@ -1491,6 +1603,21 @@ fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool } } +/// Whether evaluating the (whitespace-free) condition `s` always calls one of `helpers`: a call +/// behind a top-level `&&` or `||` runs only on one outcome of the operand before it, so only the +/// first operand of either counts. +fn always_calls(s: &str, helpers: &[String], depth: usize) -> bool { + if depth > 64 { + false + } else if s.starts_with('(') && matching(s.as_bytes(), 0) == Some(s.len() - 1) { + always_calls(&s[1..s.len() - 1], helpers, depth + 1) + } else if let Some(at) = top_level_at(s, "||").first().copied().or_else(|| top_level_at(s, "&&").first().copied()) { + always_calls(&s[..at], helpers, depth + 1) + } else { + calls_any(s, helpers) + } +} + /// Whether `s` calls a function or method named in `names`, with or without a turbofish. fn calls_any(s: &str, names: &[String]) -> bool { names.iter().any(|n| { @@ -2988,7 +3115,9 @@ fn reads_source_hits(file: &File) -> Vec { let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); let rs = match word { - b"ends_with" => literal == "\".rs\"", + // A suffix check alone may test a generated name; it counts when it selects files + // from a listing or the file's test code also reads a file. + b"ends_with" => literal == "\".rs\"" && (selects(m, at) || reads_files(file)), // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), @@ -3005,6 +3134,36 @@ fn reads_source_hits(file: &File) -> Vec { out } +/// Whether the call at `at` sits in the closure of a `filter`, `filter_map`, `find`, `any`, +/// `all`, `position` or `retain` call, which picks entries out of a listing. +fn selects(m: &[u8], at: usize) -> bool { + const PICKS: &[&[u8]] = &[b"filter", b"filter_map", b"find", b"find_map", b"any", b"all", b"position", b"retain"]; + m[..at].iter().enumerate().rev().filter(|&(_, &c)| c == b'(').find(|&(open, _)| matching(m, open).is_none_or(|close| close > at)).is_some_and( + |(open, _)| { + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + PICKS.contains(&&head[head.len() - name..]) + }, + ) +} + +/// Whether the test code of the file (the tests, and the test modules and helpers around them) +/// reads a file or lists a directory: a helper elsewhere in it may read what a test selects. +fn reads_files(file: &File) -> bool { + file.regions.iter().any(|&(from, to)| { + [&b"read_to_string"[..], b"read_to_end", b"read_dir", b"include_str", b"read", b"open"].iter().any(|w| { + words(&file.m, w, from, to).into_iter().any(|p| { + if *w == b"open" && !norm(&file.m[..p]).ends_with("File::") { + return false; + } + let next = skip_ws(&file.m, p + w.len()); + let next = if file.m.get(next) == Some(&b'!') { skip_ws(&file.m, next + 1) } else { next }; + file.m.get(next) == Some(&b'(') + }) + }) + }) +} + /// The last string literal in a (whitespace-free) expression, quotes included. fn last_literal(arg: &str) -> Option<&str> { let close = arg.rfind('"')?; @@ -3425,7 +3584,20 @@ fn cfgs_over(m: &[u8], src: &[u8], pos: usize) -> Vec<(String, usize)> { let enclosing = m[..at].iter().rposition(|&c| c == b'{'); enclosing.and_then(|o| matching(m, o).map(|c| (o, c))).unwrap_or((0, m.len())) } else { - let after = end + 1; + // Sibling attributes such as `#[test_case(1; "one")]` come before the item and may hold + // a `;`, so the scan for the body starts after them. + let mut after = end + 1; + loop { + let hash = skip_ws(m, after); + let open = skip_ws(m, hash + 1); + match (m.get(hash), m.get(open)) { + (Some(b'#'), Some(b'[')) => match matching(m, open) { + Some(close) => after = close + 1, + None => break, + }, + _ => break, + } + } let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; match (m[open], matching(m, open)) { (b'{', Some(close)) => (at, close), @@ -3462,6 +3634,48 @@ struct Loaded<'a> { chain: &'a [String], } +/// A `#[path]` declaration: the file `path` it loads, the file `parent` that declares it, and the +/// inline modules `chain` (outermost first) around the declaration. +struct PathLoad { + path: String, + parent: String, + chain: Vec, +} + +/// The `#[path]` declarations in `src`, the file `parent`. +fn path_loads(src: &str, parent: &str) -> Vec { + let m = mask(src); + words(&m, b"mod", 0, m.len()) + .into_iter() + .filter_map(|at| { + let start = skip_ws(&m, at + 3); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') { + return None; + } + let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let rel = path_attr(&m, src.as_bytes(), item, at)?; + let chain = inline_mods(&m, at); + Some(PathLoad { path: module_path(parent, &chain, &rel), parent: parent.to_owned(), chain }) + }) + .collect() +} + +/// The file a `#[path = "rel"]` declaration in `parent` loads: relative to the file's directory +/// outside inline modules, and inside them to the inline modules' directory under the file's +/// module. +fn module_path(parent: &str, chain: &[String], rel: &str) -> String { + let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); + let mut base = dir.to_owned(); + if !chain.is_empty() && !["mod.rs", "lib.rs", "main.rs"].contains(&file) { + base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); + } + for seg in chain { + base = join_path(&base, seg); + } + join_path(&base, rel) +} + /// The `cfg` predicates under which `src`, the file `parent`, loads `want`: those on the /// `mod ;` declarations that load it (by name, or through a `#[path]` override) and on the /// items, inline modules and file around them, with the 1-based lines of those declarations and @@ -3470,8 +3684,6 @@ struct Loaded<'a> { fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, Vec)> { let m = mask(src); let lines = Lines::new(src); - let (dir, file) = parent.rsplit_once('/').unwrap_or(("", parent)); - let mod_rs = ["mod.rs", "lib.rs", "main.rs"].contains(&file); let (mut each, mut at_lines) = (vec![], vec![]); for at in words(&m, b"mod", 0, m.len()) { let start = skip_ws(&m, at + 3); @@ -3484,14 +3696,7 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, Some(rel) => { // A `#[path]` outside inline modules is relative to the file's directory; inside them, // to the inline modules' directory under the file's module. - let mut base = dir.to_owned(); - if !want.chain.is_empty() && !mod_rs { - base = join_path(&base, file.strip_suffix(".rs").unwrap_or(file)); - } - for seg in want.chain { - base = join_path(&base, seg); - } - join_path(&base, &rel) == want.path + module_path(parent, want.chain, &rel) == want.path } None => &m[start..end] == want.name.as_bytes(), }; @@ -3566,7 +3771,7 @@ fn inline_mods(m: &[u8], at: usize) -> Vec { /// For each of `paths`, the `cfg` predicates on the `mod` declarations of its module and the /// modules above it, read through `read`. fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap> { - module_gates(paths, read).into_iter().map(|(p, g)| (p, g.preds)).collect() + module_gates(paths, read).into_iter().filter(|(_, g)| !g.preds.is_empty()).map(|(p, g)| (p, g.preds)).collect() } /// The `cfg` predicates a module file inherits ([`module_cfgs`]) and, for each file that declares @@ -3575,59 +3780,94 @@ fn module_cfgs(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashM struct Gates { preds: Vec, sources: Vec<(String, Vec)>, + /// No path from the file reaches a crate root: the file, or a file on every path above it, + /// is a module file that nothing found loads. + dead: bool, } /// [`Gates`] for each of `paths` that inherits a predicate. A file is looked up in the files that -/// may declare its module and, when none does, in the files above them through inline modules +/// may declare its module and in the files above them through inline modules /// (`mod platform { mod child; }` loads `platform/child.rs`). fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option) -> HashMap { + module_gates_from(paths, read, &[]) +} + +/// [`module_gates`], with the `#[path]` declarations in `loaders` as further ways in. +fn module_gates_from(paths: &[String], read: &dyn Fn(&str) -> Option, loaders: &[PathLoad]) -> HashMap { let mut out = HashMap::new(); for path in paths { - let (mut gates, mut at) = (Gates::default(), path.clone()); - 'up: for _ in 0..16 { - let Some((name, mut candidates)) = module_parent(&at) else { break }; - let name = name.to_owned(); - let file = at.rsplit_once('/').map_or(at.as_str(), |(_, f)| f); - let Some(mut module_dir) = (if file == "mod.rs" { - at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) - } else { - at.rsplit_once('/').map(|(d, _)| d.to_owned()) - }) else { - break; - }; - let mut chain: Vec = vec![]; - for _ in 0..4 { - let want = Loaded { path: &at, name: &name, chain: &chain }; - // Every file that loads the module is another way in (a library and a binary root - // can both load it): its tests are off only when every one of them leaves them out. - let found: Vec<_> = - candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f))).collect(); - if let Some(parent) = found.first().map(|(p, _)| p.clone()) { - if let [(_, (preds, _))] = found.as_slice() { - gates.preds.extend(preds.iter().cloned()); - } else { - let each: Vec = found.iter().map(|(_, (p, _))| format!("all({})", p.join(","))).collect(); - gates.preds.push(format!("any({})", each.join(","))); - } - gates.sources.extend(found.into_iter().map(|(p, (_, lines))| (p, lines))); - at = parent; - continue 'up; - } - let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break 'up }; - let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break 'up }; - chain.insert(0, seg); - candidates = next; - module_dir = up; - } - break; - } - if !gates.preds.is_empty() { + let gates = gates_of(path, read, loaders, 0); + // A file with sources and no predicate is still listed: a change to a file that loads it + // can take that route away. + if !gates.preds.is_empty() || !gates.sources.is_empty() || gates.dead { out.insert(path.clone(), gates); } } out } +/// [`Gates`] for the file `at`. Every file that loads the module is another way in (a library and +/// a binary root can both load it), and each is followed up to its crate root: the gates along one +/// path all apply, and the tests are off only when every path leaves them out. +fn gates_of(at: &str, read: &dyn Fn(&str) -> Option, loaders: &[PathLoad], depth: usize) -> Gates { + let none = Gates::default(); + if depth >= 16 { + return none; + } + let Some((name, mut candidates)) = module_parent(at) else { return none }; + let file = at.rsplit_once('/').map_or(at, |(_, f)| f); + let Some(mut module_dir) = (if file == "mod.rs" { + at.rsplit_once('/').and_then(|(d, _)| d.rsplit_once('/')).map(|(p, _)| p.to_owned()) + } else { + at.rsplit_once('/').map(|(d, _)| d.to_owned()) + }) else { + return none; + }; + let mut chain: Vec = vec![]; + let mut found = vec![]; + for loader in loaders.iter().filter(|l| l.path == at) { + let want = Loaded { path: at, name, chain: &loader.chain }; + if let Some(f) = read(&loader.parent).and_then(|s| declared_cfgs(&s, &loader.parent, &want)) { + found.push((loader.parent.clone(), f)); + } + } + for _ in 0..4 { + let want = Loaded { path: at, name, chain: &chain }; + found.extend(candidates.iter().filter_map(|c| read(c).and_then(|s| declared_cfgs(&s, c, &want)).map(|f| (c.clone(), f)))); + let Some((up, seg)) = module_dir.rsplit_once('/').map(|(u, s)| (u.to_owned(), s.to_owned())) else { break }; + let Some((_, next)) = module_parent(&format!("{module_dir}.rs")) else { break }; + chain.insert(0, seg); + candidates = next; + module_dir = up; + } + found.sort(); + found.dedup(); + let mut gates = Gates { dead: true, ..Gates::default() }; + let mut each: Vec> = vec![]; + let mut dead_each = vec![]; + for (parent, (mut preds, lines)) in found { + let up = gates_of(&parent, read, loaders, depth + 1); + gates.dead &= up.dead; + preds.extend(up.preds); + if up.dead { + dead_each.push(preds); + } else { + each.push(preds); + } + gates.sources.push((parent, lines)); + gates.sources.extend(up.sources); + } + if gates.dead { + each = dead_each; + } + gates.preds = match each.len() { + 0 => vec![], + 1 => each.pop().unwrap_or_default(), + _ => vec![format!("any({})", each.iter().map(|p| format!("all({})", p.join(","))).collect::>().join(","))], + }; + gates +} + /// A test that a `cfg` compiles out on every target CI runs tests on. fn never_run(v: &View, ctx: &Ctx) -> Option { let local = cfgs_over(&v.file.m, v.file.src, v.t.fn_at); @@ -3870,6 +4110,8 @@ mod tests { assert_eq!(census_in(inner, &ctx()), [(2, "census")], "a helper inside the predicate behind an || can be skipped"); let outer = "#[test]\nfn t() {\n assert!(verify_entry() || COLORS.iter().all(|c| c.is_some()));\n}\n"; assert_eq!(census_in(outer, &ctx()), [], "a helper on the left of an outer || always runs"); + let guarded = "#[test]\nfn t() {\n assert!((ready && verify_entry()) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(guarded, &ctx()), [(2, "census")], "a helper behind an && on the left is skipped when ready is false"); let in_message = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some(), \"{:?}\", verify_entry(c));\n }\n}\n"; assert_eq!(census_in(in_message, &ctx()), [(2, "census")], "a helper in a failure message runs only after a failure"); let first = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| verify_entry(c) || c.is_some()));\n}\n"; @@ -4940,6 +5182,32 @@ mod tests { assert_eq!(hits_in(SOURCE_AUDITS[0], bad, &ctx()), []); let data = "#[test]\nfn t() {\n let s = include_str!(\"fixtures/a.svg\");\n assert_eq!(s.len(), 4);\n}\n"; assert_eq!(hits(data), []); + let name = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", name), [], "a suffix check on a generated name"); + let read = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert!(fs::read_to_string(p).unwrap().contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", read), [(4, "reads-source")], "the test reads the file"); + let helper = "#[cfg(test)]\nmod tests {\n fn load(p: &Path) -> String {\n if p.ends_with(\".rs\") {\n return fs::read_to_string(p).unwrap();\n }\n String::new()\n }\n #[test]\n fn t() {\n assert_eq!(load(newest()), \"x\");\n }\n}\n"; + assert_eq!(only("reads-source", helper), [(4, "reads-source")], "a helper in the test module reads the file"); + let split = "#[test]\nfn t() {\n for p in listing() {\n if !p.ends_with(\".rs\") {\n continue;\n }\n assert_eq!(load(&p), \"x\");\n }\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", split), [(4, "reads-source")], "a separate test helper reads the file"); + } + + #[test] + fn sibling_attributes_do_not_end_the_cfg_scan() { + let case = "#[cfg(target_os = \"macos\")]\n#[test_case(1; \"one\")]\nfn t(n: u8) {\n assert_eq!(f(n), 1);\n}\n"; + assert_eq!(only("never-run", case), [(3, "never-run")]); + let bodyless = "#[cfg(target_os = \"macos\")]\nuse x::y;\n#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(only("never-run", bodyless), [], "a cfg on a bodyless item"); + } + + #[test] + fn same_named_tests_in_other_modules_are_compared_by_line() { + let src = "#[cfg(target_os = \"macos\")]\nmod mac {\n #[test]\n fn smoke() {\n assert_eq!(f(), 1);\n }\n}\nmod common {\n #[test]\n fn smoke() {\n assert_eq!(f(), 1);\n }\n}\n"; + let base = lint_file("crates/x/src/child.rs", src, &ctx()); + let gated = Ctx { module_cfgs: [("crates/x/src/child.rs".to_owned(), vec!["windows".to_owned()])].into_iter().collect(), ..ctx() }; + let head = lint_file("crates/x/src/child.rs", src, &gated); + let off: Vec = head.iter().filter(|h| h.rule == Rule::NeverRun && off_since(&base, h)).map(|h| h.line).collect(); + assert_eq!(off, [10], "common::smoke is newly off; mac::smoke was off before"); } #[test] @@ -5508,4 +5776,191 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } + + #[test] + fn each_loading_path_is_followed_to_its_root() { + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let run = |files: &[(&str, &str)]| { + let files: HashMap = files.iter().map(|(p, s)| ((*p).to_owned(), (*s).to_owned())).collect(); + let read = |p: &str| files.get(p).cloned(); + let ctx = Ctx { module_cfgs: module_cfgs(&["crates/x/src/a/child.rs".to_owned()], &read), ..ctx() }; + hits_in("crates/x/src/a/child.rs", test, &ctx).into_iter().filter(|h| h.1 == "never-run").count() + }; + // `a.rs` loads the child, and `lib.rs` and `main.rs` both load `a.rs`. + let open = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod a;\n"), + ("crates/x/src/main.rs", "mod a;\n"), + ("crates/x/src/a.rs", "mod child;\n"), + ]; + assert_eq!(run(&open), 0, "the ungated path through main.rs runs it"); + let shut = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod a;\n"), + ("crates/x/src/main.rs", "#[cfg(windows)]\nmod a;\n"), + ("crates/x/src/a.rs", "mod child;\n"), + ]; + assert_eq!(run(&shut), 1, "both paths are off"); + // `a/mod.rs` and the binary root `a/main.rs` both load the child; only `a/mod.rs` sits + // under a gate. + let second = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\nmod a;\n"), + ("crates/x/src/a/mod.rs", "mod child;\n"), + ("crates/x/src/a/main.rs", "mod child;\n"), + ]; + assert_eq!(run(&second), 0, "the first parent's ancestors do not gate the second path"); + } + + #[test] + fn a_base_parent_that_stopped_loading_a_child_is_listed() { + let files: HashMap<&str, &str> = [("crates/x/src/main.rs", "mod child;\n"), ("crates/x/src/child.rs", "")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let gates = module_gates(&["crates/x/src/child.rs".to_owned()], &read); + assert_eq!( + gates.get("crates/x/src/child.rs").map(|g| (g.preds.clone(), g.sources.len())), + Some((vec![], 1)), + "an ungated loader is still a source" + ); + let paths = ["crates/x/src/child.rs".to_owned()]; + let head = module_gates(&paths, &|_| Some(String::new())); + let cfgs = head_cfgs(&paths, &head, &gates, &|_| false); + assert_eq!(cfgs.get("crates/x/src/child.rs").map(Vec::as_slice), Some(&["any()".to_owned()][..]), "no file loads it any more"); + let ctx = Ctx { module_cfgs: cfgs, ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in("crates/x/src/child.rs", test, &ctx), [(2, "never-run")]); + assert_eq!(head_cfgs(&paths, &gates, &gates, &|_| false).get("crates/x/src/child.rs").map(Vec::len), Some(0), "still loaded"); + let kept = head_cfgs(&paths, &head, &gates, &|_| true); + assert!(kept.get("crates/x/src/child.rs").is_none_or(Vec::is_empty), "a `#[path]` elsewhere may load it"); + let tree = [("tests/it/main.rs".to_owned(), "#[path = \"../../crates/x/src/child.rs\"]\nmod child;\n".to_owned())]; + let read_tree = |p: &str| tree.iter().find(|(f, _)| f == p).map(|(_, s)| s.clone()); + let listed: Vec = tree.iter().map(|(f, _)| f.clone()).collect(); + let index = OnceCell::new(); + assert!(path_names(&index, &listed, &read_tree, "crates/x/src/child.rs")); + assert!(!path_names(&index, &listed, &read_tree, "crates/y/src/child.rs"), "a different file with the same basename"); + assert!(!path_names(&index, &listed, &read_tree, "crates/x/src/other.rs")); + } + + #[test] + fn a_child_whose_ancestor_is_no_longer_loaded_is_dead() { + let child = ["crates/x/src/a/child.rs".to_owned()]; + let base: HashMap<&str, &str> = [("crates/x/src/lib.rs", "mod a;\n"), ("crates/x/src/a.rs", "mod child;\n")].into_iter().collect(); + let head: HashMap<&str, &str> = [("crates/x/src/lib.rs", ""), ("crates/x/src/a.rs", "mod child;\n")].into_iter().collect(); + let base = module_gates(&child, &|p| base.get(p).map(|s| (*s).to_owned())); + let head = module_gates(&child, &|p| head.get(p).map(|s| (*s).to_owned())); + assert!(!base["crates/x/src/a/child.rs"].dead); + assert!(head["crates/x/src/a/child.rs"].dead, "a.rs still loads it, but nothing loads a.rs"); + assert_eq!(head_cfgs(&child, &head, &base, &|_| false).get("crates/x/src/a/child.rs").map(Vec::as_slice), Some(&["any()".to_owned()][..])); + } + + #[test] + fn removed_path_loaders_select_unchanged_siblings() { + let parent = "crates/x/src/retype.rs"; + let child = "crates/x/src/retype_tests.rs"; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let files = vec![child.to_owned()]; + let dirs = vec!["crates/x/src/retype/".to_owned()]; + for deleted in [false, true] { + let changed = if deleted { BTreeMap::new() } else { [(parent.to_owned(), None)].into_iter().collect() }; + for gate in ["", "#[cfg(target_os = \"macos\")]\n"] { + let source = format!("{gate}#[path = \"./retype_tests.rs\"]\nmod tests;\n"); + let base = [("crates/x/src/lib.rs", "mod retype;\n"), (parent, source.as_str())]; + let read_base = |p: &str| base.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let loaders = path_loads(&source, parent); + let below = unchanged_children(&files, &changed, &dirs, &loaders); + assert_eq!(below, files, "deleted={deleted}, gate={gate}"); + let base_gates = module_gates_from(&below, &read_base, &loaders); + assert!(base_gates[child].sources.iter().any(|(p, _)| p == parent)); + let head = module_gates(&below, &|_| None); + let head_ctx = Ctx { module_cfgs: head_cfgs(&below, &head, &base_gates, &|_| false), ..ctx() }; + let base_ctx = Ctx { module_cfgs: base_gates.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + let before = lint_file(child, test, &base_ctx); + let after = lint_file(child, test, &head_ctx); + let newly_off = after.iter().filter(|h| h.rule == Rule::NeverRun && off_since(&before, h)).count(); + assert_eq!(newly_off, usize::from(gate.is_empty()), "deleted={deleted}, gate={gate}"); + } + } + let inline = path_loads("mod inner { #[path = \"../inline_tests.rs\"] mod tests; }", parent); + assert_eq!(inline.iter().map(|l| l.path.as_str()).collect::>(), ["crates/x/src/retype/inline_tests.rs"]); + } + + /// Both unchanged targets of a chain of `#[path]` declarations are selected at the base. + #[test] + fn base_path_loaders_select_transitive_targets() { + let parent = "crates/x/src/retype.rs"; + let child = "crates/x/src/retype_installed.rs"; + let grandchild = "crates/x/src/retype_installed_tests.rs"; + let base = [ + (parent, "#[path = \"retype_installed.rs\"] mod installed;\n"), + (child, "#[path = \"retype_installed_tests.rs\"] mod tests;\n"), + (grandchild, "#[path = \"retype.rs\"] mod parent;\n"), + ]; + let reads = RefCell::new(Vec::new()); + let read_base = |p: &str| { + reads.borrow_mut().push(p.to_owned()); + base.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()) + }; + let loaders = base_path_loads(&[parent.to_owned()], &read_base); + let files = vec![child.to_owned(), grandchild.to_owned()]; + let changed = [(parent.to_owned(), None)].into_iter().collect(); + assert_eq!(unchanged_children(&files, &changed, &[], &loaders), files); + assert_eq!(*reads.borrow(), [parent, child, grandchild], "a cycle does not read a target again"); + } + + #[test] + fn dead_routes_do_not_enable_a_gated_live_route() { + let files = [ + ("crates/x/src/lib.rs", "#[cfg(target_os = \"macos\")]\n#[path = \"a.rs\"]\nmod a;\n"), + ("crates/x/src/a.rs", "mod child;\n"), + ("crates/x/src/a/mod.rs", "mod child;\n"), + ]; + let read = |p: &str| files.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let path = "crates/x/src/a/child.rs"; + let ctx = Ctx { module_cfgs: module_cfgs(&[path.to_owned()], &read), ..ctx() }; + assert_eq!(hits_in(path, "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n", &ctx), [(2, "never-run")]); + } + + #[test] + fn inline_routes_are_checked_alongside_file_parents() { + let path = "crates/x/src/a/child.rs"; + for gate in ["", "#[cfg(target_os = \"macos\")]\n"] { + let root = format!("{gate}mod a {{ mod child; }}\n"); + let files = [("crates/x/src/lib.rs", root.as_str()), ("crates/x/src/a.rs", "mod child;\n")]; + let read = |p: &str| files.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let gates = module_gates(&[path.to_owned()], &read); + assert!(!gates[path].dead, "{gate}"); + let ctx = Ctx { module_cfgs: gates.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + let hits = hits_in(path, "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n", &ctx); + assert_eq!(hits.iter().filter(|h| h.1 == "never-run").count(), usize::from(!gate.is_empty()), "{gate}"); + } + } + + #[test] + fn suffix_selected_source_reads_include_streams() { + for read in ["File::open(p)", "File :: open(p)", "reader.read_to_end(&mut bytes)", "reader.read_to_string(&mut text)", "fs::read(p)"] { + let src = format!( + "#[test]\nfn t() {{\n let p = newest();\n if p.ends_with(\".rs\") {{\n let got = {read};\n assert_eq!(check(got), 1);\n }}\n}}\n" + ); + assert_eq!(only("reads-source", &src), [(4, "reads-source")], "{read}"); + assert_eq!(only("reads-source", &src.replace(".rs", ".svg")), [], "{read}"); + } + let name = "#[test]\nfn t() {\n let p = newest();\n assert_eq!(p.ends_with(\".rs\"), wanted());\n}\n"; + assert_eq!(only("reads-source", name), []); + } + + #[test] + fn path_names_reuses_a_lazy_workspace_index() { + let files = vec!["src/lib.rs".to_owned(), "src/other.rs".to_owned()]; + let reads = RefCell::new(Vec::new()); + let read = |p: &str| { + reads.borrow_mut().push(p.to_owned()); + Some("#[path = \"nested/child.rs\"] mod child;\n".to_owned()) + }; + let index = OnceCell::new(); + assert!(reads.borrow().is_empty()); + assert!(path_names(&index, &files, &read, "src/nested/child.rs")); + assert!(!path_names(&index, &files, &read, "src/child.rs"), "a different file with the same basename"); + assert!(!path_names(&index, &files, &read, "src/missing.rs")); + assert!(!path_names(&index, &files, &read, "src/other.rs")); + assert_eq!(*reads.borrow(), files); + let own = OnceCell::new(); + assert!(!path_names(&own, &["src/child.rs".to_owned()], &read, "src/child.rs")); + } } From 3026e08314d433a6b376f8808337ba9520defb3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:30:12 -0800 Subject: [PATCH 11/32] Step and Repeat: refuse a grid whose copies would hold too many objects The 10,000-cell limit did not count the artwork in each cell, so a large selection repeated over many cells had no bound on the objects it made. The command now also refuses a grid whose new copies would hold more than 250,000 objects, counting the art of opacity masks and the group a multi-object selection goes into. --- crates/engine/src/cmd/stepandrepeat.rs | 10 +++++++++- crates/engine/src/cmd/stepandrepeat/tests.rs | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/stepandrepeat.rs b/crates/engine/src/cmd/stepandrepeat.rs index bf15cc340e..16684a3284 100644 --- a/crates/engine/src/cmd/stepandrepeat.rs +++ b/crates/engine/src/cmd/stepandrepeat.rs @@ -12,6 +12,8 @@ use vectorcraft_doc::{Node, Scaling}; const CMD: &str = "object.stepAndRepeat"; const MAX_CELLS: usize = 10_000; +/// The most objects the copies may hold in all, counting every object inside each copy. +const MAX_COPIED_OBJECTS: usize = 250_000; const EPS: f64 = 1e-9; pub fn specs() -> Vec { @@ -20,7 +22,7 @@ pub fn specs() -> Vec { "Step and Repeat…", ["Object", "Transform"], None, - "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", + "{rows?: n (default 1), columns?: n (default 1), fill?: bool (rows and columns are as many as fit the sheet, ignoring `rows` and `columns`; the first copy goes to the sheet's top-left corner plus `margin`), sheet?: {x, y, width, height} (pt; default the artboard that holds the selection's center, else the first), margin?: pt (fill only, default 0, not negative), gap?: pt (between neighbors, both axes), gapX?: pt, gapY?: pt (default `gap`, default 0; measured between the bounds of `cutId`, else of the selection, not between centers; a negative gap overlaps neighbors and must be smaller than the width or height it is between), cutId?: id (a selected object whose geometric bounds measure the spacing and the 180° turn; default the selection), rotate?: \"none\"|\"columns\"|\"rows\" (turn every other column or row by 180° about its cell's center, the same clockwise or counter-clockwise; default none), patterns?: bool} copy the selection into a grid of cells, left to right and top to bottom, the first cell being the selection itself (moved to the sheet's corner with fill); copies of pixel-aligned objects stay on the pixel grid, so a fractional gap between them is rounded to it, and gaps of other objects are exact; a selection of several objects is grouped first, so that a cut contour stays with its artwork in every copy; a grid of more than 10,000 cells, or one whose new copies (every cell but the first) would hold more than 250,000 objects in all (the art of opacity masks and the group of a multi-object selection counted), is refused; one undo step; the copies are selected → {ids: [id…], rows, columns, count}", has_selection, step_and_repeat )] @@ -174,6 +176,12 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { if rows.saturating_mul(cols) > MAX_CELLS { return Err(bad(CMD, format!("more than {MAX_CELLS} copies"))); } + // Each copy holds every object of the selection, the art of opacity masks included, and the + // group that a selection of several objects goes into. + let objects = roots.iter().filter_map(|r| d.node(*r)).fold(usize::from(roots.len() > 1), |sum, n| sum.saturating_add(n.count_with_masks())); + if objects.saturating_mul(rows * cols - 1) > MAX_COPIED_OBJECTS { + return Err(bad(CMD, format!("the copies would hold more than {MAX_COPIED_OBJECTS} objects"))); + } let origin = anchor.map_or(Vec2::ZERO, |(sh, m)| Vec2::new(sh.x0 + m - b.x0, sh.y0 + m - b.y0)); let cells = layout(w, h, gx, gy, rows, cols, alt); let center = b.center().to_vec2(); diff --git a/crates/engine/src/cmd/stepandrepeat/tests.rs b/crates/engine/src/cmd/stepandrepeat/tests.rs index 4d807f7d8d..133d79ff48 100644 --- a/crates/engine/src/cmd/stepandrepeat/tests.rs +++ b/crates/engine/src/cmd/stepandrepeat/tests.rs @@ -131,6 +131,21 @@ fn rejects_bad_params_and_a_selection_that_does_not_fit() { assert!(e.execute(CMD, &json!({})).is_err()); } +#[test] +fn rejects_a_grid_whose_copies_would_hold_too_many_objects() { + let (mut s, _) = setup(); + for i in 1..25 { + s.execute("shape.rectangle", &json!({"x": i, "y": 0, "width": 10, "height": 10})).unwrap(); + } + s.execute("select.all", &json!({})).unwrap(); + let (count, steps) = (s.doc().unwrap().doc.node_count(), undo_steps(&s)); + // 25 objects and the group they go into, in each of 9,999 copies, are more than the limit, + // though the cells are not. + let e = s.execute(CMD, &json!({"rows": 100, "columns": 100})).unwrap_err(); + assert!(e.to_string().contains("objects"), "{e}"); + assert_eq!((s.doc().unwrap().doc.node_count(), undo_steps(&s)), (count, steps)); +} + #[test] fn rejects_a_negative_margin_and_gaps_that_fold_the_grid_back() { let (mut s, _) = setup(); From 6598763bfc09bdce631c516a5314da1554715180 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 07:42:41 -0800 Subject: [PATCH 12/32] xtask: test-lint follows path targets' children, head path gates and inline path dirs - Files in the directory of a `#[path]` target are checked with it, so a plain `mod child;` under the target is not missed when the declaration is removed. - A helper inside one arm of an `if` or `match` on the left of `||` no longer counts as always called; only the condition does. - A `.ends_with(".rs")` check counts as reading source only when the checked name is passed to a file read (directly, through a helper, or by a stream read in the same test), or when it filters an iterator over a file listing. A predicate over generated names is not reported. - An inline module's `#[path]` sets the directory of the declarations inside it. - Scoped and `--all` runs pass the head's `#[path]` declarations into gate evaluation, so a `cfg` added to one gates its target. --- xtask/src/test_lint.rs | 175 +++++++++++++++++++++++++++++++++++------ 1 file changed, 149 insertions(+), 26 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 2644bf2044..a9f4b50819 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -283,7 +283,13 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); if opts.all { let sources = read_all(root, &files)?; - let module_cfgs = module_cfgs(&files, &|p| read_small(root, p)); + // Every `#[path]` declaration is another way in, so its `cfg` gates the file it loads. + let loaders: Vec = sources.iter().flat_map(|(p, s)| path_loads(s, p)).collect(); + let module_cfgs = module_gates_from(&files, &|p| read_small(root, p), &loaders) + .into_iter() + .filter(|(_, g)| !g.preds.is_empty()) + .map(|(p, g)| (p, g.preds)) + .collect(); let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env, module_cfgs }; let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); print!("{}", report(&hits, sources.len())); @@ -328,7 +334,9 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { let loaders = base_path_loads(&present.iter().chain(&deleted).cloned().collect::>(), &read_base); let below = unchanged_children(&files, &changed, &module_dirs, &loaders); let gated: Vec = present.iter().chain(&below).cloned().collect(); - let gates = module_gates(&gated, &|p| read_small(root, p)); + // The head's `#[path]` declarations reachable from the changed files gate their targets too. + let head_loaders = base_path_loads(&present.iter().cloned().collect::>(), &|p| read_small(root, p)); + let gates = module_gates_from(&gated, &|p| read_small(root, p), &head_loaders); let base_gates = module_gates_from(&gated, &read_base, &loaders); // A changed or deleted file that loaded a child at the base may have stopped loading it, which // the head's gates do not show; the base comparison below still drops a test that was already @@ -428,16 +436,21 @@ fn base_path_loads(paths: &[String], read: &dyn Fn(&str) -> Option) -> V } /// The unchanged files whose tests a changed or deleted file can turn off: those under one of -/// `module_dirs`, and those a `#[path]` declaration in `loaders` loaded at the base. +/// `module_dirs`, those a `#[path]` declaration in `loaders` loaded at the base, and those in the +/// directory of such a file, where its own `mod` declarations load their children. fn unchanged_children( files: &[String], changed: &BTreeMap>>, module_dirs: &[String], loaders: &[PathLoad], ) -> Vec { + let load_dirs: Vec = loaders.iter().filter_map(|l| l.path.rsplit_once('/').map(|(dir, _)| format!("{dir}/"))).collect(); files .iter() - .filter(|p| !changed.contains_key(*p) && (module_dirs.iter().any(|d| p.starts_with(d.as_str())) || loaders.iter().any(|l| l.path == **p))) + .filter(|p| { + !changed.contains_key(*p) + && (module_dirs.iter().chain(&load_dirs).any(|d| p.starts_with(d.as_str())) || loaders.iter().any(|l| l.path == **p)) + }) .cloned() .collect() } @@ -1619,6 +1632,10 @@ fn always_calls(s: &str, helpers: &[String], depth: usize) -> bool { always_calls(&s[1..s.len() - 1], helpers, depth + 1) } else if let Some(at) = top_level_at(s, "||").first().copied().or_else(|| top_level_at(s, "&&").first().copied()) { always_calls(&s[..at], helpers, depth + 1) + } else if let Some(&at) = top_level_at(s, "{").first() { + // An `if` or `match` always runs only its condition or scrutinee, the text before its + // first block; a call inside one arm may be skipped. + always_calls(&s[..at], helpers, depth + 1) } else { calls_any(s, helpers) } @@ -3135,8 +3152,8 @@ fn reads_source_hits(file: &File) -> Vec { let literal = raw.unwrap_or(&arg); let rs = match word { // A suffix check alone may test a generated name; it counts when it selects files - // from a listing or the file's test code also reads a file. - b"ends_with" => literal == "\".rs\"" && (selects(m, at) || reads_files(file)), + // from a listing or the checked path is passed to a file read. + b"ends_with" => literal == "\".rs\"" && (selects(m, at) || reads_checked(file, at)), // The last path literal in the argument names the file read: `root.join("src/lib.rs")`, // `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`. b"read_to_string" => last_literal(&arg).is_some_and(|l| l.ends_with(".rs\"")), @@ -3154,32 +3171,92 @@ fn reads_source_hits(file: &File) -> Vec { } /// Whether the call at `at` sits in the closure of a `filter`, `filter_map`, `find`, `any`, -/// `all`, `position` or `retain` call, which picks entries out of a listing. +/// `all`, `position` or `retain` call on an iterator whose chain names a listing (`read_dir`, `files`, +/// `listing`, `walk` and the like), which picks entries out of the listing. fn selects(m: &[u8], at: usize) -> bool { const PICKS: &[&[u8]] = &[b"filter", b"filter_map", b"find", b"find_map", b"any", b"all", b"position", b"retain"]; + const LISTINGS: &[&str] = &["read_dir", "files", "listing", "walk", "walkdir", "glob", "entries", "paths", "sources"]; m[..at].iter().enumerate().rev().filter(|&(_, &c)| c == b'(').find(|&(open, _)| matching(m, open).is_none_or(|close| close > at)).is_some_and( |(open, _)| { let head = m[..open].trim_ascii_end(); let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); - PICKS.contains(&&head[head.len() - name..]) + if !PICKS.contains(&&head[head.len() - name..]) { + return false; + } + // The receiver chain: back from the pick to the start of its statement. + let start = head[..head.len() - name].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}' | b'=')).map_or(0, |p| p + 1); + let chain = String::from_utf8_lossy(&head[start..head.len() - name]); + chain.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(|w| LISTINGS.iter().any(|l| w == *l || w.ends_with(&format!("_{l}")))) }, ) } -/// Whether the test code of the file (the tests, and the test modules and helpers around them) -/// reads a file or lists a directory: a helper elsewhere in it may read what a test selects. -fn reads_files(file: &File) -> bool { - file.regions.iter().any(|&(from, to)| { - [&b"read_to_string"[..], b"read_to_end", b"read_dir", b"include_str", b"read", b"open"].iter().any(|w| { - words(&file.m, w, from, to).into_iter().any(|p| { - if *w == b"open" && !norm(&file.m[..p]).ends_with("File::") { - return false; +/// The reading calls whose argument names the file read. +const READS: &[&[u8]] = &[b"read_to_string", b"read_to_end", b"read_dir", b"include_str", b"read", b"open"]; + +/// The argument spans `(open, close)` of the reading calls in the test code of the file (the tests, +/// and the test modules and helpers around them). +fn read_calls(file: &File) -> Vec<(usize, usize)> { + let m = &file.m; + let mut out = vec![]; + for &(from, to) in &file.regions { + for w in READS { + for p in words(m, w, from, to) { + if *w == b"open" && !norm(&m[..p]).ends_with("File::") { + continue; } - let next = skip_ws(&file.m, p + w.len()); - let next = if file.m.get(next) == Some(&b'!') { skip_ws(&file.m, next + 1) } else { next }; - file.m.get(next) == Some(&b'(') + let next = skip_ws(m, p + w.len()); + let next = if m.get(next) == Some(&b'!') { skip_ws(m, next + 1) } else { next }; + if m.get(next) == Some(&b'(') + && let Some(close) = matching(m, next) + { + out.push((next, close)); + } + } + } + } + out +} + +/// Whether the path checked by the `.ends_with` at `at` is read: its receiver, a plain name, is an +/// argument of a reading call, or of a call to a function in the file whose body reads a file. +fn reads_checked(file: &File, at: usize) -> bool { + let m = &file.m; + let before = m[..at].trim_ascii_end(); + let Some(dot) = before.strip_suffix(b".") else { return false }; + let dot = dot.trim_ascii_end(); + let len = dot.iter().rev().take_while(|&&c| is_ident(c)).count(); + let recv = &dot[dot.len() - len..]; + // A call, an index or a field chain is not a plain name: its value cannot be followed. + if len == 0 || recv[0].is_ascii_digit() || dot[..dot.len() - len].trim_ascii_end().ends_with(b".") { + return false; + } + let reads = read_calls(file); + let passes = |open: usize, close: usize| !words(m, recv, open + 1, close).is_empty(); + // A stream method such as `reader.read_to_end(…)` takes a buffer, not the path: it counts when + // it reads in the same test as the check. + let region = file.regions.iter().find(|&&(from, to)| from <= at && at < to); + let streams = + |open: usize| m[..open].trim_ascii_end().iter().rev().skip_while(|&&c| is_ident(c)).find(|c| !c.is_ascii_whitespace()) == Some(&b'.'); + if reads.iter().any(|&(open, close)| passes(open, close) || streams(open) && region.is_some_and(|&(from, to)| from <= open && open < to)) { + return true; + } + // Functions whose body holds a reading call, called with the checked name. + words(m, b"fn", 0, m.len()).into_iter().any(|f| { + let name_at = skip_ws(m, f + 2); + let name_len = m[name_at..].iter().take_while(|&&c| is_ident(c)).count(); + let Some(body) = m[name_at..].iter().position(|&c| c == b'{' || c == b';').map(|p| name_at + p).filter(|&b| m[b] == b'{') else { + return false; + }; + let Some(end) = matching(m, body) else { return false }; + name_len > 0 + && reads.iter().any(|&(open, _)| open > body && open < end) + && file.regions.iter().any(|&(from, to)| { + words(m, &m[name_at..name_at + name_len], from, to).into_iter().any(|c| { + let open = skip_ws(m, c + name_len); + c != name_at && m.get(open) == Some(&b'(') && matching(m, open).is_some_and(|close| passes(open, close)) + }) }) - }) }) } @@ -3674,7 +3751,7 @@ fn path_loads(src: &str, parent: &str) -> Vec { } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); let rel = path_attr(&m, src.as_bytes(), item, at)?; - let chain = inline_mods(&m, at); + let chain = inline_mods(&m, src.as_bytes(), at); Some(PathLoad { path: module_path(parent, &chain, &rel), parent: parent.to_owned(), chain }) }) .collect() @@ -3707,7 +3784,7 @@ fn declared_cfgs(src: &str, parent: &str, want: &Loaded) -> Option<(Vec, for at in words(&m, b"mod", 0, m.len()) { let start = skip_ws(&m, at + 3); let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); - if end == start || m.get(skip_ws(&m, end)) != Some(&b';') || inline_mods(&m, at) != want.chain { + if end == start || m.get(skip_ws(&m, end)) != Some(&b';') || inline_mods(&m, src.as_bytes(), at) != want.chain { continue; } let item = m[..at].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); @@ -3771,8 +3848,10 @@ fn join_path(base: &str, rel: &str) -> String { } /// The names of the inline `mod { … }` blocks around `at` in the masked text `m`, outermost -/// first. A `mod x;` inside them loads a file under their directory instead of a sibling file. -fn inline_mods(m: &[u8], at: usize) -> Vec { +/// first. A `mod x;` inside them loads a file under their directory instead of a sibling file. An +/// inline module with a `#[path = "dir"]` attribute gives `dir`, the directory it sets, in place of +/// its name. +fn inline_mods(m: &[u8], src: &[u8], at: usize) -> Vec { m[..at] .iter() .enumerate() @@ -3781,8 +3860,12 @@ fn inline_mods(m: &[u8], at: usize) -> Vec { let head = m[..open].trim_ascii_end(); let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); let before = head[..head.len() - name].trim_ascii_end(); - (name > 0 && before.ends_with(b"mod") && !before[..before.len() - 3].last().copied().is_some_and(is_ident)) - .then(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned()) + if name == 0 || !before.ends_with(b"mod") || before[..before.len() - 3].last().copied().is_some_and(is_ident) { + return None; + } + let kw = before.len() - 3; + let item = m[..kw].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + Some(path_attr(m, src, item, kw).unwrap_or_else(|| String::from_utf8_lossy(&head[head.len() - name..]).into_owned())) }) .collect() } @@ -4155,6 +4238,8 @@ mod tests { assert_eq!(census_in(outer, &ctx()), [], "a helper on the left of an outer || always runs"); let guarded = "#[test]\nfn t() {\n assert!((ready && verify_entry()) || COLORS.iter().all(|c| c.is_some()));\n}\n"; assert_eq!(census_in(guarded, &ctx()), [(2, "census")], "a helper behind an && on the left is skipped when ready is false"); + let arm = "#[test]\nfn t() {\n assert!((if ready { verify_entry() } else { false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(arm, &ctx()), [(2, "census")], "a helper in one arm of an if on the left is skipped when ready is false"); let in_message = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some(), \"{:?}\", verify_entry(c));\n }\n}\n"; assert_eq!(census_in(in_message, &ctx()), [(2, "census")], "a helper in a failure message runs only after a failure"); let first = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| verify_entry(c) || c.is_some()));\n}\n"; @@ -5237,6 +5322,10 @@ mod tests { assert_eq!(hits(data), []); let name = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n"; assert_eq!(only("reads-source", name), [], "a suffix check on a generated name"); + let other_read = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n#[test]\nfn u() {\n assert!(fs::read_to_string(\"data.json\").unwrap().contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", other_read), [], "another test reads a file the suffix check did not name"); + let names = "#[test]\nfn t() {\n assert!(generated_names().iter().all(|name| name.ends_with(\".rs\")));\n}\n"; + assert_eq!(only("reads-source", names), [], "a suffix predicate over generated names"); let read = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert!(fs::read_to_string(p).unwrap().contains(\"x\"));\n}\n"; assert_eq!(only("reads-source", read), [(4, "reads-source")], "the test reads the file"); let helper = "#[cfg(test)]\nmod tests {\n fn load(p: &Path) -> String {\n if p.ends_with(\".rs\") {\n return fs::read_to_string(p).unwrap();\n }\n String::new()\n }\n #[test]\n fn t() {\n assert_eq!(load(newest()), \"x\");\n }\n}\n"; @@ -5957,6 +6046,40 @@ mod tests { assert_eq!(*reads.borrow(), [parent, child, grandchild], "a cycle does not read a target again"); } + /// A file that a `#[path]` target loads with a plain `mod` is selected with the target. + #[test] + fn base_path_loaders_select_plain_children_of_targets() { + let parent = "crates/x/src/platform.rs"; + let loaders = path_loads("#[path = \"backend/mod.rs\"]\nmod backend;\n", parent); + let files = vec!["crates/x/src/backend/mod.rs".to_owned(), "crates/x/src/backend/child.rs".to_owned()]; + let changed = [(parent.to_owned(), None)].into_iter().collect(); + assert_eq!(unchanged_children(&files, &changed, &[], &loaders), files); + } + + /// A `#[path]` on an enclosing inline module sets the directory of the declarations inside it. + #[test] + fn inline_path_overrides_set_the_directory() { + let loads = path_loads("#[path = \".\"]\nmod wrapper {\n #[path = \"child.rs\"]\n mod inner;\n}\n", "crates/x/src/lib.rs"); + assert_eq!(loads.iter().map(|l| l.path.as_str()).collect::>(), ["crates/x/src/child.rs"]); + } + + /// A `cfg` on the head's `#[path]` declaration gates the file it loads, unless another route runs. + #[test] + fn head_path_loaders_gate_their_targets() { + let parent = "crates/x/src/platform.rs"; + let child = "crates/x/src/backend_tests.rs"; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + for (extra, off) in [("", true), ("#[path = \"backend_tests.rs\"]\nmod also;\n", false)] { + let lib = format!("mod platform;\n{extra}"); + let files = [("crates/x/src/lib.rs", lib.as_str()), (parent, "#[cfg(windows)]\n#[path = \"backend_tests.rs\"]\nmod tests;\n")]; + let read = |p: &str| files.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let loaders = base_path_loads(&["crates/x/src/lib.rs".to_owned(), parent.to_owned()], &read); + let gates = module_gates_from(&[child.to_owned()], &read, &loaders); + let ctx = Ctx { module_cfgs: gates.into_iter().map(|(p, g)| (p, g.preds)).collect(), ..ctx() }; + assert_eq!(hits_in(child, test, &ctx).iter().any(|h| h.1 == "never-run"), off, "{extra}"); + } + } + #[test] fn dead_routes_do_not_enable_a_gated_live_route() { let files = [ From c683302d4e3c11fe2c373c3746ad9aed8a8f5bb0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:00:09 -0800 Subject: [PATCH 13/32] Text Wrap: Make's no-type warning checks the wrap objects without copying their shapes Make Text Wrap called wrap_sources to learn whether a new wrap object sits above area type, which copied every wrap shape of every area text object in the document into text space and threw the copies away. wrap_source_objects gives the same text objects and wrap objects without making those copies, and Make uses it. --- crates/doc/src/text.rs | 2 +- crates/doc/src/text/tests.rs | 9 +++++++++ crates/doc/src/text/wrap.rs | 16 ++++++++++++++++ crates/engine/src/cmd/textwrap.rs | 2 +- 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 073a0f2efd..7ba5cb6199 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -44,7 +44,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_sources, wrap_work}; +pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_source_objects, wrap_sources, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 9371947565..8a17fd880b 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -695,6 +695,15 @@ fn a_wrap_object_below_every_area_type_object_makes_no_outline() { }); assert_eq!(sources, 1); assert_eq!(wrap::OUTLINES_MADE.with(|c| c.get()), 1, "only the wrap object above the type is outlined"); + // The objects alone come without a copy of any shape into text space. + let mut found = vec![]; + wrap_source_objects(&d, |n, objects| found.push((n.id, objects.iter().map(|o| o.id).collect::>()))); + let mut expected = vec![]; + wrap_sources(&d, |n, objects, _| expected.push((n.id, objects.iter().map(|o| o.id).collect::>()))); + assert_eq!(found, expected); + wrap::SHAPES_COPIED.with(|c| c.set(0)); + wrap_source_objects(&d, |_, _| {}); + assert_eq!(wrap::SHAPES_COPIED.with(|c| c.get()), 0, "no wrap shape is copied"); } #[test] diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 33fdcb4687..2061de7092 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -11,6 +11,8 @@ use crate::{Document, Node, NodeId, NodeKind}; thread_local! { /// How many wrap outlines [`each_text`] has made on this thread (for tests). pub(super) static OUTLINES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many wrap shapes [`shapes_of`] has copied into text space on this thread (for tests). + pub(super) static SHAPES_COPIED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Outline of a wrap object in document coordinates: its paths, or its bounds for other art. @@ -167,6 +169,8 @@ fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec { .iter() .rev() .map(|(_, s)| { + #[cfg(test)] + SHAPES_COPIED.with(|c| c.set(c.get() + 1)); let mut path = s.path.clone(); path.transform(inv); WrapShape { path, wrap: s.wrap } @@ -189,6 +193,18 @@ pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a N } } +/// [`wrap_sources`] without the shapes: each area text object that gets wrap shapes, with the wrap +/// objects whose outlines make them, bottom first. No shape is copied into text space. +pub fn wrap_source_objects<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>)) { + for layer in &doc.layers { + each_text(layer, |n, above| { + if matches!(n.kind, NodeKind::Text(_)) && !above.is_empty() { + f(n, above.iter().rev().map(|(s, _)| *s).collect()); + } + }); + } +} + /// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the /// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged /// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes diff --git a/crates/engine/src/cmd/textwrap.rs b/crates/engine/src/cmd/textwrap.rs index ade875b4c9..6daa8cdd26 100644 --- a/crates/engine/src/cmd/textwrap.rs +++ b/crates/engine/src/cmd/textwrap.rs @@ -115,7 +115,7 @@ fn make(s: &mut Session, p: &Value) -> Result { } let mut out = json!({ "ids": objects.iter().map(|i| i.0).collect::>() }); let mut wraps = false; - vectorcraft_doc::text::wrap_sources(&s.doc()?.doc, |_, sources, _| wraps |= sources.iter().any(|n| objects.contains(&n.id))); + vectorcraft_doc::text::wrap_source_objects(&s.doc()?.doc, |_, sources| wraps |= sources.iter().any(|n| objects.contains(&n.id))); if !wraps { out["warning"] = json!(NO_AREA_TYPE_BELOW); } From f01f2ce6c0ee1a8223e37bf8c95e3d6ab93d0574 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:26:04 -0800 Subject: [PATCH 14/32] Fix #10463: $.evalFile reads File URI paths File.parent gives a folder in URI notation (/c/Users/..., with %20 for a space). $.evalFile joined that text to the script's folder as written, so on Windows $.evalFile(File($.fileName).parent + '/more.jsx') looked under C:\c\Users\... and reported "include file not found". When an absolute path starting with one / names no file the script may read, $.evalFile now also tries it with its escapes decoded and, on Windows, with /c/... as the drive C:. The path as written is still tried first, and the scope check, the .. refusal and the file limits apply to every form. Share and device paths are not converted, and #include lines are read as before. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/files.rs | 2 +- crates/engine/src/script/include.rs | 49 ++++++++++++++++++++++++--- crates/engine/src/tests/script_run.rs | 34 +++++++++++++++++++ docs/mcp.md | 4 ++- docs/target-app-parity.md | 2 +- 6 files changed, 85 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 6ad6c51d8f..37a661dfcb 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a script file (.js, .mjs or .jsx) | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), an absolute path in a File's URI notation is read too, with escapes decoded and /c/... naming drive C: on Windows, $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog; app.undo() and app.redo() undo and redo the run's own edits in the active document, change nothing when the run has no such step, and throw No active document with no document open. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 1cded460ab..85c01d6a74 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1352,7 +1352,7 @@ fn encode(s: &str) -> String { } /// `s` with its `%xx` escapes read as UTF-8 bytes; `s` as it is when they do not make UTF-8. -fn decode(s: &str) -> String { +pub(crate) fn decode(s: &str) -> String { let b = s.as_bytes(); let mut out = Vec::with_capacity(b.len()); let mut i = 0; diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index acaee51910..058d37f35b 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -359,6 +359,32 @@ fn has_parent(p: &str) -> bool { p.split(['/', '\\']).any(|name| name == "..") } +/// The paths `value` can name in a `File`'s URI notation, as `File.parent` and `File.fullName` give +/// them, other than `value` as written: on a platform that reads drive letters (`windows`), `/c/…` +/// is the drive path `C:/…`, and on every platform `%20` and the other escapes are decoded. Only a +/// path that starts with one `/` has them; `$.evalFile` tries them after `value` as written +/// misses. A `//host/share` path, and a form with a `..` name, is left out. +pub fn uri_forms(value: &str, windows: bool) -> Vec { + if !value.starts_with('/') || value.starts_with("//") { + return Vec::new(); + } + let drive = value.strip_prefix('/').filter(|_| windows && !value.starts_with("//")).and_then(|rest| { + let (first, after) = rest.split_once('/').unwrap_or((rest, "")); + let letter = first.as_bytes(); + (letter.len() == 1 && letter[0].is_ascii_alphabetic()).then(|| format!("{}:/{after}", letter[0].to_ascii_uppercase() as char)) + }); + let mut forms = Vec::new(); + for form in drive.iter().map(String::as_str).chain(drive.is_none().then_some(value)) { + let decoded = crate::script::files::decode(form); + for f in [decoded.as_str(), form] { + if f != value && !has_parent(f) && !(windows && f.replace('\\', "/").starts_with("//")) && !forms.iter().any(|g| g == f) { + forms.push(f.to_string()); + } + } + } + forms +} + /// A real path as people read it. fn display(path: &Path) -> Arc { Arc::from(crate::cmd::findfiles::plain(path.to_path_buf()).to_string_lossy().as_ref()) @@ -575,13 +601,18 @@ impl Files { let refused = || (FailKind::Error, format!("script file read refused: {value}")); // A script given as text has no folder, and so no file it may read. let Some(dir) = dir.filter(|_| !has_parent(value)) else { return Err(refused()) }; - // Each candidate, and whether the scope's refusal passes it over. - let mut candidates: Vec<(Option, bool)> = vec![(Some(dir.join(path)), false)]; + // Each candidate, and whether the scope's refusal passes it over. The path as written comes + // first; for `$.evalFile` only, when it misses, fails or is refused, the forms of a path in + // URI notation are tried, and when none of them is read either, the error of the path as written stands. + let forms = if search { Vec::new() } else { uri_forms(value, cfg!(windows)) }; + let mut literal_error = None; + let mut candidates: Vec<(Option, bool)> = vec![(Some(dir.join(path)), !forms.is_empty())]; + candidates.extend(forms.into_iter().map(|f| (Some(dir.join(f)), true))); if search && !path.is_absolute() { candidates.extend(self.include_path.iter().map(|p| ((!has_parent(p)).then(|| dir.join(p).join(path)), false))); candidates.extend(self.jsinclude.iter().filter(|p| p.is_absolute()).map(|p| (Some(p.join(path)), true))); } - for (candidate, passed_over_when_refused) in candidates { + for (i, (candidate, passed_over_when_refused)) in candidates.into_iter().enumerate() { let Some(candidate) = candidate else { return Err(refused()) }; self.probes += 1; if self.probes > MAX_PROBES { @@ -590,12 +621,22 @@ impl Files { match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) { Ok(found) => return Ok(found), Err(ScriptRead::Missing) => {} - Err(ScriptRead::Refused) if passed_over_when_refused => {} + Err(ScriptRead::Refused) if passed_over_when_refused => { + if i == 0 { + literal_error = Some(refused()); + } + } Err(ScriptRead::Refused) => return Err(refused()), Err(ScriptRead::TooLarge) => return Err((FailKind::Limit, format!("script file is too large: {value}"))), + Err(ScriptRead::Failed(e)) if i == 0 && passed_over_when_refused => { + literal_error = Some((FailKind::Error, format!("cannot read script file {value}: {e}"))); + } Err(ScriptRead::Failed(e)) => return Err((FailKind::Error, format!("cannot read script file {value}: {e}"))), } } + if let Some(error) = literal_error { + return Err(error); + } Err((FailKind::Error, format!("include file not found: {value}"))) } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index fe56754ca3..7e81dbc730 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -301,6 +301,40 @@ fn files_are_checked_before_they_are_read() { assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err()); } +/// `$.evalFile` also tries a path in a `File`'s URI notation, as `File.parent` gives +/// it: on Windows `/c/…` as the drive path `C:/…`, and on every platform with its escapes decoded, +/// after the path as written misses. Relative, share, device and `..` forms are not tried. +#[test] +fn include_paths_in_uri_notation_name_a_windows_drive() { + use crate::script::include::uri_forms; + assert_eq!(uri_forms("/c/Users/Test/more.jsx", true), ["C:/Users/Test/more.jsx"]); + assert_eq!(uri_forms("/d", true), ["D:/"]); + assert_eq!(uri_forms("/c/My%20Scripts/more.jsx", true), ["C:/My Scripts/more.jsx", "C:/My%20Scripts/more.jsx"]); + assert_eq!(uri_forms("/home/My%20Scripts/more.jsx", false), ["/home/My Scripts/more.jsx"]); + assert!(uri_forms("/c/Users/Test/more.jsx", false).is_empty()); + for kept in + ["//host/share/more.jsx", "//?/c/more.jsx", "/c/x/../more.jsx", "/Users/more.jsx", "more.jsx", "my%20file.jsx", "C:/more.jsx", "/1/more.jsx"] + { + assert!(uri_forms(kept, true).is_empty(), "{kept}: {:?}", uri_forms(kept, true)); + } + assert_eq!(uri_forms("/c/%2E%2E/more.jsx", true), ["C:/%2E%2E/more.jsx"], "an escaped `..` is not decoded into a parent name"); + // From a folder whose name has a space, `File.parent` gives `%20`, and the sibling is read. + let dir = fresh_folder("uri forms"); + std::fs::write(dir.join("more.jsx"), "'more';").unwrap(); + let main = dir.join("main.jsx"); + std::fs::write(&main, "vc.log(File($.fileName).parent + '');\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n").unwrap(); + let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert!(r["log"][0].as_str().is_some_and(|p| p.contains("uri%20forms")), "{r}"); + assert_eq!(r["log"][1], "more", "{r}"); + // A file whose name holds `%20` as written is read before the decoded name. + std::fs::write(dir.join("part%20one.jsx"), "'literal';").unwrap(); + std::fs::write(dir.join("part one.jsx"), "'decoded';").unwrap(); + let literal = dir.join("part%20one.jsx").to_string_lossy().replace('\\', "/"); + std::fs::write(&main, format!("vc.log($.evalFile({literal:?}));\n")).unwrap(); + let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["literal"]), "{r}"); +} + #[test] fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { let dir = fresh_folder("es2015"); diff --git a/docs/mcp.md b/docs/mcp.md index 5a32fe1e32..a8c23770b5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3480,7 +3480,9 @@ through `$`: `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global environment, so its functions and variables stay defined, and returns its last value (`undefined` for an empty - file). Its preprocessor lines are read as the script's are. `timeout` is a number of milliseconds from 0; the file + file). Its preprocessor lines are read as the script's are. An absolute path in a `File`'s URI notation, as + `File.parent` gives it, is read too: when the path as written names no file it may read, `%20` and the other + escapes are decoded, and on Windows `/c/…` names the drive `C:`. `timeout` is a number of milliseconds from 0; the file is read at once and `timeout` is not waited on. The run's fuel and limits apply to the file. An empty path, a missing file and a refused path throw errors the script can catch. - `$.fileName` is the file of the code that reads it: the script, a file it included with `#include`, or a file diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1cda4bba80..3b9c712257 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1138,7 +1138,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. - Scripts: an uncaught error that one or more `finally` blocks pass on unchanged, in the script or in a function it called, is reported at the line and column where it was thrown, in `script.run`'s report and the Script Console. An error a `finally` block throws is reported at that throw, and one its `return`, `break` or `continue` discards is not reported. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. - Scripts: an error a `finally` block passes on is still reported where it was thrown when the block's allocations collect garbage under a small heap limit, and a `finally` block that `return`, `break` or `continue` leaves drops the saved location of its error as it leaves, so a collection no longer counts that code as live. VectorCraft's own rule. `crates/js/src/host_tests.rs`. - - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). + - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. `$.evalFile` also reads absolute paths in a `File`'s URI notation, with escapes decoded and `/c/...` naming drive C: on Windows. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). - Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`. - Scripts: `$.fileName` is a read-only name of the script file in use ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: it names the file of the code that reads it, so a function a file included with `#include` or run with `$.evalFile` defined, or one an earlier run of a named engine kept, gives its own file and not the calling file; code from a script given as `source`, and kept code whose place the engine dropped, gives an empty name, and code that `eval` or `Function` compiled gives the file being run. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`. - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. From 6a13fa05ac88f17dc7d83ac081eb0450e77b8bc4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:39:44 -0800 Subject: [PATCH 15/32] Import PDF: a PDF with editing data opens on its trim boxes unless a box is picked Opening a PDF with editing data without naming a box gives its trim boxes, but the Import PDF dialog always sent cropTo, so OK with Crop To left as it started opened the crop boxes instead. Opening such a file, Crop To now starts on Trim Box, also once a password unlocks it, and OK names the box only when one was picked. Picking Crop Box still opens the crop boxes, and a place still starts on Crop Box. --- crates/ui-egui/src/dialogs/import_pdf.rs | 36 +++++++++++++++--- .../ui-egui/src/dialogs/tests_import_pdf.rs | 37 +++++++++++++++++++ 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 8bf7e37874..fd141eb74b 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -9,7 +9,9 @@ //! without a password; `null` until it is checked or cleared, when it follows the pages picked: on //! for All, off for a range; picking the other of All and Range sets it back to `null`; `linksOn` //! is the effective flag, `__linkable` is false for a file `linkPages` does not take, such as one -//! over its size limit), `cropTo`, `textAs` (`text` | `outlines`; it starts from the `pdfTextAs` +//! over its size limit), `cropTo` (when opening, it starts on `trim` for a file with editing data, +//! else `crop`; OK names the box only when it was picked, so a file with the starting box opens +//! as it does without the dialog), `textAs` (`text` | `outlines`; it starts from the `pdfTextAs` //! preference for a PDF (`__pdf`; Editable for a `.ai` or `.ait` file), or from the `textAs` a place //! gives (`__textAsGiven`), and OK keeps a PDF's choice there; a linked place shows the file's own //! text, so placing linked leaves it as it is, and Outlines clears Import PDF Pages as Links) and @@ -146,6 +148,9 @@ struct State { pages: Vec, link_pages: Option, crop: CropTo, + /// Whether Crop To was picked. Opening, a box left as it starts ([`opening_crop`]) is not + /// named, so a file with editing data opens on its trim boxes, as it opens without the dialog. + crop_chosen: bool, text_as: TextAs, pdf: bool, password: String, @@ -212,10 +217,13 @@ impl State { /// Reads the file with the typed password. `Ok(true)` when the file has pages to pick; `Ok(false)` when OK /// goes straight on to open or place it. fn unlock(&mut self) -> Result { - let info = vectorcraft_pdf::info(&self.file.bytes, self.password().as_deref()).map_err(|e| e.to_string())?; + let opened = vectorcraft_pdf::open_pdf(&self.file.bytes, self.password().as_deref()).map_err(|e| e.to_string())?; self.locked = false; - self.page_count = info.pages.len(); - Ok(info.pages.len() > 1 && !self.password_only) + self.page_count = opened.page_count(); + if !self.crop_chosen && self.place.is_none() { + self.crop = opening_crop(Some(&opened)); + } + Ok(self.page_count > 1 && !self.password_only) } /// The Text choice the preview renders with (a linked place: as editable text). @@ -270,6 +278,7 @@ impl State { let text = text()?; let i = CropTo::IDS.iter().position(|id| *id == text).ok_or("cropTo is not a crop box")?; self.crop = CropTo::ALL.get(i).copied().unwrap_or_default(); + self.crop_chosen = true; } "textAs" => { let id = text()?; @@ -459,7 +468,9 @@ fn pages_body(ui: &mut egui::Ui, s: &mut State, preview: Option<&(Revision, Arc< }); Stack::new().show(ui, |ui, _| { let crops: Vec> = CropTo::ALL.iter().zip(CropTo::LABELS).map(|(crop, label)| Entry::new(*crop, *label)).collect(); + let before = s.crop; Field::new(tl!("Crop To")).show(ui, |ui, _| Select::new(tl!("Crop To"), Bind::bound(&mut s.crop), &crops).show(ui)); + s.crop_chosen |= s.crop != before; let linked = s.places_linked(); let texts = [Entry::new(TextAs::Text, tl!("Editable")), Entry::new(TextAs::Outlines, tl!("Outlines"))]; Field::new(tl!("Text")).show(ui, |ui, _| Select::new(tl!("Text"), Bind::bound(&mut s.text_as), &texts).enabled(!linked).show(ui)); @@ -506,6 +517,12 @@ fn pick_pages(ui: &mut egui::Ui, s: &mut State, count: usize, current: usize) { } } +/// The box Crop To starts on when opening the file `opened`: Trim Box for a file with editing +/// data, which opens on its trim boxes when no box is named, else Crop Box. +fn opening_crop(opened: Option<&vectorcraft_pdf::Opened>) -> CropTo { + if opened.is_some_and(vectorcraft_pdf::Opened::has_illustrator_data) { CropTo::Trim } else { CropTo::default() } +} + /// Open `bytes` (or place them with the `file.place` params `place`) through the dialog when the /// file is a PDF (or `.ai`/`.ait`) with several pages or a password; false when there's nothing to /// ask (the caller goes on), including, when opening, a file that carries its VectorCraft document @@ -528,6 +545,7 @@ fn offer_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option 1 => (count, false), Err(PdfError::NeedsPassword) => (0, true), @@ -544,7 +562,8 @@ fn offer_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option Result<(), String> { } crate::place::run_for_user(app, &p).map(|_| ()) } else { - let mut p = json!({"cropTo": s.crop.id(), "password": s.password(), "textAs": s.text_as.id()}); + let mut p = json!({"password": s.password(), "textAs": s.text_as.id()}); + // A box left as it starts ([`opening_crop`]) is not named: a file with editing data then + // opens on its trim boxes, from its editing layers where it can, as without the dialog. + if s.crop_chosen { + p["cropTo"] = json!(s.crop.id()); + } // An empty range under Range opens every page. if !s.all_pages && !s.pages.is_empty() { p["pages"] = json!(format_pages(&s.pages)); diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index c9383d0f44..8b0bedd950 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -409,6 +409,43 @@ fn opening_an_ai_with_editing_data_reads_it_without_asking() { assert!(!is_open(&app)); } +/// A PDF with editing data opens on its trim boxes when no box is named. Opening one, Crop To starts +/// on Trim Box, also once a password unlocks it, and OK with it left so names no box: the pages open +/// on their trim boxes, as without the dialog. Picking Crop Box opens the crop boxes, and a place +/// starts on Crop Box. +#[test] +fn opening_a_pdf_with_editing_data_keeps_its_trim_boxes_unless_a_box_is_picked() { + let trimmed = |password: Option<&str>| { + let mut first = PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f"); + first.entries = "/PieceInfo << /Illustrator << /Private << /AIPrivateData1 7 /NumBlock 1 >> >> >>".into(); + first.trim = Some([10.0, 10.0, 90.0, 90.0]); + let mut second = PdfPage::new(200.0, 100.0, "1 0 0 rg 0 0 30 30 re f"); + second.trim = Some([10.0, 10.0, 190.0, 90.0]); + pdf(&[first, second], password) + }; + let mut app = app(); + assert!(import_pdf::offer(&mut app, "two.pdf", &trimmed(None), None, None)); + assert_eq!(field(&app, "cropTo"), "trim"); + confirm(&mut app).unwrap(); + assert_eq!(artboard_widths(&app), [80.0, 180.0], "the trim boxes"); + + let mut app = self::app(); + assert!(import_pdf::offer(&mut app, "two.pdf", &trimmed(None), None, None)); + set(&mut app, "cropTo", json!("crop")); + confirm(&mut app).unwrap(); + assert_eq!(artboard_widths(&app), [100.0, 200.0], "an explicit crop box"); + + let mut app = self::app(); + assert!(import_pdf::offer(&mut app, "locked.pdf", &trimmed(Some("pw")), None, None)); + set(&mut app, "password", json!("pw")); + confirm(&mut app).unwrap(); + assert_eq!((field(&app, "__locked"), field(&app, "cropTo")), (json!(false), json!("trim")), "unlocked"); + + let mut app = self::app(); + assert!(import_pdf::offer(&mut app, "two.pdf", &trimmed(None), None, Some(&json!({})))); + assert_eq!(field(&app, "cropTo"), "crop", "a place"); +} + /// A `.ai` whose editing data can't be read asks nothing either, and every page opens from the PDF /// part. Asking at that point is #6134. #[test] From ce596d4f579d048c183db7bf711dc88a56104c88 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:47:43 -0800 Subject: [PATCH 16/32] Arrange Tools: Mark Bounds of Each draws no empty group for an object too small for corner legs Each corner leg is at most half the side it runs along. An object wider or taller than the flat limit but with both half-sides under it got a Corner Marks group with no paths in it. Such an object now gets no corner marks, and a selection of only such objects is refused with "nothing to mark: the selection is too small for corner marks" and no undo step. The Rectangle style still marks it. Follows up #10148. --- crates/engine/src/cmd/addons/arrange/marks.rs | 21 +++++++++++++++--- .../src/cmd/addons/arrange/marks/tests.rs | 22 +++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 42 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/addons/arrange/marks.rs b/crates/engine/src/cmd/addons/arrange/marks.rs index fc01a8730d..f9bfa01329 100644 --- a/crates/engine/src/cmd/addons/arrange/marks.rs +++ b/crates/engine/src/cmd/addons/arrange/marks.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Mark Bounds of Each", ["Object", "Plug-ins", "Arrange Tools"], None, - "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, and objects without bounds such as empty groups, get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", + "{style?: \"corners\" (an L-shaped mark on each corner, its two legs running inward along the edges) | \"rectangle\" (a rectangle on the bounds) (\"corners\"), bounds?: \"geometric\" (strokes not counted) | \"visual\" (strokes, brush art and effects as drawn) (\"geometric\"), length?: pt 0.001..1000000 (10; corners: each leg's length, at most half the side it runs along), weight?: pt 0.01..1000 (1), color?: color (\"#ff0000\"; an RGB color takes the document's color mode)} draw marks on the bounds of each selected object (the top-level ones, at most 20000) as new art: a group of four corner marks, or one rectangle, with no fill and the stroke given, stacked directly above its object (above the outermost clip group or clipping sublayer that holds it, so the clip does not hide them). A clip group is measured by its clipping path and other groups by their members together. Guides, objects without bounds such as empty groups, and (for corners) objects whose sides are too short for any leg get no marks. The marks are selected; one undo step, and none when nothing gets marks (an error) → {ids: [the new marks…], count}", has_selection, mark_bounds )] @@ -55,10 +55,16 @@ fn corners(r: Rect) -> Vec<(Point, f64, f64)> { out } +/// The lengths of the across and down legs of the corner marks of `r`: `length`, at most half the +/// side each runs along. +fn legs(r: Rect, length: f64) -> (f64, f64) { + (length.min(r.width() / 2.0), length.min(r.height() / 2.0)) +} + /// The corner marks of `r` with legs `length` long, each at most half its side: one open path per /// corner, a line where `r` has no width or no height. fn corner_paths(r: Rect, length: f64) -> Vec { - let (lx, ly) = (length.min(r.width() / 2.0), length.min(r.height() / 2.0)); + let (lx, ly) = legs(r, length); corners(r) .into_iter() .filter_map(|(p, sx, sy)| { @@ -103,14 +109,23 @@ fn mark_bounds(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let symbols = d.symbol_boxes(); let mut marked: Vec<(NodeId, Rect)> = Vec::with_capacity(roots.len()); + let mut too_small = false; for id in roots { let Some(n) = d.node(id).filter(|n| !n.is_guide()) else { continue }; let bounds = if visual { drawn_bounds_with(&symbols, n) } else { n.geometric_bounds_with(&symbols) }; - if let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) { + let Some(r) = bounds.filter(|r| r.width() > FLAT || r.height() > FLAT) else { continue }; + // Corner legs are at most half a side, so an object too small for any leg gets no marks. + let (lx, ly) = legs(r, length); + if rectangle || lx > FLAT || ly > FLAT { marked.push((anchor(d, id), r)); + } else { + too_small = true; } } if marked.is_empty() { + if too_small { + return Err(bad(C, "nothing to mark: the selection is too small for corner marks")); + } return Err(bad(C, "nothing to mark: the selection has no bounds")); } let ap = Appearance::basic(Paint::None, Paint::solid(color), weight); diff --git a/crates/engine/src/cmd/addons/arrange/marks/tests.rs b/crates/engine/src/cmd/addons/arrange/marks/tests.rs index dc44f47d5b..13c9401464 100644 --- a/crates/engine/src/cmd/addons/arrange/marks/tests.rs +++ b/crates/engine/src/cmd/addons/arrange/marks/tests.rs @@ -325,6 +325,28 @@ fn flat_objects_get_lines_and_guides_and_empty_groups_none() { assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0))); } +#[test] +fn an_object_too_small_for_corner_legs_gets_no_empty_group() { + let mut s = session(); + // Wider than the flat limit, but each leg (half the side at most) is shorter than it. + let tiny = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 50, "x2": 1.5e-9, "y2": 50})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, &[tiny]); + let (before, n) = (s.doc().unwrap().doc.clone(), steps(&s)); + let refused = s.execute(COMMAND, &json!({})).unwrap_err().to_string(); + assert!(refused.contains("nothing to mark") && refused.contains("too small for corner marks"), "{refused}"); + assert_eq!(steps(&s), n, "no undo step"); + assert!(*s.doc().unwrap().doc == *before); + // The rectangle style still marks it, and a real object beside it gets its corner marks alone. + let r = s.execute(COMMAND, &json!({"style": "rectangle"})).unwrap(); + assert_eq!(r["count"], 1); + s.execute("edit.undo", &json!({})).unwrap(); + let a = rect(&mut s, 100.0, 100.0, 20.0, 20.0); + select(&mut s, &[tiny, a]); + let r = s.execute(COMMAND, &json!({})).unwrap(); + assert_eq!(r["count"], 1); + assert!(near(marks_bounds(&s, ids_of(&r)[0]), (100.0, 100.0, 120.0, 120.0))); +} + #[test] fn bad_params_are_refused_and_it_is_off_without_a_selection() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 5a32fe1e32..021109ca94 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17787,7 +17787,7 @@ with strokes and vector effects included and raster effects left out (see its ro | `addon.arrange.groupRows` | `direction`: `row` (vertical extents), `column` (horizontal extents) (`row` when omitted; `null` is invalid). Parameters must be an object. | Groups the selected objects (at most 20000) into one group for each row (column): an object joins a row when its visual bounds overlap the row's extent from top to bottom (left to right). Measurement includes strokes and vector effects, measures a clipping group by its mask, and excludes raster effects such as shadows, glows, and blurs. Extents that only touch stay apart, and an object that overlaps two rows joins them into one. Only objects in the same layer or group and on the same artboard (the one holding the object's center, else the one it overlaps most) share a row. Objects outside all artboards, locked or hidden objects, clipping masks, layers, and sublayers stay in place. Every grouping candidate must have a parent that is a layer or group. The command rejects selections containing editable live blend keys, direct children of Shaper groups, live compound shapes, Objects on Path groups, or Live Paint groups, and any descendants of live graphs. Complete live groups and graphs can be grouped with other artwork. An object alone in its row stays as it is. Each new group goes where its frontmost member was in the stacking order, and the groups (top to bottom, or left to right) and the objects left alone stay selected; with no row of two objects or more it makes no step. Needs two objects or more. → `{groups: [id…], grouped}` (how many objects went into groups) | | `addon.arrange.randomizeOpacity` | `min`, `max` % 0…100 (30, 100; `min` not more than `max`); `seed` whole number (0); `ids` (the selection) | Gives each selected object its own opacity (the object opacity the Transparency panel sets), picked at random and evenly from `min` to `max`; the same seed, objects and range give the same opacities. Groups take one opacity of their own; the objects inside keep theirs. A run that changes no opacity, such as `min` and `max` both at the opacity every object has, records no undo step. → `{count}` | | `addon.arrange.sort` | `by`, `apply`: `width`, `height`, `area` (width × height), `x` (left edge), `y` (top edge), `opacity` (%), `stacking` (stacking order from the back) (`area`, `stacking`); `order`: `ascending` (small to large), `descending` (large to small), `random` (`ascending`); `distribute` (false); `seed` whole number (0, for `random`); `scaleStrokes`; `ids` (the selection) | Sorts the selected objects (at most 20000) by `by` and gives them the values of `apply` in that order: the first gets the smallest value. Without `distribute` the objects trade the values they have; with it the values step evenly from the smallest to the largest. A width, height or area changes about each object's centre (an area in proportion), a place moves the top-left corner. Stacking order always trades places, and only among objects in the same layer or group. Needs two objects or more. → `{count}` | -| `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | +| `addon.arrange.markBounds` | `style`: `corners`, `rectangle` (`corners`); `bounds`: `geometric` (strokes not counted), `visual` (strokes, brush art and effects as drawn) (`geometric`); `length` pt 0.001…1000000 (10, for `corners`); `weight` pt 0.01…1000 (1); `color` (`#ff0000`; an RGB color takes the document's color mode) | Draws marks on the bounds of each selected object (at most 20000), not around the whole selection: a group named Corner Marks of four L-shaped marks, one on each corner with its two legs running inward along the edges (each leg at most half the side it runs along), or a rectangle named Bounds. The marks have no fill and the stroke given, and go directly above their object, or above the outermost clip group or clipping sublayer that holds it. A clip group is measured by its clipping path and other groups by their members together. Guides and objects without bounds, such as empty groups, get no marks, and with `corners` neither does an object whose sides are too short for any leg; a selection with nothing to mark is an error that makes no step. The marks are selected. → `{ids, count}` | Zoom to Selection is the UI command `addon.arrange.zoomSelection {}` (remote mode only): it zooms and centres the active view so the selection's visual bounds fill the window with a margin, as `view.fitArtboard` fits the artboard, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1cda4bba80..b006d3d335 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3170,7 +3170,7 @@ A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange ## Arrange Tools add-on: Mark Bounds of Each (2026-11-29) -A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws marks on each top-level selected object's bounds (at most 20000 objects), rather than around the whole selection. Draw is Corner Marks by default (four inward L-shaped marks in a group named Corner Marks), or Rectangle (one closed path named Bounds). Bounds is Geometric Bounds by default (strokes not counted), or Visual Bounds (strokes, brush art and effects as drawn). Length is 0.001 to 1000000 pt (10 by default), with each corner leg capped at half the side it runs along; Length is off in the dialog for Rectangle. Weight is 0.01 to 1000 pt (1 by default), and Color defaults to red (`#ff0000`); an RGB color takes the document's color mode. The marks have no fill and the stroke given. Each goes directly above its object, or above the outermost clip group or clipping sublayer that holds it; a clipping top-level layer keeps the marks inside it. Clip groups are measured by their clipping path, other groups by their members together. For flat objects, corner marks become lines along their nonzero side. Guides and objects without bounds, such as empty groups, are skipped; nothing to mark is an error with no undo step. The new marks become selected, in one undo step. The dialog has Preview; OK keeps the marks and Cancel removes the preview. Tests: `each_object_gets_inward_corner_marks_above_it_in_one_step`, `length_weight_color_and_the_rectangle_style`, `a_leg_is_at_most_half_the_side_it_runs_along_vertically`, `geometric_bounds_leave_strokes_out_and_visual_bounds_count_them`, `visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out`, `visual_bounds_enclose_brush_art_on_paths_and_in_groups`, `groups_by_their_members_and_clip_groups_by_the_clipping_path`, `marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer`, `flat_objects_get_lines_and_guides_and_empty_groups_none` and `bad_params_are_refused_and_it_is_off_without_a_selection` in `cmd::addons::arrange::marks::tests` in `vectorcraft-engine`; `real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them` and `mark_bounds_sends_the_dialog_values_to_its_command` in `crates/ui-egui/src/addons/arrange/tests.rs` in `vectorcraft-ui-egui`; and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. +A VectorCraft addition, so no area score moves. Object › Plug-ins › Arrange Tools › Mark Bounds of Each… draws marks on each top-level selected object's bounds (at most 20000 objects), rather than around the whole selection. Draw is Corner Marks by default (four inward L-shaped marks in a group named Corner Marks), or Rectangle (one closed path named Bounds). Bounds is Geometric Bounds by default (strokes not counted), or Visual Bounds (strokes, brush art and effects as drawn). Length is 0.001 to 1000000 pt (10 by default), with each corner leg capped at half the side it runs along; Length is off in the dialog for Rectangle. Weight is 0.01 to 1000 pt (1 by default), and Color defaults to red (`#ff0000`); an RGB color takes the document's color mode. The marks have no fill and the stroke given. Each goes directly above its object, or above the outermost clip group or clipping sublayer that holds it; a clipping top-level layer keeps the marks inside it. Clip groups are measured by their clipping path, other groups by their members together. For flat objects, corner marks become lines along their nonzero side; an object whose sides are too short for any leg gets no corner marks. Guides and objects without bounds, such as empty groups, are skipped; nothing to mark is an error with no undo step. The new marks become selected, in one undo step. The dialog has Preview; OK keeps the marks and Cancel removes the preview. Tests: `each_object_gets_inward_corner_marks_above_it_in_one_step`, `length_weight_color_and_the_rectangle_style`, `a_leg_is_at_most_half_the_side_it_runs_along_vertically`, `geometric_bounds_leave_strokes_out_and_visual_bounds_count_them`, `visual_bounds_enclose_a_drop_shadow_and_geometric_bounds_leave_it_out`, `visual_bounds_enclose_brush_art_on_paths_and_in_groups`, `groups_by_their_members_and_clip_groups_by_the_clipping_path`, `marks_go_outside_a_clipping_sublayer_but_stay_in_a_clipping_top_layer`, `flat_objects_get_lines_and_guides_and_empty_groups_none`, `an_object_too_small_for_corner_legs_gets_no_empty_group` and `bad_params_are_refused_and_it_is_off_without_a_selection` in `cmd::addons::arrange::marks::tests` in `vectorcraft-engine`; `real_mark_bounds_edits_reach_the_preview_ok_keeps_them_and_cancel_drops_them` and `mark_bounds_sends_the_dialog_values_to_its_command` in `crates/ui-egui/src/addons/arrange/tests.rs` in `vectorcraft-ui-egui`; and `command_sweep`. Commands: `docs/mcp.md` › Arrange Tools add-on. ## Arrange Tools add-on: Group by Row (2026-11-29) From 8f76825e7a47f6be9a1fde84530dadc2675e3100 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:50:16 -0800 Subject: [PATCH 17/32] Import PDF: name Crop To only when it differs from the box it started on A keyboard preview canceled with Escape restores the starting box, so it no longer counts as a pick. --- crates/ui-egui/src/dialogs/import_pdf.rs | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index fd141eb74b..5121f37c16 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -10,9 +10,9 @@ //! for All, off for a range; picking the other of All and Range sets it back to `null`; `linksOn` //! is the effective flag, `__linkable` is false for a file `linkPages` does not take, such as one //! over its size limit), `cropTo` (when opening, it starts on `trim` for a file with editing data, -//! else `crop`; OK names the box only when it was picked, so a file with the starting box opens -//! as it does without the dialog), `textAs` (`text` | `outlines`; it starts from the `pdfTextAs` -//! preference for a PDF (`__pdf`; Editable for a `.ai` or `.ait` file), or from the `textAs` a place +//! else `crop`; OK names the box only when it differs from the box it started on, so a file with +//! the starting box opens as it does without the dialog), `textAs` (`text` | `outlines`; it starts +//! from the `pdfTextAs` preference for a PDF (`__pdf`; Editable for a `.ai` or `.ait` file), or from the `textAs` a place //! gives (`__textAsGiven`), and OK keeps a PDF's choice there; a linked place shows the file's own //! text, so placing linked leaves it as it is, and Outlines clears Import PDF Pages as Links) and //! `password`. `__locked` is set until the password is accepted: OK then unlocks the file, and with @@ -148,9 +148,9 @@ struct State { pages: Vec, link_pages: Option, crop: CropTo, - /// Whether Crop To was picked. Opening, a box left as it starts ([`opening_crop`]) is not - /// named, so a file with editing data opens on its trim boxes, as it opens without the dialog. - crop_chosen: bool, + /// The box Crop To started on ([`opening_crop`] when opening). OK names the box only when + /// it differs from this box. + start_crop: CropTo, text_as: TextAs, pdf: bool, password: String, @@ -220,8 +220,9 @@ impl State { let opened = vectorcraft_pdf::open_pdf(&self.file.bytes, self.password().as_deref()).map_err(|e| e.to_string())?; self.locked = false; self.page_count = opened.page_count(); - if !self.crop_chosen && self.place.is_none() { + if self.crop == self.start_crop && self.place.is_none() { self.crop = opening_crop(Some(&opened)); + self.start_crop = self.crop; } Ok(self.page_count > 1 && !self.password_only) } @@ -278,7 +279,6 @@ impl State { let text = text()?; let i = CropTo::IDS.iter().position(|id| *id == text).ok_or("cropTo is not a crop box")?; self.crop = CropTo::ALL.get(i).copied().unwrap_or_default(); - self.crop_chosen = true; } "textAs" => { let id = text()?; @@ -468,9 +468,7 @@ fn pages_body(ui: &mut egui::Ui, s: &mut State, preview: Option<&(Revision, Arc< }); Stack::new().show(ui, |ui, _| { let crops: Vec> = CropTo::ALL.iter().zip(CropTo::LABELS).map(|(crop, label)| Entry::new(*crop, *label)).collect(); - let before = s.crop; Field::new(tl!("Crop To")).show(ui, |ui, _| Select::new(tl!("Crop To"), Bind::bound(&mut s.crop), &crops).show(ui)); - s.crop_chosen |= s.crop != before; let linked = s.places_linked(); let texts = [Entry::new(TextAs::Text, tl!("Editable")), Entry::new(TextAs::Outlines, tl!("Outlines"))]; Field::new(tl!("Text")).show(ui, |ui, _| Select::new(tl!("Text"), Bind::bound(&mut s.text_as), &texts).enabled(!linked).show(ui)); @@ -563,7 +561,7 @@ fn offer_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option Result<(), String> { let mut p = json!({"password": s.password(), "textAs": s.text_as.id()}); // A box left as it starts ([`opening_crop`]) is not named: a file with editing data then // opens on its trim boxes, from its editing layers where it can, as without the dialog. - if s.crop_chosen { + if s.crop != s.start_crop { p["cropTo"] = json!(s.crop.id()); } // An empty range under Range opens every page. From 709791372438c59f24f7619ee8b1587a080d2eaf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:58:35 -0800 Subject: [PATCH 18/32] Docs: $.evalFile tries the path as written before its URI forms The parity entry now says the path as written is read first, and the decoded URI forms are tried only when it is missing, fails to read or is refused. A file over the size limit stops the lookup. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b9c712257..ff3ac14a89 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1138,7 +1138,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. - Scripts: an uncaught error that one or more `finally` blocks pass on unchanged, in the script or in a function it called, is reported at the line and column where it was thrown, in `script.run`'s report and the Script Console. An error a `finally` block throws is reported at that throw, and one its `return`, `break` or `continue` discards is not reported. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`. - Scripts: an error a `finally` block passes on is still reported where it was thrown when the block's allocations collect garbage under a small heap limit, and a `finally` block that `return`, `break` or `continue` leaves drops the saved location of its error as it leaves, so a collection no longer counts that code as live. VectorCraft's own rule. `crates/js/src/host_tests.rs`. - - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. `$.evalFile` also reads absolute paths in a `File`'s URI notation, with escapes decoded and `/c/...` naming drive C: on Windows. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). + - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. `$.evalFile` tries the path as written first; only when that file is missing, fails to read (a file over the size limit stops the lookup) or is refused does it read an absolute path in a `File`'s URI notation, with escapes decoded and `/c/...` naming drive C: on Windows. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). - Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`. - Scripts: `$.fileName` is a read-only name of the script file in use ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: it names the file of the code that reads it, so a function a file included with `#include` or run with `$.evalFile` defined, or one an earlier run of a named engine kept, gives its own file and not the calling file; code from a script given as `source`, and kept code whose place the engine dropped, gives an empty name, and code that `eval` or `Function` compiled gives the file being run. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`. - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. From fd6c41368b3f2c8994800d2c0e6b3fb7ae744e5a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 09:59:07 -0800 Subject: [PATCH 19/32] Import PDF: unlocking a file refreshes the box Crop To started on A box set while the file was locked no longer leaves the old starting box, so a later pick of Crop Box is still named. --- crates/ui-egui/src/dialogs/import_pdf.rs | 9 ++++++--- crates/ui-egui/src/dialogs/tests_import_pdf.rs | 9 +++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 5121f37c16..d128aba2e4 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -220,9 +220,12 @@ impl State { let opened = vectorcraft_pdf::open_pdf(&self.file.bytes, self.password().as_deref()).map_err(|e| e.to_string())?; self.locked = false; self.page_count = opened.page_count(); - if self.crop == self.start_crop && self.place.is_none() { - self.crop = opening_crop(Some(&opened)); - self.start_crop = self.crop; + if self.place.is_none() { + let start_crop = opening_crop(Some(&opened)); + if self.crop == self.start_crop { + self.crop = start_crop; + } + self.start_crop = start_crop; } Ok(self.page_count > 1 && !self.password_only) } diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 8b0bedd950..1d1d434f2d 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -441,6 +441,15 @@ fn opening_a_pdf_with_editing_data_keeps_its_trim_boxes_unless_a_box_is_picked() confirm(&mut app).unwrap(); assert_eq!((field(&app, "__locked"), field(&app, "cropTo")), (json!(false), json!("trim")), "unlocked"); + let mut app = self::app(); + assert!(import_pdf::offer(&mut app, "locked.pdf", &trimmed(Some("pw")), None, None)); + set(&mut app, "cropTo", json!("media")); + set(&mut app, "password", json!("pw")); + confirm(&mut app).unwrap(); + set(&mut app, "cropTo", json!("crop")); + confirm(&mut app).unwrap(); + assert_eq!(artboard_widths(&app), [100.0, 200.0]); + let mut app = self::app(); assert!(import_pdf::offer(&mut app, "two.pdf", &trimmed(None), None, Some(&json!({})))); assert_eq!(field(&app, "cropTo"), "crop", "a place"); From 4c883f94ccbba24d177a4cd9e2cd5e6ea82c8dd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 16:28:48 -0800 Subject: [PATCH 20/32] Print: the Size list shows the chosen printer's paper sizes File > Print offered the same built-in sizes for every printer, so a card printer's CR80 size could not be chosen. The Size list now holds the paper sizes the chosen printer's driver lists: the CUPS PPD's PaperDimension entries on macOS and Linux, and the printer's forms on Windows. A size the dialog has itself (Letter, A4) keeps its own id under the driver's name; others print as a custom size of the driver's width and height. Custom is always offered, and a printer whose driver lists nothing keeps the built-in list. The lookup runs on a worker thread and the dialog updates when it answers; the Windows lookup stops after 10 seconds. Each opening of the dialog and each printer change reads the driver again. A paper the new printer does not list becomes a custom size of the same width and height. The preset editor keeps the built-in list. --- apps/vectorcraft/src/host_services.rs | 2 +- apps/vectorcraft/src/printing.rs | 108 +++++++++- crates/ui-egui/src/dialogs/print.rs | 184 ++++++++++++++++- crates/ui-egui/src/dialogs/tests_print.rs | 238 +++++++++++++++++++++- crates/ui-egui/src/print.rs | 89 ++++++++ 5 files changed, 608 insertions(+), 13 deletions(-) diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 47813f192e..9e416d7711 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -188,7 +188,7 @@ pub(crate) fn services(window: Parent) -> Services { check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))), open_in_application: Some(Box::new(open_in_application)), // File → Print: the system's printers and print queue. - print: Some(Box::new(printing::SystemPrint)), + print: Some(Box::new(printing::SystemPrint::default())), // The tablet driver's Wintab context, which reads an airbrush pen's finger wheel, opens // only while the active tool uses the wheel. #[cfg(all(windows, not(target_vendor = "win7")))] diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index fb28192f05..6725b72884 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -1,11 +1,16 @@ //! Desktop printer transport. VectorCraft composes every page and copy before submission; //! craft-print owns discovery and spooling. use std::process::Command; -use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer}; +use vectorcraft_ui_egui::print::{Paper, Papers, PrintJob, PrintService, Printer}; mod direct_pdf; -pub struct SystemPrint; +#[derive(Default)] +pub struct SystemPrint { + /// Channels for pending paper-size lookups, removed when each worker answers or disconnects. + papers: std::collections::HashMap>>, +} + impl PrintService for SystemPrint { fn printers(&mut self) -> Vec { system::printers() @@ -15,7 +20,7 @@ impl PrintService for SystemPrint { Ok(sent(job.title, job.printer, ¬e)) } fn shared_print(&self) -> Option { - Some(std::sync::Arc::new(|job| SystemPrint.print(job))) + Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e)))) } fn turns_landscape(&self) -> bool { // macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright @@ -28,6 +33,31 @@ impl PrintService for SystemPrint { fn setup(&mut self, printer: Option<&str>) -> Result<(), String> { system::setup(printer) } + fn papers(&mut self, printer: &str) -> Papers { + let receive = self.papers.entry(printer.to_string()).or_insert_with(|| { + let (send, receive) = std::sync::mpsc::channel(); + let printer = printer.to_string(); + let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || { + let _ = send.send(installed_papers(&printer)); + }); + receive + }); + let result = match receive.try_recv() { + Ok(papers) => Papers::Ready(papers), + Err(std::sync::mpsc::TryRecvError::Disconnected) => Papers::Ready(Vec::new()), + Err(std::sync::mpsc::TryRecvError::Empty) => return Papers::Pending, + }; + self.papers.remove(printer); + result + } +} + +/// Look up only an installed printer's own name. +fn installed_papers(printer: &str) -> Vec { + if printer.is_empty() || !system::printers().iter().any(|p| p.name == printer) { + return Vec::new(); + } + system::papers(printer) } /// The status after the job `title` went to `printer` (the default one without a name), with the @@ -40,10 +70,80 @@ fn sent(title: &str, printer: Option<&str>, note: &str) -> String { } mod system { - use super::{Command, PrintJob, Printer}; + use super::{Command, Paper, PrintJob, Printer}; pub fn printers() -> Vec { craft::print::printers().into_iter().map(Printer::from).collect() } + /// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings. + pub fn papers(printer: &str) -> Vec { + #[cfg(windows)] + { + // The name goes in as an environment variable, never into the script's text. + const SCRIPT: &str = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Add-Type -AssemblyName System.Drawing; $s = New-Object System.Drawing.Printing.PrinterSettings; \ + $s.PrinterName = $env:VC_PRINTER; foreach ($p in $s.PaperSizes) { \"$($p.RawKind)`t$($p.PaperName)`t$($p.Width)`t$($p.Height)\" }"; + use std::os::windows::process::CommandExt as _; + // CREATE_NO_WINDOW: no console window opens over the app. + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let mut command = Command::new("powershell.exe"); + command.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("VC_PRINTER", printer).creation_flags(CREATE_NO_WINDOW); + paper_output(&mut command).map(|out| vectorcraft_ui_egui::print::windows_papers(&String::from_utf8_lossy(&out))).unwrap_or_default() + } + #[cfg(not(windows))] + { + use std::io::Read as _; + // CUPS queue names never hold `/`, so the name can't leave the PPD folder. + if printer.contains(['/', '\\']) || printer.starts_with('.') { + return Vec::new(); + } + const PPD_CAP: u64 = 16 << 20; + let mut bytes = Vec::new(); + let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes)); + if read.is_err() { + return Vec::new(); + } + vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) + } + } + /// Drain output while polling the child, and stop discovery after ten seconds. + #[cfg(windows)] + fn paper_output(command: &mut Command) -> Option> { + use std::io::Read as _; + use std::process::Stdio; + use std::time::{Duration, Instant}; + + const LIMIT: Duration = Duration::from_secs(10); + let started = Instant::now(); + let mut child = command.stdout(Stdio::piped()).stderr(Stdio::null()).spawn().ok()?; + let (send, receive) = std::sync::mpsc::channel(); + let stdout = child.stdout.take(); + let reader = std::thread::Builder::new().name("printer-paper-output".into()).spawn(move || { + let mut bytes = Vec::new(); + // Retain at most 16 MiB, but drain the rest so the child can finish. + let read = stdout.map(|mut out| { + out.by_ref().take(16 << 20).read_to_end(&mut bytes)?; + std::io::copy(&mut out, &mut std::io::sink()) + }); + let _ = send.send(read.and_then(Result::ok).map(|_| bytes)); + }); + if reader.is_err() { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + loop { + match child.try_wait() { + Ok(Some(status)) => { + return if status.success() { receive.recv_timeout(LIMIT.saturating_sub(started.elapsed())).ok().flatten() } else { None }; + } + Ok(None) if started.elapsed() < LIMIT => std::thread::sleep(Duration::from_millis(25)), + _ => { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + } + } + } pub fn print(job: &PrintJob) -> Result { if job.direct_pdf { return super::direct_pdf::print(job); diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 05d46c3979..3021537994 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -46,6 +46,7 @@ use vectorcraft_pdf::{ }; use super::form; +use crate::print::{Paper, Papers}; use crate::{VectorcraftApp, graphics}; pub(crate) const SECTIONS: [&str; 7] = ["General", "Marks and Bleed", "Output", "Graphics", "Color Management", "Advanced", "Summary"]; @@ -111,6 +112,12 @@ struct Open { preview: Option<(Stamp, Arc>)>, /// The printer row's driver controls, as the dialog was last given them. driver: DriverControls, + /// The printer the Media list was made for, and the paper sizes its driver offers. + papers: (String, Vec), + /// Whether the chosen printer still has a lookup running. + papers_pending: bool, + /// The ids of the Size choices the dialog was last given. + media: Vec, } /// The document (uid, revision) and the settings a cached preview belongs to. @@ -132,24 +139,105 @@ struct Drained { ok: Option, settings: Value, sheet: usize, + /// The printer chosen (empty: the default printer or PDF File). + printer: String, } -/// The lists the rows offer that the app holds (the profiles, the flattener presets). +/// The lists the rows offer that the app holds (the profiles, the flattener presets, the printer's papers). #[derive(Default)] struct Lists { profiles: Vec, flatteners: Vec, + /// The Size choices: the printer's paper sizes, or the dialog's own papers when it offers none. + media: Vec<(String, String)>, } impl Lists { - fn of(app: &VectorcraftApp) -> Self { + fn of(app: &VectorcraftApp, papers: &[Paper], media: &str) -> Self { Self { profiles: vectorcraft_color::cms::profiles().iter().map(|p| p.name.clone()).collect(), flatteners: app.session.flattener_presets().iter().map(|p| p.name.clone()).collect(), + media: media_choices(papers, media), } } } +/// The prefix of a Size choice that is one of the printer's own paper sizes (`printer:CR80`). +const PRINTER_PAPER: &str = "printer:"; + +/// The dialog's own papers, as (id, label). +fn own_media() -> Vec<(String, String)> { + Media::IDS.iter().zip(Media::LABELS).map(|(i, l)| (i.to_string(), tl!(*l).to_string())).collect() +} + +/// The Size choices for a printer whose driver offers `papers`, with `current` (the row's choice) kept when it is one of +/// the dialog's own papers. A paper the dialog has itself, by size, keeps the dialog's id (so `letter` stays `letter`) +/// under the driver's name; the others are `printer:`. Custom is always offered. No papers: the dialog's own +/// list. +fn media_choices(papers: &[Paper], current: &str) -> Vec<(String, String)> { + let mut out = if papers.is_empty() { + own_media() + } else { + let mut out: Vec<(String, String)> = Vec::new(); + for p in papers { + let id = own_media_of(p).map_or_else(|| format!("{PRINTER_PAPER}{}", p.key), |m| m.id().to_string()); + if out.iter().all(|(i, _)| *i != id) { + out.push((id, p.label.clone())); + } + } + out.push((Media::Custom.id().to_string(), tl!(Media::Custom.label()).to_string())); + out + }; + if !current.is_empty() && !current.starts_with(PRINTER_PAPER) && out.iter().all(|(i, _)| i != current) { + // A built-in paper the printer doesn't list stays chosen until it is changed. + let label = Media::from_name(current).map_or_else(|| current.trim_start_matches(PRINTER_PAPER).to_string(), |m| tl!(m.label()).to_string()); + out.push((current.to_string(), label)); + } + out +} + +/// The dialog's own paper of the size of `p`, either way up, to within half a point. +fn own_media_of(p: &Paper) -> Option { + let (w, h) = (p.width.min(p.height), p.width.max(p.height)); + Media::ALL.iter().copied().find(|m| m.size().is_some_and(|(mw, mh)| (mw.min(mh) - w).abs() <= 0.5 && (mw.max(mh) - h).abs() <= 0.5)) +} + +/// The printer's paper the Size row names (`printer:CR80`), when it is one of `papers`. +fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a Paper> { + let key = fields.text("media")?.strip_prefix(PRINTER_PAPER)?; + papers.iter().find(|p| p.key == key) +} + +/// The print settings of `fields`, with Width and Height at the size of the printer's paper the Size row names. +fn settings_with_paper(fields: &DialogFields, papers: &[Paper]) -> Value { + let mut out = settings(fields); + if let Some(paper) = printer_paper(fields, papers) { + out["width"] = json!(paper.width); + out["height"] = json!(paper.height); + } + out +} + +/// The paper sizes the driver of `printer` offers (none for preset editing, the default printer and PDF File). +fn papers_of(app: &mut VectorcraftApp, mode: PrintMode, printer: &str) -> (Vec, bool) { + if mode == PrintMode::PresetEditor || printer.is_empty() || printer == PDF_FILE { + return (Vec::new(), false); + } + match app.services.print.as_mut().map(|s| s.papers(printer)) { + Some(Papers::Ready(papers)) => (papers, false), + Some(Papers::Pending) => (Vec::new(), true), + None => (Vec::new(), false), + } +} + +/// The printer `destination` names, empty for none. +fn printer_of(destination: &Destination) -> String { + match destination { + Destination::Printer(name) => name.clone(), + _ => String::new(), + } +} + /// Open the Print dialog on the document's print settings and the system's default printer. pub fn open(app: &mut VectorcraftApp) -> Result { let st = app.session.active().ok_or("no document")?; @@ -207,7 +295,15 @@ fn start( let taken: Vec = taken_names(app); let named = editing.clone(); let driver = driver(has_setup(app), &state.settings.destination); - let mut hosted = HostedPrint::new(state, fields, sections(&Lists::of(app))) + let printer = printer_of(&state.settings.destination); + let (papers, papers_pending) = papers_of(app, mode, &printer); + if papers_pending { + ctx.request_repaint(); + } + let media = fields.text("media").map(str::to_string).unwrap_or_default(); + let lists = Lists::of(app, &papers, &media); + let media: Vec = lists.media.iter().map(|(i, _)| i.clone()).collect(); + let mut hosted = HostedPrint::new(state, fields, sections(&lists)) .mode(mode) .layout(PrintLayout::Sections) .driver(driver) @@ -220,7 +316,8 @@ fn start( hosted.set_json_field(&ctx, "name", json!(name))?; } let id = dialogs.with(|h| h.open(hosted)); - app.print_dialog.open = Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver }); + app.print_dialog.open = + Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver, papers: (printer, papers), papers_pending, media }); Ok(Value::Null) } @@ -320,6 +417,10 @@ pub(super) fn settings(fields: &DialogFields) -> Value { for k in NOT_SETTINGS { p.remove(k); } + // A printer's own paper prints as a custom size: the pump keeps Width and Height at its size. + if p.get("media").and_then(Value::as_str).is_some_and(|m| m.starts_with(PRINTER_PAPER)) { + p.insert("media".into(), json!(Media::Custom.id())); + } Value::Object(nested(p)) } @@ -363,6 +464,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, ok: p.take_ok(), settings: settings(p.fields_mut()), sheet: p.sheet_index(), + printer: printer_of(&p.state().settings.destination), } }) else { // Closed: its answer was acted on when the OK was held. @@ -372,6 +474,73 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, for event in std::mem::take(&mut d.events) { apply_preset_event(app, dialogs, open, &mut d.settings, event); } + // Another printer, or its driver's answer arriving: the Size list becomes the driver's paper sizes. A preset can + // choose a size the list lacks, so the Size row is read after the preset events and the list is made again to + // hold it. + let mut media = on(dialogs, |p| p.fields().text("media").map(str::to_string)).flatten().unwrap_or_default(); + let printer_changed = d.printer != open.papers.0; + let mut papers_changed = false; + // The paper chosen from the previous list, read before the list is replaced. + let chosen = on(dialogs, |p| printer_paper(p.fields(), &open.papers.1).cloned()).flatten(); + if printer_changed || open.papers_pending { + // The held answer still names a paper from the previous list. + if let Some(answer) = &mut d.ok + && let Some(paper) = printer_paper(&answer.fields, &open.papers.1) + { + answer.fields.set("width", paper.width); + answer.fields.set("height", paper.height); + answer.fields.set("media", Media::Custom.id()); + } + let (papers, pending) = papers_of(app, open.mode, &d.printer); + papers_changed = printer_changed || !pending; + open.papers = (d.printer.clone(), papers); + open.papers_pending = pending; + } + if open.papers_pending { + ctx.request_repaint(); + } + // A paper the new printer doesn't list becomes a custom size of the same Width and Height. + if papers_changed + && media.starts_with(PRINTER_PAPER) + && let Some(s) = on(dialogs, |p| { + let fields = p.fields_mut(); + if printer_paper(fields, &open.papers.1).is_some() { + return None; + } + if let Some(paper) = &chosen { + fields.set("width", paper.width); + fields.set("height", paper.height); + } + fields.set("media", Media::Custom.id()); + Some(settings(fields)) + }) + .flatten() + { + media = Media::Custom.id().to_string(); + d.settings = s; + } + if papers_changed || (!media.is_empty() && !open.media.contains(&media)) { + let lists = Lists::of(app, &open.papers.1, &media); + open.media = lists.media.iter().map(|(i, _)| i.clone()).collect(); + on(dialogs, |p| p.set_sections(sections(&lists))); + ctx.request_repaint(); + } + // One of the printer's papers: Width and Height hold its size, which is what prints. + let papers = &open.papers.1; + if let Some(s) = on(dialogs, |p| { + let fields = p.fields_mut(); + let paper = printer_paper(fields, papers)?; + let size = (fields.number("width"), fields.number("height")); + (size != (Some(paper.width), Some(paper.height))).then(|| { + fields.set("width", paper.width); + fields.set("height", paper.height); + settings(fields) + }) + }) + .flatten() + { + d.settings = s; + } if open.mode == PrintMode::Print { let same = serde_json::from_value::(d.settings.clone()) .ok() @@ -508,7 +677,9 @@ fn drags(moves: EditEvents) -> Vec<(f64, f64)> { /// Print, or Done: keep the settings with the document (one undo step when they changed), then print them; settings /// that can't print are refused, and the dialog stays open. The preset editor saves the preset under `name` instead. fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &str) -> Result<(), String> { - let settings = settings(&answer.fields); + // The answer holds the fields as they were when OK was pressed, which can be before the pump set a printer's + // paper's size. + let settings = settings_with_paper(&answer.fields, &open.papers.1); if open.mode == PrintMode::PresetEditor { return save_preset(app, open, name, settings); } @@ -696,6 +867,7 @@ fn sections(lists: &Lists) -> Vec { let composite: Vec<&str> = OutputMode::IDS.iter().copied().filter(|i| *i != separations).collect(); let scaling_on: Vec<&str> = tiles.iter().copied().chain([PrintScaling::Custom.id()]).collect(); let counts: Vec = (2..=i64::from(vectorcraft_pdf::MAX_COPIES)).collect(); + let media = if lists.media.is_empty() { own_media() } else { lists.media.clone() }; let artboards = vec![ (PrintArtboards::All.id().to_string(), tl!("All").into()), (PrintArtboards::Range.id().to_string(), tl!("Range:").into()), @@ -712,7 +884,7 @@ fn sections(lists: &Lists) -> Vec { .under_option(PrintArtboards::Range.id()), flag("skipBlank", tl!("Skip Blank Artboards")).enabled_when_in("artboards", [PrintArtboards::All.id(), PrintArtboards::Range.id()]), Param::section(tl!("Media")), - pick::("media", tl!("Size:")), + Param::new("media", tl!("Size:"), ParamKind::choice(media.into_iter().map(|(i, l)| (i, l.into())).collect(), None)), length("width", tl!("Width:")).enabled_when("media", "custom"), length("height", tl!("Height:")).enabled_when("media", "custom"), Param::section(tl!("Orientation")), diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 183d6f1056..48002b08d8 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -1,14 +1,14 @@ //! File → Print: the Print dialog hosted on the window (Print and Done, the preview's drag), the //! print service it prints through (a mock here) and the PDF it saves without one. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; use craft::print::ui::Printer; use serde_json::{Value, json}; use vectorcraft_engine::Session; -use crate::print::{PrintJob, PrintService}; +use crate::print::{Papers, PrintJob, PrintService}; use crate::{Services, VectorcraftApp}; /// What the mock service was sent: (printer, title, PDF). @@ -234,6 +234,240 @@ fn print_does_not_send_or_update_the_other_drawing() { assert!(!is_open(&app)); } +/// The printers the paper service was asked for, in order. +type Asked = Rc>>; + +/// Two printers: Office's driver lists no papers, and Card's lists US Letter and a CR80 card. +struct PaperPrint(Jobs, Asked); + +impl PrintService for PaperPrint { + fn printers(&mut self) -> Vec { + vec![Printer::new("Office").is_default(true), Printer::new("Card")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(self.0.clone()).print(job) + } + + fn papers(&mut self, printer: &str) -> Papers { + self.1.borrow_mut().push(printer.to_string()); + let paper = |key: &str, label: &str, width, height| crate::print::Paper { key: key.into(), label: label.into(), width, height }; + Papers::Ready(match printer { + "Card" => vec![paper("Letter", "US Letter", 612.0, 792.0), paper("CR80", "CR80 Card", 153.0, 243.0)], + _ => vec![], + }) + } +} + +/// The driver returns its papers on the second test frame. +struct PendingPaperPrint(PaperPrint, Rc>); + +impl PrintService for PendingPaperPrint { + fn printers(&mut self) -> Vec { + vec![Printer::new("Card").is_default(true)] + } + + fn print(&mut self, job: &PrintJob) -> Result { + self.0.print(job) + } + + fn papers(&mut self, printer: &str) -> Papers { + if self.1.get() < 2 { Papers::Pending } else { self.0.papers(printer) } + } +} + +#[test] +fn preset_editor_keeps_its_own_sizes_without_asking_the_default_printer() { + let asked = Asked::default(); + let service = PendingPaperPrint(PaperPrint(Jobs::default(), asked.clone()), Rc::new(Cell::new(2))); + let services = Services { print: Some(Box::new(service)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("ui.printPresetDialog", json!({})).unwrap(); + assert!(asked.borrow().is_empty()); + set(&mut app, "media", json!("a3")); + for _ in 0..2 { + pump(&mut app); + } + assert_eq!(fields(&app)["media"], "a3"); + assert!(asked.borrow().is_empty(), "preset editing never asks for printer paper sizes"); +} + +#[test] +fn pending_paper_sizes_arrive_on_a_later_frame() { + let asked = Asked::default(); + let frame = Rc::new(Cell::new(0)); + let service = PendingPaperPrint(PaperPrint(Jobs::default(), asked.clone()), frame.clone()); + let services = Services { print: Some(Box::new(service)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); + frame.set(1); + pump(&mut app); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); + set(&mut app, "media", json!("a3")); + frame.set(2); + pump(&mut app); + assert_eq!(fields(&app)["media"], "a3", "the chosen size survives discovery"); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_ok()); + pump(&mut app); + pump(&mut app); + assert_eq!(*asked.borrow(), ["Card"], "ready results are not polled again"); +} + +#[test] +fn the_media_sizes_follow_the_printer_chosen() { + let (jobs, asked) = (Jobs::default(), Asked::default()); + let services = Services { print: Some(Box::new(PaperPrint(jobs.clone(), asked.clone()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err(), "Office's driver has no CR80 card"); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + // The card printer's Letter is the dialog's own Letter. + set(&mut app, "media", json!("letter")); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + let f = fields(&app); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + confirm(&mut app); + assert!(!is_open(&app)); + let job = jobs.borrow(); + let page = &vectorcraft_pdf::info(&job[0].2, None).unwrap().pages[0]; + let (short, long) = (page.width.min(page.height), page.width.max(page.height)); + assert!((short - 153.0).abs() < 0.5 && (long - 243.0).abs() < 0.5, "printed on the card: {} × {}", page.width, page.height); + let saved = app.session.active().unwrap().doc.print_setup.clone().unwrap(); + assert_eq!(saved["media"], "custom", "the document keeps the card as its size"); + // Each printer's driver is asked once, when it is chosen. + assert_eq!(*asked.borrow(), ["Office", "Card"]); +} + +#[test] +fn switching_printers_keeps_an_unlisted_paper_as_a_custom_size() { + let services = Services { print: Some(Box::new(PaperPrint(Jobs::default(), Asked::default()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + // The printer changes in the same frame as the card is chosen, before Width and Height take its size. + set(&mut app, "media", json!("printer:CR80")); + set(&mut app, "printer", json!("Office")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "custom"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); +} + +#[test] +fn confirming_after_switching_printers_keeps_the_selected_paper_size() { + let jobs = Jobs::default(); + let services = Services { print: Some(Box::new(PaperPrint(jobs.clone(), Asked::default()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + set(&mut app, "printer", json!("Office")); + confirm(&mut app); + assert!(!is_open(&app)); + let job = jobs.borrow(); + assert_eq!(job.len(), 1); + assert_eq!(job[0].0.as_deref(), Some("Office")); + let page = &vectorcraft_pdf::info(&job[0].2, None).unwrap().pages[0]; + let (short, long) = (page.width.min(page.height), page.width.max(page.height)); + assert!((short - 153.0).abs() < 0.5 && (long - 243.0).abs() < 0.5, "printed on the card: {} × {}", page.width, page.height); +} + +#[test] +fn a_printer_paper_prints_at_its_size_and_a_preset_replaces_it() { + let jobs = Jobs::default(); + let services = Services { print: Some(Box::new(PaperPrint(jobs.clone(), Asked::default()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("print.presets.save", json!({"name": "Big", "settings": {"media": "custom", "width": 400, "height": 500}})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + // A preset's own size replaces the card's. + set(&mut app, "preset", json!("Big")); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!((f["media"].as_str(), f["width"].as_f64(), f["height"].as_f64()), (Some("custom"), Some(400.0), Some(500.0)), "{f}"); + // The card chosen and OK pressed before the dialog is served again still prints on the card. + set(&mut app, "media", json!("printer:CR80")); + confirm(&mut app); + assert!(!is_open(&app)); + let job = jobs.borrow(); + let page = &vectorcraft_pdf::info(&job[0].2, None).unwrap().pages[0]; + let (short, long) = (page.width.min(page.height), page.width.max(page.height)); + assert!((short - 153.0).abs() < 0.5 && (long - 243.0).abs() < 0.5, "printed on the card: {} × {}", page.width, page.height); +} + +#[test] +fn a_preset_size_the_printer_does_not_list_stays_a_choice() { + let services = Services { print: Some(Box::new(PaperPrint(Jobs::default(), Asked::default()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("print.presets.save", json!({"name": "Tall", "settings": {"media": "a3"}})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + assert!(try_set(&mut app, "media", json!("a3")).is_err(), "the card printer lists no A3"); + set(&mut app, "preset", json!("Tall")); + pump(&mut app); + pump(&mut app); + assert_eq!(fields(&app)["media"], "a3"); + // A3 is offered while it is chosen, so choosing another size and going back works. + set(&mut app, "media", json!("letter")); + set(&mut app, "media", json!("a3")); +} + +#[test] +fn a_ppd_lists_its_paper_dimensions_by_name() { + let ppd = "*OpenUI *PageSize/Media Size: PickOne\r\n\ + *PageSize Letter/US Letter: \"<>setpagedevice\"\r\n\ + *PageSize CR80/CR80 Card: \"<>setpagedevice\"\r\n\ + *CloseUI: *PageSize\r\n\ + *PaperDimension Letter: \"612 792\"\r\n\ + *PaperDimension CR80: \"153 243\"\r\n\ + *PaperDimension CR80: \"100 100\"\r\n\ + *PaperDimension Stamp/Stamp: \"20 20\"\r\n\ + *PaperDimension Bad: \"612\"\r\n\ + *PaperDimension Roll/Banner Roll: \"612 14400\"\r\n"; + let papers = crate::print::ppd_papers(ppd); + let got: Vec<(&str, &str, f64, f64)> = papers.iter().map(|p| (p.key.as_str(), p.label.as_str(), p.width, p.height)).collect(); + // The repeated CR80, a size below 72 pt and a line without a height are left out. + assert_eq!(got, [("Letter", "US Letter", 612.0, 792.0), ("CR80", "CR80 Card", 153.0, 243.0), ("Roll", "Banner Roll", 612.0, 14400.0)]); +} + +#[test] +fn windows_paper_sizes_are_read_in_hundredths_of_an_inch() { + let out = "1\tLetter\t850\t1100\r\n\ + 256\tCard\t213\t338\r\n\ + 256\tBanner\t850\t2000\r\n\ + 256\t\t213\t338\r\nbroken line\r\n9\tTiny\t10\t10\r\n"; + let papers = crate::print::windows_papers(out); + let got: Vec<(&str, &str, f64, f64)> = papers.iter().map(|p| (p.key.as_str(), p.label.as_str(), p.width, p.height)).collect(); + assert_eq!(got.len(), 4, "{got:?}"); + assert_eq!((got[0].0, got[0].1), ("Letter", "Letter")); + assert!((got[0].2 - 612.0).abs() < 1e-9 && (got[0].3 - 792.0).abs() < 1e-9); + assert_eq!((got[1].0, got[1].1), ("Card", "Card")); + assert_eq!((got[2].0, got[2].1), ("Banner", "Banner")); + assert_eq!((got[3].0, got[3].1), ("256", "256"), "no name: the number"); +} + /// A print queue that puts each page on the paper as it is, as `lp` does. struct UprightQueue(Jobs); diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index 863c94673d..7989474924 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -52,6 +52,95 @@ pub trait PrintService { fn setup(&mut self, _printer: Option<&str>) -> Result<(), String> { Err("there are no printer settings to open here".into()) } + /// The driver's paper sizes, in its order, without waiting for a program. The dialog polls + /// pending lookups and offers its own sizes until the driver returns a nonempty list. + fn papers(&mut self, _printer: &str) -> Papers { + Papers::Ready(Vec::new()) + } +} + +/// A driver's paper sizes, or a lookup still running on a worker. +pub enum Papers { + /// The lookup finished; an empty list uses the dialog's sizes. + Ready(Vec), + /// Poll again on a later frame. + Pending, +} + +/// A paper size a printer's driver offers. +#[derive(Clone, Debug, PartialEq)] +pub struct Paper { + /// The driver's keyword for it (`Letter`, `CR80`), or its form name on Windows (the number when unnamed). + pub key: String, + /// What the driver calls it (`US Letter`); the keyword when it gives no name. + pub label: String, + /// Width in points. + pub width: f64, + /// Height in points. + pub height: f64, +} + +/// Most sizes kept from one driver; a PPD is a text file from the printer vendor. +const MAX_PAPERS: usize = 400; +/// Longest paper label kept, in characters. +const MAX_PAPER_LABEL: usize = 128; +/// The smallest and largest paper side the print settings take (`media: custom`), in points. +const PAPER_SIDE: std::ops::RangeInclusive = 72.0..=14400.0; + +/// `paper`, unless the list is full, its key is taken or a side is outside 72–14400 pt. +fn push_paper(papers: &mut Vec, paper: Paper) { + let fits = PAPER_SIDE.contains(&paper.width) && PAPER_SIDE.contains(&paper.height); + if fits && papers.len() < MAX_PAPERS && papers.iter().all(|p| p.key != paper.key) { + papers.push(Paper { label: paper.label.chars().take(MAX_PAPER_LABEL).collect(), ..paper }); + } +} + +/// The paper sizes of a PPD: each `*PaperDimension` entry (`*PaperDimension CR80/CR80 Card: "153 243"`), named by +/// its own label or else by the `*PageSize` entry with the same keyword. Sizes outside 72–14400 pt, repeated keywords +/// and malformed lines are skipped. +pub fn ppd_papers(ppd: &str) -> Vec { + fn entry<'a>(line: &'a str, key: &str) -> Option<(&'a str, &'a str, &'a str)> { + let rest = line.strip_prefix('*')?.strip_prefix(key)?.strip_prefix(' ')?; + let (head, value) = rest.split_once(':')?; + let (name, label) = head.split_once('/').map_or((head.trim(), ""), |(n, l)| (n.trim(), l.trim())); + (!name.is_empty() && !name.contains(char::is_whitespace)).then_some((name, label, value.trim())) + } + let mut labels: Vec<(&str, &str)> = Vec::new(); + let mut papers: Vec = Vec::new(); + for line in ppd.lines().map(|l| l.trim_end_matches('\r')) { + if let Some((name, label, _)) = entry(line, "PageSize") { + if !label.is_empty() && labels.len() < MAX_PAPERS { + labels.push((name, label)); + } + } else if let Some((name, label, value)) = entry(line, "PaperDimension") { + let mut nums = value.trim_matches('"').split_whitespace().map(str::parse::); + let (Some(Ok(width)), Some(Ok(height)), None) = (nums.next(), nums.next(), nums.next()) else { continue }; + push_paper(&mut papers, Paper { key: name.into(), label: label.into(), width, height }); + } + } + for p in &mut papers { + if p.label.is_empty() { + let label = labels.iter().find(|(n, _)| *n == p.key).map_or(p.key.as_str(), |(_, l)| l); + p.label = label.chars().take(MAX_PAPER_LABEL).collect(); + } + } + papers +} + +/// The paper sizes in tab-separated lines of number, name, width and height (hundredths of an inch), as Windows' +/// printer settings list them (`PrinterSettings.PaperSizes`). The same limits as [`ppd_papers`] apply. +pub fn windows_papers(out: &str) -> Vec { + let mut papers: Vec = Vec::new(); + for line in out.lines() { + let fields: Vec<&str> = line.trim_end_matches('\r').split('\t').map(str::trim).collect(); + let [key, label, w, h] = fields[..] else { continue }; + let (Ok(w), Ok(h)) = (w.parse::(), h.parse::()) else { continue }; + if !key.is_empty() { + let label = if label.is_empty() { key } else { label }; + push_paper(&mut papers, Paper { key: label.into(), label: label.into(), width: w * 0.72, height: h * 0.72 }); + } + } + papers } /// `print.printers`: the system's printers, and what the print service offers. From e8ecd67f2db0cd8e9511c74454230797979ec78f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 17:39:31 -0800 Subject: [PATCH 21/32] Dock: the docked Tools card keeps its rounded top corners In the Classic look, the docked Tools card at the window edge drew a rounded dark bar over a body with square top corners, so the body's corners showed past the bar and the card's top corners did not look rounded. craft-libs#4723 paints the bar with the card's corner radius and starts the body under the bar. craft-libs moves to 823f0d1a, the head of #4723, which is the current pin a5669ed2 plus that fix; egui and winit stay at the revs craft-libs pins. craft-web-api and xtask pdf-deps move with the other craft-libs crates. the_docked_tools_card_keeps_its_rounded_top_corners checks the Classic and Modern looks at UI Scaling 100% and 200%: every opaque surface that reaches a top corner of the Tools card is rounded there at least as much as the card's foot. --- Cargo.lock | 172 +++++++++++----------- Cargo.toml | 76 +++++----- apps/vectorcraft-web/Cargo.toml | 2 +- crates/ui-egui/src/panel_docking/tests.rs | 59 ++++++++ xtask/src/pdf_deps.rs | 2 +- 5 files changed, 185 insertions(+), 126 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9a3010412f..985e7d0ae4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1231,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-automation", "craft-behavior", @@ -1272,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "crc32fast", "flate2", @@ -1283,7 +1283,7 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -1295,7 +1295,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "rustix 1.1.6", ] @@ -1303,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1328,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-docpath", @@ -1364,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "crc32fast", "flate2", @@ -1373,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "md-5", "rayon", @@ -1390,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-cms", @@ -1415,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1426,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1436,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1470,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "blake3", "craft-ecproj-format", @@ -1486,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1513,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-codepage", "encoding_rs", @@ -1525,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "serde", "serde_json", @@ -1535,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1555,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1574,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1583,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "cap-primitives", "craft-atomic", @@ -1606,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1640,7 +1640,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "brotli 9.1.3", "brotli-decompressor 6.3.2", @@ -1670,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-dds", "craft-jpeg", @@ -1697,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1715,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "thiserror 2.0.21", ] @@ -1723,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1734,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-host", "craft-i18n", @@ -1749,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-i18n", @@ -1763,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-host", @@ -1781,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1793,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "encoding_rs", "image", @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "chrono", "craft-codepage", @@ -1814,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-nightly" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "uds_windows", "winsafe", @@ -1823,7 +1823,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-keymap", @@ -1839,7 +1839,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "flate2", "serde", @@ -1850,7 +1850,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1862,7 +1862,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "async-channel", "async-io", @@ -1895,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1904,7 +1904,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-host", @@ -1928,7 +1928,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1939,7 +1939,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-eps", "flate2", @@ -1953,7 +1953,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "encoding_rs", "flate2", @@ -1964,7 +1964,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "dispatch2", "egui", @@ -1977,7 +1977,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1996,7 +1996,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-atomic", "craft-host", @@ -2013,7 +2013,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "fax", "hayro-ccitt", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2045,7 +2045,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-keymap", @@ -2057,7 +2057,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2082,7 +2082,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2097,7 +2097,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-atomic", "craft-behavior", @@ -2112,7 +2112,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "serde", "thiserror 2.0.21", @@ -2122,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "serde", "thiserror 2.0.21", @@ -2131,7 +2131,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-keymap", @@ -2146,12 +2146,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2165,7 +2165,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-i18n", @@ -2181,7 +2181,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "accesskit", "craft-behavior", @@ -2219,7 +2219,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2230,7 +2230,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-host", @@ -2248,7 +2248,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-host", @@ -2269,7 +2269,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-host", @@ -2290,7 +2290,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-behavior", "craft-host", @@ -2309,7 +2309,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "base64 0.22.1", "chrono", @@ -2341,7 +2341,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "flate2", "serde", @@ -2352,7 +2352,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2362,7 +2362,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "js-sys", "serde_json", @@ -2373,7 +2373,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "winsafe", ] @@ -2381,7 +2381,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "craft-appkit", "craft-atomic", @@ -2413,7 +2413,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3772,7 +3772,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3781,7 +3781,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3799,7 +3799,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3817,12 +3817,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "flate2", "hayro-ccitt", @@ -4805,7 +4805,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4962,7 +4962,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0#a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" +source = "git+https://github.com/storytold/craft-libs?rev=823f0d1a40cd485a3cb0730e610d46333e8aa7e0#823f0d1a40cd485a3cb0730e610d46333e8aa7e0" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index e1a20cac68..56bfdc826f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,51 +10,51 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # The `.vectorcraft` envelope: its members, version, embedded images and the data after the JSON. -craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names # the members it imports. -craft = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui # without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes. -craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # Nightly profile isolation, launch protocol, and security fence. -craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -194,13 +194,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } emath = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } epaint = { git = "https://github.com/storytold/egui.git", rev = "07c20531f89717e461c0f387dd1f9649553f9321" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 30d529a5e7..ba3bc2c321 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -28,7 +28,7 @@ egui_extras = { workspace = true } # `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 3476f5c2b0..ea85426b5d 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -1107,6 +1107,65 @@ fn a_docked_column_is_never_narrower_than_the_panel_minimum() { assert!(body_width(&h, "Properties") >= PANEL_MIN_WIDTH - 0.5, "saved 100 pt wide: {}", body_width(&h, "Properties")); } +/// The opaque rects the last frame painted inside `cell`. +fn opaque_rects_in(shapes: &[egui::epaint::ClippedShape], cell: Rect) -> Vec { + crate::tests_labels::painted_shapes(shapes) + .into_iter() + .filter_map(|(shape, transform, _)| match shape { + egui::Shape::Rect(r) if r.fill.a() == 255 => { + let mut r = r.clone(); + r.rect = transform * r.rect; + cell.expand(0.75).contains_rect(r.rect).then_some(r) + } + _ => None, + }) + .collect() +} + +/// The docked Tools card, in each color scheme and at UI Scaling 100% and 200%: its bar and its body keep to the +/// card's rounded top corners. Every opaque surface that reaches a top corner of the card is rounded there at least as +/// much as the card's foot is, so no square corner shows past the bar's rounded one. +#[test] +fn the_docked_tools_card_keeps_its_rounded_top_corners() { + let near = |a: f32, b: f32| (a - b).abs() <= 0.75; + for scheme in ["classic", "modern"] { + for scaling in [1.0, 2.0] { + let case = format!("{scheme} at {scaling}"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.ui_color_scheme = scheme.into(); + app.session.prefs.ui_scaling = scaling; + Arc::make_mut(&mut app.ui.dock_workspace).replace(builtin_workspace(&[], 2)); + let ctx = crate::testing::ui_context(); + let mut shapes = Vec::new(); + for frame in 0..4 { + let input = egui::RawInput { time: Some(f64::from(frame) * 0.05), screen_rect: Some(SCREEN), ..Default::default() }; + shapes = crate::testing::app_frame(&mut app, &ctx, input).shapes; + } + let cell = app.dock_rt.columns.iter().find(|(panel, _)| panel == crate::toolbar::TOOLS).map(|(_, rect)| *rect); + let cell = cell.unwrap_or_else(|| panic!("{case}: the Tools column is docked")); + let rects = opaque_rects_in(&shapes, cell); + // The card's foot: the largest surface in the column with rounded lower corners. + let foot = rects + .iter() + .filter(|r| r.corner_radius.sw > 0 && r.corner_radius.se > 0) + .max_by(|a, b| a.rect.area().total_cmp(&b.rect.area())) + .unwrap_or_else(|| panic!("{case}: the Tools card is painted: {rects:?}")); + let spans = |r: &&egui::epaint::RectShape| near(r.rect.left(), foot.rect.left()) && near(r.rect.right(), foot.rect.right()); + let top = rects.iter().filter(spans).map(|r| r.rect.top()).fold(foot.rect.top(), f32::min); + let at_top: Vec<_> = rects.iter().filter(|r| near(r.rect.top(), top)).collect(); + let left: Vec<_> = at_top.iter().filter(|r| near(r.rect.left(), foot.rect.left())).collect(); + let right: Vec<_> = at_top.iter().filter(|r| near(r.rect.right(), foot.rect.right())).collect(); + assert!(!left.is_empty() && !right.is_empty(), "{case}: the card's top is painted: {at_top:?}"); + for r in left { + assert!(r.corner_radius.nw >= foot.corner_radius.sw, "{case}: a square corner shows at the card's top left: {r:?}"); + } + for r in right { + assert!(r.corner_radius.ne >= foot.corner_radius.se, "{case}: a square corner shows at the card's top right: {r:?}"); + } + } + } +} + /// A tab group dragged out of the icon column by its grip floats as an expanded panel: its tabs show /// in the window, and a click on each tab shows that panel. #[test] diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index 216d23d43d..f98d2ead3d 100644 --- a/xtask/src/pdf_deps.rs +++ b/xtask/src/pdf_deps.rs @@ -5,7 +5,7 @@ use std::process::Command; use serde_json::Value; -const REV: &str = "a5669ed2f1ba62545a1f0d884ecbd0fd0fbd06e0"; +const REV: &str = "823f0d1a40cd485a3cb0730e610d46333e8aa7e0"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From c33f0cfa133d170df1bdd533a19704643a212038 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 18:06:39 -0800 Subject: [PATCH 22/32] Print: each printer choice reads the driver's paper sizes again A lookup that was still running when the person chose another printer stayed in the service, and choosing that printer again returned its old answer without reading the driver. Reopening the dialog on a printer whose lookup was still running did the same. `PrintService::papers` now takes `fresh`, which the dialog sets when it opens and when the printer changes. The desktop service keeps one lookup in flight and replaces it on a fresh call or a call for another printer, so an earlier answer is dropped. --- apps/vectorcraft/src/printing.rs | 87 +++++++++++++++++++---- crates/ui-egui/src/dialogs/print.rs | 11 +-- crates/ui-egui/src/dialogs/tests_print.rs | 46 +++++++++++- crates/ui-egui/src/print.rs | 4 +- 4 files changed, 126 insertions(+), 22 deletions(-) diff --git a/apps/vectorcraft/src/printing.rs b/apps/vectorcraft/src/printing.rs index 9e64fcc75c..e7f5db9a69 100644 --- a/apps/vectorcraft/src/printing.rs +++ b/apps/vectorcraft/src/printing.rs @@ -7,8 +7,8 @@ mod direct_pdf; #[derive(Default)] pub struct SystemPrint { - /// Channels for pending paper-size lookups, removed when each worker answers or disconnects. - papers: std::collections::HashMap>>, + /// The paper-size lookup in flight, dropped when its worker answers or disconnects. + papers: PaperLookup, } impl PrintService for SystemPrint { @@ -36,21 +36,33 @@ impl PrintService for SystemPrint { fn scripts_may_print(&self) -> bool { true } - fn papers(&mut self, printer: &str) -> Papers { - let receive = self.papers.entry(printer.to_string()).or_insert_with(|| { + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + self.papers.poll(printer, fresh, |printer| installed_papers(&printer)) + } +} + +/// The paper-size lookup in flight: the printer it reads and its worker's channel. +#[derive(Default)] +struct PaperLookup(Option<(String, std::sync::mpsc::Receiver>)>); + +impl PaperLookup { + /// Poll the lookup of `printer`. A new lookup runs `read` on a worker when `fresh` is set, when the one in flight + /// reads another printer, or when none is in flight; the earlier one's answer is dropped. + fn poll(&mut self, printer: &str, fresh: bool, read: impl FnOnce(String) -> Vec + Send + 'static) -> Papers { + if fresh || self.0.as_ref().is_none_or(|(p, _)| p != printer) { let (send, receive) = std::sync::mpsc::channel(); - let printer = printer.to_string(); + let name = printer.to_string(); let _ = std::thread::Builder::new().name("printer-papers".into()).spawn(move || { - let _ = send.send(installed_papers(&printer)); + let _ = send.send(read(name)); }); - receive - }); - let result = match receive.try_recv() { - Ok(papers) => Papers::Ready(papers), - Err(std::sync::mpsc::TryRecvError::Disconnected) => Papers::Ready(Vec::new()), - Err(std::sync::mpsc::TryRecvError::Empty) => return Papers::Pending, + self.0 = Some((printer.to_string(), receive)); + } + let result = match self.0.as_ref().map(|(_, receive)| receive.try_recv()) { + Some(Ok(papers)) => Papers::Ready(papers), + Some(Err(std::sync::mpsc::TryRecvError::Empty)) => return Papers::Pending, + Some(Err(std::sync::mpsc::TryRecvError::Disconnected)) | None => Papers::Ready(Vec::new()), }; - self.papers.remove(printer); + self.0 = None; result } } @@ -233,6 +245,55 @@ mod tests { } } +#[cfg(test)] +mod paper_lookup_tests { + use super::PaperLookup; + use vectorcraft_ui_egui::print::{Paper, Papers}; + + fn paper(key: &str) -> Vec { + vec![Paper { key: key.into(), label: key.into(), width: 100.0, height: 200.0 }] + } + + /// Start a fresh lookup of `printer` that answers `key`, and poll it until it answers. + fn answer(lookup: &mut PaperLookup, printer: &str, key: &'static str) -> Vec { + let mut polled = lookup.poll(printer, true, move |_| paper(key)); + loop { + match polled { + Papers::Ready(papers) => return papers, + Papers::Pending => std::thread::yield_now(), + } + polled = lookup.poll(printer, false, |_| panic!("polling starts no lookup")); + } + } + + /// A read that answers `key` once `gate` lets it. + fn gated(key: &'static str) -> (std::sync::mpsc::Sender<()>, impl FnOnce(String) -> Vec + Send + 'static) { + let (open, gate) = std::sync::mpsc::channel::<()>(); + (open, move |_| { + let _ = gate.recv(); + paper(key) + }) + } + + #[test] + fn a_fresh_lookup_drops_the_answer_of_an_earlier_one() { + let mut lookup = PaperLookup::default(); + let (open, read) = gated("Old"); + assert!(matches!(lookup.poll("Card", true, read), Papers::Pending)); + let (other, read) = gated("Office"); + assert!(matches!(lookup.poll("Office", true, read), Papers::Pending)); + let _ = open.send(()); + let _ = other.send(()); + // Back on the card printer. + assert_eq!(answer(&mut lookup, "Card", "New"), paper("New")); + // The dialog opens again on the card printer while a lookup of it is still running. + let (open, read) = gated("Stale"); + assert!(matches!(lookup.poll("Card", true, read), Papers::Pending)); + let _ = open.send(()); + assert_eq!(answer(&mut lookup, "Card", "Newer"), paper("Newer")); + } +} + #[cfg(test)] mod turn_tests { use super::sent; diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 3021537994..6828d54559 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -218,12 +218,13 @@ fn settings_with_paper(fields: &DialogFields, papers: &[Paper]) -> Value { out } -/// The paper sizes the driver of `printer` offers (none for preset editing, the default printer and PDF File). -fn papers_of(app: &mut VectorcraftApp, mode: PrintMode, printer: &str) -> (Vec, bool) { +/// The paper sizes the driver of `printer` offers (none for preset editing, the default printer and PDF File). `fresh` +/// starts a new lookup: the dialog opened or the printer changed. +fn papers_of(app: &mut VectorcraftApp, mode: PrintMode, printer: &str, fresh: bool) -> (Vec, bool) { if mode == PrintMode::PresetEditor || printer.is_empty() || printer == PDF_FILE { return (Vec::new(), false); } - match app.services.print.as_mut().map(|s| s.papers(printer)) { + match app.services.print.as_mut().map(|s| s.papers(printer, fresh)) { Some(Papers::Ready(papers)) => (papers, false), Some(Papers::Pending) => (Vec::new(), true), None => (Vec::new(), false), @@ -296,7 +297,7 @@ fn start( let named = editing.clone(); let driver = driver(has_setup(app), &state.settings.destination); let printer = printer_of(&state.settings.destination); - let (papers, papers_pending) = papers_of(app, mode, &printer); + let (papers, papers_pending) = papers_of(app, mode, &printer, true); if papers_pending { ctx.request_repaint(); } @@ -491,7 +492,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, answer.fields.set("height", paper.height); answer.fields.set("media", Media::Custom.id()); } - let (papers, pending) = papers_of(app, open.mode, &d.printer); + let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed); papers_changed = printer_changed || !pending; open.papers = (d.printer.clone(), papers); open.papers_pending = pending; diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 48002b08d8..c52e5782da 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -249,7 +249,7 @@ impl PrintService for PaperPrint { MockPrint(self.0.clone()).print(job) } - fn papers(&mut self, printer: &str) -> Papers { + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { self.1.borrow_mut().push(printer.to_string()); let paper = |key: &str, label: &str, width, height| crate::print::Paper { key: key.into(), label: label.into(), width, height }; Papers::Ready(match printer { @@ -271,11 +271,51 @@ impl PrintService for PendingPaperPrint { self.0.print(job) } - fn papers(&mut self, printer: &str) -> Papers { - if self.1.get() < 2 { Papers::Pending } else { self.0.papers(printer) } + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + if self.1.get() < 2 { Papers::Pending } else { self.0.papers(printer, fresh) } } } +/// The lookups the dialog asked for, as (printer, fresh). +type Lookups = Rc>>; + +/// Two printers whose drivers never answer. +struct SlowPaperPrint(Jobs, Lookups); + +impl PrintService for SlowPaperPrint { + fn printers(&mut self) -> Vec { + vec![Printer::new("Office").is_default(true), Printer::new("Card")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(self.0.clone()).print(job) + } + + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + self.1.borrow_mut().push((printer.to_string(), fresh)); + Papers::Pending + } +} + +#[test] +fn choosing_a_printer_again_starts_a_new_paper_lookup() { + let lookups = Lookups::default(); + let services = Services { print: Some(Box::new(SlowPaperPrint(Jobs::default(), lookups.clone()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + set(&mut app, "printer", json!("Office")); + pump(&mut app); + pump(&mut app); + let log = lookups.borrow(); + let fresh: Vec<&str> = log.iter().filter(|(_, f)| *f).map(|(p, _)| p.as_str()).collect(); + assert_eq!(fresh, ["Office", "Card", "Office"], "the opening and each printer change start a lookup: {log:?}"); + assert_eq!(log.last(), Some(&("Office".to_string(), false)), "later frames poll the lookup in flight: {log:?}"); +} + #[test] fn preset_editor_keeps_its_own_sizes_without_asking_the_default_printer() { let asked = Asked::default(); diff --git a/crates/ui-egui/src/print.rs b/crates/ui-egui/src/print.rs index d6c7794912..0451cb5b5c 100644 --- a/crates/ui-egui/src/print.rs +++ b/crates/ui-egui/src/print.rs @@ -65,7 +65,9 @@ pub trait PrintService { } /// The driver's paper sizes, in its order, without waiting for a program. The dialog polls /// pending lookups and offers its own sizes until the driver returns a nonempty list. - fn papers(&mut self, _printer: &str) -> Papers { + /// `fresh` is set when the dialog opens or the printer changes: the driver is read again, + /// and a lookup still running from an earlier choice is dropped. + fn papers(&mut self, _printer: &str, _fresh: bool) -> Papers { Papers::Ready(Vec::new()) } } From f251709e54caee8253c339a0bb839a462ea4fd1b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:24:47 -0800 Subject: [PATCH 23/32] Print: a paper keyword at another size on the new printer becomes Custom Paper keywords belong to each printer's driver. When the printer changes and the new driver lists the chosen keyword at a different size, the Size row now keeps the previous Width and Height as a Custom size instead of taking the new printer's dimensions. A keyword listed at the same size stays chosen. --- crates/ui-egui/src/dialogs/print.rs | 10 ++++-- crates/ui-egui/src/dialogs/tests_print.rs | 41 +++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 6828d54559..314e2bc032 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -208,6 +208,11 @@ fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a P papers.iter().find(|p| p.key == key) } +/// Whether two papers have the same Width and Height, to within half a point. +fn same_size(a: &Paper, b: &Paper) -> bool { + (a.width - b.width).abs() <= 0.5 && (a.height - b.height).abs() <= 0.5 +} + /// The print settings of `fields`, with Width and Height at the size of the printer's paper the Size row names. fn settings_with_paper(fields: &DialogFields, papers: &[Paper]) -> Value { let mut out = settings(fields); @@ -500,12 +505,13 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, if open.papers_pending { ctx.request_repaint(); } - // A paper the new printer doesn't list becomes a custom size of the same Width and Height. + // A paper the new printer doesn't list, or lists under the same keyword at another size, becomes a custom size of + // the same Width and Height. if papers_changed && media.starts_with(PRINTER_PAPER) && let Some(s) = on(dialogs, |p| { let fields = p.fields_mut(); - if printer_paper(fields, &open.papers.1).is_some() { + if printer_paper(fields, &open.papers.1).is_some_and(|new| chosen.as_ref().is_none_or(|old| same_size(old, new))) { return None; } if let Some(paper) = &chosen { diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index c52e5782da..10ec8a5a70 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -403,6 +403,47 @@ fn switching_printers_keeps_an_unlisted_paper_as_a_custom_size() { assert!(try_set(&mut app, "media", json!("printer:CR80")).is_err()); } +/// Three card printers: Card and Twin list a CR80 card at 153 × 243 points, and Badge lists a CR80 at 200 × 300. +struct CardPrinters; + +impl PrintService for CardPrinters { + fn printers(&mut self) -> Vec { + vec![Printer::new("Card").is_default(true), Printer::new("Twin"), Printer::new("Badge")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { + let (width, height) = if printer == "Badge" { (200.0, 300.0) } else { (153.0, 243.0) }; + Papers::Ready(vec![crate::print::Paper { key: "CR80".into(), label: "CR80 Card".into(), width, height }]) + } +} + +#[test] +fn a_paper_keyword_another_printer_lists_at_another_size_becomes_a_custom_size() { + let services = Services { print: Some(Box::new(CardPrinters)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + // Twin's CR80 is the same size, so it stays chosen. + set(&mut app, "printer", json!("Twin")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:CR80", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + // Badge's CR80 is another size: the card keeps its size as a custom size. + set(&mut app, "printer", json!("Badge")); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "custom", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); +} + #[test] fn confirming_after_switching_printers_keeps_the_selected_paper_size() { let jobs = Jobs::default(); From 70d70ca909b61eb26566f0b7e48bac07b79bbdc1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:09:17 -0800 Subject: [PATCH 24/32] Scripts: width, height and position setters measure after the document comes to the front Setting width, height, left, top or position on an item in a document in the back measured the item before its document was made active. Making a document active measures its type again where it is not measured yet or where a composite font of the same name changed, so the scale ratio or the move distance applied to bounds that no longer held, and the item ended at a different size or place than the one asked for. The measurement now runs inside the edit, after the switch, through a new edit_item_with that edit_item also uses. --- crates/engine/src/script/dom.rs | 56 +++++++++++++++++---------- crates/engine/src/tests/script_dom.rs | 31 +++++++++++++++ 2 files changed, 66 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index ec258ffae2..b29b037908 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -975,9 +975,16 @@ pub(super) fn after_kept_command(h: &Host) { /// selection cannot be put back, the edit is undone too. The points the run read of the item's /// paths stay valid through the change ([`paths::see_all_points`]). fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { + edit_item_with(h, item, |h| command(h, id, params)) +} + +/// Runs `f` on the item's document as [`edit_item`] runs its command. `f` runs after the document +/// is made active, so bounds it reads take in type that the switch measured again (in the +/// document's own composite fonts, [`Session::set_active`]). +fn edit_item_with(h: &Host, item: Item, f: impl FnOnce(&Host) -> std::result::Result) -> std::result::Result { paths::see_all_points(h); let kept = h.dom.editing.replace(Some(item)); - let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| command(h, id, params))); + let r = atomically(h, |h| on_doc(h, item.doc.uid, true, f)); h.dom.editing.set(kept); r } @@ -2549,14 +2556,18 @@ fn move_to(h: &Host, a: &[Data], x: Option, y: Option) -> Answer { let item = this_item(h, a)?; refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; - let c = h.dom.coords.get(); - let now = f.to_script(c, Point::new(r.x0, r.y0)); - let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); - let (dx, dy) = (to.x - r.x0, to.y - r.y0); - if dx.abs() > 1e-9 || dy.abs() > 1e-9 { - edit_item(h, item, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?; - } + // Measured once the document is active. + edit_item_with(h, item, |h| { + let (Some(r), f) = item_rect(h, item, false)? else { return Ok(()) }; + let c = h.dom.coords.get(); + let now = f.to_script(c, Point::new(r.x0, r.y0)); + let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]); + let (dx, dy) = (to.x - r.x0, to.y - r.y0); + if dx.abs() > 1e-9 || dy.abs() > 1e-9 { + command(h, "object.move", &json!({"ids": [item.id.0], "dx": dx, "dy": dy}))?; + } + Ok(()) + })?; Ok(Data::Undefined) } @@ -2590,18 +2601,21 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer { } refuse_protected_edit(h, item)?; selection_ids(h, item.doc, arg(a, 0))?; - let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) }; - let now = if width { r.width() } else { r.height() }; - if now <= 0.0 { - return Err(HostError::Error(format!("the object has no {what} to scale"))); - } - if (now - size).abs() < 1e-9 { - return Ok(Data::Undefined); - } - let pct = size / now * 100.0; - let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; - let p = json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}); - edit_item(h, item, "object.scale", &p)?; + // Measured once the document is active, so the ratio applies to the bounds the scale works on. + edit_item_with(h, item, |h| { + let (Some(r), _) = item_rect(h, item, false)? else { return Ok(()) }; + let now = if width { r.width() } else { r.height() }; + if now <= 0.0 { + return Err(HostError::Error(format!("the object has no {what} to scale"))); + } + if (now - size).abs() < 1e-9 { + return Ok(()); + } + let pct = size / now * 100.0; + let (sx, sy) = if width { (pct, 100.0) } else { (100.0, pct) }; + command(h, "object.scale", &json!({"ids": [item.id.0], "sx": sx, "sy": sy, "origin": [r.x0, r.y0], "basis": "page"}))?; + Ok(()) + })?; Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 74311f240f..f731eef72d 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -155,6 +155,37 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was"); } +/// Type in a document in the back that the switch to that document measures again (here: not +/// measured yet) is sized and moved by the bounds measured after the switch. +#[test] +fn page_item_size_and_position_setters_measure_type_in_a_back_document_after_the_switch() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Wide type here", "size": 40})).unwrap()["id"].as_u64().unwrap()); + let uid = s.active().unwrap().uid; + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let front = s.active().unwrap().uid; + let unmeasure = |s: &mut Session| { + let st = s.document_mut(uid).unwrap(); + if let Some(NodeKind::Text(t)) = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).map(|n| &mut n.kind) { + t.cached_bounds = None; + t.cached_baselines.clear(); + } + }; + let mut got = Vec::new(); + for (set, want) in + [("t.width = 150; vc.log(t.width);", 150.0), ("t.height = 90; vc.log(t.height);", 90.0), ("t.top = 200; vc.log(t.top);", 200.0)] + { + unmeasure(&mut s); + let out = log(&mut s, &format!("var t = app.documents[1].pageItems[0]; {set}")); + got.push((set, out[0].as_f64().unwrap(), want)); + } + for (set, got, want) in got { + assert!((got - want).abs() < 1e-6, "{set} read {got}"); + } + assert_eq!(s.active().unwrap().uid, front, "the front document stays in front"); +} + /// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the /// visible bounds. #[test] From 8fa6a542077a803d45560050d99000ea47997cf9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:10:19 -0800 Subject: [PATCH 25/32] Print: a paper keeps its size while a printer is looked up and in a new preset While the newly chosen printer's driver has not answered, the Size list keeps the previous printer's sizes, so a printer paper stays chosen at its size. It becomes Custom only when the answer lists it at another size or not at all. A preset created in the same pass as a printer paper is chosen now saves that paper's Width and Height, the size the dialog shows, instead of the size before it. --- crates/ui-egui/src/dialogs/print.rs | 16 ++++-- crates/ui-egui/src/dialogs/tests_print.rs | 65 +++++++++++++++++++++++ 2 files changed, 77 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 314e2bc032..8ec1176cfa 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -112,7 +112,8 @@ struct Open { preview: Option<(Stamp, Arc>)>, /// The printer row's driver controls, as the dialog was last given them. driver: DriverControls, - /// The printer the Media list was made for, and the paper sizes its driver offers. + /// The printer the Media list was made for, and the paper sizes its driver offers (while its lookup runs, the sizes + /// of the printer before it). papers: (String, Vec), /// Whether the chosen printer still has a lookup running. papers_pending: bool, @@ -498,8 +499,13 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, answer.fields.set("media", Media::Custom.id()); } let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed); - papers_changed = printer_changed || !pending; - open.papers = (d.printer.clone(), papers); + // While the new printer's lookup runs, the Size list keeps the sizes before it, so the paper chosen keeps its + // name and size until the driver answers. + papers_changed = !pending; + open.papers.0 = d.printer.clone(); + if !pending { + open.papers.1 = papers; + } open.papers_pending = pending; } if open.papers_pending { @@ -654,7 +660,9 @@ fn apply_preset_event(app: &mut VectorcraftApp, dialogs: &WindowDialogs, open: & } } NamedPresetEvent::Create { name, .. } => { - match app.run("print.presets.save", json!({ "name": name, "preset": DEFAULT_PRESET, "settings": settings })) { + // A printer's paper chosen this pass is saved at its size, which the dialog shows once the pump has run. + let saved = on(dialogs, |p| settings_with_paper(p.fields(), &open.papers.1)).unwrap_or_else(|| settings.clone()); + match app.run("print.presets.save", json!({ "name": name, "preset": DEFAULT_PRESET, "settings": saved })) { Ok(r) => open.preset = r["name"].as_str().unwrap_or(&name).to_string(), Err(e) => app.status(e), } diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index 10ec8a5a70..f325276084 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -444,6 +444,71 @@ fn a_paper_keyword_another_printer_lists_at_another_size_becomes_a_custom_size() assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); } +/// Card lists a CR80 card; Twin's driver answers with the same CR80 once `ready` is set. +struct PendingTwin(Rc>); + +impl PrintService for PendingTwin { + fn printers(&mut self) -> Vec { + vec![Printer::new("Card").is_default(true), Printer::new("Twin")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + fn papers(&mut self, printer: &str, fresh: bool) -> Papers { + if printer == "Twin" && !self.0.get() { Papers::Pending } else { CardPrinters.papers(printer, fresh) } + } +} + +#[test] +fn a_paper_stays_chosen_while_the_new_printer_looks_up_its_sizes() { + let ready = Rc::new(Cell::new(false)); + let services = Services { print: Some(Box::new(PendingTwin(ready.clone()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + set(&mut app, "printer", json!("Twin")); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:CR80", "Twin's driver has not answered yet: {f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); + // Twin lists the same CR80, so it stays chosen. + ready.set(true); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "printer:CR80", "{f}"); + assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); +} + +#[test] +fn a_preset_saved_as_a_printer_paper_is_chosen_keeps_its_size() { + let services = Services { print: Some(Box::new(PaperPrint(Jobs::default(), Asked::default()))), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "printer", json!("Card")); + pump(&mut app); + press(&mut app, "New…"); + pump(&mut app); + call(&mut app, "ui.text", json!({"text": "Cards"})); + // The card is chosen in the frame the name is confirmed, before Width and Height take its size. + let ctx = ctx(&app); + let (enter, _reply) = craft::automation::ControlRequest::new("ui.key", json!({"key": "Enter"})); + let _ = crate::control::handle(&mut app, &ctx, &enter); + set(&mut app, "media", json!("printer:CR80")); + pump(&mut app); + pump(&mut app); + let saved = app.session.prefs.print_presets.iter().find(|p| p.name == "Cards").expect("the preset was saved").settings.clone(); + assert_eq!((saved.media, saved.width, saved.height), (vectorcraft_pdf::Media::Custom, 153.0, 243.0)); +} + #[test] fn confirming_after_switching_printers_keeps_the_selected_paper_size() { let jobs = Jobs::default(); From e5df2445e39b00d9ee2fcccda695405554719efc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:31:56 -0800 Subject: [PATCH 26/32] Scripts: new IllustratorSaveOptions reads compatibility as ILLUSTRATOR19 A new IllustratorSaveOptions left compatibility unset, so a script that read it before setting it got undefined. It now starts at Compatibility.ILLUSTRATOR19, the documented default, which saveAs already accepts without changing what it writes. --- crates/engine/src/script/dom/save_open.rs | 7 ++++++- crates/engine/src/tests/script_save_open.rs | 22 +++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index fd933f7d60..237576b64d 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -366,7 +366,12 @@ const AI_KEPT: &[(&str, Default)] = &[ ]; fn ai_starts() -> Vec<(&'static str, Data)> { - vec![("compressed", Data::Bool(true)), ("pdfCompatible", Data::Bool(true)), ("embedICCProfile", Data::Bool(false))] + vec![ + ("compatibility", text("Compatibility.ILLUSTRATOR19")), + ("compressed", Data::Bool(true)), + ("pdfCompatible", Data::Bool(true)), + ("embedICCProfile", Data::Bool(false)), + ] } fn eps_map(name: &str, d: &Data, p: &mut Map) -> std::result::Result { diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 12db366846..04cfbeb2fc 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -212,6 +212,28 @@ fn omitted_options_are_a_new_options_objects_defaults() { let _ = std::fs::remove_dir_all(base); } +/// A new `IllustratorSaveOptions` reads `compatibility` as its default, ILLUSTRATOR19, and saves +/// with it untouched. +#[test] +fn illustrator_save_options_start_at_illustrator19_compatibility() { + let base = folder("aicompat"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var o = new IllustratorSaveOptions(); vc.log(o.compatibility);\ + app.activeDocument.saveAs(new File({}), o);", + quoted(&dir.join("a.ai")) + ), + ); + assert_eq!(out[0], json!("Compatibility.ILLUSTRATOR19")); + assert!(dir.join("a.ai").is_file()); + let _ = std::fs::remove_dir_all(base); +} + /// A path that resolves to a name that is not valid UTF-8 is refused before anything is written or /// opened, so no file with a lossy copy of the name is touched. #[cfg(unix)] From d54e2cf55b2a8d6497ec0e0efe1d90e520b4b9b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 22:04:15 -0800 Subject: [PATCH 27/32] Print: a kept paper the new printer lists at a built-in size becomes that size When the new printer listed the chosen paper at a size within half a point of one of the dialog's own papers, the Size row kept the `printer:` choice, but the new Size list offers that paper under the built-in id instead. The row then held a choice the list did not contain, and the list was rebuilt and repainted on every frame. The row now switches to the built-in paper the list offers. --- crates/ui-egui/src/dialogs/print.rs | 17 +++++++---- crates/ui-egui/src/dialogs/tests_print.rs | 36 +++++++++++++++++++++++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index 8ec1176cfa..6546b2ff5b 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -512,24 +512,29 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, ctx.request_repaint(); } // A paper the new printer doesn't list, or lists under the same keyword at another size, becomes a custom size of - // the same Width and Height. + // the same Width and Height. One the new printer lists at the size of one of the dialog's own papers becomes that + // paper, the choice the new list offers for it. if papers_changed && media.starts_with(PRINTER_PAPER) - && let Some(s) = on(dialogs, |p| { + && let Some((id, s)) = on(dialogs, |p| { let fields = p.fields_mut(); - if printer_paper(fields, &open.papers.1).is_some_and(|new| chosen.as_ref().is_none_or(|old| same_size(old, new))) { - return None; + if let Some(new) = printer_paper(fields, &open.papers.1) + && chosen.as_ref().is_none_or(|old| same_size(old, new)) + { + let own = own_media_of(new)?; + fields.set("media", own.id()); + return Some((own.id().to_string(), settings(fields))); } if let Some(paper) = &chosen { fields.set("width", paper.width); fields.set("height", paper.height); } fields.set("media", Media::Custom.id()); - Some(settings(fields)) + Some((Media::Custom.id().to_string(), settings(fields))) }) .flatten() { - media = Media::Custom.id().to_string(); + media = id; d.settings = s; } if papers_changed || (!media.is_empty() && !open.media.contains(&media)) { diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index f325276084..d2ebf74122 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -444,6 +444,42 @@ fn a_paper_keyword_another_printer_lists_at_another_size_becomes_a_custom_size() assert_eq!((f["width"].as_f64(), f["height"].as_f64()), (Some(153.0), Some(243.0)), "{f}"); } +/// Two printers list a paper named Wide: Near at 611.2 × 792 points, Far at 611.6 × 792, within half a point of Letter. +struct NearLetter; + +impl PrintService for NearLetter { + fn printers(&mut self) -> Vec { + vec![Printer::new("Near").is_default(true), Printer::new("Far")] + } + + fn print(&mut self, job: &PrintJob) -> Result { + MockPrint(Jobs::default()).print(job) + } + + fn papers(&mut self, printer: &str, _fresh: bool) -> Papers { + let width = if printer == "Far" { 611.6 } else { 611.2 }; + Papers::Ready(vec![crate::print::Paper { key: "Wide".into(), label: "Wide".into(), width, height: 792.0 }]) + } +} + +#[test] +fn a_kept_paper_the_new_printer_lists_at_a_built_in_size_becomes_that_size() { + let services = Services { print: Some(Box::new(NearLetter)), ..Default::default() }; + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services)); + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + app.run("file.print", json!({})).unwrap(); + pump(&mut app); + set(&mut app, "media", json!("printer:Wide")); + pump(&mut app); + // Far's Wide is within half a point of Near's and of Letter, and its Size list offers it as Letter. + set(&mut app, "printer", json!("Far")); + pump(&mut app); + pump(&mut app); + let f = fields(&app); + assert_eq!(f["media"], "letter", "{f}"); + assert!(try_set(&mut app, "media", json!("printer:Wide")).is_err(), "the Size list offers Letter in its place"); +} + /// Card lists a CR80 card; Twin's driver answers with the same CR80 once `ready` is set. struct PendingTwin(Rc>); From 4cb6f8f152ab71560150b90c613268222739b84f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 22:06:44 -0800 Subject: [PATCH 28/32] Save: checked writes go into the folder that was checked While automation roots or a script's file grants are in force, a save, export or print to a file checked its path and then wrote it by name: the temporary file was created beside the target by name and renamed over it by name. A folder on the path replaced by a link between the check and the rename sent the file outside the allowed folders. vectorcraft_format::write_atomic_checked opens the target's folder once, checks the path that open folder has with the caller's check, and makes the temporary file, the rename, the copy over the file where the folder refuses the rename, and the folder flush through that open folder (openat, renameat, fsync). A folder replaced before it is opened fails the check; one replaced after it is opened does not receive the file. A link put at the final name after the check is replaced, not followed. The replaced file's permissions, group and ACL are copied through the open handles. write_file, write_file_with and write_save_file_with use it while writes are checked, and keep write_atomic_with otherwise. Outside Unix the check runs on the path and the write is unchanged. --- crates/engine/src/cmd/fileio/access.rs | 27 ++- crates/engine/src/file_access.rs | 14 +- crates/format/src/atomic.rs | 291 ++++++++++++++++++++++++- crates/format/src/lib.rs | 2 +- 4 files changed, 316 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 84b8bc1a4f..8691ebb1fb 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -1,5 +1,3 @@ -#[cfg(not(target_arch = "wasm32"))] -use super::write_atomic; use super::{EngineError, Result, Session, Value, bad, json}; // ---------- the file system (none on the web, where commands take and return bytes) ---------- @@ -325,8 +323,25 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { // Work that stops early for a cancel can leave a truncated result: none of it is written. vectorcraft_doc::cancel::check()?; may_write(path)?; - // Never a half-written file: see [`write_atomic`]. - write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e)) + // Never a half-written file: see [`vectorcraft_format::write_atomic`]. + write_checked(path, |f| std::io::Write::write_all(f, bytes)).map_err(|e| write_error(path, e)) +} + +/// [`vectorcraft_format::write_atomic_with`] for `path`, which [`may_write`] allowed. While writes +/// are checked ([`crate::file_access::writes_checked`]), the folder that receives the file is +/// checked again as it is opened, and the file goes into that open folder +/// ([`vectorcraft_format::write_atomic_checked`]): a folder on the path that is replaced after the +/// check does not redirect the write. +#[cfg(not(target_arch = "wasm32"))] +fn write_checked(path: &str, fill: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>) -> std::io::Result<()> { + let path = std::path::Path::new(path); + if !crate::file_access::writes_checked() { + return vectorcraft_format::write_atomic_with(path, fill); + } + vectorcraft_format::write_atomic_checked(path, fill, |opened| { + let opened = opened.to_str().ok_or_else(|| std::io::Error::other(format!("{}: path is not valid UTF-8", opened.display())))?; + crate::file_access::check_write_unrecorded(opened).map_err(std::io::Error::other) + }) } /// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the @@ -344,7 +359,7 @@ fn write_error(path: &str, error: std::io::Error) -> EngineError { pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; - vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e)) + write_checked(path, |f| fill(f)).map_err(|e| write_error(path, e)) } /// The save commands' writer: preserves a filesystem location refusal as a typed error. Other @@ -358,7 +373,7 @@ pub fn write_save_file(path: &str, bytes: &[u8]) -> Result<()> { pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; - vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| save_write_error(path, e)) + write_checked(path, |f| fill(f)).map_err(|e| save_write_error(path, e)) } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 7daa75e0ae..bc2acda5e6 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -462,8 +462,7 @@ pub fn is_path_key(key: &str) -> bool { /// May `path` be written here? Always, without roots in force and outside a script's command /// ([`with_script_gate`]). pub fn check_write(path: &str) -> Result<(), String> { - current().map_or(Ok(()), |r| r.check(path, Access::Write))?; - check_gate(path, Access::Write)?; + check_write_unrecorded(path)?; WRITES.with(|w| { if let Some(paths) = w.borrow_mut().as_mut() && !paths.iter().any(|(p, _)| p == path) @@ -474,6 +473,17 @@ pub fn check_write(path: &str) -> Result<(), String> { Ok(()) } +/// [`check_write`] without recording `path` as written. +pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check(path, Access::Write))?; + check_gate(path, Access::Write) +} + +/// Whether a write here is checked: roots are in force, or a script's command runs. +pub(crate) fn writes_checked() -> bool { + current().is_some() || in_script_command() +} + /// A file's modification time and length; `None` when there is no file at `path`. type Stamp = Option<(Option, u64)>; diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index f314fcdd15..54a0fe0432 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -82,6 +82,171 @@ fn create_new(path: &Path) -> io::Result { OpenOptions::new().write(true).create_new(true).open(path) } +/// [`write_atomic_with`] for a `path` the caller has allowed by its name. On Unix the folder that +/// holds the file is opened once, and `allowed` is asked again with the path that open folder has +/// then, joined with the file's name. The temporary file, the replacement, a copy over the file +/// where the folder refuses the replacement, and the folder flush all go through that open folder, +/// and none of them looks its path up again. A folder replaced (or swapped for a link) before it is +/// opened fails `allowed`. A folder replaced after it is opened does not receive the file. A link at +/// the final name is followed once before the folder is opened, as [`write_atomic_with`] follows it; +/// a link put there later is replaced, never followed. Elsewhere this is `allowed(path)` followed by +/// [`write_atomic_with`]. +#[cfg(unix)] +pub fn write_atomic_checked( + path: &Path, + fill: impl FnOnce(&mut File) -> io::Result<()>, + allowed: impl FnOnce(&Path) -> io::Result<()>, +) -> io::Result<()> { + use rustix::fs::{AtFlags, Mode, OFlags}; + let resolved = resolve_link(path)?; + let name = resolved + .file_name() + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", resolved.display())))? + .to_os_string(); + let parent = resolved.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + let dir = rustix::fs::open(parent, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())?; + let target = opened_folder_path(&dir, parent)?.join(&name); + allowed(&target)?; + let old = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW).ok(); + let tmp_name = temp_path(&target)?.file_name().map(std::ffi::OsStr::to_os_string).unwrap_or_default(); + let tmp = target.with_file_name(&tmp_name); + // Replacing a file: owner-only while it is written, as in `write_atomic_with`. + let mode = if old.is_some() { Mode::RUSR | Mode::WUSR } else { Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::WGRP | Mode::ROTH | Mode::WOTH }; + let new_file = OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC; + let remove_tmp = || { + // Best effort: the temporary file is all there is to clean up. + let _ = rustix::fs::unlinkat(&dir, &tmp_name, AtFlags::empty()); + }; + let synced = + || rustix::fs::fsync(&dir).map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: target.clone(), error: e.into() })); + let open_target = |write: bool| -> io::Result { + let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY }; + Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?)) + }; + match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) { + Ok(mut f) => { + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); + if let Err(e) = filled { + drop(f); + remove_tmp(); + return Err(e); + } + if let Some(old) = &old { + // Best effort, as in `write_atomic_with`. + let _ = keep_permissions_at(&dir, &name, old, &f); + } + drop(f); + let Err(refused) = rustix::fs::renameat(&dir, &tmp_name, &dir, &name) else { return synced() }; + let over = Over { + tmp: &tmp, + old: std::env::temp_dir().join(&tmp_name).with_extension("old"), + open_tmp: &|| { + Ok(File::from(rustix::fs::openat(&dir, &tmp_name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())?)) + }, + remove_tmp: &remove_tmp, + open_target: &open_target, + synced: &synced, + }; + write_over_in(&over, refused.into()) + } + // A folder that isn't there, a full volume: nothing can be saved there. + Err(e) if matches!(io::Error::from(e).kind(), io::ErrorKind::NotFound | io::ErrorKind::StorageFull | io::ErrorKind::QuotaExceeded) => { + Err(e.into()) + } + Err(refused) => { + // The folder takes no temporary file: it is written in the system's folder and copied in. + let elsewhere = std::env::temp_dir().join(&tmp_name); + let mut f = create_private(&elsewhere).map_err(|_| io::Error::from(refused))?; + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); + drop(f); + let remove = || { + // Best effort: the temporary file is all there is to clean up. + let _ = std::fs::remove_file(&elsewhere); + }; + if let Err(e) = filled { + remove(); + return Err(e); + } + let over = Over { + tmp: &elsewhere, + old: elsewhere.with_extension("old"), + open_tmp: &|| File::open(&elsewhere), + remove_tmp: &remove, + open_target: &open_target, + synced: &synced, + }; + write_over_in(&over, refused.into()) + } + } +} + +/// See the Unix version. +#[cfg(not(unix))] +pub fn write_atomic_checked( + path: &Path, + fill: impl FnOnce(&mut File) -> io::Result<()>, + allowed: impl FnOnce(&Path) -> io::Result<()>, +) -> io::Result<()> { + allowed(path)?; + write_atomic_with(path, fill) +} + +/// The path folder `dir` has now, which `parent` named when it was opened: `parent` with its links +/// followed, when that is still the folder `dir` holds (the same device and inode). A folder +/// replaced in between is an error. +#[cfg(unix)] +fn opened_folder_path(dir: &std::os::fd::OwnedFd, parent: &Path) -> io::Result { + let real = std::fs::canonicalize(parent)?; + let (open, now) = (rustix::fs::fstat(dir)?, rustix::fs::stat(&real)?); + if (open.st_dev, open.st_ino) != (now.st_dev, now.st_ino) { + return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the folder changed while it was opened", parent.display()))); + } + Ok(real) +} + +/// [`keep_permissions`] for the temporary file `tmp`, about to replace `name` in folder `dir`, whose +/// file had the status `old`. A name that does not hold a plain file has none to keep. +#[cfg(unix)] +fn keep_permissions_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> io::Result<()> { + use rustix::fs::{FileType, Mode}; + if FileType::from_raw_mode(old.st_mode) != FileType::RegularFile { + return Ok(()); + } + let mut mode = Mode::from_raw_mode(old.st_mode); + let gid = rustix::fs::Gid::from_raw(old.st_gid); + let kept_group = rustix::fs::fstat(tmp).is_ok_and(|t| t.st_gid == old.st_gid) || rustix::fs::fchown(tmp, None, Some(gid)).is_ok(); + if !kept_group || !keep_acl_at(dir, name, tmp) { + mode.remove(Mode::RWXG | Mode::RWXO); + } + rustix::fs::fchmod(tmp, mode).map_err(io::Error::from) +} + +/// [`keep_acl`] for `name` in folder `dir`, opened without following a link and without waiting on +/// a pipe put in its place. +#[cfg(target_os = "linux")] +fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, tmp: &File) -> bool { + use rustix::fs::{Mode, OFlags}; + use rustix::io::Errno; + const ACL: &str = "system.posix_acl_access"; + let Ok(target) = rustix::fs::openat(dir, name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty()) else { + return false; + }; + let mut buf = vec![0u8; 64 << 10]; + match rustix::fs::fgetxattr(&target, ACL, &mut buf[..]) { + Ok(n) => buf.get(..n).is_some_and(|acl| rustix::fs::fsetxattr(tmp, ACL, acl, rustix::fs::XattrFlags::empty()).is_ok()), + Err(e) if e == Errno::NODATA => match rustix::fs::fremovexattr(tmp, ACL) { + Ok(()) => true, + Err(e) => e == Errno::NODATA || e == Errno::NOTSUP, + }, + Err(e) => e == Errno::NOTSUP, + } +} + +#[cfg(all(unix, not(target_os = "linux")))] +fn keep_acl_at(_: &std::os::fd::OwnedFd, _: &std::ffi::OsStr, _: &File) -> bool { + true +} + /// [`write_atomic_with`], with `create` making the temporary file beside the target and `rename` /// moving it over the target. fn write_atomic_stepping( @@ -130,16 +295,49 @@ fn write_atomic_stepping( /// the copy into `target` fails it is damaged: `tmp` and the copy of the old content stay and the /// error says where they are. fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { - let opened = File::open(tmp).and_then(|from| Ok((from, OpenOptions::new().write(true).create(true).truncate(false).open(target)?))); + let over = Over { + tmp, + old: tmp.with_extension("old"), + open_tmp: &|| File::open(tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(tmp); + }, + open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) }, + synced: &|| sync_written_parent(target), + }; + write_over_in(&over, refused) +} + +/// How [`write_over_in`] reaches its files: by their paths, or through a folder opened once +/// ([`write_atomic_checked`]). +struct Over<'a> { + /// The temporary file, as error messages name it. + tmp: &'a Path, + /// Where the file as it was is copied aside. + old: PathBuf, + open_tmp: &'a dyn Fn() -> io::Result, + /// Best effort. + remove_tmp: &'a dyn Fn(), + /// The target for writing (created when missing, not truncated) when `true`, for reading when + /// `false`. + open_target: &'a dyn Fn(bool) -> io::Result, + /// The target's folder flushed, after the target is written. + synced: &'a dyn Fn() -> io::Result<()>, +} + +/// [`write_over`] through `over`. +fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { + let tmp = over.tmp; + let opened = (over.open_tmp)().and_then(|from| Ok((from, (over.open_target)(true)?))); let Ok((mut from, mut to)) = opened else { // Best effort: the temporary file is all there is to clean up. - let _ = std::fs::remove_file(tmp); + (over.remove_tmp)(); return Err(refused); }; // Nothing to keep of a file that is new or empty. - let old = to.metadata().map_or(true, |m| m.len() > 0).then(|| tmp.with_extension("old")); + let old = to.metadata().map_or(true, |m| m.len() > 0).then(|| over.old.clone()); if let Some(old) = &old - && let Err(e) = keep_old(target, old) + && let Err(e) = (over.open_target)(false).and_then(|mut target| keep_old(&mut target, old)) { // Best effort: a partial copy is of no use. let _ = std::fs::remove_file(old); @@ -152,11 +350,11 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { match (copied, old) { (Ok(()), old) => { // Best effort: the file is saved, so the copies are no longer needed. - let _ = std::fs::remove_file(tmp); + (over.remove_tmp)(); if let Some(old) = old { let _ = std::fs::remove_file(old); } - sync_written_parent(target) + (over.synced)() } (Err(e), Some(old)) => Err(io::Error::new( e.kind(), @@ -166,10 +364,10 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { } } -/// A flushed copy of `target` as it is, at `old` (for its owner only). -fn keep_old(target: &Path, old: &Path) -> io::Result<()> { +/// A flushed copy of what `target` holds, at `old` (for its owner only). +fn keep_old(target: &mut File, old: &Path) -> io::Result<()> { let mut to = create_private(old)?; - io::copy(&mut File::open(target)?, &mut to)?; + io::copy(target, &mut to)?; sync_file(&to) } @@ -466,6 +664,81 @@ mod tests { true } + /// A folder `root/inside` and a folder `outside` beside `root`, by their real paths, and a check + /// that allows paths under `root` only. + #[cfg(unix)] + fn checked_folders(name: &str) -> (PathBuf, PathBuf, PathBuf) { + let d = std::fs::canonicalize(dir(name)).unwrap(); + let (root, outside) = (d.join("root"), d.join("outside")); + std::fs::create_dir_all(root.join("inside")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + (d, root, outside) + } + + #[cfg(unix)] + fn under(root: &Path) -> impl FnOnce(&Path) -> io::Result<()> + '_ { + move |p: &Path| if p.starts_with(root) { Ok(()) } else { Err(io::Error::other(format!("{} is outside", p.display()))) } + } + + /// A folder on the path that is a link to a folder outside when the write starts fails the check + /// made on the folder that is opened, and nothing is written outside. + #[cfg(unix)] + #[test] + fn a_checked_write_refuses_a_folder_replaced_before_it_is_opened() { + let (d, root, outside) = checked_folders("checked-before"); + std::fs::remove_dir(root.join("inside")).unwrap(); + std::os::unix::fs::symlink(&outside, root.join("inside")).unwrap(); + let r = write_atomic_checked(&root.join("inside/doc.txt"), |f| f.write_all(b"new"), under(&root)); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("is outside")), "{r:?}"); + assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing is left outside"); + let _ = std::fs::remove_dir_all(d); + } + + /// A folder on the path replaced by a link to a folder outside after it is checked and opened + /// does not redirect the write: the file goes into the folder that was opened. + #[cfg(unix)] + #[test] + fn a_checked_write_stays_in_the_folder_it_opened() { + let (d, root, outside) = checked_folders("checked-after"); + let check = under(&root); + let r = write_atomic_checked( + &root.join("inside/doc.txt"), + |f| f.write_all(b"new"), + |p| { + check(p)?; + std::fs::rename(root.join("inside"), root.join("moved"))?; + std::os::unix::fs::symlink(&outside, root.join("inside")) + }, + ); + r.unwrap(); + assert!(!outside.join("doc.txt").exists(), "the write followed the replaced folder"); + assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// A link put at the file's name after the check is replaced by the file, not followed. + #[cfg(unix)] + #[test] + fn a_checked_write_replaces_a_link_put_at_its_name() { + let (d, root, outside) = checked_folders("checked-link"); + std::fs::write(outside.join("other.txt"), b"keep").unwrap(); + let path = root.join("inside/doc.txt"); + let check = under(&root); + write_atomic_checked( + &path, + |f| f.write_all(b"new"), + |p| { + check(p)?; + std::os::unix::fs::symlink(outside.join("other.txt"), &path) + }, + ) + .unwrap(); + assert_eq!(std::fs::read(outside.join("other.txt")).unwrap(), b"keep"); + assert!(std::fs::symlink_metadata(&path).unwrap().is_file()); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 654f0ac065..9975527f78 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -58,7 +58,7 @@ use vectorcraft_doc::{Document, ImageBlob}; #[cfg(all(unix, not(target_arch = "wasm32")))] pub use atomic::sync_parent; #[cfg(not(target_arch = "wasm32"))] -pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; +pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_checked, write_atomic_with, write_new_with}; use craft_gzip::Gz; pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode}; use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json}; From 8b8e2467137bbe9171bed5043e96c13a9caa1784 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 21:58:32 -0800 Subject: [PATCH 29/32] xtask: test-lint keeps the route, suffix and census refinements main lacks - never-run: in changed mode, a file that a crate target loaded at the base and no target loads now counts as compiled out, so removing the last `mod` or `#[path]` declaration on the way to it, or deleting the only target root that loads it, fails the check for its tests. - reads-source: an `ends_with(".rs")` check counts only when it picks entries from a file listing (an iterator filter or a `for` loop over one), or when the function around it reads a file or calls a function in the file that does. A suffix check on a generated name in a test that reads nothing is not reported. - census: a helper on the left of an `||` hides the whole-table check on the right only when it always runs: not behind an `&&`, and not inside one arm of an `if` or `match`. - docs: unchanged-line `never-run` hits fail the command when the change takes away a test's last CI route. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 330 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 323 insertions(+), 9 deletions(-) diff --git a/docs/development.md b/docs/development.md index 4244e28738..cd047d8810 100644 --- a/docs/development.md +++ b/docs/development.md @@ -353,7 +353,7 @@ The app decides which cursors exist; whoever draws them works from the list. For ## Test lint -`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. +`cargo xtask test-lint` (part of `cargo xtask ci`) checks tests that a wrong result can pass, in the lines and tests changed since a base. It fails on an `assert_eq!` or `assert_ne!` of an expression with itself, such as `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`), `thread::sleep` in test code (`sleep`), test code that reads Rust source outside the audits listed in `SOURCE_AUDITS` (`reads-source`), and a test that a `cfg` on it or on a `mod` above it excludes from every CI target that builds the crate (`never-run`). `never-run` reports a test only when it can evaluate the `cfg` on every such target; a predicate it does not evaluate, such as a `feature`, counts as unknown, so `#[cfg(all(feature = "gpu", not(feature = "gpu")))]` is not reported. It lists the hits of the other rules without failing: a test whose only checks are that a value exists or a collection is not empty (`is_ok`, `is_some`, `!is_empty`, `len() > 0`: `only-weak`), `assert!(….all(…))` on a collection the test does not show to be non-empty (`all-unguarded`), a process test that checks only the exit status, a test with no assertion and no asserting helper, a silent early `return` on a value from the code under test, an environment variable that no CI leg sets, and the hits of `census`, `mirror`, `constant-echo`, `fixture-only` and `exact-pixel`. The base is `--base ` or `TEST_LINT_BASE`; in CI it is the first parent of the checked-out commit, and elsewhere the merge base with `upstream/main` or `origin/main`. Hits on unchanged lines are counted but do not fail it, except a `never-run` test in an unchanged file whose last CI route the change takes away: a changed `mod` declaration or `cfg` in a file that loads it, or a removed `mod` or `#[path]` declaration that was the last one loading it. A `// test-lint: allow ` comment exempts its own line and the line below it; `xtask/src/test_lint.rs` lists the rules and their ids. `cargo xtask test-lint --all` lists every hit in the workspace by crate and rule, and does not fail. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 449885209f..51d7132b4d 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -38,8 +38,10 @@ //! reads do not; //! * `sleep`: `thread::sleep` in test code, or a bare `sleep(…)` in a file that imports it; //! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, -//! `read_to_string` of a path with a `.rs` literal, or a walk that keeps files ending in `.rs`), -//! outside the source audits in [`SOURCE_AUDITS`]; +//! `read_to_string` of a path with a `.rs` literal, or a `.ends_with(".rs")` check that selects +//! files from a listing, is in a function that reads a file or stream, or is in a function that +//! calls a function defined in the file whose body reads one, regardless of the receiver or +//! arguments), outside the source audits in [`SOURCE_AUDITS`]; //! * `census`: a test that loops over a whole table (a `SCREAMING_CASE` constant, `Type::ALL`, //! `Type::iter()`, or a call named `all`, `catalog`, `registry`, `presets`, `swatches`, //! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of @@ -342,7 +344,13 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { descendants(&seeds, &files, &overrides, &base_overrides, &read_work, &read_base).into_iter().filter(|p| !changed.contains_key(p)).collect(); let gated: Vec = present.iter().chain(&below).cloned().collect(); let gates = module_gates(&gated, &read_work, &overrides); - let module_cfgs = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); + let mut module_cfgs: HashMap> = gates.iter().map(|(p, g)| (p.clone(), g.preds.clone())).collect(); + // A file that a crate target loaded at the base and no longer loads is compiled out: `any()` + // holds on no target. + let lost = lost_routes(&gated, &read_work, &overrides, &read_base, &base_overrides); + for path in lost.keys() { + module_cfgs.insert(path.clone(), vec!["any()".to_owned()]); + } let ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env, module_cfgs }; // The gates the parent declarations gave at the base: a parent edit counts against a child's // test only when the test ran in CI before it. @@ -361,9 +369,13 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { }); !already_off(off, base_src, src, hit) }; + let route_changed = |path: &str| { + route_gate_changed(path, gates.get(path), base_gates.get(path), &base_overrides, &changed) + || lost.get(path).is_some_and(|parents| parents.iter().any(|p| changed.contains_key(p))) + }; let (mut counted, mut older) = (vec![], 0usize); for (path, src) in read_all(root, &present)? { - let parent_changed = route_gate_changed(&path, gates.get(&path), base_gates.get(&path), &base_overrides, &changed); + let parent_changed = route_changed(&path); for hit in lint_file(&path, &src, &ctx) { if touches(&hit, changed.get(&path).and_then(Option::as_ref)) || (hit.rule == Rule::NeverRun && parent_changed && newly_off(&path, &src, &hit)) @@ -374,7 +386,7 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { } } } - for path in below.iter().filter(|p| route_gate_changed(p, gates.get(*p), base_gates.get(*p), &base_overrides, &changed)) { + for path in below.iter().filter(|p| route_changed(p)) { let Some(src) = read_work(path) else { continue }; counted.extend(lint_file(path, &src, &ctx).into_iter().filter(|h| h.rule == Rule::NeverRun && newly_off(path, &src, h))); } @@ -1654,7 +1666,7 @@ fn census(v: &View, helpers: &HashSet) -> Vec { /// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions /// nested deeper than 64 operators are not judged. An operand that calls one of `helpers` (asserting /// helpers called in the condition) is not a presence check, and a weak right side of an `||` does -/// not count when the left side calls one, since the left side always runs. +/// not count when the left side always calls one ([`always_calls`]). fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool) { let or = top_level_at(cond, "||").first().copied(); if depth > 64 || !cond.contains(".all(") { @@ -1670,7 +1682,7 @@ fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool } }; let (l, r) = (side(&cond[..at]), side(&cond[at + 2..])); - let r = if or.is_some() && (calls_any(&cond[..at], helpers) || rejects(&cond.as_bytes()[..at])) { (false, false) } else { r }; + let r = if or.is_some() && (always_calls(&cond[..at], helpers, depth) || rejects(&cond.as_bytes()[..at])) { (false, false) } else { r }; if or.is_none() { (l.0 && r.0, l.1 || r.1) } else if l == (true, true) || r == (true, true) { @@ -1684,6 +1696,53 @@ fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool } } +/// Whether evaluating the (whitespace-free) condition `s` always calls one of `helpers`: a call +/// behind a top-level `&&` or `||` runs only on one outcome of the operand before it, so only the +/// first operand of either counts. +fn always_calls(s: &str, helpers: &[String], depth: usize) -> bool { + if depth > 64 { + false + } else if s.starts_with('(') && matching(s.as_bytes(), 0) == Some(s.len() - 1) { + always_calls(&s[1..s.len() - 1], helpers, depth + 1) + } else if let Some(at) = top_level_at(s, "||").first().copied().or_else(|| top_level_at(s, "&&").first().copied()) { + always_calls(&s[..at], helpers, depth + 1) + } else if let Some(&at) = top_level_at(s, "{").first() + && let Some(cond) = s[..at].strip_prefix("if").or_else(|| s[..at].strip_prefix("match")) + { + // An `if` or `match` always runs only its condition or scrutinee, the text before its + // first block; a call inside one arm may be skipped. Without whitespace the keyword runs + // into the condition (`ifverify()`); the text before the block is also checked whole, for + // a name that only starts with the keyword. + always_calls(cond, helpers, depth + 1) || always_calls(&s[..at], helpers, depth + 1) + } else if s.starts_with('{') && matching(s.as_bytes(), 0) == Some(s.len() - 1) { + // A plain block runs each of its statements in order. + block_statements(&s[1..s.len() - 1]).into_iter().any(|st| always_calls(st, helpers, depth + 1)) + } else { + calls_any(s, helpers) + } +} + +/// The statements of a (whitespace-free) block body: split at each top-level `;` and after each +/// top-level `}` that no `else` follows (`if a{x();}y();` is two statements). +fn block_statements(body: &str) -> Vec<&str> { + let b = body.as_bytes(); + let (mut out, mut depth, mut start) = (vec![], 0i32, 0); + for (i, &c) in b.iter().enumerate() { + match c { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + _ => {} + } + let end = depth == 0 && (c == b';' || c == b'}' && !body[i + 1..].starts_with("else")); + if end { + out.push(&body[start..=i]); + start = i + 1; + } + } + out.push(&body[start..]); + out.into_iter().filter(|s| !s.is_empty()).collect() +} + /// Whether `s` calls a function or method named in `names`, with or without a turbofish. fn calls_any(s: &str, names: &[String]) -> bool { names.iter().any(|n| { @@ -3206,7 +3265,10 @@ fn reads_source_hits(file: &File) -> Vec { let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); let literal = raw.unwrap_or(&arg); let rs = match word { - b"ends_with" => literal == "\".rs\"", + // A suffix check alone may test a generated name; it counts when it selects files + // from a listing, its function reads a file or stream, or its function calls a + // function defined in this file whose body reads one, with any arguments. + b"ends_with" => literal == "\".rs\"" && (selects(m, at) || reads_checked(file, at)), // The final path step names the file read: the last literal of `root.join("src/lib.rs")` // or `concat!(…, "/x.rs")`, but not `root.join("fixtures.rs").join("data.json")`; the // extension of a final `.with_extension("json")`. A final step whose argument is not a @@ -3237,6 +3299,112 @@ fn reads_source_hits(file: &File) -> Vec { out } +/// Words that name a file listing in an iterator chain or a loop source. +const LISTINGS: &[&str] = &["read_dir", "files", "listing", "walk", "walkdir", "glob", "entries", "paths", "sources"]; + +/// Whether `text` names a listing ([`LISTINGS`]), as a whole word or as the end of one (`rust_files`). +fn names_listing(text: &str) -> bool { + text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).any(|w| LISTINGS.iter().any(|l| w == *l || w.ends_with(&format!("_{l}")))) +} + +/// Whether the call at `at` picks entries out of a listing: it sits in the closure of a `filter`, +/// `filter_map`, `find`, `any`, `all`, `position` or `retain` call on an iterator whose chain names +/// a listing (`read_dir`, `files`, `listing`, `walk` and the like), or in the body of a `for` loop +/// over one. +fn selects(m: &[u8], at: usize) -> bool { + const PICKS: &[&[u8]] = &[b"filter", b"filter_map", b"find", b"find_map", b"any", b"all", b"position", b"retain"]; + let in_loop = words(m, b"for", 0, at).into_iter().any(|f| { + let Some(&kw) = words(m, b"in", f, at).first() else { return false }; + loop_open(m, kw + 2, at) + .is_some_and(|open| matching(m, open).is_none_or(|close| close > at) && names_listing(&String::from_utf8_lossy(&m[kw + 2..open]))) + }); + // The parentheses that enclose `at`, innermost first. + let mut depth = 0usize; + let mut enclosing = m[..at].iter().enumerate().rev().filter_map(move |(i, &c)| match c { + b')' => { + depth += 1; + None + } + b'(' if depth > 0 => { + depth -= 1; + None + } + b'(' => Some(i), + _ => None, + }); + in_loop + || enclosing.any(|open| { + let head = m[..open].trim_ascii_end(); + let name = head.iter().rev().take_while(|&&c| is_ident(c)).count(); + if !PICKS.contains(&&head[head.len() - name..]) { + return false; + } + // The receiver chain: back from the pick to the start of its statement. + let start = head[..head.len() - name].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}' | b'=')).map_or(0, |p| p + 1); + names_listing(&String::from_utf8_lossy(&head[start..head.len() - name])) + }) +} + +/// File and stream reading calls, including directory listings and file opens. +const READS: &[&[u8]] = &[b"read_to_string", b"read_to_end", b"read_dir", b"include_str", b"read", b"open"]; + +/// The argument spans `(open, close)` of the reading calls anywhere in the file. +fn read_calls(file: &File) -> Vec<(usize, usize)> { + let m = &file.m; + let mut out = vec![]; + for w in READS { + for p in words(m, w, 0, m.len()) { + // `fn read(…)` declares a function; it does not read. + if (*w == b"open" && !norm(&m[..p]).ends_with("File::")) || m[..p].trim_ascii_end().ends_with(b"fn") { + continue; + } + let next = skip_ws(m, p + w.len()); + let next = if m.get(next) == Some(&b'!') { skip_ws(m, next + 1) } else { skip_ws(m, skip_turbofish(m, next)) }; + if m.get(next) == Some(&b'(') + && let Some(close) = matching(m, next) + { + out.push((next, close)); + } + } + } + out +} + +/// Whether the function containing the `.ends_with` check reads a file or stream, or calls a +/// function defined in this file whose body reads one, regardless of the receiver or arguments. +fn reads_checked(file: &File, at: usize) -> bool { + let m = &file.m; + let reads = read_calls(file); + // The function around the check (the test, or a helper). + let scope = words(m, b"fn", 0, at) + .into_iter() + .rev() + .find_map(|f| { + let body = f + m[f..at].iter().position(|&c| c == b'{')?; + matching(m, body).filter(|&end| end > at).map(|end| (body, end)) + }) + .or_else(|| file.regions.iter().copied().find(|&(from, to)| from <= at && at < to)); + let Some((from, to)) = scope else { return false }; + if reads.iter().any(|&(open, _)| from < open && open < to) { + return true; + } + // Functions whose body holds a reading call and whose name is called in this scope. + words(m, b"fn", 0, m.len()).into_iter().any(|f| { + let name_at = skip_ws(m, f + 2); + let name_len = m[name_at..].iter().take_while(|&&c| is_ident(c)).count(); + let Some(body) = m[name_at..].iter().position(|&c| c == b'{' || c == b';').map(|p| name_at + p).filter(|&b| m[b] == b'{') else { + return false; + }; + let Some(end) = matching(m, body) else { return false }; + name_len > 0 + && reads.iter().any(|&(open, _)| open > body && open < end) + && words(m, &m[name_at..name_at + name_len], from, to).into_iter().any(|c| { + let open = skip_turbofish(m, skip_ws(m, c + name_len)); + c != name_at && m.get(open) == Some(&b'(') + }) + }) +} + /// The offset of the last `pat` in `expr` outside every bracket and string literal. fn rfind_outer(expr: &str, pat: &str) -> Option { let b = expr.as_bytes(); @@ -4498,6 +4666,30 @@ fn module_gates(paths: &[String], read: &dyn Fn(&str) -> Option, overrid .collect() } +/// The files of `paths` that a crate target loaded through a parent at the base (read through +/// `read_base`) and that no crate target loads now, each with the base files of its routes: a change +/// that removes the last `mod` or `#[path]` declaration on the way to a file compiles its tests out. +fn lost_routes( + paths: &[String], + read: &dyn Fn(&str) -> Option, + overrides: &Overrides, + read_base: &dyn Fn(&str) -> Option, + base_overrides: &Overrides, +) -> HashMap> { + paths + .iter() + .filter_map(|path| { + let base = module_gate(path, read_base, base_overrides, 0, Via::Any); + // A head with no route at all is lost too: when no file that could load it is left, the + // parent is unknown and [`module_gate`] counts it as reached, but the base had one. + if !base.reached || base.sources.is_empty() || !module_gate(path, read, overrides, 0, Via::Any).sources.is_empty() { + return None; + } + Some((path.clone(), base.sources.into_iter().map(|(p, _)| p).collect())) + }) + .collect() +} + /// Which routes to a file [`module_gate`] follows: a file that is not a `mod.rs` or a crate root /// declares its modules in a directory named after it when a `mod ;` loads it (`Named`), and /// in its own directory when a `#[path]` loads it (`Path`). @@ -4927,6 +5119,24 @@ mod tests { assert_eq!(census_in(filled, &ctx()), [(2, "census")]); } + #[test] + fn census_counts_a_helper_on_the_left_of_an_or_only_when_it_always_runs() { + let census_in = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::>(); + let guarded = "#[test]\nfn t() {\n assert!((ready && verify_entry()) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(guarded), [(2, "census")], "a helper behind an && on the left is skipped when ready is false"); + let arm = "#[test]\nfn t() {\n assert!((if ready { verify_entry() } else { false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(arm), [(2, "census")], "a helper in one arm of an if on the left is skipped when ready is false"); + let scrutinee = "#[test]\nfn t() {\n assert!((if verify_entry() { true } else { false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(scrutinee), [], "the condition of an if on the left always runs"); + let block = "#[test]\nfn t() {\n assert!(({ verify_entry(); false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(block), [], "a plain block on the left always runs its statements"); + let block_if = "#[test]\nfn t() {\n assert!(({ if ready { verify_entry(); } false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(block_if), [(2, "census")], "a helper in an if inside a block on the left can be skipped"); + let after_if = + "#[test]\nfn t() {\n assert!(({ if ready { setup(); } verify_entry(); false }) || COLORS.iter().all(|c| c.is_some()));\n}\n"; + assert_eq!(census_in(after_if), [], "a helper after an if statement in the block always runs"); + } + #[test] fn census_is_report_only() { assert!(!Rule::Census.fails()); @@ -7307,4 +7517,108 @@ mod tests { let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []); } + + #[test] + fn a_suffix_check_reads_source_only_when_the_checked_file_is_read() { + let name = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", name), [], "a suffix check on a generated name"); + let names = "#[test]\nfn t() {\n assert!(generated_names().iter().all(|name| name.ends_with(\".rs\")));\n}\n"; + assert_eq!(only("reads-source", names), [], "a suffix predicate over generated names"); + let other_read = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n#[test]\nfn u() {\n assert!(fs::read_to_string(\"data.json\").unwrap().contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", other_read), [], "another test reads a file the suffix check did not name"); + let same_name = "#[test]\nfn t() {\n let p = generated_name();\n assert!(p.ends_with(\".rs\"));\n}\n#[test]\nfn u() {\n let p = data_path();\n assert!(fs::read_to_string(p).unwrap().contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", same_name), [], "another test reads its own local of the same name"); + let read = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert!(fs::read_to_string(p).unwrap().contains(\"x\"));\n}\n"; + assert_eq!(only("reads-source", read), [(4, "reads-source")], "the test reads the file"); + let src = "#[test]\nfn t() {\n let path = newest();\n if path.to_string_lossy().ends_with(\".rs\") {\n assert!(fs::read_to_string(&path).unwrap().contains(\"x\"));\n }\n}\n"; + assert_eq!(only("reads-source", src), [(4, "reads-source")], "the converted path is read"); + let src = "#[test]\nfn t() {\n let path = newest();\n assert!(path.to_string_lossy().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", src), [], "the converted path is not read"); + let src = "#[test]\nfn t() {\n assert!(generated_name().to_string_lossy().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", src), [], "a conversion of a generated name"); + let src = "#[test]\nfn t() {\n assert!(generated_name().to_string_lossy().ends_with(\".rs\"));\n assert_eq!(fs::read_to_string(other_path()).unwrap(), \"x\");\n}\n"; + assert_eq!(only("reads-source", src), [(3, "reads-source")], "the same function reads a file, regardless of the receiver"); + let src = "#[test]\nfn t() {\n let entry = newest();\n if entry.path.to_string_lossy().ends_with(\".rs\") {\n assert!(fs::read_to_string(&entry.path).unwrap().contains(\"x\"));\n }\n}\n"; + assert_eq!(only("reads-source", src), [(4, "reads-source")], "the test reads the checked field"); + let src = "#[test]\nfn t() {\n assert!(entry.path.to_string_lossy().ends_with(\".rs\"));\n assert_eq!(load(&entry.path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", src), [(3, "reads-source")], "a separate helper reads the checked field"); + let src = "fn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n#[cfg(test)]\nmod tests {\n #[test]\n fn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert_eq!(load(&p), \"x\");\n }\n}\n"; + assert_eq!(only("reads-source", src), [(9, "reads-source")], "a helper outside the test module reads the checked file"); + let found: Vec<_> = hits_in("crates/x/src/lib.rs", src, &ctx()).into_iter().filter(|h| h.1 == "reads-source").collect(); + assert_eq!(found, [(9, "reads-source")], "the reading helper is outside the test regions of a regular source file"); + let src = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert_eq!(load::(&p), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", src), [(4, "reads-source")], "a generic helper reads the checked file"); + let src = "#[test]\nfn t() {\n let p = newest();\n assert!(p.ends_with(\".rs\"));\n assert_eq!(std::fs::read::<_>(&p).unwrap().len(), 1);\n}\n"; + assert_eq!(only("reads-source", src), [(4, "reads-source")], "a read with a turbofish"); + let src = "#[test]\nfn t() {\n assert!(entry.path.to_string_lossy().ends_with(\".rs\"));\n assert_eq!(load(&other.path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", src), [(3, "reads-source")], "the helper reads a file, regardless of its argument"); + let derived_helper = "#[test]\nfn t() {\n let path = newest();\n let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();\n assert!(name.ends_with(\".rs\"));\n assert_eq!(load(&path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", derived_helper), [(5, "reads-source")], "the test calls a reading helper after checking a derived name"); + let other_call = "#[test]\nfn t() {\n assert!(path.ends_with(\".rs\"));\n}\n#[test]\nfn u() {\n assert_eq!(load(&path), \"x\");\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", other_call), [], "only another test calls the reading helper"); + let declared = "#[test]\nfn t() {\n fn read() -> u8 {\n 1\n }\n assert!(generated_name().ends_with(\".rs\"));\n}\n"; + assert_eq!(only("reads-source", declared), [], "a function named read is declared, not called"); + let helper = "#[cfg(test)]\nmod tests {\n fn load(p: &Path) -> String {\n if p.ends_with(\".rs\") {\n return fs::read_to_string(p).unwrap();\n }\n String::new()\n }\n #[test]\n fn t() {\n assert_eq!(load(newest()), \"x\");\n }\n}\n"; + assert_eq!(only("reads-source", helper), [(4, "reads-source")], "a helper in the test module reads the file"); + let split = "#[test]\nfn t() {\n for p in listing() {\n if !p.ends_with(\".rs\") {\n continue;\n }\n assert_eq!(load(&p), \"x\");\n }\n}\n#[cfg(test)]\nfn load(p: &Path) -> String {\n fs::read_to_string(p).unwrap()\n}\n"; + assert_eq!(only("reads-source", split), [(4, "reads-source")], "a separate test helper reads the file"); + let walk = "#[test]\nfn t() {\n for entry in std::fs::read_dir(&d).unwrap() {\n let path = entry.unwrap().path();\n let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();\n if !name.ends_with(\".rs\") {\n continue;\n }\n assert!(check(&path));\n }\n}\n"; + assert_eq!(only("reads-source", walk), [(6, "reads-source")], "a suffix check in a loop over a directory listing"); + let derived = "#[test]\nfn t() {\n let path = newest();\n let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();\n if name.ends_with(\".rs\") {\n assert!(std::fs::read_to_string(&path).unwrap().contains(\"x\"));\n }\n}\n"; + assert_eq!(only("reads-source", derived), [(5, "reads-source")], "the checked name comes from the path that is read"); + let generated = + "#[test]\nfn t() {\n for n in 0..3 {\n let name = generated_name(n);\n assert!(name.ends_with(\".rs\"));\n }\n}\n"; + assert_eq!(only("reads-source", generated), [], "a loop over generated names lists no files"); + let nested = "#[test]\nfn t() {\n let n = files.iter().filter(|p| p.to_str().is_some_and(|s| s.ends_with(\".rs\"))).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(only("reads-source", nested), [(3, "reads-source")], "a suffix check nested inside the closure of a listing filter"); + } + + #[test] + fn suffix_selected_source_reads_include_streams() { + for read in ["File::open(p)", "File :: open(p)", "reader.read_to_end(&mut bytes)", "reader.read_to_string(&mut text)", "fs::read(p)"] { + let src = format!( + "#[test]\nfn t() {{\n let p = newest();\n if p.ends_with(\".rs\") {{\n let got = {read};\n assert_eq!(check(got), 1);\n }}\n}}\n" + ); + assert_eq!(only("reads-source", &src), [(4, "reads-source")], "{read}"); + assert_eq!(only("reads-source", &src.replace(".rs", ".svg")), [], "{read}"); + } + let name = "#[test]\nfn t() {\n let p = newest();\n assert_eq!(p.ends_with(\".rs\"), wanted());\n}\n"; + assert_eq!(only("reads-source", name), [], "the suffix check's result is compared, and nothing is read"); + } + + #[test] + fn a_file_whose_last_route_was_removed_is_lost() { + let child = "crates/x/src/a/child.rs"; + let paths = [child.to_owned()]; + let base = [("crates/x/src/lib.rs", "mod a;\n"), ("crates/x/src/a.rs", "mod child;\n")]; + let read_base = |p: &str| base.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + for (lib, lost) in [("", true), ("mod a;\n", false), ("#[path = \"a/child.rs\"]\nmod again;\n", false)] { + let head = [("crates/x/src/lib.rs", lib), ("crates/x/src/a.rs", "mod child;\n")]; + let read = |p: &str| head.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let found = lost_routes(&paths, &read, &path_overrides(head), &read_base, &Overrides::new()); + assert_eq!(found.contains_key(child), lost, "{lib:?}"); + if lost { + assert!(found[child].iter().any(|p| p == "crates/x/src/lib.rs"), "the removed declaration's file is a base route"); + } + } + let common = "crates/x/tests/common/mod.rs".to_owned(); + let smoke = [("crates/x/tests/smoke.rs", "mod common;\n")]; + let read_smoke = |p: &str| smoke.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + let smoke_routes = with_root_routes(path_overrides(smoke), &[smoke[0].0.to_owned(), common.clone()]); + let deleted = lost_routes( + std::slice::from_ref(&common), + &|_| None, + &with_root_routes(Overrides::new(), std::slice::from_ref(&common)), + &read_smoke, + &smoke_routes, + ); + assert_eq!(deleted.get(&common).map(Vec::as_slice), Some(&[smoke[0].0.to_owned()][..]), "the deleted target root was its only route"); + let kept = lost_routes(std::slice::from_ref(&common), &read_smoke, &smoke_routes, &read_smoke, &smoke_routes); + assert!(kept.is_empty(), "the target root still loads it"); + let never_loaded = [("crates/x/src/lib.rs", ""), ("crates/x/src/a.rs", "mod child;\n")]; + let read = |p: &str| never_loaded.iter().find(|(f, _)| *f == p).map(|(_, s)| (*s).to_owned()); + assert!(lost_routes(&paths, &read, &Overrides::new(), &read, &Overrides::new()).is_empty(), "a file no target loaded at the base either"); + let ctx = Ctx { module_cfgs: [(child.to_owned(), vec!["any()".to_owned()])].into_iter().collect(), ..ctx() }; + assert_eq!(hits_in(child, "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n", &ctx), [(2, "never-run")]); + } } From 6cf914589051de064adb3997cb8bbee3742cc79d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 23:24:20 -0800 Subject: [PATCH 30/32] Save: checked writes check the open folder's path as it is The second check of a checked write passed the open folder's path as text and looked it up again. A path that was not valid UTF-8 was refused, and a folder on that path replaced by a link into an allowed folder between the two lookups could let a place outside pass. check_write_real compares the open folder's real path with the write roots and the script's grants as it is, without looking it up again. - The folder is opened with O_PATH on Linux, Android and FreeBSD, so a folder that can be written and searched but not listed takes the file. The folder flush opens it for reading, and an error there still reports the completed write. - The replaced file's permissions are read after the new content is written, as write_atomic_with reads them, so permissions taken away meanwhile stay taken away. Its ACL is read only from the same file. - A folder that changed while it was opened is no longer reported as a read-only location. - Errors name the kept temporary file where its folder is now, after the folder moved. - A file already at the name the old content is copied to is left as it is: only a copy this save made and could not finish is removed. --- crates/engine/src/cmd/fileio/access.rs | 48 ++++- crates/engine/src/file_access.rs | 100 ++++++++--- crates/format/src/atomic.rs | 231 +++++++++++++++++++++---- 3 files changed, 318 insertions(+), 61 deletions(-) diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 8691ebb1fb..0edfc53c54 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -339,8 +339,13 @@ fn write_checked(path: &str, fill: impl FnOnce(&mut std::fs::File) -> std::io::R return vectorcraft_format::write_atomic_with(path, fill); } vectorcraft_format::write_atomic_checked(path, fill, |opened| { - let opened = opened.to_str().ok_or_else(|| std::io::Error::other(format!("{}: path is not valid UTF-8", opened.display())))?; - crate::file_access::check_write_unrecorded(opened).map_err(std::io::Error::other) + // On Unix `opened` is the open folder's real path with the file's name: compared as it is, + // without looking the folder up again. Elsewhere it is `path` itself. + #[cfg(unix)] + let checked = crate::file_access::check_write_real(opened); + #[cfg(not(unix))] + let checked = crate::file_access::check_write_unrecorded(&opened.to_string_lossy()); + checked.map_err(std::io::Error::other) }) } @@ -766,4 +771,43 @@ mod tests { assert_eq!(naming_in_error(EngineError::Other(raw.clone()), &file).to_string(), raw); let _ = std::fs::remove_dir_all(base); } + + /// The second check of a checked write compares the open folder's real path as it is: a folder + /// on that path replaced afterwards by a link into the write root does not make a place outside + /// the root pass. + #[cfg(unix)] + #[test] + fn a_checked_write_compares_the_open_folder_without_looking_it_up_again() { + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-real-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (root, out) = (base.join("root"), base.join("out")); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(out.join("x")).unwrap(); + let real = out.join("x/doc.svg"); + std::fs::remove_dir(out.join("x")).unwrap(); + std::os::unix::fs::symlink(&root, out.join("x")).unwrap(); + let roots = AutomationRoots::new(&[], &[root.as_path()]).unwrap(); + assert!(confine(roots.as_ref(), || crate::file_access::check_write_unrecorded(&real.to_string_lossy())).is_ok(), "looked up, it passes"); + let checked = confine(roots.as_ref(), || crate::file_access::check_write_real(&real)); + assert!(checked.is_err_and(|e| e.contains("outside the write root"))); + let _ = std::fs::remove_dir_all(base); + } + + /// A checked write through a link to a folder whose name is not valid UTF-8, inside the write + /// root, is saved. + #[cfg(target_os = "linux")] + #[test] + fn a_checked_write_saves_into_a_folder_whose_name_is_not_text() { + use std::os::unix::ffi::OsStrExt; + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-bytes-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let bytes = base.join(std::ffi::OsStr::from_bytes(b"folder-\xff")); + std::fs::create_dir_all(&bytes).unwrap(); + std::os::unix::fs::symlink(&bytes, base.join("text")).unwrap(); + let roots = AutomationRoots::new(&[], &[base.as_path()]).unwrap(); + let path = base.join("text/doc.svg").to_string_lossy().into_owned(); + confine(roots.as_ref(), || write_file(&path, b"new")).unwrap(); + assert_eq!(std::fs::read(bytes.join("doc.svg")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(base); + } } diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index bc2acda5e6..d705682dcb 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -100,16 +100,9 @@ impl AutomationRoots { /// May the file or folder at `path` be read (or written)? It must lie inside one of the roots /// of that kind. `Err` says why not. pub fn check(&self, path: &str, access: Access) -> Result<(), String> { - let roots = match access { - Access::Read => &self.read, - Access::Write => &self.write, - }; - // The messages are spelled out whole, as the translation catalogs match them. + let roots = self.of(access); if roots.is_empty() { - return match access { - Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")), - Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")), - }; + return Err(refused(roots, path, access)); } // Resolving a path on another computer connects to it: unless a root is on a network // share, such a path is refused by its name before anything is looked up. @@ -120,12 +113,22 @@ impl AutomationRoots { return Ok(()); } } - let shown: Vec = roots.iter().map(|r| r.shown.display().to_string()).collect(); - match (shown.as_slice(), access) { - ([root], Access::Read) => Err(format!("automation path rejected: outside the read root {root}: {path}")), - ([root], Access::Write) => Err(format!("automation path rejected: outside the write root {root}: {path}")), - (_, Access::Read) => Err(format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", "))), - (_, Access::Write) => Err(format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", "))), + Err(refused(roots, path, access)) + } + + /// [`AutomationRoots::check`] for `real`, a path whose links have been followed already: it is + /// compared with the roots as it is, and not looked up again. + #[cfg(unix)] + pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> { + let roots = self.of(access); + if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) } + } + + /// The roots of the kind `access`. + fn of(&self, access: Access) -> &[Root] { + match access { + Access::Read => &self.read, + Access::Write => &self.write, } } @@ -157,6 +160,24 @@ impl AutomationRoots { } } +/// Why `path` is refused `access` under `roots`, the roots of that kind. +fn refused(roots: &[Root], path: &str, access: Access) -> String { + // The messages are spelled out whole, as the translation catalogs match them. + if roots.is_empty() { + return match access { + Access::Read => format!("automation filesystem access is not granted: read authority is absent: {path}"), + Access::Write => format!("automation filesystem access is not granted: write authority is absent: {path}"), + }; + } + let shown: Vec = roots.iter().map(|r| r.shown.display().to_string()).collect(); + match (shown.as_slice(), access) { + ([root], Access::Read) => format!("automation path rejected: outside the read root {root}: {path}"), + ([root], Access::Write) => format!("automation path rejected: outside the write root {root}: {path}"), + (_, Access::Read) => format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", ")), + (_, Access::Write) => format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", ")), + } +} + /// Where the roots are in force on a thread ([`confine`], [`unconfined`]). #[derive(Clone, Debug)] enum Scope { @@ -371,18 +392,34 @@ impl ScriptGate { also.check(path, access)?; } let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; - let allowed = real.is_some_and(|real| { - let scoped = match access { - Access::Read => self.read.allows(&real) || self.write.allows(&real), - Access::Write => self.write.allows(&real), - }; - // A read-only file is not written over, also where a rename could replace it. - let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly()); - let held = matches!(access, Access::Write) && self.held.contains(&real); - let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real); - !read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked) - }); - if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } + if real.is_some_and(|real| self.allows_real(&real, access)) { Ok(()) } else { Err(format!("Script file access denied: {path}")) } + } + + /// [`ScriptGate::check`] for `real`, a path whose links have been followed already: it is + /// compared as it is, and not looked up again. + #[cfg(unix)] + pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> { + if let Some(also) = &self.also { + also.check_real(real, access)?; + } + if !ScriptScope::refused_by_name(real) && self.allows_real(real, access) { + Ok(()) + } else { + Err(format!("Script file access denied: {}", real.display())) + } + } + + /// May the place at the real path `real` be read (or written) through this gate alone? + fn allows_real(&self, real: &Path, access: Access) -> bool { + let scoped = match access { + Access::Read => self.read.allows(real) || self.write.allows(real), + Access::Write => self.write.allows(real), + }; + // A read-only file is not written over, also where a rename could replace it. + let read_only = matches!(access, Access::Write) && std::fs::metadata(real).is_ok_and(|m| m.is_file() && m.permissions().readonly()); + let held = matches!(access, Access::Write) && self.held.iter().any(|h| h == real); + let linked = matches!(access, Access::Read) && self.linked.has(real) && !self.read.keeps_out(real); + !read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked) } } @@ -479,6 +516,15 @@ pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { check_gate(path, Access::Write) } +/// [`check_write_unrecorded`] for `real`, the path of a file in a folder whose links have been +/// followed already (the folder a checked write has opened): it is compared as it is, so the folder +/// is not looked up again by its path. +#[cfg(unix)] +pub(crate) fn check_write_real(real: &Path) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check_real(real, Access::Write))?; + GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write)) +} + /// Whether a write here is checked: roots are in force, or a script's command runs. pub(crate) fn writes_checked() -> bool { current().is_some() || in_script_command() diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 54a0fe0432..34d980071d 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -104,21 +104,28 @@ pub fn write_atomic_checked( .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", resolved.display())))? .to_os_string(); let parent = resolved.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); - let dir = rustix::fs::open(parent, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())?; - let target = opened_folder_path(&dir, parent)?.join(&name); + let dir = open_folder(parent)?; + let real = opened_folder_path(&dir, parent)?; + let target = real.join(&name); allowed(&target)?; - let old = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW).ok(); + // Only whether a file is there: its permissions are read again once it is about to be replaced. + let replacing = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW).is_ok(); let tmp_name = temp_path(&target)?.file_name().map(std::ffi::OsStr::to_os_string).unwrap_or_default(); - let tmp = target.with_file_name(&tmp_name); // Replacing a file: owner-only while it is written, as in `write_atomic_with`. - let mode = if old.is_some() { Mode::RUSR | Mode::WUSR } else { Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::WGRP | Mode::ROTH | Mode::WOTH }; + let mode = if replacing { Mode::RUSR | Mode::WUSR } else { Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::WGRP | Mode::ROTH | Mode::WOTH }; let new_file = OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC; let remove_tmp = || { // Best effort: the temporary file is all there is to clean up. let _ = rustix::fs::unlinkat(&dir, &tmp_name, AtFlags::empty()); }; - let synced = - || rustix::fs::fsync(&dir).map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: target.clone(), error: e.into() })); + // The folder may have moved since it was opened: messages name it where it is now. + let now = |file: &std::ffi::OsStr| folder_now(&dir, &real).join(file); + let synced = || { + // Opened for reading here: the folder handle above may allow name lookups only. + let flushed = + rustix::fs::openat(&dir, ".", OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()).and_then(|d| rustix::fs::fsync(&d)); + flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() })) + }; let open_target = |write: bool| -> io::Result { let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY }; Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?)) @@ -131,14 +138,21 @@ pub fn write_atomic_checked( remove_tmp(); return Err(e); } - if let Some(old) = &old { - // Best effort, as in `write_atomic_with`. - let _ = keep_permissions_at(&dir, &name, old, &f); + // The file's permissions as they are now, after `fill`, as in `write_atomic_with`: a + // change made to them meanwhile is kept. Best effort; a file that can't be looked at + // leaves the replacement owner-only. + if let Ok(old) = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW) { + let _ = keep_permissions_at(&dir, &name, &old, &f); } drop(f); - let Err(refused) = rustix::fs::renameat(&dir, &tmp_name, &dir, &name) else { return synced() }; + #[cfg(test)] + let refuse = RENAME_REFUSED.with(std::cell::Cell::get); + #[cfg(not(test))] + let refuse = false; + let renamed = if refuse { Err(rustix::io::Errno::ACCESS) } else { rustix::fs::renameat(&dir, &tmp_name, &dir, &name) }; + let Err(refused) = renamed else { return synced() }; let over = Over { - tmp: &tmp, + tmp: &|| now(&tmp_name), old: std::env::temp_dir().join(&tmp_name).with_extension("old"), open_tmp: &|| { Ok(File::from(rustix::fs::openat(&dir, &tmp_name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())?)) @@ -168,7 +182,7 @@ pub fn write_atomic_checked( return Err(e); } let over = Over { - tmp: &elsewhere, + tmp: &|| elsewhere.clone(), old: elsewhere.with_extension("old"), open_tmp: &|| File::open(&elsewhere), remove_tmp: &remove, @@ -199,13 +213,47 @@ fn opened_folder_path(dir: &std::os::fd::OwnedFd, parent: &Path) -> io::Result

io::Result { + use rustix::fs::{Mode, OFlags}; + #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] + let access = OFlags::PATH; + #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "freebsd")))] + let access = OFlags::RDONLY; + Ok(rustix::fs::open(parent, access | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())?) +} + +/// The path the open folder `dir` has now, which may differ from `opened`, its real path when it +/// was opened, after it moved. `opened` where the system does not say. +#[cfg(unix)] +fn folder_now(dir: &std::os::fd::OwnedFd, opened: &Path) -> PathBuf { + #[cfg(any(target_os = "linux", target_os = "android"))] + if let Ok(now) = std::fs::read_link(format!("/proc/self/fd/{}", std::os::fd::AsRawFd::as_raw_fd(dir))) + && now.is_absolute() + { + return now; + } + #[cfg(target_vendor = "apple")] + if let Ok(now) = rustix::fs::getpath(dir) { + return PathBuf::from(::from_vec(now.into_bytes())); + } + let _ = dir; + opened.to_path_buf() +} + /// [`keep_permissions`] for the temporary file `tmp`, about to replace `name` in folder `dir`, whose -/// file had the status `old`. A name that does not hold a plain file has none to keep. +/// file has the status `old`. A name that does not hold a plain file has none to keep. The ACL is +/// read only from that same file (the same device and inode); when it can't be, the replacement +/// keeps no group or other permissions. #[cfg(unix)] fn keep_permissions_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> io::Result<()> { use rustix::fs::{FileType, Mode}; @@ -215,22 +263,25 @@ fn keep_permissions_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: let mut mode = Mode::from_raw_mode(old.st_mode); let gid = rustix::fs::Gid::from_raw(old.st_gid); let kept_group = rustix::fs::fstat(tmp).is_ok_and(|t| t.st_gid == old.st_gid) || rustix::fs::fchown(tmp, None, Some(gid)).is_ok(); - if !kept_group || !keep_acl_at(dir, name, tmp) { + if !kept_group || !keep_acl_at(dir, name, old, tmp) { mode.remove(Mode::RWXG | Mode::RWXO); } rustix::fs::fchmod(tmp, mode).map_err(io::Error::from) } /// [`keep_acl`] for `name` in folder `dir`, opened without following a link and without waiting on -/// a pipe put in its place. +/// a pipe put in its place, when it is still the file with the status `old`. #[cfg(target_os = "linux")] -fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, tmp: &File) -> bool { +fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> bool { use rustix::fs::{Mode, OFlags}; use rustix::io::Errno; const ACL: &str = "system.posix_acl_access"; let Ok(target) = rustix::fs::openat(dir, name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty()) else { return false; }; + if !rustix::fs::fstat(&target).is_ok_and(|t| (t.st_dev, t.st_ino) == (old.st_dev, old.st_ino)) { + return false; + } let mut buf = vec![0u8; 64 << 10]; match rustix::fs::fgetxattr(&target, ACL, &mut buf[..]) { Ok(n) => buf.get(..n).is_some_and(|acl| rustix::fs::fsetxattr(tmp, ACL, acl, rustix::fs::XattrFlags::empty()).is_ok()), @@ -243,7 +294,7 @@ fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, tmp: &File) - } #[cfg(all(unix, not(target_os = "linux")))] -fn keep_acl_at(_: &std::os::fd::OwnedFd, _: &std::ffi::OsStr, _: &File) -> bool { +fn keep_acl_at(_: &std::os::fd::OwnedFd, _: &std::ffi::OsStr, _: &rustix::fs::Stat, _: &File) -> bool { true } @@ -296,7 +347,7 @@ fn write_atomic_stepping( /// error says where they are. fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { let over = Over { - tmp, + tmp: &|| tmp.to_path_buf(), old: tmp.with_extension("old"), open_tmp: &|| File::open(tmp), remove_tmp: &|| { @@ -311,8 +362,8 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { /// How [`write_over_in`] reaches its files: by their paths, or through a folder opened once /// ([`write_atomic_checked`]). struct Over<'a> { - /// The temporary file, as error messages name it. - tmp: &'a Path, + /// Where the temporary file is when an error message names it (its folder may have moved). + tmp: &'a dyn Fn() -> PathBuf, /// Where the file as it was is copied aside. old: PathBuf, open_tmp: &'a dyn Fn() -> io::Result, @@ -327,7 +378,6 @@ struct Over<'a> { /// [`write_over`] through `over`. fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { - let tmp = over.tmp; let opened = (over.open_tmp)().and_then(|from| Ok((from, (over.open_target)(true)?))); let Ok((mut from, mut to)) = opened else { // Best effort: the temporary file is all there is to clean up. @@ -339,10 +389,10 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { if let Some(old) = &old && let Err(e) = (over.open_target)(false).and_then(|mut target| keep_old(&mut target, old)) { - // Best effort: a partial copy is of no use. - let _ = std::fs::remove_file(old); - let why = - format!("{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", tmp.display()); + let why = format!( + "{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", + (over.tmp)().display() + ); return Err(io::Error::new(refused.kind(), RecoveryError(why))); } let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to)); @@ -358,17 +408,23 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { } (Err(e), Some(old)) => Err(io::Error::new( e.kind(), - RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", tmp.display(), old.display())), + RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", (over.tmp)().display(), old.display())), )), - (Err(e), None) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", tmp.display())))), + (Err(e), None) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", (over.tmp)().display())))), } } -/// A flushed copy of what `target` holds, at `old` (for its owner only). +/// A flushed copy of what `target` holds, at `old` (for its owner only). A copy this call made and +/// could not finish is removed; a file already at `old` is left as it is. fn keep_old(target: &mut File, old: &Path) -> io::Result<()> { let mut to = create_private(old)?; - io::copy(target, &mut to)?; - sync_file(&to) + let copied = io::copy(target, &mut to).and_then(|_| sync_file(&to)); + if copied.is_err() { + drop(to); + // Best effort: a partial copy is of no use. + let _ = std::fs::remove_file(old); + } + copied } /// A new file for its owner only (Unix): the system's temporary folder is shared. @@ -523,6 +579,9 @@ thread_local! { static FLUSHES_LEFT: std::cell::Cell> = const { std::cell::Cell::new(None) }; /// Tests: how many plain `fsync` fallbacks were made on this thread. static PLAIN_FSYNCS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: [`write_atomic_checked`]'s folder refuses the rename. + #[cfg(unix)] + static RENAME_REFUSED: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// A symbolic link keeps pointing at its file: write the file it names. @@ -739,6 +798,87 @@ mod tests { let _ = std::fs::remove_dir_all(d); } + /// Permissions taken away from the file while the new content is written stay taken away. + #[cfg(unix)] + #[test] + fn a_checked_write_keeps_permissions_changed_while_it_fills() { + use std::os::unix::fs::PermissionsExt; + let (d, root, _) = checked_folders("checked-mode"); + let path = root.join("inside/doc.txt"); + std::fs::write(&path, b"old").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + let fill = |f: &mut File| { + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?; + f.write_all(b"new") + }; + write_atomic_checked(&path, fill, under(&root)).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// A folder that changed between being opened and being looked up by its path is not reported + /// as a read-only location. + #[cfg(unix)] + #[test] + fn a_changed_folder_is_not_a_read_only_location() { + let (d, root, outside) = checked_folders("checked-identity"); + let opened = open_folder(&root.join("inside")).unwrap(); + let e = opened_folder_path(&opened, &outside).unwrap_err(); + assert!(e.to_string().contains("the folder changed while it was opened"), "{e}"); + assert!(!read_only_location(&e), "{e:?}"); + let _ = std::fs::remove_dir_all(d); + } + + /// A checked write whose folder moved after it was opened, refused the rename, and failed to + /// copy into the file: the error names the temporary file where it is now. + #[cfg(unix)] + #[test] + fn a_checked_write_names_the_kept_file_where_its_folder_moved() { + let (d, root, _) = checked_folders("checked-moved"); + std::fs::write(root.join("inside/doc.txt"), b"original").unwrap(); + let check = under(&root); + let r = write_atomic_checked( + &root.join("inside/doc.txt"), + |f| f.write_all(b"new"), + |p| { + check(p)?; + std::fs::rename(root.join("inside"), root.join("moved"))?; + RENAME_REFUSED.with(|c| c.set(true)); + // The temporary file's flush and the copy of the old content work, the next doesn't. + FLUSHES_LEFT.with(|c| c.set(Some(2))); + Ok(()) + }, + ); + RENAME_REFUSED.with(|c| c.set(false)); + FLUSHES_LEFT.with(|c| c.set(None)); + let message = r.unwrap_err().to_string(); + let kept: Vec<_> = + std::fs::read_dir(root.join("moved")).unwrap().map(|e| e.unwrap().path()).filter(|p| p.extension().is_some_and(|x| x == "tmp")).collect(); + let [kept] = kept.as_slice() else { panic!("one temporary file: {kept:?}") }; + let kept = std::fs::canonicalize(kept).unwrap(); + assert!(message.contains(&kept.display().to_string()), "{message}"); + assert_eq!(std::fs::read(&kept).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// A folder that can be written and searched but not listed takes the file. (The permission + /// does not hold for root, which can list any folder.) + #[cfg(target_os = "linux")] + #[test] + fn a_checked_write_saves_into_a_folder_that_cannot_be_listed() { + use std::os::unix::fs::PermissionsExt; + let (d, root, _) = checked_folders("checked-search-only"); + let folder = root.join("inside"); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o300)).unwrap(); + let r = write_atomic_checked(&folder.join("doc.txt"), |f| f.write_all(b"new"), under(&root)); + std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap(); + // The folder flush needs it opened for reading: the file is written, and the error says so. + assert!(r.as_ref().map_or_else(|e| e.get_ref().is_some_and(|e| e.is::()), |()| true), "{r:?}"); + assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() @@ -995,6 +1135,33 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// A refused rename where a file is already at the name the old content would be copied to: + /// that file is left as it is, and the temporary file with the new content stays. + #[test] + fn a_refused_rename_leaves_a_file_already_at_the_backup_name() { + let d = dir("no-rename-backup-taken"); + let path = d.join("doc.vectorcraft"); + std::fs::write(&path, b"original").unwrap(); + let r = write_atomic_stepping( + &path, + |f| f.write_all(b"new"), + create_new, + |tmp, _| { + std::fs::write(tmp.with_extension("old"), b"an earlier copy")?; + denied() + }, + ); + let message = r.unwrap_err().to_string(); + let mut left = leftovers(&d, "doc.vectorcraft"); + left.sort(); + let [old, tmp] = left.as_slice() else { panic!("the earlier copy and the new content: {left:?}") }; + assert!(message.contains(tmp.as_str()), "{message}"); + assert_eq!(std::fs::read(d.join(old)).unwrap(), b"an earlier copy"); + assert_eq!(std::fs::read(d.join(tmp)).unwrap(), b"new"); + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + let _ = std::fs::remove_dir_all(&d); + } + /// A refused rename where the old content can't be copied aside (here: no flush works): the /// file is left as it was, the temporary file with the whole new content stays and the error /// names it. From 0c8fd2021b52beb819f83784f316c63ae8b27d5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:25:05 -0800 Subject: [PATCH 31/32] Save: checked writes keep the file's backup, ACL and grant name - A path written as a folder (`draft.svg/`, `draft.svg/.`) is refused instead of saving `draft.svg`. - The second check uses the name the file is stored under, so on a volume that ignores letter case a grant for `Report.svg` allows a save to `report.svg`. - Where the rename is refused, the copy of the old content is made beside the temporary file through the open folder, and in the system's temporary folder only when the folder takes no new file. - The copy of the old content is read from the file that is then overwritten: when another file is at the name by then, nothing is overwritten and the new content stays in the temporary file. - On Apple platforms the folder is opened with `O_SEARCH`, so a folder that can be written and searched but not listed takes the file. - On Linux the replaced file's ACL is read through an `O_PATH` handle, so a file its owner can write but not read keeps its ACL. - The moved-folder test expects the original folder in the message on FreeBSD, which does not report where an open folder is now. --- crates/format/src/atomic.rs | 286 +++++++++++++++++++++++++++++++----- 1 file changed, 249 insertions(+), 37 deletions(-) diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 34d980071d..d759ff6d9f 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -98,6 +98,12 @@ pub fn write_atomic_checked( allowed: impl FnOnce(&Path) -> io::Result<()>, ) -> io::Result<()> { use rustix::fs::{AtFlags, Mode, OFlags}; + // A path written as a folder (`draft.svg/`, `draft.svg/.`) is not a file path: `file_name` + // would drop the slash and save `draft.svg`. + let spelled = std::os::unix::ffi::OsStrExt::as_bytes(path.as_os_str()); + if spelled.ends_with(b"/") || spelled.ends_with(b"/.") || spelled == b"." { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display()))); + } let resolved = resolve_link(path)?; let name = resolved .file_name() @@ -106,7 +112,7 @@ pub fn write_atomic_checked( let parent = resolved.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); let dir = open_folder(parent)?; let real = opened_folder_path(&dir, parent)?; - let target = real.join(&name); + let target = real.join(stored_name(&dir, &real, &name)); allowed(&target)?; // Only whether a file is there: its permissions are read again once it is about to be replaced. let replacing = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW).is_ok(); @@ -151,9 +157,33 @@ pub fn write_atomic_checked( let refuse = false; let renamed = if refuse { Err(rustix::io::Errno::ACCESS) } else { rustix::fs::renameat(&dir, &tmp_name, &dir, &name) }; let Err(refused) = renamed else { return synced() }; + // The file as it was is copied beside the temporary file, through the open folder, or + // to the system's folder where the open folder takes no new file. + let old_name = Path::new(&tmp_name).with_extension("old").into_os_string(); + let old_elsewhere = std::env::temp_dir().join(&old_name); + let old_in_folder = std::cell::Cell::new(true); let over = Over { tmp: &|| now(&tmp_name), - old: std::env::temp_dir().join(&tmp_name).with_extension("old"), + create_old: &|| match rustix::fs::openat(&dir, &old_name, new_file, Mode::RUSR | Mode::WUSR) { + Ok(f) => { + old_in_folder.set(true); + Ok(File::from(f)) + } + Err(e) if e == rustix::io::Errno::EXIST => Err(e.into()), + Err(_) => { + old_in_folder.set(false); + create_private(&old_elsewhere) + } + }, + old: &|| if old_in_folder.get() { now(&old_name) } else { old_elsewhere.clone() }, + remove_old: &|| { + // Best effort: an unfinished copy is of no use. + if old_in_folder.get() { + let _ = rustix::fs::unlinkat(&dir, &old_name, AtFlags::empty()); + } else { + let _ = std::fs::remove_file(&old_elsewhere); + } + }, open_tmp: &|| { Ok(File::from(rustix::fs::openat(&dir, &tmp_name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())?)) }, @@ -181,9 +211,14 @@ pub fn write_atomic_checked( remove(); return Err(e); } + let old = elsewhere.with_extension("old"); let over = Over { tmp: &|| elsewhere.clone(), - old: elsewhere.with_extension("old"), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, open_tmp: &|| File::open(&elsewhere), remove_tmp: &remove, open_target: &open_target, @@ -219,14 +254,40 @@ fn opened_folder_path(dir: &std::os::fd::OwnedFd, parent: &Path) -> io::Result

std::ffi::OsString { + use rustix::fs::AtFlags; + let Ok(here) = rustix::fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) else { return name.to_os_string() }; + let Ok(stored) = std::fs::canonicalize(real.join(name)) else { return name.to_os_string() }; + let same = stored.parent() == Some(real) && rustix::fs::lstat(&stored).is_ok_and(|s| (s.st_dev, s.st_ino) == (here.st_dev, here.st_ino)); + match stored.file_name() { + Some(stored) if same => stored.to_os_string(), + _ => name.to_os_string(), + } +} + /// The folder at `parent`, opened for looking names up in it. On Linux, Android and FreeBSD that -/// is `O_PATH`, which needs no permission to list the folder, so a folder that can be written and -/// searched but not listed still takes the file. +/// is `O_PATH`, and on Apple platforms `O_SEARCH`: neither needs permission to list the folder, so +/// a folder that can be written and searched but not listed still takes the file. Where the system +/// refuses `O_SEARCH`, the folder is opened for reading. #[cfg(unix)] fn open_folder(parent: &Path) -> io::Result { use rustix::fs::{Mode, OFlags}; #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))] let access = OFlags::PATH; + #[cfg(target_vendor = "apple")] + { + // `O_EXEC`, which with `O_DIRECTORY` is `O_SEARCH` (). + let search = OFlags::from_bits_retain(0x4000_0000); + match rustix::fs::open(parent, search | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()) { + Err(e) if e == rustix::io::Errno::INVAL => {} + opened => return Ok(opened?), + } + } #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "freebsd")))] let access = OFlags::RDONLY; Ok(rustix::fs::open(parent, access | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())?) @@ -269,21 +330,23 @@ fn keep_permissions_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: rustix::fs::fchmod(tmp, mode).map_err(io::Error::from) } -/// [`keep_acl`] for `name` in folder `dir`, opened without following a link and without waiting on -/// a pipe put in its place, when it is still the file with the status `old`. +/// [`keep_acl`] for `name` in folder `dir`, when it is still the file with the status `old`. The +/// file is opened with `O_PATH` without following a link, which needs no permission to read it, and +/// its ACL is read through `/proc/self/fd`, which names that open file. #[cfg(target_os = "linux")] fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> bool { use rustix::fs::{Mode, OFlags}; use rustix::io::Errno; const ACL: &str = "system.posix_acl_access"; - let Ok(target) = rustix::fs::openat(dir, name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty()) else { + let Ok(target) = rustix::fs::openat(dir, name, OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty()) else { return false; }; if !rustix::fs::fstat(&target).is_ok_and(|t| (t.st_dev, t.st_ino) == (old.st_dev, old.st_ino)) { return false; } + let opened = format!("/proc/self/fd/{}", std::os::fd::AsRawFd::as_raw_fd(&target)); let mut buf = vec![0u8; 64 << 10]; - match rustix::fs::fgetxattr(&target, ACL, &mut buf[..]) { + match rustix::fs::getxattr(opened.as_str(), ACL, &mut buf[..]) { Ok(n) => buf.get(..n).is_some_and(|acl| rustix::fs::fsetxattr(tmp, ACL, acl, rustix::fs::XattrFlags::empty()).is_ok()), Err(e) if e == Errno::NODATA => match rustix::fs::fremovexattr(tmp, ACL) { Ok(()) => true, @@ -346,9 +409,14 @@ fn write_atomic_stepping( /// the copy into `target` fails it is damaged: `tmp` and the copy of the old content stay and the /// error says where they are. fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { + let old = tmp.with_extension("old"); let over = Over { tmp: &|| tmp.to_path_buf(), - old: tmp.with_extension("old"), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, open_tmp: &|| File::open(tmp), remove_tmp: &|| { let _ = std::fs::remove_file(tmp); @@ -364,8 +432,12 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { struct Over<'a> { /// Where the temporary file is when an error message names it (its folder may have moved). tmp: &'a dyn Fn() -> PathBuf, - /// Where the file as it was is copied aside. - old: PathBuf, + /// A new file, for its owner only and never replacing one, that the file as it was is copied to. + create_old: &'a dyn Fn() -> io::Result, + /// Where the file `create_old` made is when an error message names it. + old: &'a dyn Fn() -> PathBuf, + /// Best effort: removes the file `create_old` made. + remove_old: &'a dyn Fn(), open_tmp: &'a dyn Fn() -> io::Result, /// Best effort. remove_tmp: &'a dyn Fn(), @@ -384,10 +456,16 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { (over.remove_tmp)(); return Err(refused); }; - // Nothing to keep of a file that is new or empty. - let old = to.metadata().map_or(true, |m| m.len() > 0).then(|| over.old.clone()); - if let Some(old) = &old - && let Err(e) = (over.open_target)(false).and_then(|mut target| keep_old(&mut target, old)) + // Nothing to keep of a file that is new or empty. The copy is read from the file `to` writes + // into: one put at its name meanwhile is not copied in its place. + let kept = to.metadata().map_or(true, |m| m.len() > 0); + if kept + && let Err(e) = (over.open_target)(false).and_then(|mut target| { + if !same_file(&target, &to) { + return Err(io::Error::other("the file was replaced while it was opened")); + } + keep_old(&mut target, over) + }) { let why = format!( "{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", @@ -397,36 +475,50 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> { } let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to)); drop((from, to)); - match (copied, old) { - (Ok(()), old) => { + match (copied, kept) { + (Ok(()), kept) => { // Best effort: the file is saved, so the copies are no longer needed. (over.remove_tmp)(); - if let Some(old) = old { - let _ = std::fs::remove_file(old); + if kept { + (over.remove_old)(); } (over.synced)() } - (Err(e), Some(old)) => Err(io::Error::new( + (Err(e), true) => Err(io::Error::new( e.kind(), - RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", (over.tmp)().display(), old.display())), + RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", (over.tmp)().display(), (over.old)().display())), )), - (Err(e), None) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", (over.tmp)().display())))), + (Err(e), false) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", (over.tmp)().display())))), } } -/// A flushed copy of what `target` holds, at `old` (for its owner only). A copy this call made and -/// could not finish is removed; a file already at `old` is left as it is. -fn keep_old(target: &mut File, old: &Path) -> io::Result<()> { - let mut to = create_private(old)?; +/// A flushed copy of what `target` holds, in the file `over.create_old` makes. A copy this call made +/// and could not finish is removed; a file already at that name is left as it is. +fn keep_old(target: &mut File, over: &Over<'_>) -> io::Result<()> { + let mut to = (over.create_old)()?; let copied = io::copy(target, &mut to).and_then(|_| sync_file(&to)); if copied.is_err() { drop(to); - // Best effort: a partial copy is of no use. - let _ = std::fs::remove_file(old); + (over.remove_old)(); } copied } +/// Whether `a` and `b` are open on the same file (the same device and inode). Always `true` off +/// Unix. +fn same_file(a: &File, b: &File) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + matches!((a.metadata(), b.metadata()), (Ok(a), Ok(b)) if (a.dev(), a.ino()) == (b.dev(), b.ino())) + } + #[cfg(not(unix))] + { + let _ = (a, b); + true + } +} + /// A new file for its owner only (Unix): the system's temporary folder is shared. fn create_private(path: &Path) -> io::Result { let mut options = OpenOptions::new(); @@ -831,7 +923,9 @@ mod tests { } /// A checked write whose folder moved after it was opened, refused the rename, and failed to - /// copy into the file: the error names the temporary file where it is now. + /// copy into the file: the temporary file and the copy of the old content stay in that folder, + /// and the error names them where they are now. (FreeBSD does not say where an open folder is + /// now: there the error names them where the folder was opened.) #[cfg(unix)] #[test] fn a_checked_write_names_the_kept_file_where_its_folder_moved() { @@ -853,18 +947,136 @@ mod tests { RENAME_REFUSED.with(|c| c.set(false)); FLUSHES_LEFT.with(|c| c.set(None)); let message = r.unwrap_err().to_string(); - let kept: Vec<_> = - std::fs::read_dir(root.join("moved")).unwrap().map(|e| e.unwrap().path()).filter(|p| p.extension().is_some_and(|x| x == "tmp")).collect(); - let [kept] = kept.as_slice() else { panic!("one temporary file: {kept:?}") }; - let kept = std::fs::canonicalize(kept).unwrap(); - assert!(message.contains(&kept.display().to_string()), "{message}"); - assert_eq!(std::fs::read(&kept).unwrap(), b"new"); + let kept = |ext: &str| -> PathBuf { + let found: Vec<_> = std::fs::read_dir(root.join("moved")) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.extension().is_some_and(|x| x == ext)) + .collect(); + let [kept] = found.as_slice() else { panic!("one .{ext} file: {found:?}") }; + std::fs::canonicalize(kept).unwrap() + }; + let (tmp, old) = (kept("tmp"), kept("old")); + assert_eq!((std::fs::read(&tmp).unwrap(), std::fs::read(&old).unwrap()), (b"new".to_vec(), b"original".to_vec())); + let named_in = + if cfg!(any(target_os = "linux", target_os = "android", target_vendor = "apple")) { root.join("moved") } else { root.join("inside") }; + for file in [&tmp, &old] { + let named = named_in.join(file.file_name().unwrap()); + assert!(message.contains(&named.display().to_string()), "{} in {message}", named.display()); + } + let _ = std::fs::remove_dir_all(d); + } + + /// A refused rename copies the old content through the file handle it then overwrites: when a + /// different file is at the name by the time it is opened for reading, nothing is overwritten and + /// the new content stays in the temporary file. + #[cfg(unix)] + #[test] + fn a_refused_rename_copies_aside_the_file_it_overwrites() { + let d = dir("no-rename-swapped"); + let (path, other, tmp) = (d.join("doc.txt"), d.join("other.txt"), d.join("doc.tmp")); + std::fs::write(&path, b"original").unwrap(); + std::fs::write(&other, b"someone else's").unwrap(); + std::fs::write(&tmp, b"new").unwrap(); + let old = d.join("doc.old"); + let over = Over { + tmp: &|| tmp.clone(), + create_old: &|| create_private(&old), + old: &|| old.clone(), + remove_old: &|| { + let _ = std::fs::remove_file(&old); + }, + open_tmp: &|| File::open(&tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(&tmp); + }, + open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&other) }, + synced: &|| Ok(()), + }; + let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err(); + assert!(e.to_string().contains("the file was replaced while it was opened"), "{e}"); + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + assert_eq!(std::fs::read(&tmp).unwrap(), b"new"); + assert!(!old.exists()); + let _ = std::fs::remove_dir_all(d); + } + + /// A path written as a folder is refused, and no file is made under the name before the slash. + #[cfg(unix)] + #[test] + fn a_checked_write_refuses_a_path_written_as_a_folder() { + let (d, root, _) = checked_folders("checked-slash"); + for spelled in ["inside/draft.svg/", "inside/draft.svg/."] { + let r = write_atomic_checked(&root.join(spelled), |f| f.write_all(b"new"), under(&root)); + assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::InvalidInput), "{spelled}"); + } + assert!(!root.join("inside/draft.svg").exists()); + write_atomic_checked(&root.join("inside/draft.svg"), |f| f.write_all(b"new"), under(&root)).unwrap(); + assert_eq!(std::fs::read(root.join("inside/draft.svg")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// On a volume that ignores letter case, a write to `report.txt` where `Report.txt` is stored + /// is checked as `Report.txt`, the name a grant for the file has. (Skipped where the volume keeps + /// letter case apart.) + #[cfg(unix)] + #[test] + fn a_checked_write_checks_the_stored_name_of_the_file() { + let (d, root, _) = checked_folders("checked-case"); + let stored = root.join("inside/Report.txt"); + std::fs::write(&stored, b"old").unwrap(); + if !root.join("inside/report.txt").exists() { + let _ = std::fs::remove_dir_all(d); + return; + } + let exact = |p: &Path| if p == stored { Ok(()) } else { Err(io::Error::other(format!("{} is not granted", p.display()))) }; + write_atomic_checked(&root.join("inside/report.txt"), |f| f.write_all(b"new"), exact).unwrap(); + assert_eq!(std::fs::read(&stored).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// A replaced file that its owner may write but not read keeps the ACL that lets someone else + /// read it. (Skipped on a file system without ACLs, and for root, which can read any file.) + #[cfg(target_os = "linux")] + #[test] + fn a_checked_write_keeps_the_acl_of_a_file_its_owner_cannot_read() { + use std::os::unix::fs::PermissionsExt; + const ACL: &str = "system.posix_acl_access"; + let (d, root, _) = checked_folders("checked-acl-write-only"); + let path = root.join("inside/doc.txt"); + std::fs::write(&path, b"old").unwrap(); + // u::-w-, u:nobody:r--, g::---, m::r--, o::--- + let mut acl = 2u32.to_le_bytes().to_vec(); + for (tag, perm, id) in [(0x01u16, 2u16, u32::MAX), (0x02, 4, 65534), (0x04, 0, u32::MAX), (0x10, 4, u32::MAX), (0x20, 0, u32::MAX)] { + acl.extend(tag.to_le_bytes()); + acl.extend(perm.to_le_bytes()); + acl.extend(id.to_le_bytes()); + } + match rustix::fs::setxattr(&path, ACL, &acl, rustix::fs::XattrFlags::empty()) { + Ok(()) => {} + Err(e) if e == rustix::io::Errno::NOTSUP => { + let _ = std::fs::remove_dir_all(d); + return; + } + Err(e) => panic!("setting the ACL: {e}"), + } + if File::open(&path).is_ok() { + // Root reads any file. + let _ = std::fs::remove_dir_all(d); + return; + } + write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root)).unwrap(); + let mut buf = vec![0u8; 4096]; + let n = rustix::fs::getxattr(&path, ACL, &mut buf[..]).unwrap(); + assert_eq!(buf.get(..n).unwrap(), acl.as_slice(), "the ACL is kept"); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); let _ = std::fs::remove_dir_all(d); } /// A folder that can be written and searched but not listed takes the file. (The permission /// does not hold for root, which can list any folder.) - #[cfg(target_os = "linux")] + #[cfg(any(target_os = "linux", target_vendor = "apple"))] #[test] fn a_checked_write_saves_into_a_folder_that_cannot_be_listed() { use std::os::unix::fs::PermissionsExt; From 859a6b4dd323b73022e474e52756b2cf0e2f1114 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:33:38 -0800 Subject: [PATCH 32/32] xtask: test-lint decodes escapes in #[path] values A plain #[path = "\x63hild.rs"] after #[cfg_attr(windows, path = "child.rs")] loads child.rs on Linux and FreeBSD, but test-lint compared the undecoded spelling with the file name, dropped that route and reported a test in child.rs as never-run. The plain attribute and the path argument of cfg_attr now decode the escapes of an ordinary string literal with the same unescape the cfg values use. Raw string literals are read as written. --- xtask/src/test_lint.rs | 43 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index c95215cd4c..37bd14d863 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -4820,7 +4820,8 @@ fn path_overrides<'a>(sources: impl IntoIterator) -> } /// The string value of a `#[path = "…"]` attribute in `m[from..to]`, written as an ordinary or a -/// raw string literal (`#[path = r"shared.rs"]`, `#[path = r#"shared.rs"#]`). +/// raw string literal (`#[path = r"shared.rs"]`, `#[path = r#"shared.rs"#]`). The escapes of an +/// ordinary literal are decoded (`"\x63hild.rs"` names `child.rs`); a raw literal is read as written. fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { words(m, b"path", from, to).into_iter().find_map(|at| { let attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); @@ -4829,7 +4830,8 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { if !attr || m.get(eq) != Some(&b'=') { return None; } - let hashes = if m.get(q) == Some(&b'r') { + let raw = m.get(q) == Some(&b'r'); + let hashes = if raw { let h = m[q + 1..].iter().take_while(|&&c| c == b'#').count(); q += 1 + h; h @@ -4841,13 +4843,17 @@ fn path_attr(m: &[u8], src: &[u8], from: usize, to: usize) -> Option { } let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); let end = find(m, &close, q + 1)?; - Some(String::from_utf8_lossy(&src[q + 1..end]).into_owned()) + let body = String::from_utf8_lossy(&src[q + 1..end]); + Some(if raw { body.into_owned() } else { unescape(&body) }) }) } /// The value of a whitespace-free `path=` argument, for an ordinary or a raw string literal. -fn path_arg(arg: &str) -> Option<&str> { - whole_literal(arg.strip_prefix("path=")?).map(|l| &l[1..l.len() - 1]) +/// The escapes of an ordinary literal are decoded, as in [`path_attr`]. +fn path_arg(arg: &str) -> Option { + let lit = arg.strip_prefix("path=")?; + let body = whole_literal(lit).map(|l| &l[1..l.len() - 1])?; + Some(if lit.starts_with('"') { unescape(body) } else { body.to_owned() }) } /// The `#[cfg_attr(, path = "…")]` overrides in `m[from..to]`, each as its condition and @@ -4867,7 +4873,7 @@ fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String, for cut in cuts[1..].iter().copied().chain([text.len()]) { let arg = text.get(start..cut).unwrap_or(""); if let Some(rel) = path_arg(arg) { - out.push((text[..first].to_owned(), rel.to_owned())); + out.push((text[..first].to_owned(), rel)); } start = cut + 1; } @@ -7851,6 +7857,10 @@ mod tests { assert_eq!(cfg_attr_paths(&mask(src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "a,b.rs".to_owned())]); let raw = "#[cfg_attr(unix, path = r#\"a.rs\"#)]\nmod x;\n"; assert_eq!(cfg_attr_paths(&mask(raw), raw.as_bytes(), 0, raw.len()), [("unix".to_owned(), "a.rs".to_owned())]); + let escaped = "#[cfg_attr(unix, path = \"\\x61.rs\")]\nmod x;\n"; + assert_eq!(cfg_attr_paths(&mask(escaped), escaped.as_bytes(), 0, escaped.len()), [("unix".to_owned(), "a.rs".to_owned())]); + let raw_escape = "#[cfg_attr(unix, path = r\"\\x61.rs\")]\nmod x;\n"; + assert_eq!(cfg_attr_paths(&mask(raw_escape), raw_escape.as_bytes(), 0, raw_escape.len()), [("unix".to_owned(), "\\x61.rs".to_owned())]); } #[test] @@ -7873,6 +7883,27 @@ mod tests { assert_eq!(hits_in(&shared, test, &ctx), [], "the raw-string route runs it on Linux"); } + #[test] + fn path_attributes_decode_escapes_in_ordinary_strings() { + let escaped = "#[path = \"\\x63hild.rs\"]\nmod c;\n"; + assert_eq!(path_attr(&mask(escaped), escaped.as_bytes(), 0, escaped.len()).as_deref(), Some("child.rs")); + let raw = "#[path = r\"\\x63hild.rs\"]\nmod c;\n"; + assert_eq!(path_attr(&mask(raw), raw.as_bytes(), 0, raw.len()).as_deref(), Some("\\x63hild.rs"), "a raw string keeps its backslash"); + } + + #[test] + fn an_escaped_plain_path_after_a_cfg_attr_path_is_the_fallback_route() { + // Linux loads `child.rs` through the plain attribute, the fallback of the `cfg_attr` override. + let files: HashMap<&str, &str> = + [("crates/x/src/lib.rs", "#[cfg_attr(windows, path = \"child.rs\")]\n#[path = \"\\x63hild.rs\"]\nmod c;\n")].into_iter().collect(); + let read = |p: &str| files.get(p).map(|s| (*s).to_owned()); + let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s))); + let child = "crates/x/src/child.rs".to_owned(); + let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..ctx() }; + let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits_in(&child, test, &ctx), [], "the plain attribute's route runs it on Linux"); + } + #[test] fn a_module_loaded_by_two_roots_runs_if_either_runs_it() { let files: HashMap<&str, &str> = [