From 8f1edd06449ee3231095bf4e062184478251660f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 06:33:02 -0800 Subject: [PATCH 01/37] Colors: a color with a component too large to store is refused A color given as {"c": 1e300, ...}, [1e300, 0, 0], {"gray": 1e300}, a Lab color or a color object with a number past f32::MAX was stored with an infinite component. paint.setFill, artboard.setProps, swatch.new, text.create and the other commands that read colors through cmd::color_value took it. - color_value refuses a color whose components are not finite, so the commands that read a color through it answer an error and change nothing. - An effect's color (Drop Shadow, Inner Glow, Outer Glow, Shift to Color) with such a number is refused with "`color` must be a #rrggbb color". - ui.colorWheel's contrastBackground refuses it as well. Docs: docs/mcp.md. --- crates/engine/src/cmd.rs | 18 +++++++- crates/engine/src/cmd/params.rs | 12 ++--- crates/engine/src/tests/panelcmds.rs | 46 +++++++++++++++++++ crates/engine/tests/it/param_keys.rs | 14 +++++- crates/ui-egui/src/panels/color_wheel.rs | 6 ++- .../src/panels/tests_color_wheel_contrast.rs | 2 + docs/mcp.md | 10 ++-- 7 files changed, 93 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8a4e6ebe6f..cc0abc05a3 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -672,8 +672,24 @@ pub fn matrix_param(p: &Value, key: &str) -> Option { } /// A colour from `"#rrggbb"`, a colour key (`"cmyk 0 100 100 0"`, `"lab 55 60 40"`), `[r,g,b]` (0..1), /// `{"c":..,"m":..,"y":..,"k":..}` (percent when any component is above 1, else 0..1), `{"gray":..}` or `{"l":..,"a":..,"b":..}` (CIE Lab: L 0..100, a and b about -/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`). +/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`), +/// and for a color with a component too large to store ([`color_is_finite`]). pub fn color_value(v: &Value) -> Option { + given_color(v).filter(color_is_finite) +} + +/// Is every component of `c` finite? A number past `f32::MAX`, such as `{"c": 1e300}`, is stored +/// as an infinity. +pub fn color_is_finite(c: &Color) -> bool { + match *c { + Color::Rgb { r, g, b } | Color::Lab { l: r, a: g, b } => [r, g, b].iter().all(|x| x.is_finite()), + Color::Cmyk { c, m, y, k } => [c, m, y, k].iter().all(|x| x.is_finite()), + Color::Gray { k } => k.is_finite(), + } +} + +/// The color `v` gives, as [`color_value`] reads it, with its components unchecked. +fn given_color(v: &Value) -> Option { match v { Value::String(s) if hex_with_alpha(s) => None, // A hex, or a colour key ("cmyk 0 100 100 0", as Recolor Artwork lists colours). diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index dcc3eade04..9b498f1ca8 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -43,7 +43,7 @@ use std::sync::OnceLock; use serde_json::Value; use vectorcraft_apischema::shown_key; -use super::{bad, command_specs, find_command}; +use super::{bad, color_is_finite, command_specs, find_command}; use crate::Result; /// What a params description says about the keys of the params object. @@ -608,16 +608,16 @@ pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option { /// Can an effect read `v` as its `color`: a string [`Color::from_hex`] reads (`#rrggbb`, `#rgb`, /// `#rrggbbaa`, black, white, red, green, blue), `[r, g, b]` whose first three entries are numbers -/// (read on a 0..1 scale) or a color object (`{"model": "rgb", "r": …}`)? The effect draws its -/// default color for any other value, except that an array of three or more entries draws an -/// entry that isn't a number as 0. +/// (read on a 0..1 scale) or a color object (`{"model": "rgb", "r": …}`), with no component too +/// large to store ([`color_is_finite`])? The effect draws its default color for any other value, +/// except that an array of three or more entries draws an entry that isn't a number as 0. /// /// [`Color::from_hex`]: vectorcraft_color::Color::from_hex fn is_effect_color(v: &Value) -> bool { match v { Value::String(s) => vectorcraft_color::Color::from_hex(s).is_some(), - Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(Value::is_number), - Value::Object(_) => serde_json::from_value::(v.clone()).is_ok(), + Value::Array(a) => a.len() >= 3 && a.iter().take(3).all(|n| n.as_f64().is_some_and(|n| (n as f32).is_finite())), + Value::Object(_) => serde_json::from_value::(v.clone()).is_ok_and(|c| color_is_finite(&c)), _ => false, } } diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 397c9252b5..c99f58359f 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -266,6 +266,52 @@ fn a_color_with_an_alpha_part_is_refused() { s.execute("object.rasterize", &json!({"ppi": 72, "background": "#ff0000"})).unwrap(); } +/// A color param with a component too large to store (past `f32::MAX`, which would be stored as an +/// infinity) is refused and changes nothing, in every form a color is given in: CMYK, `[r, g, b]`, +/// Gray, Lab and a color object. The ends of each range still set the color. +#[test] +fn a_color_with_a_component_too_large_to_store_is_refused() { + let mut s = session(); + let id = rect(&mut s); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for bad in [ + json!({"c": f64::MAX, "m": 0, "y": 0, "k": 0}), + json!({"c": 0, "m": 0, "y": 0, "k": 1e308}), + json!([1e300, 0, 0]), + json!([0, 0, -1e300]), + json!({"gray": 1e300}), + json!({"l": 1e300, "a": 0, "b": 0}), + json!({"l": 50, "a": 0, "b": -1e300}), + json!({"model": "rgb", "r": 1e300, "g": 0, "b": 0}), + json!({"model": "cmyk", "c": 0, "m": 1e300, "y": 0, "k": 0}), + ] { + for (cmd, p) in [ + ("artboard.setProps", json!({"index": 0, "color": bad})), + ("artboard.new", json!({"color": bad})), + ("paint.setFill", json!({"ids": [id.0], "color": bad})), + ("paint.setStroke", json!({"ids": [id.0], "color": bad})), + ("swatch.new", json!({"name": "Far", "color": bad})), + ("swatch.new", json!({"colors": ["#00ff00", bad]})), + ("text.create", json!({"x": 10, "y": 10, "text": "a", "color": bad})), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + } + assert_eq!(*s.doc().unwrap().doc, *before, "a color too large to store changes nothing"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "and records no undo step"); + let fill = |s: &Session| node(s, id).appearance.fill_paint().color(); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"c": 100, "m": 0, "y": 0, "k": 0}})).unwrap(); + assert_eq!(fill(&s), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0))); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": [1, 0, 0]})).unwrap(); + assert_eq!(fill(&s).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"gray": 100}})).unwrap(); + assert_eq!(fill(&s), Some(Color::gray(1.0))); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": {"l": 100, "a": -128, "b": 127}})).unwrap(); + assert_eq!(fill(&s), Some(Color::lab(100.0, -128.0, 127.0))); +} + /// The native format writes an artboard's background color and reads it back. An artboard without /// one is written as before, with no `color` key. #[test] diff --git a/crates/engine/tests/it/param_keys.rs b/crates/engine/tests/it/param_keys.rs index fb30bf3c5c..7e80c1aedc 100644 --- a/crates/engine/tests/it/param_keys.rs +++ b/crates/engine/tests/it/param_keys.rs @@ -170,7 +170,8 @@ fn effect_params_no_longer_taken_still_replay_and_open() { } /// An effect's `color` that the effect can't read (a string `Color::from_hex` doesn't read, an -/// `[r, g, b]` without three numbers, an object that isn't a color, `null`) is refused by +/// `[r, g, b]` without three numbers, an object that isn't a color, `null`, a color with a component +/// too large to store) is refused by /// `effect.apply`, `appearance.addEffect` and `effect.setParams` themselves, not only by the check, /// and the document and its undo history stay as they were. The forms the effect reads pass. A /// document saved with an unreadable color still opens with it. @@ -186,7 +187,16 @@ fn an_effect_color_it_cannot_draw_is_refused() { }; let before = state(&s); let why = "`color` must be a #rrggbb color"; - for bad in [json!("not-a-color"), json!("#ff00"), json!([1, 0]), json!(["#ff0000", 0, 0]), json!({"gray": 50}), json!(null)] { + for bad in [ + json!("not-a-color"), + json!("#ff00"), + json!([1, 0]), + json!(["#ff0000", 0, 0]), + json!({"gray": 50}), + json!(null), + json!([1e300, 0, 0]), + json!({"model": "rgb", "r": 0, "g": 1e300, "b": 0}), + ] { for (cmd, params) in [ ("effect.setParams", json!({"index": 0, "params": {"color": bad}})), ("effect.apply", json!({"effect": "stylize.outerGlow", "params": {"color": bad}})), diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 3e706b06c1..71aab82559 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -334,9 +334,11 @@ fn deserialize_category<'de, D: serde::Deserializer<'de>>(d: D) -> Result Option { - serde_json::from_value(v.clone()).ok().or_else(|| vectorcraft_engine::cmd::color_value(v)) + let saved = serde_json::from_value(v.clone()).ok().filter(vectorcraft_engine::cmd::color_is_finite); + saved.or_else(|| vectorcraft_engine::cmd::color_value(v)) } fn deserialize_background<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs index 2f938cc8e2..0b825aedc8 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs @@ -347,6 +347,8 @@ fn ui_color_wheel_sets_the_keys_given_and_refuses_bad_values() { (json!({"contrastFor": 3}), "`contrastFor` must be one of normalText, largeText, graphics"), (json!({"contrastBackground": "nope"}), "`contrastBackground` must be a color or null"), (json!({"contrast": false, "contrastBackground": 5}), "`contrastBackground` must be a color or null"), + (json!({"contrastBackground": {"model": "rgb", "r": 1e300, "g": 0, "b": 0}}), "`contrastBackground` must be a color or null"), + (json!({"contrastBackground": {"c": 0, "m": 0, "y": 0, "k": 1e300}}), "`contrastBackground` must be a color or null"), ] { assert_eq!(app.run("ui.colorWheel", p.clone()).unwrap_err(), e, "{p}"); } diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..61fa504972 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -642,7 +642,8 @@ Paint values (`fill`, `stroke`) accept `"#rrggbb"`, `"none"`, `[r,g,b]` (0..1), or a full `paint.setFill` params object (`{"gradient": …}`, `{"swatch": "name"}`). A color read this way (a fill or stroke color, a swatch's, an artboard's or new type's color, and the other colors commands read in these forms) that is given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without -the `#`) is an error and changes nothing, as VectorCraft's own rule. The `color` of Drop Shadow, Inner Glow, Outer Glow +the `#`) is an error and changes nothing, as VectorCraft's own rule. So is a color with a component too large to store +as a 32-bit float, such as `{"c": 1e300, "m": 0, "y": 0, "k": 0}`. The `color` of Drop Shadow, Inner Glow, Outer Glow and Shift to Color is read differently and takes `#rrggbbaa`, as described below. For `draw_shape` and `draw_path`, omitted paint fields inherit the current [new-art appearance](#new-art). Both also style the new object in the same call: `dash` (lengths, or null for solid), `cap` @@ -2231,9 +2232,10 @@ in a replayed journal or action too, and nothing changes. The `color` of Drop Shadow, Inner Glow, Outer Glow and Shift to Color must be one the effect can read: a hex color (`#rrggbb`, `#rgb` or `#rrggbbaa`, with or without the `#`), `black`, `white`, `red`, `green` or `blue`, `[r, g, b]` -(three numbers, each read on a 0 to 1 scale), or a color object (`{"model": "rgb", "r": 1, "g": 0, "b": 0}`). -`effect.apply` and `effect.setParams` refuse any other value themselves (where the parameter check runs first, a number -or a boolean is refused as not a string), so the app's effect dialogs and Appearance panel, a step of +(three numbers, each read on a 0 to 1 scale), or a color object (`{"model": "rgb", "r": 1, "g": 0, "b": 0}`), with no +number too large to store as a 32-bit float (`[1e300, 0, 0]` is refused). `effect.apply` and `effect.setParams` +refuse any other value themselves (where the parameter check runs first, a number or a boolean is refused as not a +string), so the app's effect dialogs and Appearance panel, a step of `command.batch` and a replayed journal get the same error, and the document and its undo history stay as they were: ```json From 295296947eba240c08058b41fcb14b6d4dc0de8e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 08:09:58 -0800 Subject: [PATCH 02/37] MCP: the Simplify and Smooth sliders show in ui.inspect and answer ui.dialog The params text of ui.simplifyAuto and ui.smoothAuto and docs/mcp.md say Object > Path > Simplify and Smooth open the dialogs simplifySlider and smoothSlider with field `level`, kept by ui.dialog.confirm. The sliders are a strip over the canvas, not hosted dialogs, so ui.inspect listed no dialog while one was open and ui.dialog.set and ui.dialog.confirm had nothing to answer. - ui.inspect lists the open slider as {id, parent, key, fields: {level}}, first in `dialogs`, so "top" still names a hosted dialog open over it. - ui.dialog.set {field: "level", value} moves the slider to a level from 0 to 100 and previews it. A value outside that range, a value that is not a number, another field, or a set while another edit holds the interaction is refused and leaves the level as it was. - ui.dialog.confirm keeps the preview as one undo step, as Enter does, and ui.dialog.cancel puts the paths back, as Escape does. A set with `action` answers in the same request and replies {dialog, result}. --- crates/ui-egui/src/control.rs | 13 +- crates/ui-egui/src/dialogs/simplify_slider.rs | 143 +++++++++++++++++ crates/ui-egui/src/dialogs/tests_modal.rs | 146 ++++++++++++++++++ 3 files changed, 301 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c0c6bd0bc6..7495e0ed02 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -18,7 +18,8 @@ //! - `ui.find`: the controls of the window's access tree that match a name or role //! - `ui.set {brightness?, panel?, dockTab?, rulers?, outline?, …}` //! - `ui.dialog.set` / `ui.dialog.confirm` / `ui.dialog.cancel`: answered by -//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`) +//! `craft::automation::dialogs::dialog_method` for the dialog asked for (`dialog`, default `"top"`), and by +//! `dialogs::simplify_slider::dialog_method` for the Simplify and Smooth sliders //! - `ui.resize {width, height}`, `ui.focus`, `ui.screenshot {path?, focus?}` (without a path the //! PNG comes back in the reply) //! - `ui.render {path?, scale?, artboard?, data?, traceViews?}`: render an artboard headlessly @@ -152,6 +153,10 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { } let mut dialogs = app.dialogs().map_or_else(|| json!([]), |dialogs| dialogs.with(|host| craft::automation::dialogs::inspect(host))); crate::dialogs::javascript_files::show_selected(app, &mut dialogs); + // The Simplify or Smooth slider over the canvas, listed first: `"top"` names a hosted dialog open with it. + if let (Some(open), Some(strip)) = (dialogs.as_array_mut(), crate::dialogs::simplify_slider::inspected(app)) { + open.insert(0, strip); + } json!({ "scriptRunning": app.session.script_running(), "scriptReport": app.session.shown_script_report(), @@ -1437,6 +1442,12 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val if crate::prefs_dialog::is_open(app) && (p["dialog"] == "preferences" || (top && dialogs.with(|host| host.stack().is_empty()))) { return wrap(preferences_method(app, method, p)); } + // The Simplify and Smooth sliders are the app's own strip over the canvas, not hosted dialogs: they take a + // request that names them, or the top dialog while no hosted dialog is open. + let hosted_open = dialogs.with(|host| !host.stack().is_empty()); + if let Some(r) = crate::dialogs::simplify_slider::dialog_method(app, method, p, hosted_open) { + return wrap(r); + } // The dialog asked for is `dialog`, the top one when it is missing. let mut params = if p.is_object() { p.clone() } else { json!({}) }; if params.get("dialog").is_none_or(Value::is_null) { diff --git a/crates/ui-egui/src/dialogs/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs index cb58f856a7..2a4f5b0f9c 100644 --- a/crates/ui-egui/src/dialogs/simplify_slider.rs +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -13,11 +13,14 @@ // PLAN: the framework paths below (`craft_ui_widgets`, `craft_ui_contract`, `craft_behavior`) and // `LivePreview`'s module are assumed; no app file imports them yet. +use craft::automation::dialogs::MAX_DIALOG_FIELDS; +use craft::automation::protocol::Params; use craft::behavior::overlay::{Align, Side}; use craft::behavior::{CanvasView, IconId}; use craft::ui::buttons::IconButton; use craft::ui::contract::overlay::{Anchor, Dismiss, Outside, Place}; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::dialog::dialog_id; use craft::ui::layout_components::Row; use craft::ui::popover::Popover; use craft::ui::primitives::IconSpec; @@ -78,6 +81,20 @@ impl StripKind { StripKind::Smooth => SMOOTH_AUTO_LEVEL, } } + + /// The dialog key `ui.inspect` lists the strip under, which `ui.dialog.set`, `ui.dialog.confirm` and + /// `ui.dialog.cancel` take as `dialog`. + pub(crate) fn key(self) -> &'static str { + match self { + StripKind::Simplify => "simplifySlider", + StripKind::Smooth => "smoothSlider", + } + } + + /// The id `ui.inspect` lists the strip under: the one a hosted dialog with the same key has, as a decimal string. + fn id(self) -> String { + dialog_id(self.key()).value().to_string() + } } /// An open slider strip: the level the canvas previews, the selection's bounds from before any @@ -210,6 +227,132 @@ pub(crate) fn more_options(app: &mut VectorcraftApp) -> Result { Ok(json!({ "tolerance": tolerance })) } +/// The open strip as `ui.inspect` lists a dialog, `{id, parent, key, fields: {level}}`; `None` when no strip shows. +pub(crate) fn inspected(app: &VectorcraftApp) -> Option { + let strip = app.object_dialogs.strip.as_ref().filter(|strip| strip.in_source(app))?; + let kind = strip.kind; + Some(json!({ "id": kind.id(), "parent": null, "key": kind.key(), "fields": { "level": strip.level() } })) +} + +/// The level a `ui.dialog.set` on a strip of `kind` asks for: field `level`, a number from 0 to 100, as `field` and +/// `value` or as the last item of `fields`. `None` when it sets nothing. +fn requested_level(kind: StripKind, params: &Value) -> Result, String> { + let level = |field: &Value, value: &Value| { + let field = field.as_str().ok_or("`field` is not a string")?; + if field != "level" { + return Err(format!("the {} slider has no field `{field}`", kind.label())); + } + match value.as_f64() { + Some(level) if (0.0..=100.0).contains(&level) => Ok(level), + _ => Err("`level` must be a number from 0 to 100".to_string()), + } + }; + let Some(list) = params.get("fields") else { + return match params.get("field") { + Some(field) => level(field, params.get("value").unwrap_or(&Value::Null)).map(Some), + None if params.get("value").is_some() => Err("missing `field`".into()), + None => Ok(None), + }; + }; + if params.get("field").is_some() || params.get("value").is_some() { + return Err("`fields` takes the place of `field` and `value`".into()); + } + let items = list.as_array().ok_or("`fields` is not a list")?; + if items.len() > MAX_DIALOG_FIELDS { + return Err(format!("`fields` holds {} items; at most {MAX_DIALOG_FIELDS}", items.len())); + } + let mut last = None; + for item in items { + last = Some(level(item.get("field").unwrap_or(&Value::Null), item.get("value").unwrap_or(&Value::Null))?); + } + Ok(last) +} + +/// `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` (`method`) when `params.dialog` names the open strip: +/// its key or the id [`inspected`] lists, or `"top"` (or no `dialog`) while `hosted_open` is false. `None` for any +/// other dialog. +/// +/// `ui.dialog.set {field: "level", value}` moves the slider and previews the level, then answers with `action` +/// (`confirm` or `cancel`) when one is given; a set it refuses leaves the slider as it was. `ui.dialog.confirm` keeps +/// the preview as one undo step, as Enter does, and `ui.dialog.cancel` puts the paths back, as Escape does. +pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Value, hosted_open: bool) -> Option> { + let kind = app.object_dialogs.strip.as_ref().filter(|strip| strip.in_source(app))?.kind; + let ours = match params.get("dialog") { + None | Some(Value::Null) => !hosted_open, + Some(Value::String(named)) if named == "top" => !hosted_open, + Some(Value::String(named)) => named == kind.key() || *named == kind.id(), + Some(named) => named.as_u64().is_some_and(|id| id.to_string() == kind.id()), + }; + if !ours { + return None; + } + let keys: &[&str] = match method { + "ui.dialog.set" => &["dialog", "field", "value", "fields", "action"], + "ui.dialog.confirm" | "ui.dialog.cancel" => &["dialog"], + _ => return None, + }; + if let Err(e) = Params(params).only(None, keys) { + return Some(Err(e)); + } + let answer = match (method, params.get("action")) { + ("ui.dialog.confirm", _) => Some(true), + ("ui.dialog.cancel", _) => Some(false), + (_, None | Some(Value::Null)) => None, + (_, Some(action)) if action == "confirm" => Some(true), + (_, Some(action)) if action == "cancel" => Some(false), + (_, Some(_)) => return Some(Err("`action` must be confirm or cancel".into())), + }; + let level = if method == "ui.dialog.set" { + match requested_level(kind, params) { + Ok(None) if answer.is_none() => return Some(Err("missing `field`".into())), + Ok(level) => level, + Err(e) => return Some(Err(e)), + } + } else { + None + }; + let mut strip = app.object_dialogs.strip.take()?; + if let Some(level) = level { + let before = strip.level; + strip.level = level; + let params = strip.params(); + let ran = strip.preview.run(app, true, kind.label(), kind.cmd(), ¶ms); + // Nothing ran: the canvas already previews this level, or another edit holds the interaction. + let shown = || { + app.session + .active() + .and_then(|doc| doc.interaction.as_ref()?.preview.as_ref()) + .is_some_and(|(cmd, showing)| cmd == kind.cmd() && showing == ¶ms) + }; + let error = match ran { + Some(Err(e)) => Some(e), + None if !shown() => Some(tl!("Finish the active edit first.").to_owned()), + _ => None, + }; + if let Some(e) = error { + strip.level = before; + app.object_dialogs.strip = Some(strip); + return Some(Err(e)); + } + } + app.object_dialogs.strip = Some(strip); + let set = inspected(app).unwrap_or(Value::Null); + let Some(answer) = answer else { return Some(Ok(set)) }; + let strip = app.object_dialogs.strip.take()?; + let result = if answer { + let params = strip.params(); + strip.preview.commit(app, kind.cmd(), params).map(|_| Value::Null) + } else { + strip.cancel(app); + Ok(Value::Null) + }; + // A set with an `action` replies `{dialog, result}`: the slider as the set left it, and the answer's result. + Some(match (method, result) { + ("ui.dialog.set", Ok(result)) => Ok(json!({ "dialog": set, "result": result })), + (_, result) => result, + }) +} + /// Where the strip hangs: a point under the lowest corner on screen of the selection's bounds from /// before the preview, centred on them, kept on the canvas. fn anchor_rect(view: &CanvasView, bounds: Option) -> ScreenRect { diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index e9a2166fa7..f54cd71999 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -326,3 +326,149 @@ fn path_sliders_close_when_file_revert_restores_the_artwork() { assert!(app.session.in_interaction()); } } + +/// The two sliders: the dialog key `ui.inspect` lists, the menu command that opens it and its undo step's name. +const PATH_SLIDERS: [(&str, &str, &str); 2] = + [("simplifySlider", "object.path.simplify", "Simplify"), ("smoothSlider", "object.path.smooth", "Smooth")]; + +/// One control channel request, answered at once. +fn control(app: &mut VectorcraftApp, method: &str, params: serde_json::Value) -> serde_json::Value { + let ctx = app.ui_ctx.clone().unwrap(); + let (req, _) = craft::automation::ControlRequest::new(method, params); + let craft::automation::Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("{method} answered later") }; + r +} + +/// The open dialog `key` in `ui.inspect`'s `dialogs`. +fn inspected_dialog(app: &mut VectorcraftApp, key: &str) -> Option { + let r = control(app, "ui.inspect", json!({})); + r["result"]["dialogs"].as_array()?.iter().find(|d| d["key"] == key).cloned() +} + +/// Both sliders show in `ui.inspect` as the dialog their params text names, with field `level`. `ui.dialog.set` +/// moves the slider and previews the level, and `ui.dialog.confirm` keeps the result as one undo step. +#[test] +fn path_sliders_show_in_ui_inspect_and_ui_dialog_confirm_keeps_the_level() { + for (key, command, label) in PATH_SLIDERS { + let mut app = app_with_dense_path(); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + let open = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect")); + assert!(open["fields"]["level"].is_number(), "{open}"); + + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 20})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(r["result"]["fields"]["level"], 20.0, "{r}"); + let preview = app.session.doc().unwrap().interaction.as_ref().and_then(|it| it.preview.clone()).map(|p| p.1); + assert_eq!(preview, Some(json!({"level": 20.0})), "{key}"); + settle(&mut app); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(json!(20.0)), "{key}"); + + let r = control(&mut app, "ui.dialog.confirm", json!({"dialog": key})); + assert_eq!(r["ok"], true, "{r}"); + assert!(inspected_dialog(&mut app, key).is_none(), "{key}"); + assert!(!app.session.in_interaction(), "{key}"); + let history = &app.session.doc().unwrap().history; + assert_eq!(history.undo.len(), undo_len + 1, "{key}"); + assert_eq!(history.undo.last().map(|step| step.label.as_str()), Some(label), "{key}"); + } +} + +/// A repeated level succeeds, but another active edit blocks a set and leaves the slider's level unchanged. +#[test] +fn path_sliders_refuse_a_set_when_another_edit_owns_the_interaction() { + for (key, command, _) in PATH_SLIDERS { + let mut app = app_with_dense_path(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + for _ in 0..2 { + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 30})); + assert_eq!(r["ok"], true, "{key}: {r}"); + } + let level = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"))["fields"]["level"].clone(); + app.session.cancel_interaction().unwrap(); + app.begin_interaction("Other").unwrap(); + + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "field": "level", "value": 20})); + assert_eq!(r["ok"], false, "{key}: {r}"); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level.clone()), "{key}"); + settle(&mut app); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level), "{key}"); + } +} + +/// `ui.dialog.set` with `action` sets the level and answers in one request, replying `{dialog, result}` with the +/// slider as the set left it: `confirm` keeps the level as one undo step, and `cancel` puts the paths back. +#[test] +fn path_sliders_answer_a_set_with_an_action_in_one_request() { + for (key, command, label) in PATH_SLIDERS { + for action in ["confirm", "cancel"] { + let mut app = app_with_dense_path(); + let before = app.session.active().unwrap().doc.clone(); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + let r = control(&mut app, "ui.dialog.set", json!({"dialog": key, "fields": [{"field": "level", "value": 30}], "action": action})); + assert_eq!(r["ok"], true, "{key} {action}: {r}"); + assert_eq!(r["result"]["dialog"]["key"], key, "{r}"); + assert_eq!(r["result"]["dialog"]["fields"]["level"], 30.0, "{r}"); + assert!(r["result"].get("result").is_some(), "{r}"); + assert!(inspected_dialog(&mut app, key).is_none(), "{key} {action}"); + assert!(!app.session.in_interaction(), "{key} {action}"); + let history = &app.session.doc().unwrap().history; + if action == "confirm" { + assert_eq!(history.undo.len(), undo_len + 1, "{key}"); + assert_eq!(history.undo.last().map(|step| step.label.as_str()), Some(label), "{key}"); + } else { + assert_eq!(history.undo.len(), undo_len, "{key}"); + assert_eq!(app.session.active().unwrap().doc, before, "{key}"); + } + } + } +} + +/// With a hosted dialog open over a slider, `ui.inspect` lists the slider first, and `"top"` names the hosted dialog. +#[test] +fn path_sliders_list_below_a_hosted_dialog_that_top_names() { + let mut app = app_with_dense_path(); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + settle(&mut app); + app.run("ui.javascriptFilesDialog", json!({})).unwrap(); + let r = control(&mut app, "ui.inspect", json!({})); + let open = r["result"]["dialogs"].as_array().cloned().unwrap_or_default(); + assert!(open.len() >= 2 && open[0]["key"] == "simplifySlider", "{open:?}"); + let r = control(&mut app, "ui.dialog.cancel", json!({"dialog": "top"})); + assert_eq!(r["ok"], true, "{r}"); + assert!(inspected_dialog(&mut app, "simplifySlider").is_some(), "the hosted dialog closed, the slider stays"); + let r = control(&mut app, "ui.inspect", json!({})); + assert_eq!(r["result"]["dialogs"].as_array().map(Vec::len), Some(open.len() - 1), "{r}"); +} + +/// `ui.dialog.cancel` on the top dialog puts the paths back, as Escape does. A level outside 0..100, a value that +/// isn't a number and another field are refused, and the slider keeps its level. +#[test] +fn path_sliders_answer_ui_dialog_cancel_and_refuse_bad_fields() { + for (key, command, _) in PATH_SLIDERS { + let mut app = app_with_dense_path(); + let before = app.session.active().unwrap().doc.clone(); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, command, json!({})); + settle(&mut app); + let level = inspected_dialog(&mut app, key).unwrap_or_else(|| panic!("{key} in ui.inspect"))["fields"]["level"].clone(); + for bad in [json!({"field": "level", "value": 101}), json!({"field": "level", "value": "20"}), json!({"field": "tolerance", "value": 2})] { + let mut params = bad.clone(); + params["dialog"] = json!(key); + let r = control(&mut app, "ui.dialog.set", params); + assert_eq!(r["ok"], false, "{key} {bad}: {r}"); + assert_eq!(inspected_dialog(&mut app, key).map(|d| d["fields"]["level"].clone()), Some(level.clone()), "{key} {bad}"); + } + + let r = control(&mut app, "ui.dialog.cancel", json!({})); + assert_eq!(r["ok"], true, "{r}"); + assert!(inspected_dialog(&mut app, key).is_none(), "{key}"); + assert!(!app.session.in_interaction(), "{key}"); + assert_eq!(app.session.active().unwrap().doc, before, "{key}"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len, "{key}"); + } +} From b19aac26ec46020afc30997752ad3d699f9155db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 09:21:40 -0800 Subject: [PATCH 03/37] Selection Tools: Edit Points Only narrows a Direct Selection to its anchor points addon.select.editPointsOnly {segmentEnds?} turns the current selection into one that holds only anchor points, so a move or transform that follows acts on the points alone. Selected segments leave the selection, and the points at their ends leave it too unless segmentEnds is true. Paths selected whole keep every point. A group or compound path selected whole gives way to the visible, unlocked paths inside it (no Shaper Group originals, and no guide paths while guides are locked). Type, images, symbols and other objects without anchor points leave the selection. Only the selection changes, so there is no undo step. With nothing selected or nothing left to keep it is an error and the selection stays as it was. The command is on the plug-in allowed list. Object > Plug-ins > Selection Tools > Edit Points Only... opens a dialog with Keep Ends of Selected Segments; it previews the narrowed selection on the canvas, OK keeps it and Cancel puts the selection back. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/addons/select.rs | 122 ++++++++++++- crates/engine/src/cmd/addons/select/tests.rs | 160 ++++++++++++++++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/tests/command_sweep.rs | 2 + crates/ui-egui/src/addons/dialogs.rs | 1 + crates/ui-egui/src/addons/select.rs | 7 +- .../ui-egui/src/addons/select/points_only.rs | 51 ++++++ .../src/addons/select/points_only/tests.rs | 85 ++++++++++ docs/mcp.md | 21 +++ docs/target-app-parity.md | 1 + 10 files changed, 444 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/addons/select/points_only.rs create mode 100644 crates/ui-egui/src/addons/select/points_only/tests.rs diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index c9ae29a303..6c3346ca80 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -1,17 +1,19 @@ //! Selection Tools (`addon.select.*`), a built-in add-on: Select by Artboards selects the objects //! overlapping, fully inside or fully outside one or more chosen artboards (#5525), and Select by //! Link Status selects the images and placed documents whose file is linked, embedded, missing or -//! modified (#5526), saying which ones it had to leave out and why. Its submenu (Object › Plug-ins -//! › Selection Tools), the Links panel's menu items and the dialogs are the UI's. +//! modified (#5526), saying which ones it had to leave out and why. Edit Points Only narrows the +//! selection to the anchor points selected in it, dropping selected segments and objects without +//! anchor points. Its submenu (Object › Plug-ins › Selection Tools), the Links panel's menu items +//! and the dialogs are the UI's. #[cfg(test)] mod tests; -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use serde_json::{Value, json}; -use vectorcraft_doc::{LockedArtboards, Node, NodeId, NodeKind}; -use vectorcraft_geom::Point; +use vectorcraft_doc::{AnchorRef, LockedArtboards, Node, NodeId, NodeKind}; +use vectorcraft_geom::{PathData, Point}; use super::super::links::{Status, statuses}; use super::super::panelcmds::listed_artboards; @@ -47,6 +49,15 @@ pub fn specs() -> Vec { has_doc, by_link_status ), + cmd!( + "addon.select.editPointsOnly", + "Edit Points Only", + ["Object", "Plug-ins", "Selection Tools"], + None, + "{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points)} narrow the selection to the anchor points selected in it, so that a move or transform that follows acts on those points alone: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole keeps all its points; a group or compound path selected whole gives way to the paths inside it, each selected whole, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. Only the selection changes, not the document, so there is nothing to undo → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}", + has_doc, + edit_points_only + ), ] } @@ -193,3 +204,104 @@ fn by_link_status(s: &mut Session, p: &Value) -> Result { } Ok(out) } + +/// The anchor points of `path` that `refs` names, leaving out references to points it does not have. +fn on_path(path: &PathData, refs: &BTreeSet) -> BTreeSet { + refs.iter().copied().filter(|&(si, ai)| path.subpaths.get(si).is_some_and(|sp| ai < sp.anchors.len())).collect() +} + +/// The points at the ends of the segments `segments` of `path`. +fn segment_ends(path: &PathData, segments: &BTreeSet) -> BTreeSet { + let mut ends = BTreeSet::new(); + for &(si, seg) in segments { + if let Some(sp) = path.subpaths.get(si) { + ends.extend([(si, seg), (si, (seg + 1) % sp.anchors.len().max(1))]); + } + } + ends +} + +/// The paths inside container `n` with at least one anchor point, depth first, through the groups +/// and compound paths in it: hidden and locked objects (and what they hold), a Shaper Group's +/// original shapes, and paths made into guides while `guides_locked`, are left out. +fn paths_inside<'a>(n: &'a Node, guides_locked: bool, out: &mut Vec<&'a Node>) { + let originals = usize::from(n.extras().shaper.is_some()); + for c in n.children().into_iter().flatten().skip(originals) { + if !c.visible || c.locked { + continue; + } + match &c.kind { + NodeKind::Path { guide: true, .. } if guides_locked => {} + NodeKind::Path { path, .. } if path.anchors().next().is_some() => out.push(c), + NodeKind::Group { .. } | NodeKind::Compound { .. } => paths_inside(c, guides_locked, out), + _ => {} + } + } +} + +/// `addon.select.editPointsOnly`: narrow the selection to the anchor points selected in it. +fn edit_points_only(s: &mut Session, p: &Value) -> Result { + const C: &str = "addon.select.editPointsOnly"; + let keep_ends = switch_or(p, "segmentEnds", false, C)?; + let guides_locked = s.menu.guides_locked; + let st = s.doc()?; + let (doc, sel) = (&st.doc, &st.selection); + if sel.objects.is_empty() { + return Err(bad(C, "select anchor points or segments first")); + } + // Each path once, in selection order, with its points kept: `None` for all of them. + let mut seen = HashSet::new(); + let mut kept: Vec<(NodeId, usize, Option>)> = vec![]; + for id in &sel.objects { + let Some(n) = doc.node(*id) else { continue }; + match &n.kind { + NodeKind::Path { path, .. } => { + let Some(refs) = sel.anchors.get(id) else { + let count = path.anchors().count(); + if count > 0 && seen.insert(*id) { + kept.push((*id, count, None)); + } + continue; + }; + let mut picked = on_path(path, refs); + if let Some(segments) = sel.segments.get(id) + && !keep_ends + { + let ends = segment_ends(path, segments); + picked.retain(|r| !ends.contains(r)); + } + if !picked.is_empty() && seen.insert(*id) { + kept.push((*id, picked.len(), Some(picked))); + } + } + NodeKind::Group { .. } | NodeKind::Compound { .. } => { + let mut inside = vec![]; + paths_inside(n, guides_locked, &mut inside); + for c in inside { + if seen.insert(c.id) { + kept.push((c.id, c.path_data().map_or(0, |path| path.anchors().count()), None)); + } + } + } + _ => {} + } + } + let points: usize = kept.iter().map(|(_, n, _)| n).sum(); + let objects: Vec = kept.iter().map(|(id, ..)| *id).collect(); + let anchors: BTreeMap> = kept.into_iter().filter_map(|(id, _, set)| Some((id, set?))).collect(); + if objects.is_empty() { + return Err(bad(C, "no anchor points are selected")); + } + let changed = objects != sel.objects || anchors != sel.anchors || !sel.segments.is_empty() || !sel.guides.is_empty(); + let count = objects.len(); + if changed { + s.select(|_, sel| { + let (key, key_anchor) = (sel.key.filter(|k| objects.contains(k)), sel.key_anchor); + sel.set(objects); + sel.anchors = anchors; + sel.key = key; + sel.key_anchor = key_anchor; + })?; + } + Ok(json!({ "changed": changed, "count": count, "points": points })) +} diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index 09106a3652..85844c241d 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -337,3 +337,163 @@ mod by_link_status { assert!(Session::new().execute(C, &json!({"status": "linked"})).is_err()); } } + +/// Edit Points Only. +mod edit_points_only { + use std::collections::{BTreeMap, BTreeSet}; + + use serde_json::{Value, json}; + use vectorcraft_doc::NodeId; + + use super::rect; + use crate::Session; + + const C: &str = "addon.select.editPointsOnly"; + + /// A document with two rectangles, `a` and `b` (four anchors each, anchor 0 first). + fn two() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 10.0, 50.0, 50.0); + let b = rect(&mut s, 100.0, 10.0, 50.0, 50.0); + (s, a, b) + } + + /// Anchors 0 and 1 of `a`, anchor 3 of `b`, and then segment 1 of `b` (its ends are anchors 1 and 2). + fn mixed(s: &mut Session, a: NodeId, b: NodeId) { + let items = json!([{"id": a.0, "anchors": [[0, 0], [0, 1]]}, {"id": b.0, "anchors": [[0, 3]]}]); + s.execute("select.anchorsMany", &json!({"items": items})).unwrap(); + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + } + + fn refs(v: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { + v.iter().copied().collect() + } + + /// Selected objects, with the selected anchors of those selected in part. + type Picked = (Vec, BTreeMap>); + + /// The selected objects and their selected anchors. + fn picked(s: &Session) -> Picked { + let sel = &s.doc().unwrap().selection; + (sel.objects.clone(), sel.anchors.clone()) + } + + #[test] + fn selected_segments_drop_out_and_the_anchor_points_stay() { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + let before = s.doc().unwrap().selection.clone(); + assert_eq!(before.anchors[&b], refs(&[(0, 1), (0, 2), (0, 3)]), "a segment's ends move with it"); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 2, "points": 3})); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.objects, vec![a, b]); + assert_eq!(sel.anchors[&a], refs(&[(0, 0), (0, 1)])); + assert_eq!(sel.anchors[&b], refs(&[(0, 3)]), "the segment's ends leave the selection"); + assert!(sel.segments.is_empty(), "no segment stays selected"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "only the selection changes"); + } + + #[test] + fn segment_ends_stay_as_anchor_points_when_asked() { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + let r = s.execute(C, &json!({"segmentEnds": true})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 2, "points": 5})); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.anchors[&b], refs(&[(0, 1), (0, 2), (0, 3)])); + assert!(sel.segments.is_empty()); + // With the default, a path holding only a selected segment leaves the selection. + s.execute("select.segments", &json!({"id": b.0, "segments": [[0, 0]]})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 2]], "mode": "add"})).unwrap(); + let r = s.execute(C, &json!({"segmentEnds": false})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 1, "points": 1})); + assert_eq!(picked(&s), (vec![a], BTreeMap::from([(a, refs(&[(0, 2)]))]))); + } + + #[test] + fn a_selection_of_anchor_points_alone_is_left_as_it_is() { + let (mut s, a, b) = two(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]]})).unwrap(); + let before = picked(&s); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": false, "count": 1, "points": 2})); + assert_eq!(picked(&s), before); + // Paths selected whole keep all their points. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": false, "count": 2, "points": 8})); + assert_eq!(picked(&s), (vec![a, b], BTreeMap::new())); + } + + #[test] + fn groups_and_compound_paths_give_way_to_their_paths_and_other_objects_leave() { + let (mut s, a, b) = two(); + let c = rect(&mut s, 200.0, 10.0, 20.0, 20.0); + let hidden = rect(&mut s, 200.0, 100.0, 20.0, 20.0); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [b.0, c.0, hidden.0, text.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + let d = rect(&mut s, 20.0, 20.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0, d.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.doc().unwrap().selection.objects.clone(); + assert_eq!(compound.len(), 1); + let members: Vec = s.doc().unwrap().doc.node(compound[0]).unwrap().children().unwrap().iter().map(|m| m.id).collect(); + assert_eq!(members.len(), 2); + s.execute("select.set", &json!({"ids": [compound[0].0, group]})).unwrap(); + let r = s.execute(C, &json!({})).unwrap(); + assert_eq!(r, json!({"changed": true, "count": 4, "points": 16}), "{r}"); + let mut want = members; + want.extend([b, c]); + assert_eq!(picked(&s), (want, BTreeMap::new()), "the hidden path and the type are left out"); + } + + #[test] + fn guide_paths_in_a_group_are_left_out_while_guides_are_locked() { + let (mut s, a, b) = two(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [b.0, text.0]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + s.execute("select.set", &json!({"ids": [group]})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + let e = s.execute(C, &json!({})).unwrap_err().to_string(); + assert!(e.contains("no anchor points are selected"), "{e}"); + assert_eq!(s.doc().unwrap().selection, before); + s.execute("select.set", &json!({"ids": [a.0, group]})).unwrap(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 1, "points": 4})); + assert_eq!(picked(&s), (vec![a], BTreeMap::new())); + // Unlocked, the guide path is a path like any other. + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + s.execute("select.set", &json!({"ids": [group]})).unwrap(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 1, "points": 4})); + assert_eq!(picked(&s), (vec![b], BTreeMap::new())); + } + + #[test] + fn nothing_to_keep_is_an_error_that_leaves_the_selection() { + let (mut s, a, b) = two(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "Points"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute(C, &json!({})).is_err(), "nothing selected"); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + s.execute("select.add", &json!({"ids": [text.0]})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + let e = s.execute(C, &json!({})).unwrap_err().to_string(); + assert!(e.contains("no anchor points are selected"), "{e}"); + assert_eq!(s.doc().unwrap().selection, before); + for p in [json!({"segmentEnds": "yes"}), json!({"segmentEnds": 1}), json!({"segmentEnds": [true]}), json!({"segmentEnd": true})] { + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]]})).unwrap(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "add"})).unwrap(); + let before = s.doc().unwrap().selection.clone(); + assert!(s.execute(C, &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().selection, before, "{p}"); + } + assert!(Session::new().execute(C, &Value::Null).is_err(), "without a document"); + } +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index c2699f219c..6b146b91ec 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -81,6 +81,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.pen.segment", "addon.pen.togglePoint", "addon.select.byArtboards", + "addon.select.editPointsOnly", "addon.shapes.box3d", "addon.shapes.configure", "addon.shapes.ellipse", diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 462641b953..44919a7960 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -538,6 +538,8 @@ fn structured_junk() { ("addon.select.byLinkStatus", json!({"status": "embedded", "ids": {"a": 1}, "add": [1], "zoom": "yes"})), ("addon.select.byLinkStatus", json!({"status": ["modified", "embedded"], "ids": [], "add": true, "zoom": true})), ("addon.select.byLinkStatus", json!({"status": [[["linked"]]], "ids": null})), + ("addon.select.editPointsOnly", json!({"segmentEnds": "yes"})), + ("addon.select.editPointsOnly", json!({"segmentEnds": [true], "ids": [2, u64::MAX]})), ("links.relink", json!({"scope": "each", "paths": [{"ids": [2, u64::MAX, -1, "x"], "path": ""}, null, 7, {"path": [1]}]})), ("links.relink", json!({"scope": ["all"], "path": "/no/such/file.png", "ids": {"a": 1}})), ("links.relink", json!({"scope": "missingInFolder", "path": "", "folder": [], "paths": "x"})), diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index e58443e259..3273764d5f 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -108,6 +108,7 @@ pub(crate) fn open_from_menu(app: &mut VectorcraftApp, id: &str) -> Option color::legend::open, color::nearest::COMMAND => color::nearest::open, select::COMMAND => select::open, + select::points_only::COMMAND => select::points_only::open, _ => return super::arrange::open(app, id), }; Some(open(app)) diff --git a/crates/ui-egui/src/addons/select.rs b/crates/ui-egui/src/addons/select.rs index 6ae9a2ae91..22428bef53 100644 --- a/crates/ui-egui/src/addons/select.rs +++ b/crates/ui-egui/src/addons/select.rs @@ -1,8 +1,8 @@ //! Selection Tools in the interface: its submenu (Object › Plug-ins › Selection Tools) and the //! Select by Artboards dialog (#5548), which lists the artboards with their number, name and size, //! filters them by name, picks several, fits one in the window on double-click (#5549), and on OK -//! runs `addon.select.byArtboards` with the relation chosen; and Select by Link Status -//! ([`link_status`], #5526). +//! runs `addon.select.byArtboards` with the relation chosen; Select by Link Status +//! ([`link_status`], #5526); and Edit Points Only ([`points_only`]). use craft::behavior::{Selection, keyed}; use craft::i18n::Folder; @@ -27,6 +27,7 @@ use crate::VectorcraftApp; use crate::menus::{Sep, cp}; pub mod link_status; +pub mod points_only; /// Select by Artboards, and its dialog's kind. pub const COMMAND: &str = "addon.select.byArtboards"; @@ -40,6 +41,8 @@ const LIST_ROWS: u16 = 9; pub fn menu() -> Vec { let mut v = vec![cp("Select by Artboards…", COMMAND, Value::Null), Sep]; v.extend(link_status::menu()); + v.push(Sep); + v.extend(points_only::menu()); v } diff --git a/crates/ui-egui/src/addons/select/points_only.rs b/crates/ui-egui/src/addons/select/points_only.rs new file mode 100644 index 0000000000..f4b0d157d2 --- /dev/null +++ b/crates/ui-egui/src/addons/select/points_only.rs @@ -0,0 +1,51 @@ +//! Edit Points Only in the interface: its item in Object › Plug-ins › Selection Tools and its +//! dialog, which previews the narrowed selection on the canvas and runs +//! `addon.select.editPointsOnly` on OK; Cancel puts the selection back. + +use std::borrow::Cow; + +use craft::menu::Node; +use craft::ui::contract::Bind; +use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind}; +use serde_json::{Map, Value, json}; + +use crate::VectorcraftApp; +use crate::addons::dialogs::Spec; +use crate::dialogs::form; +use crate::menus::c; + +/// Edit Points Only: the dialog's key and the command its OK runs. +pub const COMMAND: &str = "addon.select.editPointsOnly"; + +static SPEC: Spec = Spec { command: COMMAND, params, found: None }; + +/// The menu item. +pub fn menu() -> Vec { + vec![c("Edit Points Only…", COMMAND)] +} + +/// The dialog's rows. +fn rows() -> Vec { + vec![Param::new("segmentEnds", tl!("Keep Ends of Selected Segments"), ParamKind::bool(false))] +} + +/// The command's params for the dialog's `fields`. +fn params(fields: &DialogFields) -> Value { + Value::Object(form::json_of(&rows(), fields)) +} + +/// Opens the dialog on the active document, with the ends of selected segments left out. +pub(crate) fn open(app: &mut VectorcraftApp) -> Result { + if app.session.active().is_none() { + return Err("no document".into()); + } + let mut opening = Map::new(); + opening.insert("segmentEnds".into(), json!(false)); + let fields = form::fields_of(&rows(), &opening); + crate::addons::dialogs::open(app, &SPEC, fields, |fields| { + ParamDialog::new(COMMAND, tl!("Edit Points Only"), Cow::Owned(rows())).previews(true).values(Bind::bound(fields)) + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/select/points_only/tests.rs b/crates/ui-egui/src/addons/select/points_only/tests.rs new file mode 100644 index 0000000000..21285a1e8e --- /dev/null +++ b/crates/ui-egui/src/addons/select/points_only/tests.rs @@ -0,0 +1,85 @@ +use std::collections::BTreeSet; + +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +use crate::VectorcraftApp; +use crate::addons::dialogs::tests as host; +use crate::tests::panel_harness::Panel as Harness; + +/// An app with a window and two rectangles: anchors 0 and 1 of the first selected, and segment 1 +/// of the second (whose ends are its anchors 1 and 2) beside its anchor 3. +fn app() -> (VectorcraftApp, NodeId, NodeId) { + let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default())); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut rect = |x| NodeId(app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + let (a, b) = (rect(10), rect(100)); + let items = json!([{"id": a.0, "anchors": [[0, 0], [0, 1]]}, {"id": b.0, "anchors": [[0, 3]]}]); + app.run("select.anchorsMany", json!({"items": items})).unwrap(); + app.run("select.segments", json!({"id": b.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + (app, a, b) +} + +fn refs(v: &[(usize, usize)]) -> BTreeSet<(usize, usize)> { + v.iter().copied().collect() +} + +/// The selected anchors of `id`, and whether any segment is selected. +fn points(app: &VectorcraftApp, id: NodeId) -> (Option>, bool) { + let sel = &app.session.doc().unwrap().selection; + (sel.anchors.get(&id).cloned(), !sel.segments.is_empty()) +} + +#[test] +fn the_dialog_previews_keeps_on_ok_and_takes_the_segment_ends_from_the_keyboard() { + let (app, a, b) = app(); + let undo = app.session.doc().unwrap().history.undo.len(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + host::open_item(&mut panel.app(), "Selection Tools", "Edit Points Only…"); + panel.frame(); + let id = host::dialog_id(&panel.app()); + assert_eq!(host::read(&panel.app(), id, |f| f.bool("segmentEnds")), Some(false)); + assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 3)])), false), "the preview drops the segment and its ends"); + assert_eq!(points(&panel.app(), a).0, Some(refs(&[(0, 0), (0, 1)]))); + panel.focus("Keep Ends of Selected Segments"); + panel.key(egui::Key::Space, egui::Modifiers::NONE); + panel.frame(); + assert_eq!(host::read(&panel.app(), id, |f| f.bool("segmentEnds")), Some(true)); + assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 1), (0, 2), (0, 3)])), false), "the ends are kept as anchor points"); + panel.click("OK"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(points(&app, b), (Some(refs(&[(0, 1), (0, 2), (0, 3)])), false)); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "a selection change is not an undo step"); +} + +#[test] +fn cancel_puts_the_selection_back() { + let (app, _, b) = app(); + let before = app.session.doc().unwrap().selection.clone(); + let mut panel = Harness::new(app, crate::tests::picks::dialogs); + host::open_item(&mut panel.app(), "Selection Tools", "Edit Points Only…"); + panel.frame(); + assert_eq!(points(&panel.app(), b), (Some(refs(&[(0, 3)])), false)); + panel.click("Cancel"); + panel.frame(); + let app = panel.app(); + assert!(!app.any_dialog_open()); + assert_eq!(app.session.doc().unwrap().selection, before); +} + +#[test] +fn ok_with_nothing_to_keep_says_why_and_leaves_the_selection() { + let (mut app, a, _) = app(); + app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + let before = app.session.doc().unwrap().selection.clone(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + assert_eq!(app.session.doc().unwrap().selection, before); + assert!(app.ui.status.contains("no anchor points are selected"), "{}", app.ui.status); +} diff --git a/docs/mcp.md b/docs/mcp.md index d698534089..1c9c20ff48 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17313,6 +17313,27 @@ locked". Select by Link Status… lists every image and placed document with its name and filters by status (Show), chooses rows with checkboxes (All / None act on the rows shown), and on Select selects the rows chosen, zooming to them when Zoom to Selection is on (the default). +`addon.select.editPointsOnly {segmentEnds?}` (Edit Points Only…) narrows the selection to the anchor points selected in +it, so that a move or transform that follows acts on those points alone. A path with selected anchor points keeps them. +A path with selected segments drops the segments and keeps its other selected anchor points; the points at the ends of +the segments leave the selection unless `segmentEnds` is `true` (default `false`), which keeps them as selected anchor +points. A path selected whole keeps all its points. A group or compound path selected whole is replaced by the paths +inside it, each selected whole, without hidden and locked ones, without a Shaper Group's original shapes and, while +guides are locked, without paths made into guides. Type, +images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. Only the +selection changes, so there is nothing to undo. It returns `{changed, count, points}`: `changed` is `false` when the +selection already held only anchor points, `count` is the number of paths left selected and `points` the number of +anchor points selected on them. Nothing selected, no anchor point left to keep ("no anchor points are selected"), or a +`segmentEnds` that is not `true` or `false` is an error, and the selection is left as it was. + +```json +{"name":"run_command","arguments":{"command":"addon.select.editPointsOnly","params":{"segmentEnds":false}}} +``` + +In the desktop app, Object › Plug-ins › Selection Tools › Edit Points Only… opens a dialog with Keep Ends of Selected +Segments (off). With Preview on, the canvas shows the narrowed selection; OK keeps it and Cancel puts the selection +back. + ### Vector Halftone (live) `addon.color.halftone` (Effect › Color Effects › Vector Halftone…, also in Object › Plug-ins › Color Effects) draws its diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 032041c2a1..ad53f0194a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1529,6 +1529,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins. Its tool is also in the Lasso tool's group in both shipped toolbars, after the Enclosing Lasso, and All Tools lists it there, under Select; a toolbar edited before it joined keeps its saved layout until Reset Toolbar (tests `polygonal_lasso_is_in_the_lasso_flyout`, `a_saved_toolbar_without_polygonal_lasso_keeps_its_layout` and `a_torn_off_lasso_group_shows_polygonal_lasso` in `edit_toolbar::tests`, `polygonal_lasso_is_in_the_lasso_group_once` in `addons::tests`, `headless_lists_the_lasso_group` in `vectorcraft-mcp`). It has no default shortcut. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. + Edit Points Only (Object › Plug-ins › Selection Tools, a VectorCraft addition) narrows a Direct Selection to its selected anchor points (`addon.select.editPointsOnly {segmentEnds?}`): selected segments leave the selection, and the points at their ends leave it too unless Keep Ends of Selected Segments is on; paths selected whole keep every point; a group or compound path selected whole gives way to the visible, unlocked paths inside it; type, images, symbols and other objects without anchor points leave the selection. Only the selection changes, so there is no undo step; with nothing left to keep it is an error and the selection stays as it was. The dialog previews the narrowed selection, and Cancel puts the selection back. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`edit_points_only`), `crates/ui-egui/src/addons/select/points_only/tests.rs`, `crates/engine/tests/command_sweep.rs`. The Links panel provides an item right-click context menu on link rows offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Separator, and Embed Image / Unembed…. Right-clicking an unselected row selects that row first; right-clicking a row that is already part of a multi-selection preserves the multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. The Location row of the Links panel's Link Info has a folder button, Show in Folder, that opens the folder of the file Link Info shows in the system's file manager (`links.reveal {id}` with that image's id); the help page describes a folder icon on this row ([Links information](https://helpx.adobe.com/illustrator/using/links-info.html)). The button's name and its off state while the file is missing or no file manager is available (the web build) are VectorCraft's own. Tests: `panels::tests_links::link_infos_location_row_shows_the_file_in_its_folder`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). From 8cd15651fbee9394615927fca81296c805f3485c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 12:33:55 -0800 Subject: [PATCH 04/37] Canvas: a touchpad pinch zooms on native Wayland Fixes #5981. The winit patch rev moves from a517b384 to 0dfcec0e (storytold/winit craft/0.30.13, with storytold/winit#20), whose Wayland backend binds zwp_pointer_gestures_v1 and reports a touchpad pinch and rotation as PinchGesture and RotationGesture. egui-winit turns them into Event::Zoom and Event::Rotate, which the canvas already reads, so a pinch zooms about the pointer and a two-finger turn rotates the view. Before, winit's Wayland backend never bound the protocol, so the gesture never reached the app. X11 and XWayland still report no pinch. The same winit range types an Alt + keypad code's character itself on Windows (W36: the WM_CHAR after Alt's release becomes a key press with that text). windows_alt_codes typed it too, which would type it twice, so it now only takes the keypad digits typed with Alt out of the frame. Docs: docs/hardware-parity.md (Trackpad row, Linux), docs/type-parity.md (Alt + numeric-keypad codes row). --- Cargo.lock | 2 +- Cargo.toml | 2 +- apps/vectorcraft/src/app.rs | 2 +- apps/vectorcraft/src/main.rs | 4 +- apps/vectorcraft/src/windows_alt_codes.rs | 175 ++++++++-------------- docs/hardware-parity.md | 2 +- docs/type-parity.md | 2 +- 7 files changed, 69 insertions(+), 120 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d7b77b1065..dbfa5d703c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10067,7 +10067,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45" dependencies = [ "ahash", "android-activity", diff --git a/Cargo.toml b/Cargo.toml index 41bca3bd33..5bd5b732b5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -217,4 +217,4 @@ egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index b91282e7da..d998e23a0d 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -44,7 +44,7 @@ impl eframe::App for App { if let Some(window_frame) = self.window_frame.as_mut() { window_frame(); } - // The characters Alt + keypad codes typed (#5108). + // The keypad digits of Alt + keypad codes leave the frame (#5108). #[cfg(windows)] super::windows_alt_codes::raw_input_hook(raw); // Symbol-font characters a keyboard tool typed (NHM Writer legacy Tamil). diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 5a7d3e33ba..007a9a3bdb 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -695,14 +695,14 @@ fn main() -> std::process::ExitCode { // With Windows Ink, winit reports a pen as a touch and drops its barrel button and which end // is down; the message hook notes each pointer contact and whether it starts with the barrel // button held, and writes the pen's end into the pen feed (`windows_stylus`). It also notes the - // characters Alt + keypad codes type (`windows_alt_codes`). + // keypad digits of Alt + keypad codes (`windows_alt_codes`). #[cfg(windows)] let options = { use winit::platform::windows::EventLoopBuilderExtWindows as _; let mut options = options; options.event_loop_builder = Some(Box::new(|builder| { builder.with_msg_hook(|msg| { - // Alt + keypad codes (#5108), which winit drops; neither hook consumes a message. + // Alt + keypad codes (#5108); neither hook consumes a message. windows_alt_codes::msg_hook(msg); windows_stylus::msg_hook(msg) }); diff --git a/apps/vectorcraft/src/windows_alt_codes.rs b/apps/vectorcraft/src/windows_alt_codes.rs index 0abf65ddc9..c358a65653 100644 --- a/apps/vectorcraft/src/windows_alt_codes.rs +++ b/apps/vectorcraft/src/windows_alt_codes.rs @@ -4,14 +4,12 @@ //! Windows does the work: when Alt comes up after keypad digits, `TranslateMessage` posts a //! `WM_CHAR` holding the character the code stands for (in the system's ANSI code page for a code //! with a leading 0, else its OEM code page), the convention every Windows text field follows -//! (). winit -//! 0.30 reads a `WM_CHAR` only as part of the key press before it, so it drops this one, which -//! follows a key release, and egui never sees the text. winit's message hook ([`msg_hook`]) sees -//! the message before winit handles it: [`AltCodes`] notes keypad digits typed with Alt held, takes -//! the character that follows Alt's release, and [`raw_input_hook`] hands it to the frame as typed -//! text, so the Type tool (or a panel's text field) types it like any other character, in the -//! same undo step as the typing round it. The keypad digits themselves are taken out of the frame, -//! so they don't run a shortcut bound to Alt and a digit. +//! (). winit reports +//! that character as a key press of its own with the character as its text (storytold/winit W36), +//! so egui types it like any other character. Each keypad digit typed with Alt held also arrives +//! as Alt and a digit, which would run a shortcut bound to Alt and that digit: winit's message +//! hook ([`msg_hook`]) sees each message before winit handles it, [`AltCodes`] notes the keypad +//! digits typed with Alt held, and [`raw_input_hook`] takes them out of the frame. //! //! With NumLock off the keypad keys arrive as Insert, End, Down, Page Down, Left, Clear, Right, //! Home, Up and Page Up, and Windows still composes the code from them. They are told from the @@ -29,11 +27,11 @@ use std::cell::RefCell; use egui::{Event, Key}; +#[cfg(windows)] const WM_KEYDOWN: u32 = 0x0100; -const WM_KEYUP: u32 = 0x0101; -const WM_CHAR: u32 = 0x0102; const WM_SYSKEYDOWN: u32 = 0x0104; const WM_SYSKEYUP: u32 = 0x0105; +#[cfg(windows)] const WM_SYSCHAR: u32 = 0x0106; /// `VK_NUMPAD0` to `VK_NUMPAD9` (`winuser.h`): keypad digits with NumLock on. const VK_NUMPAD0: usize = 0x60; @@ -49,25 +47,15 @@ const DIGIT_KEYS: [Key; 10] = [Key::Num0, Key::Num1, Key::Num2, Key::Num3, Key:: /// Bit 24 of a key message's `lParam`: an extended key, such as the navigation keys beside the /// keypad (the keypad's own keys clear it). const EXTENDED_KEY: isize = 1 << 24; -/// `VK_MENU`, `VK_LMENU` and `VK_RMENU`: Alt. -const ALT_KEYS: [usize; 3] = [0x12, 0xA4, 0xA5]; thread_local! { /// The UI thread's sequence: [`msg_hook`] and [`raw_input_hook`] both run on it. static CODES: RefCell = RefCell::new(AltCodes::default()); } -/// Where an Alt + keypad code stands, from the keyboard messages of the thread's queue. +/// The keypad digits typed with Alt held, from the keyboard messages of the thread's queue. #[derive(Default)] struct AltCodes { - /// Keypad digits typed while Alt has been held. - digits: usize, - /// Alt came up after keypad digits: the next character message is the code's character. - armed: bool, - /// A high surrogate waiting for its low half. - high: Option, - /// Characters the codes typed, for the next frame. - typed: String, /// The digits of the keypad presses and releases with Alt held since the last frame, which /// egui reports as Alt and a digit (or, with NumLock off, Alt and a navigation key): taken /// out of the frame. @@ -88,80 +76,45 @@ fn keypad_digit(wparam: usize, lparam: isize) -> Option { impl AltCodes { /// Note a keyboard message `message` with `wparam` (the virtual-key code, or a UTF-16 unit) - /// and `lparam` (its flags). + /// and `lparam` (its flags). Windows sends a key pressed or released with Alt held as a system + /// key. fn message(&mut self, message: u32, wparam: usize, lparam: isize) { - let keypad = match message { - WM_SYSKEYDOWN | WM_SYSKEYUP => keypad_digit(wparam, lparam), - _ => None, - }; - if let Some(d) = keypad { - // Windows sends a key pressed with Alt held as a system key. - if message == WM_SYSKEYDOWN { - self.digits += 1; - self.armed = false; - } + if matches!(message, WM_SYSKEYDOWN | WM_SYSKEYUP) + && let Some(d) = keypad_digit(wparam, lparam) + { self.keypad_events.push(d); - return; - } - match message { - WM_KEYDOWN | WM_SYSKEYDOWN if ALT_KEYS.contains(&wparam) => {} - // Any other key ends the sequence and keeps its own meaning. - WM_KEYDOWN | WM_SYSKEYDOWN => self.reset(), - WM_KEYUP | WM_SYSKEYUP if ALT_KEYS.contains(&wparam) => { - self.armed = self.digits > 0; - self.digits = 0; - } - WM_CHAR | WM_SYSCHAR if self.armed => { - let unit = (wparam & 0xffff) as u16; - if (0xd800..0xdc00).contains(&unit) { - self.high = Some(unit); - return; - } - let units: Vec = self.high.take().into_iter().chain([unit]).collect(); - self.typed.extend(char::decode_utf16(units).filter_map(Result::ok).filter(|c| !c.is_control())); - self.armed = false; - } - _ => {} } } - fn reset(&mut self) { - self.digits = 0; - self.armed = false; - self.high = None; - } - - /// Hand the frame `events` the characters typed since the last frame, as typed text, and take - /// out the keypad digits typed with Alt held. + /// Take out of the frame `events` the keypad digits typed with Alt held since the last frame. + /// The character a code types comes from winit, as typed text. fn drain(&mut self, events: &mut Vec) { let mut keypad = std::mem::take(&mut self.keypad_events); - if !keypad.is_empty() { - events.retain(|e| { - let Event::Key { key, modifiers, .. } = e else { - return true; - }; - if !modifiers.alt { - return true; - } - // The first keypad key still to take out that egui reports as `key`. - let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key); - match keypad.iter().position(stands_for) { - Some(i) => { - keypad.remove(i); - false - } - None => true, - } - }); - } - if !self.typed.is_empty() { - events.push(Event::Text(std::mem::take(&mut self.typed))); + if keypad.is_empty() { + return; } + events.retain(|e| { + let Event::Key { key, modifiers, .. } = e else { + return true; + }; + if !modifiers.alt { + return true; + } + // The first keypad key still to take out that egui reports as `key`. + let stands_for = |d: &usize| DIGIT_KEYS.get(*d) == Some(key) || NUMLOCK_OFF_EGUI_KEYS.get(*d) == Some(key); + match keypad.iter().position(stands_for) { + Some(i) => { + keypad.remove(i); + false + } + None => true, + } + }); } } -/// winit's message hook for the keyboard: notes Alt + keypad codes and the characters they type, -/// and hands each message to `windows_symbol_chars`. It never consumes the message. +/// winit's message hook for the keyboard: notes the keypad digits typed with Alt held, and hands +/// each message to `windows_symbol_chars`. It never consumes the message. #[cfg(windows)] #[allow(unsafe_code)] pub fn msg_hook(msg: *const std::ffi::c_void) { @@ -182,7 +135,7 @@ pub fn msg_hook(msg: *const std::ffi::c_void) { } } -/// Before egui reads the main window's frame: the characters Alt + keypad codes typed, as text. +/// Before egui reads the main window's frame: the keypad digits typed with Alt held are taken out. pub fn raw_input_hook(raw: &mut egui::RawInput) { CODES.with(|c| { if let Ok(mut c) = c.try_borrow_mut() { @@ -196,6 +149,9 @@ mod tests { use super::*; const ALT: usize = 0x12; + const WM_KEYDOWN: u32 = 0x0100; + const WM_KEYUP: u32 = 0x0101; + const WM_CHAR: u32 = 0x0102; /// Alt held, keypad digits `code`, Alt released, and the character Windows then posts. fn alt_code(c: &mut AltCodes, code: &str, posted: u16) { @@ -215,59 +171,53 @@ mod tests { } #[test] - fn an_alt_code_types_its_character_when_alt_comes_up() { + fn an_alt_codes_keypad_digits_leave_the_frame_and_its_character_is_typed_once() { let mut c = AltCodes::default(); alt_code(&mut c, "0176", 0xB0); alt_code(&mut c, "0151", 0x2014); - let mut events = vec![key(Key::Num0, true, true), key(Key::Num0, true, false), key(Key::Num1, false, true)]; + // winit reports each code's character as typed text. + let mut events = vec![ + key(Key::Num0, true, true), + key(Key::Num0, true, false), + key(Key::Num1, false, true), + Event::Text("°".into()), + Event::Text("—".into()), + ]; c.drain(&mut events); // The keypad digits typed with Alt are gone (eight presses and eight releases, two here); - // the digit typed without Alt stays, and the characters follow. - assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°—".into())]); + // the digit typed without Alt stays, and each character stays once. + assert_eq!(events, vec![key(Key::Num1, false, true), Event::Text("°".into()), Event::Text("—".into())]); let mut events = vec![key(Key::Num0, true, true)]; c.drain(&mut events); assert_eq!(events.len(), 1, "counts don't carry over to a later frame"); } #[test] - fn a_character_without_a_code_before_it_is_left_to_winit() { + fn characters_are_left_to_winit() { let mut c = AltCodes::default(); - // A plain key press's character (winit types it), and Alt pressed and released alone. + // A plain key press's character, Alt pressed and released alone, and a code's character. c.message(WM_KEYDOWN, 0x41, 0); c.message(WM_CHAR, usize::from(b'a'), 0); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_KEYUP, ALT, 0); c.message(WM_CHAR, usize::from(b'b'), 0); + alt_code(&mut c, "0176", 0xB0); let mut events = vec![]; c.drain(&mut events); assert!(events.is_empty(), "{events:?}"); } #[test] - fn another_key_while_alt_is_held_cancels_the_code() { + fn alt_with_another_key_keeps_its_shortcut() { let mut c = AltCodes::default(); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0); // Alt+F: a shortcut, not a code. c.message(WM_SYSKEYDOWN, 0x46, 0); c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0x41, 0); - let mut events = vec![]; + let mut events = vec![key(Key::Num1, true, true), key(Key::F, true, true)]; c.drain(&mut events); - assert!(!events.iter().any(|e| matches!(e, Event::Text(_))), "{events:?}"); - } - - #[test] - fn a_code_above_the_basic_plane_arrives_as_two_halves() { - let mut c = AltCodes::default(); - c.message(WM_SYSKEYDOWN, ALT, 0); - c.message(WM_SYSKEYDOWN, VK_NUMPAD0 + 1, 0); - c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0xD83D, 0); - c.message(WM_CHAR, 0xDE00, 0); - let mut events = vec![]; - c.drain(&mut events); - assert_eq!(events, vec![Event::Text("😀".into())]); + assert_eq!(events, vec![key(Key::F, true, true)]); } /// Alt held, keypad digits `code` with NumLock off (keypad Insert, End, …, flags without the @@ -284,7 +234,7 @@ mod tests { } #[test] - fn with_numlock_off_the_keypad_keys_type_the_code_and_leave_the_caret_alone() { + fn with_numlock_off_the_keypad_keys_leave_the_caret_alone() { let mut c = AltCodes::default(); alt_code_numlock_off(&mut c, "0176", 0xB0); // What egui reports for keypad 0, 1, 7 and 6 with NumLock off and Alt held, a press and a @@ -296,7 +246,7 @@ mod tests { } events.push(key(Key::Home, false, true)); c.drain(&mut events); - assert_eq!(events, vec![key(Key::Home, false, true), Event::Text("°".into())]); + assert_eq!(events, vec![key(Key::Home, false, true)]); } #[test] @@ -309,11 +259,11 @@ mod tests { let mut events = vec![key(Key::Num5, true, true), key(Key::ArrowDown, true, true), key(Key::PageDown, true, true), key(Key::ArrowLeft, true, true)]; c.drain(&mut events); - assert_eq!(events, vec![Event::Text("—ê".into())]); + assert!(events.is_empty(), "{events:?}"); } #[test] - fn the_separate_navigation_keys_still_move_the_caret_and_cancel_the_code() { + fn the_separate_navigation_keys_still_move_the_caret() { let mut c = AltCodes::default(); c.message(WM_SYSKEYDOWN, ALT, 0); c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[1], 0); @@ -322,7 +272,6 @@ mod tests { c.message(WM_SYSKEYDOWN, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_SYSKEYUP, NUMLOCK_OFF_KEYS[7], EXTENDED_KEY); c.message(WM_KEYUP, ALT, 0); - c.message(WM_CHAR, 0x41, 0); let mut events = vec![key(Key::End, true, true), key(Key::End, true, false), key(Key::Home, true, true), key(Key::Home, true, false)]; c.drain(&mut events); assert_eq!(events, vec![key(Key::Home, true, true), key(Key::Home, true, false)]); diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 0c3a73b8cc..f36a536288 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -25,7 +25,7 @@ It reads the pen's tilt and barrel rotation on macOS and on Linux under X11 and | Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none, and Bristle brushes do not use them (an Art brush's Width and a Pattern brush's Scale follow them); 3–6 h (#372) | | Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | with Windows Ink, an inverted pen or its eraser button (`PEN_FLAG_INVERTED`, `PEN_FLAG_ERASER` in the pen's pointer messages) selects the Eraser tool and the tip brings back the tool used before, as on Linux (not yet tried with a pen) | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | a press of the eraser end (Pointer Events eraser button, `button` 5) selects the Eraser tool, and that press erases; a press of the tip brings back the tool used before; Pointer Events report no end while the pen hovers | partial | | Touch gestures (pinch zoom, two-finger pan, rotate view, Touch workspace) | yes (Windows touch, Surface) | trackpad pinch, scroll and rotate | pinch, pan (a second finger cancels the first finger's tool press, #4198); two-finger tap undo, three-finger redo (#585); in the Touch workspace a two-finger tap switches between the Selection tool and the last drawing tool | same where winit reports touch | eframe until the first pen contact, then Pointer Events (pen and fingers told apart); long press opens the context menu | partial: touch workspace and touch-screen rotation missing, 3–5 h | -| Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | yes | yes | done | +| Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | smooth scroll; pinch and rotate on native Wayland where the compositor offers pointer gestures (#5981), not under X11 or XWayland | yes | done | | HiDPI / Retina, per-monitor scale | yes | yes | yes | yes | yes | done; a window dragged between monitors of different scale can still grow on Windows (#1459, open); the custom title bar's window on Windows stays truly borderless so the pointer lines up with what is drawn (#1791, #1758; awaiting the reporter's confirmation) ; macOS cursors use aligned 1×/2× native image representations (#2292), covered by headless construction tests; mixed-display transitions and physical cursor sizing remain unverified, no additional hardware validated | | Multiple monitors: panels and document windows on another screen | yes | no (one OS window) | no | no | — | missing: 6–10 h (with multiple windows, gap G7) | | Display colour profile (proof and display through the monitor's ICC) | yes | yes: the window is tagged sRGB and macOS converts it | yes: the display's default ICC profile, Windows' own conversion with Advanced Color on | X11: colord or `_ICC_PROFILE`; Wayland: sRGB | — | done on macOS, Windows and X11; Wayland and floating document windows remain | diff --git a/docs/type-parity.md b/docs/type-parity.md index 1587d7f8f1..19d84fdaed 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -57,7 +57,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters`: marks spaces, tabs, nonbreaking and narrow nonbreaking spaces, the spaces of a set width, discretionary hyphens, forced line breaks, paragraph ends and the story's end, in horizontal, vertical and right-to-left type and on a path, and none on type in a hidden group or layer; the mark shapes are VectorCraft's own. Evidence: `canvas::tests::hidden_characters_*` | | Spell check (Check Spelling, Auto Spell Check, custom dictionary) | done | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The modal Check Spelling dialog is done: Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in sentence context ("Not in Dictionary"), a list of suggestions with double-click or selection to replace ("Change to" field), and action buttons: Ignore, Ignore All, Change (one-step Undo/Redo via `text.editRange`), Change All (batched across occurrences in a single undo step), Add to Dictionary (`text.spelling.addWord`), Done and Cancel, with keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close). Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog), `crates/ui-egui/src/dialogs/check_spelling.rs` (the Check Spelling dialog). | | Smart Punctuation, Change Case, Find & Replace | done | Type › Smart Punctuation… opens a dialog with the ff, fi, ffi and ff, fl, ffl ligatures, Smart Quotes, Smart Spaces, En, Em Dashes, Ellipses and Expert Fractions, Replace In and Report Results, which lists the count of each replacement; ligatures and fractions are written only where the font has a glyph for them. Evidence: `tests::menucmds::smart_punctuation_ligatures_spaces_and_fractions_are_counted`, `smart_punctuation_skips_ligatures_and_fractions_the_font_lacks`, `smart_spaces_keeps_one_space_after_a_period`, `dialogs::smart_punctuation::tests::menu_item_opens_the_dialog_and_ok_reports_the_counts` | -| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | +| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step (winit reports it as typed text), and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; in a floating panel window the keypad digits typed with Alt are not taken out of the frame | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | | Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match, a part still matching exactly when some of its contours run the other way round (an o's counter alone in an even-odd compound). A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Both also compare the installed fonts not loaded yet, reading their files within VectorCraft's own limits (256 MiB per file, 2 GiB and 500,000 glyphs per search) and loading only the fonts that match; `type.retype` matches them with its tolerance and splits compound paths for them as it does for loaded fonts; in the app the search runs in the background with Cancel (`retype.cancelSearch`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | From 8f3709ce6ec4dc00100b799074fdd5db39585ca1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 13:36:49 -0800 Subject: [PATCH 05/37] Menus: a new window keymap sets the panel rows' shortcuts without a rebuild The window builds its first keymap after the first frame's menus, and the menu model's key held the keymap's address, so the next refresh built the whole model again with nothing else changed. Only the Window menu's panel rows and the Settings rows read their shortcuts from the keymap (Build::decorate). refresh now compares a key without the keymap (rows_key) and keeps the keymap's address on its own. When only the keymap changed, it sets the shortcuts of those rows again and lays the bar out again, leaving the rows' states and the catalog as they were. state_key, which the native menu sync, Help search and the Properties panel read, still holds the keymap. The rows key also holds the user's shortcut set, which the catalog's rows are made from. --- crates/ui-egui/src/menus/model.rs | 136 +++++++++++++++++++++++++++--- 1 file changed, 122 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index fffff70049..6913942fd8 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -40,9 +40,15 @@ pub(crate) struct Menus { /// The pass number of the last frame with a pointer button or a key press ([`pressed_pass`]), `None` before the /// first: the `input` of [`state_key`]. pressed: Option, + /// The address of the window's keymap that the panel rows took their shortcuts from ([`keymap_addr`]), `None` + /// before the window has one. + keymap: Option, /// How many times [`refresh`] built the model. #[cfg(test)] pub(crate) rebuilds: u64, + /// How many times [`refresh`] set the keymap's shortcuts again without building the model ([`refresh_shortcuts`]). + #[cfg(test)] + pub(crate) shortcut_refreshes: u64, /// The menus as built, before a layout. pub(crate) bar: MenuBar, /// `bar` laid out for the shell's target: what the in-window bar shows. @@ -90,14 +96,22 @@ pub(crate) fn translate_label(english: &'static str) -> String { /// doesn't list (panels shown, a tool picked). While an /// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's /// preview, or a typing session), the revision, which each of its previews changes, is left out: -/// the hash changes as the interaction begins and as it ends. +/// the hash changes as the interaction begins and as it ends. The window's keymap, which the shown +/// shortcuts are read from, is in the hash too. pub(crate) fn state_key(app: &VectorcraftApp, input: Option) -> u64 { + let mut h = DefaultHasher::new(); + (rows_key(app, input), keymap_addr(app)).hash(&mut h); + h.finish() +} + +/// [`state_key`] without the window's keymap: what the model's rows are built from. A new keymap alone changes only +/// the shortcuts of the rows that read it, which [`refresh`] sets again without a rebuild ([`refresh_shortcuts`]). +fn rows_key(app: &VectorcraftApp, input: Option) -> u64 { let mut h = DefaultHasher::new(); input.hash(&mut h); app.run_count.hash(&mut h); - // The window's keymap, which the panel rows read their shortcuts from (`Build::decorate`): the framework builds it - // after the first frame's menus, and builds a new one when the bindings or the catalog change. - app.ui_ctx.as_ref().and_then(craft::ui::runtime::commands::keymap).map(|k| std::sync::Arc::as_ptr(&k).addr()).hash(&mut h); + // The user's shortcuts, which the catalog's rows are made from. + std::sync::Arc::as_ptr(&app.shortcut_overrides).addr().hash(&mut h); let s = &app.session; (s.journal.len(), s.active_index(), s.clipboard.is_empty(), s.tool_composing()).hash(&mut h); if let Some(d) = s.active() { @@ -126,12 +140,19 @@ pub(crate) fn state_key(app: &VectorcraftApp, input: Option) -> u64 { } /// Brings the menus up to date once per frame, before the frame's input: the model is built again -/// when the rows' state ([`state_key`]) or the shell's target changed. +/// when the rows' state ([`rows_key`]) or the shell's target changed. When only the window's keymap +/// changed (the framework builds the first one after the first frame's menus), the rows that read +/// their shortcuts from it get them again ([`refresh_shortcuts`]). pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) { let target = Target::of_shell(&WindowHost::of(ctx).shell()); let press = last_press(app, ctx); - let key = state_key(app, press); + let key = rows_key(app, press); + let keymap = keymap_addr(app); if app.menus.key == Some(key) && app.menus.target == Some(target) { + if app.menus.keymap != keymap { + refresh_shortcuts(app, target); + app.menus.keymap = keymap; + } return; } rebuild(app, target); @@ -141,6 +162,54 @@ pub(crate) fn refresh(app: &mut VectorcraftApp, ctx: &egui::Context) { } app.menus.key = Some(key); app.menus.target = Some(target); + app.menus.keymap = keymap; +} + +/// The address of the window's keymap, which the panel rows read their shortcuts from ([`reads_keymap`]): the framework +/// builds it after the first frame's menus, and builds a new one when the bindings or the catalog change. +fn keymap_addr(app: &VectorcraftApp) -> Option { + app.ui_ctx.as_ref().and_then(craft::ui::runtime::commands::keymap).map(|k| std::sync::Arc::as_ptr(&k).addr()) +} + +/// Whether the row running `id` with `params` shows a shortcut read from the window's keymap ([`Build::decorate`]). +fn reads_keymap(id: &str, params: &Value) -> bool { + matches!(id, "window.panel" | "edit.preferences") && !params.is_null() +} + +/// Sets the shortcuts of the rows that read the window's keymap ([`reads_keymap`]) again and lays the bar out again. +/// The rows' states and the catalog stay as the last rebuild made them. +fn refresh_shortcuts(app: &mut VectorcraftApp, target: Target) { + fn walk(app: &VectorcraftApp, nodes: &mut [Node]) { + for node in nodes { + match node { + Node::Item(item) if reads_keymap(&item.command.id, &item.command.params) => { + let shortcut = super::labels::item_shortcut(app, &item.command.id, &item.command.params); + item.shortcut = shortcut; + } + Node::Submenu { children, .. } => walk(app, children), + _ => {} + } + } + } + let mut bar = std::mem::take(&mut app.menus.bar); + for menu in &mut bar.menus { + walk(app, &mut menu.children); + } + app.menus.bar = bar; + lay_out(app, target); + #[cfg(test)] + { + app.menus.shortcut_refreshes += 1; + } +} + +/// Lays `app.menus.bar` out for `target` into `app.menus.laid`, which is edited only when the laid-out bar differs. +fn lay_out(app: &mut VectorcraftApp, target: Target) { + let options = LayoutOptions::new(APP_NAME).label(&translate_label); + let laid = layout(&app.menus.bar, target, &options).bar; + if *app.menus.laid != laid { + app.menus.laid.edit(|l| *l = laid); + } } /// The pass number of the last frame with a pointer button pressed or released or a key pressed, the frame `ctx` read @@ -294,14 +363,9 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) { row_states(app, &rows, &mut states); crate::panels::panel_menu_states(app, &mut states); - let bar = MenuBar::new(menus); - let options = LayoutOptions::new(APP_NAME).label(&translate_label); - let laid = layout(&bar, target, &options).bar; app.menus.rows = Some(rows); - app.menus.bar = bar; - if *app.menus.laid != laid { - app.menus.laid.edit(|l| *l = laid); - } + app.menus.bar = MenuBar::new(menus); + lay_out(app, target); app.menus.states.edit(|s| *s = states); } @@ -597,7 +661,7 @@ impl Build<'_> { // A panel row shows the chord of the panel's shortcut (`panel:`), which binds `window.panel {panel}`; // a Window row runs it with `toggle: true`, so the framework finds no chord for the row's own command. // Settings' first page shows Preferences' shortcut, which binds `edit.preferences` with no page. - "window.panel" | "edit.preferences" if !params.is_null() => { + _ if reads_keymap(id, params) => { let mut item = item; item.shortcut = super::labels::item_shortcut(self.app, id, params); item @@ -658,6 +722,50 @@ mod tests { assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled)); } + /// A new window keymap with nothing else changed (the framework builds the first one after the first frame's + /// menus) sets the panel rows' shortcuts from it, in the bar and in the laid-out bar, without building the menus + /// again. + #[test] + fn a_new_keymap_alone_sets_the_shortcuts_without_a_rebuild() { + fn clear(nodes: &mut [Node]) { + for node in nodes { + match node { + Node::Item(item) if reads_keymap(&item.command.id, &item.command.params) => item.shortcut = None, + Node::Submenu { children, .. } => clear(children), + _ => {} + } + } + } + fn panel_chords(bar: &MenuBar) -> usize { + bar.items() + .into_iter() + .filter(|it| it.command.id == "window.panel" && it.command.params["toggle"] == true && it.shortcut.is_some()) + .count() + } + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + for _ in 0..2 { + crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default()); + } + let shown = panel_chords(&app.menus.bar); + assert!(shown > 0, "the panel rows show their shortcuts' chords"); + // The menus as a refresh before the window's keymap leaves them. + app.menus.keymap = None; + for menu in &mut app.menus.bar.menus { + clear(&mut menu.children); + } + app.menus.laid.edit(|laid| laid.menus.iter_mut().for_each(|menu| clear(&mut menu.children))); + let (rebuilds, refreshes) = (app.menus.rebuilds, app.menus.shortcut_refreshes); + refresh(&mut app, &ctx); + assert_eq!(app.menus.rebuilds, rebuilds, "a new keymap alone does not build the menus again"); + assert_eq!(app.menus.shortcut_refreshes, refreshes + 1, "the new keymap sets the shortcuts"); + assert_eq!(panel_chords(&app.menus.bar), shown, "the panel rows show their chords again"); + assert_eq!(panel_chords(&app.menus.laid), shown, "the laid-out bar shows them too"); + refresh(&mut app, &ctx); + assert_eq!((app.menus.rebuilds, app.menus.shortcut_refreshes), (rebuilds, refreshes + 1), "the same keymap sets nothing again"); + } + /// A rebuild asks each dimmed row's command once whether it can run, for its state and its reason together. #[test] fn a_rebuild_checks_each_dimmed_row_once() { From 7574374bc038b280468681ed88177f3ec9a3a0ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:45:51 -0800 Subject: [PATCH 06/37] Docs: Edit Points Only names the paths a group leaves out A group or compound path selected whole gives way to its visible, unlocked paths, without a Shaper Group's original shapes and, while guides are locked, without paths made into guides. --- 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 ad53f0194a..88004065be 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1529,7 +1529,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins. Its tool is also in the Lasso tool's group in both shipped toolbars, after the Enclosing Lasso, and All Tools lists it there, under Select; a toolbar edited before it joined keeps its saved layout until Reset Toolbar (tests `polygonal_lasso_is_in_the_lasso_flyout`, `a_saved_toolbar_without_polygonal_lasso_keeps_its_layout` and `a_torn_off_lasso_group_shows_polygonal_lasso` in `edit_toolbar::tests`, `polygonal_lasso_is_in_the_lasso_group_once` in `addons::tests`, `headless_lists_the_lasso_group` in `vectorcraft-mcp`). It has no default shortcut. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. - Edit Points Only (Object › Plug-ins › Selection Tools, a VectorCraft addition) narrows a Direct Selection to its selected anchor points (`addon.select.editPointsOnly {segmentEnds?}`): selected segments leave the selection, and the points at their ends leave it too unless Keep Ends of Selected Segments is on; paths selected whole keep every point; a group or compound path selected whole gives way to the visible, unlocked paths inside it; type, images, symbols and other objects without anchor points leave the selection. Only the selection changes, so there is no undo step; with nothing left to keep it is an error and the selection stays as it was. The dialog previews the narrowed selection, and Cancel puts the selection back. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`edit_points_only`), `crates/ui-egui/src/addons/select/points_only/tests.rs`, `crates/engine/tests/command_sweep.rs`. + Edit Points Only (Object › Plug-ins › Selection Tools, a VectorCraft addition) narrows a Direct Selection to its selected anchor points (`addon.select.editPointsOnly {segmentEnds?}`): selected segments leave the selection, and the points at their ends leave it too unless Keep Ends of Selected Segments is on; paths selected whole keep every point; a group or compound path selected whole gives way to the visible, unlocked paths inside it, leaving out a Shaper Group's original shapes and, while guides are locked, paths made into guides; type, images, symbols and other objects without anchor points leave the selection. Only the selection changes, so there is no undo step; with nothing left to keep it is an error and the selection stays as it was. The dialog previews the narrowed selection, and Cancel puts the selection back. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`edit_points_only`), `crates/ui-egui/src/addons/select/points_only/tests.rs`, `crates/engine/tests/command_sweep.rs`. The Links panel provides an item right-click context menu on link rows offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Separator, and Embed Image / Unembed…. Right-clicking an unselected row selects that row first; right-clicking a row that is already part of a multi-selection preserves the multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. The Location row of the Links panel's Link Info has a folder button, Show in Folder, that opens the folder of the file Link Info shows in the system's file manager (`links.reveal {id}` with that image's id); the help page describes a folder icon on this row ([Links information](https://helpx.adobe.com/illustrator/using/links-info.html)). The button's name and its off state while the file is missing or no file manager is available (the web build) are VectorCraft's own. Tests: `panels::tests_links::link_infos_location_row_shows_the_file_in_its_folder`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). From c1bfae38c20f96181fbe62dced597f63a1996576 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 16:11:19 -0800 Subject: [PATCH 07/37] Selection Tools: Edit Points Only keeps explicit anchor picks inside selected groups A path's own anchor pick now wins over its group's whole-path expansion in either selection order, a segmentEnds of null is rejected, and OK in the dialog runs the command outside the preview so dropping Puppet Warp pins adds no undo step. The docs say whole paths still take object transforms. --- crates/engine/src/cmd/addons/select.rs | 10 +++- crates/engine/src/cmd/addons/select/tests.rs | 46 ++++++++++++++++++- crates/ui-egui/src/addons/dialogs.rs | 12 ++++- .../src/addons/select/points_only/tests.rs | 26 +++++++++++ crates/ui-egui/src/dialogs/preview.rs | 6 +++ docs/mcp.md | 18 ++++---- 6 files changed, 105 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index 6c3346ca80..bda973fb2c 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Edit Points Only", ["Object", "Plug-ins", "Selection Tools"], None, - "{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points)} narrow the selection to the anchor points selected in it, so that a move or transform that follows acts on those points alone: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole keeps all its points; a group or compound path selected whole gives way to the paths inside it, each selected whole, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. Only the selection changes, not the document, so there is nothing to undo → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}", + "{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points; any non-boolean value, including null, is an error)} narrow the selection to paths and their selected anchor points: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole stays selected whole and still receives object transforms, including stroke and effect scaling when enabled; a group or compound path selected whole gives way to the paths inside it, each selected whole unless it has an explicit anchor pick, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; explicit anchor picks take precedence regardless of selection order; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. The command does not add an undo step → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}", has_doc, edit_points_only ), @@ -242,7 +242,10 @@ fn paths_inside<'a>(n: &'a Node, guides_locked: bool, out: &mut Vec<&'a Node>) { /// `addon.select.editPointsOnly`: narrow the selection to the anchor points selected in it. fn edit_points_only(s: &mut Session, p: &Value) -> Result { const C: &str = "addon.select.editPointsOnly"; - let keep_ends = switch_or(p, "segmentEnds", false, C)?; + let keep_ends = match p.get("segmentEnds") { + None => false, + Some(value) => value.as_bool().ok_or_else(|| bad(C, "`segmentEnds` must be true or false"))?, + }; let guides_locked = s.menu.guides_locked; let st = s.doc()?; let (doc, sel) = (&st.doc, &st.selection); @@ -278,6 +281,9 @@ fn edit_points_only(s: &mut Session, p: &Value) -> Result { let mut inside = vec![]; paths_inside(n, guides_locked, &mut inside); for c in inside { + if sel.objects.contains(&c.id) && sel.anchors.contains_key(&c.id) { + continue; + } if seen.insert(c.id) { kept.push((c.id, c.path_data().map_or(0, |path| path.anchors().count()), None)); } diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index 85844c241d..ec6054a237 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -426,6 +426,44 @@ mod edit_points_only { assert_eq!(picked(&s), (vec![a, b], BTreeMap::new())); } + #[test] + fn explicit_anchor_picks_override_group_expansion_in_either_order() { + for group_first in [true, false] { + let (mut s, a, b) = two(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| { + sel.set(if group_first { vec![group, a] } else { vec![a, group] }); + sel.anchors.insert(a, refs(&[(0, 0)])); + }) + .unwrap(); + let before = s.doc().unwrap().doc.node(a).unwrap().path_data().unwrap().clone(); + assert_eq!(s.execute(C, &json!({})).unwrap(), json!({"changed": true, "count": 2, "points": 5})); + assert_eq!(s.doc().unwrap().selection.anchors[&a], refs(&[(0, 0)])); + s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap(); + let after = s.doc().unwrap().doc.node(a).unwrap().path_data().unwrap(); + for ((_, i, old), (_, _, new)) in before.anchors().zip(after.anchors()) { + if i == 0 { + assert_ne!(new.p, old.p); + } else { + assert_eq!(new.p, old.p, "unselected anchors stay in place"); + } + } + } + } + + #[test] + fn whole_paths_keep_object_transforms_and_stroke_scaling() { + let (mut s, a, _) = two(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + let before = s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width(); + s.execute(C, &json!({})).unwrap(); + assert!(!s.doc().unwrap().selection.anchors.contains_key(&a)); + s.execute("object.transform", &json!({"matrix": [2, 0, 0, 2, 0, 0], "strokes": true})).unwrap(); + assert!(s.doc().unwrap().doc.node(a).unwrap().appearance.stroke_width() > before); + } + #[test] fn groups_and_compound_paths_give_way_to_their_paths_and_other_objects_leave() { let (mut s, a, b) = two(); @@ -487,7 +525,13 @@ mod edit_points_only { let e = s.execute(C, &json!({})).unwrap_err().to_string(); assert!(e.contains("no anchor points are selected"), "{e}"); assert_eq!(s.doc().unwrap().selection, before); - for p in [json!({"segmentEnds": "yes"}), json!({"segmentEnds": 1}), json!({"segmentEnds": [true]}), json!({"segmentEnd": true})] { + for p in [ + json!({"segmentEnds": null}), + json!({"segmentEnds": "yes"}), + json!({"segmentEnds": 1}), + json!({"segmentEnds": [true]}), + json!({"segmentEnd": true}), + ] { s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 0]]})).unwrap(); s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "add"})).unwrap(); let before = s.doc().unwrap().selection.clone(); diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index 3273764d5f..c2d1f138de 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -157,8 +157,16 @@ fn pump_commit(app: &mut VectorcraftApp) { app.status("The document was reverted. Reopen this dialog to continue."); } else if !on_document { app.status("The add-on settings apply only to the drawing where the dialog opened."); - } else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) { - app.status(error); + } else { + let params = (spec.params)(&result.fields); + let answer = if spec.command == super::select::points_only::COMMAND { + preview.commit_selection(app, spec.command, params) + } else { + preview.commit(app, spec.command, params) + }; + if let Err(error) = answer { + app.status(error); + } } } Some(None) => { diff --git a/crates/ui-egui/src/addons/select/points_only/tests.rs b/crates/ui-egui/src/addons/select/points_only/tests.rs index 21285a1e8e..ba0bc13b73 100644 --- a/crates/ui-egui/src/addons/select/points_only/tests.rs +++ b/crates/ui-egui/src/addons/select/points_only/tests.rs @@ -55,6 +55,32 @@ fn the_dialog_previews_keeps_on_ok_and_takes_the_segment_ends_from_the_keyboard( assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "a selection change is not an undo step"); } +#[test] +fn ok_drops_puppet_pins_without_an_undo_step() { + for previewing in [true, false] { + let (mut app, a, b) = app(); + app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); + app.run("object.group", json!({})).unwrap(); + app.run("object.puppetWarp", json!({"pins": [[35, 35]], "moved": [[35, 35]], "rest": true})).unwrap(); + assert!(app.session.doc().unwrap().doc.puppet.is_some()); + let undo = app.session.doc().unwrap().history.undo.len(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + if previewing { + host::frame(&mut app); + assert!(app.session.doc().unwrap().doc.puppet.is_none()); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(!app.any_dialog_open()); + let st = app.session.doc().unwrap(); + assert!(st.doc.puppet.is_none()); + assert_eq!(st.selection.objects, vec![a, b]); + assert!(!app.session.in_interaction()); + assert_eq!(st.history.undo.len(), undo, "pin cleanup does not add an undo step"); + } +} + #[test] fn cancel_puts_the_selection_back() { let (app, _, b) = app(); diff --git a/crates/ui-egui/src/dialogs/preview.rs b/crates/ui-egui/src/dialogs/preview.rs index 2e029fc1c6..f1585adc6b 100644 --- a/crates/ui-egui/src/dialogs/preview.rs +++ b/crates/ui-egui/src/dialogs/preview.rs @@ -125,6 +125,12 @@ impl LivePreview { Ok(Value::Null) } + /// OK for a selection command: rolls its preview back and runs the command without an interaction. + pub(crate) fn commit_selection(self, app: &mut VectorcraftApp, cmd: &str, params: Value) -> Result { + self.cancel(app); + Self::default().commit(app, cmd, params) + } + /// Cancel: rolls a shown preview back, and leaves any other edit in progress as it is. pub(crate) fn cancel(self, app: &mut VectorcraftApp) { if self.previewed.is_some() && self.owns(app) { diff --git a/docs/mcp.md b/docs/mcp.md index 1c9c20ff48..65c28a7c38 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -17313,18 +17313,20 @@ locked". Select by Link Status… lists every image and placed document with its name and filters by status (Show), chooses rows with checkboxes (All / None act on the rows shown), and on Select selects the rows chosen, zooming to them when Zoom to Selection is on (the default). -`addon.select.editPointsOnly {segmentEnds?}` (Edit Points Only…) narrows the selection to the anchor points selected in -it, so that a move or transform that follows acts on those points alone. A path with selected anchor points keeps them. +`addon.select.editPointsOnly {segmentEnds?}` (Edit Points Only…) narrows the selection to paths and their selected +anchor points. A path with selected anchor points keeps them. A path with selected segments drops the segments and keeps its other selected anchor points; the points at the ends of the segments leave the selection unless `segmentEnds` is `true` (default `false`), which keeps them as selected anchor -points. A path selected whole keeps all its points. A group or compound path selected whole is replaced by the paths -inside it, each selected whole, without hidden and locked ones, without a Shaper Group's original shapes and, while -guides are locked, without paths made into guides. Type, -images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. Only the -selection changes, so there is nothing to undo. It returns `{changed, count, points}`: `changed` is `false` when the +points. A path selected whole stays selected whole and still receives object transforms, including stroke and effect +scaling when enabled. A group or compound path selected whole is replaced by the paths +inside it, each selected whole unless it has an explicit anchor pick. Explicit anchor picks take precedence regardless +of selection order. The command leaves out hidden and locked paths, a Shaper Group's original shapes and, while +guides are locked, paths made into guides. Type, +images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. The command +does not add an undo step. It returns `{changed, count, points}`: `changed` is `false` when the selection already held only anchor points, `count` is the number of paths left selected and `points` the number of anchor points selected on them. Nothing selected, no anchor point left to keep ("no anchor points are selected"), or a -`segmentEnds` that is not `true` or `false` is an error, and the selection is left as it was. +`segmentEnds` that is not `true` or `false` (including `null`) is an error, and the selection is left as it was. ```json {"name":"run_command","arguments":{"command":"addon.select.editPointsOnly","params":{"segmentEnds":false}}} From 8d5fb2ff6b6d0de7a9f2dc32ed403705a1e79e9f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 17:19:26 -0800 Subject: [PATCH 08/37] Selection Tools: Edit Points Only skips hidden and locked art and keeps the Appearance row Edit Points Only now leaves out selected paths and groups that are hidden or locked, themselves or through an ancestor. Group expansion looks up explicit anchor picks in a set instead of scanning the selection for each path. Canceling the preview restores the active Appearance row, and a preview or OK that succeeds clears the earlier status error. --- crates/engine/src/cmd/addons/select.rs | 6 +- crates/engine/src/cmd/addons/select/tests.rs | 73 +++++++++++++++++++ crates/engine/src/interaction.rs | 1 + crates/engine/src/session/edit.rs | 12 ++- crates/ui-egui/src/addons/dialogs.rs | 5 ++ .../src/addons/select/points_only/tests.rs | 22 ++++++ 6 files changed, 116 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index bda973fb2c..fb8c49aed6 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -254,9 +254,13 @@ fn edit_points_only(s: &mut Session, p: &Value) -> Result { } // Each path once, in selection order, with its points kept: `None` for all of them. let mut seen = HashSet::new(); + let explicit: HashSet = sel.objects.iter().copied().filter(|id| sel.anchors.contains_key(id)).collect(); let mut kept: Vec<(NodeId, usize, Option>)> = vec![]; for id in &sel.objects { let Some(n) = doc.node(*id) else { continue }; + if !doc.ancestry(*id).is_some_and(|ancestors| ancestors.iter().all(|id| doc.node(*id).is_some_and(|n| n.visible && !n.locked))) { + continue; + } match &n.kind { NodeKind::Path { path, .. } => { let Some(refs) = sel.anchors.get(id) else { @@ -281,7 +285,7 @@ fn edit_points_only(s: &mut Session, p: &Value) -> Result { let mut inside = vec![]; paths_inside(n, guides_locked, &mut inside); for c in inside { - if sel.objects.contains(&c.id) && sel.anchors.contains_key(&c.id) { + if explicit.contains(&c.id) { continue; } if seen.insert(c.id) { diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index ec6054a237..6171c08ef9 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -452,6 +452,79 @@ mod edit_points_only { } } + #[test] + fn hidden_or_locked_selected_nodes_and_their_ancestors_are_left_out() { + for locked in [false, true] { + for target in ["path", "group", "ancestor", "layer"] { + let (mut s, a, b) = two(); + let good = rect(&mut s, 200.0, 10.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let blocked = match target { + "path" => a, + "layer" => s.doc().unwrap().doc.layers[0].id, + _ => group, + }; + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let node = doc.node_mut(blocked).unwrap(); + if locked { + node.locked = true; + } else { + node.visible = false; + } + let selected = if matches!(target, "path" | "ancestor") { a } else { group }; + s.execute("select.set", &json!({"ids": [good.0, selected.0]})).unwrap(); + if target == "layer" { + let before = s.doc().unwrap().selection.clone(); + assert!(s.execute(C, &json!({})).is_err()); + assert_eq!(s.doc().unwrap().selection, before); + } else { + s.execute(C, &json!({})).unwrap(); + assert_eq!(picked(&s), (vec![good], BTreeMap::new()), "{target}, locked: {locked}"); + } + } + } + } + + #[test] + fn group_expansion_does_not_scan_the_selection_for_each_descendant() { + let source = include_str!("../select.rs"); + let command = source.split("fn edit_points_only(").nth(1).unwrap(); + assert!(!command.contains("sel.objects.contains(&c.id)"), "descendant lookup must not scan every selected object"); + + let (mut s, _, _) = two(); + let mut groups = vec![]; + let mut paths = vec![]; + for x in [10.0, 100.0, 200.0] { + let a = rect(&mut s, x, 100.0, 20.0, 20.0); + let b = rect(&mut s, x, 150.0, 20.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + groups.push(NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap())); + paths.extend([a, b]); + } + s.select(|_, sel| sel.set(groups)).unwrap(); + s.execute(C, &json!({})).unwrap(); + assert_eq!(picked(&s), (paths, BTreeMap::new())); + } + + #[test] + fn canceling_a_selection_preview_restores_the_active_appearance_item() { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + let before = s.doc().unwrap().doc.node(a).unwrap().appearance.items.clone(); + s.begin_interaction("Edit Points Only").unwrap(); + s.preview(C, &json!({})).unwrap(); + assert_eq!(s.appearance_item(), None); + s.cancel_interaction().unwrap(); + assert_eq!(s.appearance_item(), Some(0)); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let after = &s.doc().unwrap().doc.node(a).unwrap().appearance.items; + assert_ne!(after[0], before[0]); + assert_eq!(&after[1..], &before[1..]); + } + #[test] fn whole_paths_keep_object_transforms_and_stroke_scaling() { let (mut s, a, _) = two(); diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index a2b9417461..dc7b5684fe 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -10,6 +10,7 @@ pub struct Interaction { pub doc: Arc, /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, + pub(crate) active_appearance_item: Option, pub preview: Option<(String, Value)>, /// The active tool began it (a drag): a command from outside the tool runs as a step of its /// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index d5d62e607c..45d0dfd370 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -536,6 +536,7 @@ impl Session { } self.clear_deferred_overlay_cache(); let paint = self.paint.clone(); + let active_appearance_item = self.active_appearance_item.clone(); let st = self.doc_mut()?; if st.interaction.is_some() { return Ok(()); @@ -545,6 +546,7 @@ impl Session { effect: None, doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), + active_appearance_item, preview: None, tool: false, paint, @@ -577,7 +579,7 @@ impl Session { // preview starts from the colors the interaction began with; so does a preview with // `defaultsOnly: true`, and one after it. let tool_paints = self.tool_paints(false) || self.tool_paints(true); - let (paint, restore_paint) = { + let (paint, restore_paint, active_appearance_item) = { let menu = self.menu.clone(); let st = self.doc_mut()?; let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; @@ -599,6 +601,7 @@ impl Session { || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some(); let paint = it.paint.clone(); + let active_appearance_item = it.active_appearance_item.clone(); it.preview_paint = None; it.color_mode_paints = None; it.deferred_color_mode = None; @@ -615,8 +618,9 @@ impl Session { // undone with it. st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); - (paint, restore_paint) + (paint, restore_paint, active_appearance_item) }; + self.active_appearance_item = active_appearance_item; if restore_paint { self.paint = paint.clone(); } @@ -782,10 +786,14 @@ impl Session { self.paint = paint; } let menu = self.menu.clone(); + let active_appearance_item = self.active().and_then(|st| st.interaction.as_ref()).map(|it| it.active_appearance_item.clone()); let st = self.doc_mut()?; st.undo_interaction(); // Guides locked and slices locked or hidden during the interaction stay deselected. deselect_hidden(&menu, &st.doc, &mut st.selection); + if let Some(active_appearance_item) = active_appearance_item { + self.active_appearance_item = active_appearance_item; + } // A canceled preview's Assign Profile is undone with it. self.sync_front_profiles(); // With New Art Has Basic Appearance off, new art takes the appearance of the selection as diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index c2d1f138de..f0642c31fc 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -140,6 +140,9 @@ fn pump_commit(app: &mut VectorcraftApp) { let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); let answer = preview.run(app, *previewing, label, spec.command, params); app.addon_dialogs.preview = preview; + if spec.command == super::select::points_only::COMMAND && matches!(&answer, Some(Ok(_))) { + app.ui.status.clear(); + } if let (Some(found), Some(answer)) = (spec.found, answer) { host.with(|h| { if let Some(d) = h.get_mut_by_id::(id) { @@ -166,6 +169,8 @@ fn pump_commit(app: &mut VectorcraftApp) { }; if let Err(error) = answer { app.status(error); + } else if spec.command == super::select::points_only::COMMAND { + app.ui.status.clear(); } } } diff --git a/crates/ui-egui/src/addons/select/points_only/tests.rs b/crates/ui-egui/src/addons/select/points_only/tests.rs index ba0bc13b73..ff0fef879f 100644 --- a/crates/ui-egui/src/addons/select/points_only/tests.rs +++ b/crates/ui-egui/src/addons/select/points_only/tests.rs @@ -96,6 +96,28 @@ fn cancel_puts_the_selection_back() { assert_eq!(app.session.doc().unwrap().selection, before); } +#[test] +fn keeping_segment_ends_clears_the_preview_error() { + for previewing in [true, false] { + let (mut app, a, _) = app(); + app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + host::frame(&mut app); + assert!(app.ui.status.contains("no anchor points are selected"), "{}", app.ui.status); + host::set(&app, id, "segmentEnds", json!(true)); + if previewing { + host::frame(&mut app); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + assert_eq!(points(&app, a), (Some(refs(&[(0, 0), (0, 1)])), false)); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + assert!(!app.any_dialog_open()); + } +} + #[test] fn ok_with_nothing_to_keep_says_why_and_leaves_the_selection() { let (mut app, a, _) = app(); From 3e29a71b9986754961467c16f90c0ec93485d7c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 18:05:26 -0800 Subject: [PATCH 09/37] Selection Tools: Edit Points Only keeps Appearance row changes and other status messages Replacing or canceling a drag's preview restores the Appearance row only when the preview itself changed it, so a row set or cleared during the drag stays. The dialog clears only its own preview error, and only while it is still the current status message. The group expansion test checks behavior instead of source text. --- crates/engine/src/cmd/addons/select.rs | 2 +- crates/engine/src/cmd/addons/select/tests.rs | 50 +++++++++++++++++-- crates/engine/src/cmd/appearance.rs | 17 ++++++- crates/engine/src/interaction.rs | 8 ++- crates/engine/src/session/edit.rs | 28 +++++++---- crates/ui-egui/src/addons/dialogs.rs | 25 ++++++++-- .../src/addons/select/points_only/tests.rs | 42 ++++++++++++++++ docs/mcp.md | 4 ++ 8 files changed, 154 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmd/addons/select.rs b/crates/engine/src/cmd/addons/select.rs index fb8c49aed6..e99294a4b0 100644 --- a/crates/engine/src/cmd/addons/select.rs +++ b/crates/engine/src/cmd/addons/select.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Edit Points Only", ["Object", "Plug-ins", "Selection Tools"], None, - "{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points; any non-boolean value, including null, is an error)} narrow the selection to paths and their selected anchor points: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole stays selected whole and still receives object transforms, including stroke and effect scaling when enabled; a group or compound path selected whole gives way to the paths inside it, each selected whole unless it has an explicit anchor pick, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; explicit anchor picks take precedence regardless of selection order; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. The command does not add an undo step → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}", + "{segmentEnds?: false (true: the points at the ends of each selected segment stay selected, as anchor points; any non-boolean value, including null, is an error)} narrow the selection to paths and their selected anchor points: a path with selected anchor points keeps them; a path with selected segments drops the segments and keeps its other selected anchor points, and the points at the segments' ends leave the selection unless segmentEnds is true; a path selected whole stays selected whole and still receives object transforms, including stroke and effect scaling when enabled; a group or compound path selected whole gives way to the paths inside it, each selected whole unless it has an explicit anchor pick, leaving out hidden and locked ones, a Shaper Group's original shapes and, while guides are locked, paths made into guides; explicit anchor picks take precedence regardless of selection order; type, images, symbols, meshes and other objects without anchor points, and ruler guides, leave the selection. With nothing selected, or no anchor point left to keep, it is an error that leaves the selection as it was. The command does not add an undo step. In the desktop dialog, a successful preview or OK clears only that dialog's preview error if it is still the current status message → {changed (false when the selection already held only anchor points), count (the paths left selected), points (the anchor points selected on them)}", has_doc, edit_points_only ), diff --git a/crates/engine/src/cmd/addons/select/tests.rs b/crates/engine/src/cmd/addons/select/tests.rs index 6171c08ef9..4b86ae5802 100644 --- a/crates/engine/src/cmd/addons/select/tests.rs +++ b/crates/engine/src/cmd/addons/select/tests.rs @@ -487,11 +487,7 @@ mod edit_points_only { } #[test] - fn group_expansion_does_not_scan_the_selection_for_each_descendant() { - let source = include_str!("../select.rs"); - let command = source.split("fn edit_points_only(").nth(1).unwrap(); - assert!(!command.contains("sel.objects.contains(&c.id)"), "descendant lookup must not scan every selected object"); - + fn group_expansion_selects_each_descendant_path() { let (mut s, _, _) = two(); let mut groups = vec![]; let mut paths = vec![]; @@ -507,6 +503,48 @@ mod edit_points_only { assert_eq!(picked(&s), (paths, BTreeMap::new())); } + #[test] + fn appearance_row_commands_survive_preview_replacement_and_cancel() { + for index in [json!(1), Value::Null] { + for selection_preview in [false, true] { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + s.begin_interaction("Drag").unwrap(); + s.doc_mut().unwrap().interaction.as_mut().unwrap().tool = !selection_preview; + if selection_preview { + s.preview(C, &json!({})).unwrap(); + assert_eq!(s.appearance_item(), None); + } else { + s.preview("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + } + s.execute("appearance.setActiveItem", &json!({"index": index})).unwrap(); + let expected = index.as_u64().map(|i| i as usize); + s.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap(); + assert_eq!(s.appearance_item(), expected, "replacement preserves the explicit row command"); + s.cancel_interaction().unwrap(); + assert_eq!(s.appearance_item(), expected, "cancel preserves the explicit row command"); + } + } + } + + #[test] + fn cancel_preserves_an_appearance_row_command_without_another_preview() { + for index in [json!(1), Value::Null] { + let (mut s, a, b) = two(); + mixed(&mut s, a, b); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + s.begin_interaction("Drag").unwrap(); + s.doc_mut().unwrap().interaction.as_mut().unwrap().tool = true; + s.preview(C, &json!({})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": index})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.appearance_item(), index.as_u64().map(|i| i as usize)); + } + } + #[test] fn canceling_a_selection_preview_restores_the_active_appearance_item() { let (mut s, a, b) = two(); @@ -517,6 +555,8 @@ mod edit_points_only { s.begin_interaction("Edit Points Only").unwrap(); s.preview(C, &json!({})).unwrap(); assert_eq!(s.appearance_item(), None); + s.preview(C, &json!({"segmentEnds": true})).unwrap(); + assert_eq!(s.appearance_item(), None); s.cancel_interaction().unwrap(); assert_eq!(s.appearance_item(), Some(0)); s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index d319e0d2a4..a530efce99 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -139,7 +139,7 @@ pub fn specs() -> Vec { "Select Appearance Item", [], None, - "{index: paint-order item index in the first selected object's stack | null} make that fill/stroke row the target of the paint.setFill/setStroke, stroke.set/setAdvanced, paint.editGradient/setGradientGeom, transparency.set and effect.* calls that omit `item` (a fill row brings the Fill proxy forward, a stroke row the Stroke proxy); null or any selection change clears it → {index}", + "{index: paint-order item index in the first selected object's stack | null} make that fill/stroke row the target of the paint.setFill/setStroke, stroke.set/setAdvanced, paint.editGradient/setGradientGeom, transparency.set and effect.* calls that omit `item` (a fill row brings the Fill proxy forward, a stroke row the Stroke proxy); null or any selection change clears it. A row set or cleared outside a drag's preview stays set or cleared when the preview is replaced or canceled → {index}", has_selection, set_active_item ), @@ -174,7 +174,7 @@ pub fn specs() -> Vec { } /// The Appearance panel's active row, remembered for the selection it was chosen in. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct ActiveItem { doc: u64, objects: Vec, @@ -956,6 +956,7 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { let index = match p.get("index") { Some(Value::Null) => { s.active_appearance_item = None; + clear_preview_item(s); return Ok(json!({ "index": Value::Null })); } Some(_) => index_param(p, "index", C)?, @@ -968,9 +969,21 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { let doc = st.uid; s.fill_active = fill; s.active_appearance_item = Some(ActiveItem { doc, objects, index }); + clear_preview_item(s); Ok(json!({ "index": index })) } +fn clear_preview_item(s: &mut Session) { + if !s.previewing { + if let Some(it) = s.active_mut().and_then(|st| st.interaction.as_mut()) { + it.active_appearance_item = None; + } + if let Some(held) = &mut s.held_interaction { + held.interaction.active_appearance_item = None; + } + } +} + fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" }; let mut ids = row_targets(s, p, cmd)?; diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index dc7b5684fe..748dd764cc 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -10,7 +10,7 @@ pub struct Interaction { pub doc: Arc, /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, - pub(crate) active_appearance_item: Option, + pub(crate) active_appearance_item: Option, pub preview: Option<(String, Value)>, /// The active tool began it (a drag): a command from outside the tool runs as a step of its /// own under it ([`crate::Session::outside_interaction`]). A dialog or a panel that begins an @@ -53,6 +53,12 @@ pub struct Interaction { pub keep_on_switch: bool, } +#[derive(Clone, Debug)] +pub(crate) struct PreviewAppearanceItem { + pub(crate) before: Option, + pub(crate) after: Option, +} + /// An interaction that a command from outside the tool set aside while it runs /// ([`crate::Session::outside_interaction`]). #[derive(Debug)] diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 45d0dfd370..e337be95ab 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -536,7 +536,6 @@ impl Session { } self.clear_deferred_overlay_cache(); let paint = self.paint.clone(); - let active_appearance_item = self.active_appearance_item.clone(); let st = self.doc_mut()?; if st.interaction.is_some() { return Ok(()); @@ -546,7 +545,7 @@ impl Session { effect: None, doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), - active_appearance_item, + active_appearance_item: None, preview: None, tool: false, paint, @@ -574,12 +573,14 @@ impl Session { if self.script_running() { return Err(EngineError::Busy); } + self.restore_preview_appearance_item(); + let before_item = self.active_appearance_item.clone(); // While the active tool paints with the chosen fill or stroke (the Live Paint Bucket, the // Shape Builder), paint previews of that kind change only the colors it paints with, so each // preview starts from the colors the interaction began with; so does a preview with // `defaultsOnly: true`, and one after it. let tool_paints = self.tool_paints(false) || self.tool_paints(true); - let (paint, restore_paint, active_appearance_item) = { + let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; @@ -601,7 +602,6 @@ impl Session { || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some(); let paint = it.paint.clone(); - let active_appearance_item = it.active_appearance_item.clone(); it.preview_paint = None; it.color_mode_paints = None; it.deferred_color_mode = None; @@ -618,9 +618,8 @@ impl Session { // undone with it. st.restore_isolation(isolation, &undone); cmd::globaledit::follow_history(st); - (paint, restore_paint, active_appearance_item) + (paint, restore_paint) }; - self.active_appearance_item = active_appearance_item; if restore_paint { self.paint = paint.clone(); } @@ -642,8 +641,11 @@ impl Session { } let params = self.noted(params); let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone()); + let after_item = self.active_appearance_item.clone(); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { + it.active_appearance_item = + (before_item != after_item).then_some(crate::interaction::PreviewAppearanceItem { before: before_item, after: after_item }); it.used_defaults_only |= ran_defaults_only; // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). @@ -761,8 +763,18 @@ impl Session { } } + fn restore_preview_appearance_item(&mut self) { + let changed = self.active_mut().and_then(|st| st.interaction.as_mut()).and_then(|it| it.active_appearance_item.take()); + if let Some(changed) = changed + && self.active_appearance_item == changed.after + { + self.active_appearance_item = changed.before; + } + } + pub fn cancel_interaction(&mut self) -> Result<()> { self.put_back_interaction(); + self.restore_preview_appearance_item(); self.clear_deferred_overlay_cache(); self.decoded_images.empty(); self.pending_paint = None; @@ -786,14 +798,10 @@ impl Session { self.paint = paint; } let menu = self.menu.clone(); - let active_appearance_item = self.active().and_then(|st| st.interaction.as_ref()).map(|it| it.active_appearance_item.clone()); let st = self.doc_mut()?; st.undo_interaction(); // Guides locked and slices locked or hidden during the interaction stay deselected. deselect_hidden(&menu, &st.doc, &mut st.selection); - if let Some(active_appearance_item) = active_appearance_item { - self.active_appearance_item = active_appearance_item; - } // A canceled preview's Assign Profile is undone with it. self.sync_front_profiles(); // With New Art Has Basic Appearance off, new art takes the appearance of the selection as diff --git a/crates/ui-egui/src/addons/dialogs.rs b/crates/ui-egui/src/addons/dialogs.rs index f0642c31fc..a1c9dcf5b8 100644 --- a/crates/ui-egui/src/addons/dialogs.rs +++ b/crates/ui-egui/src/addons/dialogs.rs @@ -34,6 +34,7 @@ pub(crate) struct Spec { pub(crate) struct AddonDialogs { open: Option, preview: LivePreview, + preview_error: Option<(u64, String)>, /// The open Tangent Circle Tool radius dialog. pub(crate) tangent_radius: Option, } @@ -65,6 +66,7 @@ fn active_document(app: &VectorcraftApp) -> Option<(u64, u64)> { /// Closes the open add-on dialog without an answer and rolls its preview back. fn close_open(app: &mut VectorcraftApp) { let Some(open) = app.addon_dialogs.open.take() else { return }; + app.addon_dialogs.preview_error = None; let id = open.id; if let (Some(host), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) { host.with(|h| { @@ -133,6 +135,7 @@ fn pump_commit(app: &mut VectorcraftApp) { if !on_document { // Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing. app.addon_dialogs.preview = LivePreview::default(); + app.addon_dialogs.preview_error = None; } let live = host.with(|h| h.get_mut_by_id::(id).map(|d| (d.is_previewing(), (spec.params)(d.fields())))); if on_document && let Some((previewing, params)) = &live { @@ -140,8 +143,12 @@ fn pump_commit(app: &mut VectorcraftApp) { let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label); let answer = preview.run(app, *previewing, label, spec.command, params); app.addon_dialogs.preview = preview; - if spec.command == super::select::points_only::COMMAND && matches!(&answer, Some(Ok(_))) { - app.ui.status.clear(); + if spec.command == super::select::points_only::COMMAND { + match &answer { + Some(Err(_)) => app.addon_dialogs.preview_error = Some((app.ui.status_sets, app.ui.status.clone())), + Some(Ok(_)) => clear_preview_error(app), + None => {} + } } if let (Some(found), Some(answer)) = (spec.found, answer) { host.with(|h| { @@ -170,18 +177,30 @@ fn pump_commit(app: &mut VectorcraftApp) { if let Err(error) = answer { app.status(error); } else if spec.command == super::select::points_only::COMMAND { - app.ui.status.clear(); + clear_preview_error(app); } } + app.addon_dialogs.preview_error = None; } Some(None) => { app.addon_dialogs.open = None; + app.addon_dialogs.preview_error = None; mem::take(&mut app.addon_dialogs.preview).cancel(app); } None if live.is_none() => { app.addon_dialogs.open = None; + app.addon_dialogs.preview_error = None; mem::take(&mut app.addon_dialogs.preview).cancel(app); } None => {} } } + +fn clear_preview_error(app: &mut VectorcraftApp) { + if let Some((sets, error)) = app.addon_dialogs.preview_error.take() + && app.ui.status_sets == sets + && app.ui.status == error + { + app.ui.status.clear(); + } +} diff --git a/crates/ui-egui/src/addons/select/points_only/tests.rs b/crates/ui-egui/src/addons/select/points_only/tests.rs index ff0fef879f..75ddaf5703 100644 --- a/crates/ui-egui/src/addons/select/points_only/tests.rs +++ b/crates/ui-egui/src/addons/select/points_only/tests.rs @@ -96,6 +96,48 @@ fn cancel_puts_the_selection_back() { assert_eq!(app.session.doc().unwrap().selection, before); } +#[test] +fn successful_preview_and_confirmation_preserve_another_status() { + for previewing in [true, false] { + let (mut app, _, _) = app(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + app.status("The active text edit reported a warning."); + if previewing { + host::frame(&mut app); + assert_eq!(app.ui.status, "The active text edit reported a warning."); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(app.ui.status, "The active text edit reported a warning."); + assert!(!app.any_dialog_open()); + } +} + +#[test] +fn recovering_from_a_preview_error_preserves_a_later_status() { + for previewing in [true, false] { + for same_text in [true, false] { + let (mut app, a, _) = app(); + app.run("select.segments", json!({"id": a.0, "segments": [[0, 0]]})).unwrap(); + host::open_item(&mut app, "Selection Tools", "Edit Points Only…"); + let id = host::dialog_id(&app); + host::frame(&mut app); + assert!(app.ui.status.contains("no anchor points are selected")); + let status = if same_text { app.ui.status.clone() } else { "Another command reported a warning.".to_owned() }; + app.status(status.clone()); + host::set(&app, id, "segmentEnds", json!(true)); + if previewing { + host::frame(&mut app); + assert_eq!(app.ui.status, status); + } + assert!(host::confirm(&app, id)); + host::frame(&mut app); + assert_eq!(app.ui.status, status); + } + } +} + #[test] fn keeping_segment_ends_clears_the_preview_error() { for previewing in [true, false] { diff --git a/docs/mcp.md b/docs/mcp.md index 65c28a7c38..c6a4aff22a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -985,6 +985,8 @@ Cmd+Alt+/ runs `appearance.addStroke` (`press_key {key: "/", mods: {cmd: true, a `item` to edit one of them; `run_command appearance.setActiveItem {"index": n}` makes that row the target of later calls that omit `item` (as clicking the row in the Appearance panel does) until the selection changes; the proxy of its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. +An `appearance.setActiveItem` call made outside a drag's preview keeps its selected row, including an explicit +`index: null`, when the preview is replaced or canceled. `inspect_document` reports it as `paint.appearanceItem`. `paint.setFill` and `paint.setStroke` also take `opacity` (0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint @@ -17335,6 +17337,8 @@ anchor points selected on them. Nothing selected, no anchor point left to keep ( In the desktop app, Object › Plug-ins › Selection Tools › Edit Points Only… opens a dialog with Keep Ends of Selected Segments (off). With Preview on, the canvas shows the narrowed selection; OK keeps it and Cancel puts the selection back. +After a failed preview, a successful preview or OK clears the dialog's error only if that error is still the current +status message. Messages from other commands stay displayed. ### Vector Halftone (live) From 616987fdec1c901900e0d74ba3e0f333a74436f7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 19:20:11 -0800 Subject: [PATCH 10/37] Properties: the Document sections replay whole, header and body The craft-libs pin moves to current craft-libs main, 19805ced1e, which has craft-libs#4359: a MemoView's content keeps the flow start and gap of the Stack around it. Each memoized Document section now shows in its MemoView with its header, so an idle frame replays the header as well as the body. Before that change in craft-libs, the Document section stood 18 pt lower in a MemoView and each later memoized section 5 pt lower again. The pin also moves the craft-web-api dependency of vectorcraft-web, the rev that `cargo xtask pdf-deps` checks, and the winit rev to 0dfcec0eb6, the one craft-libs pins. Cargo.lock takes brotli 9.1.3 for craft-i18n, objc2-core-graphics for craft-appkit and craft-platform, and drops core-graphics2 and block. memoized_sections_land_where_direct_ones_do draws the whole panel with nothing selected and compares where its text lands with the sections in their MemoViews and shown directly. It fails at the old pin. --- Cargo.lock | 211 +++++++++--------- Cargo.toml | 76 +++---- apps/vectorcraft-web/Cargo.toml | 2 +- .../panels/properties/document_sections.rs | 121 +++++++--- xtask/src/pdf_deps.rs | 2 +- 5 files changed, 240 insertions(+), 172 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3cb674e4ae..3655542d18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -626,12 +626,6 @@ dependencies = [ "cpufeatures 0.3.1", ] -[[package]] -name = "block" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" - [[package]] name = "block-buffer" version = "0.10.4" @@ -725,6 +719,17 @@ dependencies = [ "brotli-decompressor 5.0.3", ] +[[package]] +name = "brotli" +version = "9.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9071f285ed78f04f37d675abaaef5de7689e2f30a216c8dc6795465d81910a13" +dependencies = [ + "alloc-no-stdlib 3.0.0", + "alloc-stdlib 0.3.0", + "brotli-decompressor 6.3.2", +] + [[package]] name = "brotli-decompressor" version = "5.0.3" @@ -1184,19 +1189,6 @@ dependencies = [ "libc", ] -[[package]] -name = "core-graphics2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b65858d95344d2711161cd92196732f67d6c5fea238cf12f994584828731a5c" -dependencies = [ - "bitflags 2.13.2", - "block", - "cfg-if", - "core-foundation 0.10.1", - "libc", -] - [[package]] name = "core_detect" version = "1.0.0" @@ -1239,7 +1231,7 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-automation", "craft-behavior", @@ -1280,7 +1272,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "crc32fast", "flate2", @@ -1291,18 +1283,19 @@ dependencies = [ [[package]] name = "craft-appkit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "block2 0.6.2", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "objc2-core-graphics", "objc2-foundation 0.3.2", ] [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "rustix 1.1.6", ] @@ -1310,7 +1303,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1335,7 +1328,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1353,7 +1346,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-docpath", @@ -1371,7 +1364,7 @@ dependencies = [ [[package]] name = "craft-cdr" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "crc32fast", "flate2", @@ -1380,7 +1373,7 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "egui", ] @@ -1388,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "md-5", "rayon", @@ -1397,12 +1390,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-cms", @@ -1422,7 +1415,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-control-protocol", "craft-platform", @@ -1433,7 +1426,7 @@ dependencies = [ [[package]] name = "craft-control-protocol" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "getrandom 0.3.4", "serde_json", @@ -1443,7 +1436,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "rayon", ] @@ -1451,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "block2 0.6.2", "craft-appkit", @@ -1477,7 +1470,7 @@ dependencies = [ [[package]] name = "craft-doc" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "blake3", "craft-ecproj-format", @@ -1493,7 +1486,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "serde", ] @@ -1501,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1520,7 +1513,7 @@ dependencies = [ [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-codepage", "encoding_rs", @@ -1532,7 +1525,7 @@ dependencies = [ [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "serde", "serde_json", @@ -1542,12 +1535,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1562,7 +1555,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1581,7 +1574,7 @@ dependencies = [ [[package]] name = "craft-font-os-windows" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "windows-registry", "windows-sys 0.61.2", @@ -1590,7 +1583,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "cap-primitives", "craft-atomic", @@ -1613,12 +1606,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "gif", ] @@ -1626,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "flate2", ] @@ -1634,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1647,8 +1640,10 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ + "brotli 9.1.3", + "brotli-decompressor 6.3.2", "chrono", "fixed_decimal", "icu_calendar", @@ -1675,7 +1670,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-dds", "craft-jpeg", @@ -1702,7 +1697,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1720,7 +1715,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "thiserror 2.0.21", ] @@ -1728,7 +1723,7 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "brotli-decompressor 5.0.3", "jixel", @@ -1739,7 +1734,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-host", "craft-i18n", @@ -1754,7 +1749,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-i18n", @@ -1768,7 +1763,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -1786,7 +1781,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1798,7 +1793,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "encoding_rs", "image", @@ -1809,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "chrono", "craft-codepage", @@ -1819,7 +1814,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-keymap", @@ -1835,7 +1830,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "flate2", "serde", @@ -1846,7 +1841,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1858,12 +1853,12 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "async-channel", "async-io", "async-process", - "core-graphics2", + "craft-appkit", "craft-atomic", "craft-docpath", "craft-host", @@ -1873,6 +1868,8 @@ dependencies = [ "js-sys", "log", "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", "rfd", "serde", "serde_json", @@ -1889,7 +1886,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1898,7 +1895,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -1922,7 +1919,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1933,7 +1930,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-eps", "flate2", @@ -1947,7 +1944,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "encoding_rs", "flate2", @@ -1958,7 +1955,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "dispatch2", "egui", @@ -1971,7 +1968,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1990,7 +1987,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-atomic", "craft-host", @@ -2007,7 +2004,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "fax", "hayro-ccitt", @@ -2018,7 +2015,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2039,7 +2036,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-keymap", @@ -2051,7 +2048,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2076,7 +2073,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2091,7 +2088,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-atomic", "craft-behavior", @@ -2106,7 +2103,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "serde", "thiserror 2.0.21", @@ -2116,7 +2113,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "serde", "thiserror 2.0.21", @@ -2125,7 +2122,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-keymap", @@ -2140,12 +2137,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2159,7 +2156,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-i18n", @@ -2175,7 +2172,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "accesskit", "craft-behavior", @@ -2213,7 +2210,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2224,7 +2221,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -2242,7 +2239,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -2263,7 +2260,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -2284,7 +2281,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-behavior", "craft-host", @@ -2303,7 +2300,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "base64 0.22.1", "chrono", @@ -2335,7 +2332,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "flate2", "serde", @@ -2346,7 +2343,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2356,7 +2353,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "js-sys", "serde_json", @@ -2367,7 +2364,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "winsafe", ] @@ -2375,7 +2372,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "craft-appkit", "craft-atomic", @@ -2407,7 +2404,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3762,16 +3759,16 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ - "brotli", + "brotli 8.0.4", "hayro-postscript", ] [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3789,7 +3786,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3807,12 +3804,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "flate2", "hayro-ccitt", @@ -4795,7 +4792,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4952,7 +4949,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=186a229c8da8db5916f8a863dfd894f1879af735#186a229c8da8db5916f8a863dfd894f1879af735" +source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -10067,7 +10064,7 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=0dfcec0eb62fda5904137a63a6dd0c3d83295f45#0dfcec0eb62fda5904137a63a6dd0c3d83295f45" dependencies = [ "ahash", "android-activity", diff --git a/Cargo.toml b/Cargo.toml index 7ad3e4cfeb..f32179e124 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,49 +10,49 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # 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 = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # 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 = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # 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 = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -192,13 +192,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "186a229c8da8db5916f8a863dfd894f1879af735" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } @@ -210,4 +210,4 @@ egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed1817 egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +winit = { git = "https://github.com/storytold/winit.git", rev = "0dfcec0eb62fda5904137a63a6dd0c3d83295f45" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index ce4d1d3d44..98a00a7ca6 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 = "186a229c8da8db5916f8a863dfd894f1879af735", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/crates/ui-egui/src/panels/properties/document_sections.rs b/crates/ui-egui/src/panels/properties/document_sections.rs index cff44b4f44..ca142a9172 100644 --- a/crates/ui-egui/src/panels/properties/document_sections.rs +++ b/crates/ui-egui/src/panels/properties/document_sections.rs @@ -24,35 +24,27 @@ use crate::panels::transform; /// Appearance fill and stroke, the view's rulers, grids, guides and snapping, the keyboard /// increment and Scale Strokes & Effects, and Quick Actions. /// -/// The body of every section but Appearance shows in a `MemoView` keyed on what it reads, so a -/// frame that changes none of it replays the body. What a body picks comes back through an `Outbox` -/// and runs after its section. +/// Every section but Appearance shows in a `MemoView` keyed on what it reads, header and body together, +/// so a frame that changes none of it replays the whole section. What a section picks comes back +/// through an `Outbox` and runs after it. pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { let lang = crate::i18n::current(); let units = app.session.general_unit(); let unit = Unit::ALL.iter().position(|u| *u == units).unwrap_or(usize::MAX); let artboards = app.session.active().map_or(0, |d| d.doc.artboards.len()); let mut picked_units = Vec::new(); - super::section(tl!("Document")).show(ui, |ui, _| { - let document = DocumentProps { unit, units, artboards, lang, picked: Outbox::new(&mut picked_units) }; - let _ = MemoView::new("properties-document", document, document_body).show(ui); - }); + let document = DocumentProps { unit, units, artboards, lang, picked: Outbox::new(&mut picked_units) }; + memoized("properties-document", document, document_section, ui); if let Some(u) = picked_units.pop() { app.run("document.setUnits", json!({ "units": u.label() })).ok(); } super::section(tl!("Appearance")).show(ui, |ui, _| super::appearance_section::fill_stroke_rows(app, ui)); - super::section(tl!("Rulers & Grids")).show(ui, |ui, _| { - let _ = MemoView::new("properties-rulers", Language { lang }, rulers_body).show(ui); - }); - super::section(tl!("Guides")).show(ui, |ui, _| { - let _ = MemoView::new("properties-guides", Language { lang }, guides_body).show(ui); - }); + memoized("properties-rulers", Language { lang }, rulers_section, ui); + memoized("properties-guides", Language { lang }, guides_section, ui); let mut snaps = Vec::new(); let (point, grid) = (app.ui.view.snap_to_point, app.ui.view.snap_to_grid); - super::section(tl!("Snap Options")).show(ui, |ui, _| { - let snap = SnapProps { point, grid, lang, picked: Outbox::new(&mut snaps) }; - let _ = MemoView::new("properties-snap", snap, snap_body).show(ui); - }); + let snap = SnapProps { point, grid, lang, picked: Outbox::new(&mut snaps) }; + memoized("properties-snap", snap, snap_section, ui); for command in snaps { app.run(command, json!({})).ok(); } @@ -62,11 +54,9 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { let unit = Unit::ALL.iter().position(|u| *u == general).unwrap_or(usize::MAX); let (increment, scale) = (app.session.prefs.keyboard_increment, app.session.prefs.scale_strokes); let (bare_points, lengths) = (app.session.prefs.numbers_without_units_are_points, crate::canvas::rulers::general_lengths(app)); - super::section(tl!("Preferences")).show(ui, |ui, _| { - let picked = Outbox::new(&mut prefs); - let preferences = PreferencesProps { increment, unit, bare_points, lengths, scale, lang, picked }; - let _ = MemoView::new("properties-preferences", preferences, preferences_body).show(ui); - }); + let picked = Outbox::new(&mut prefs); + let preferences = PreferencesProps { increment, unit, bare_points, lengths, scale, lang, picked }; + memoized("properties-preferences", preferences, preferences_section, ui); for pick in prefs { match pick { PreferencePick::Increment(event) => { @@ -79,9 +69,49 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { PreferencePick::ScaleStrokes(on) => transform::set_pref(app, "scaleStrokes", on), } } - super::section(tl!("Quick Actions")).show(ui, |ui, _| { - let _ = MemoView::new("properties-quick-actions", Language { lang }, quick_actions_body).show(ui); - }); + memoized("properties-quick-actions", Language { lang }, quick_actions_section, ui); +} + +/// Shows `section` in a `MemoView` with `id`, keyed on `props`. Tests can show it directly instead, to compare where +/// the memoized sections land with where direct ones do. +fn memoized(id: &'static str, props: P, section: fn(&mut P, &mut Ui), ui: &mut Ui) { + #[cfg(test)] + if tests::shown_directly() { + let mut props = props; + section(&mut props, ui); + return; + } + let _ = MemoView::new(id, props, section).show(ui); +} + +/// The Document section: its header and [`document_body`]. +fn document_section(p: &mut DocumentProps<'_>, ui: &mut Ui) { + super::section(tl!("Document")).show(ui, |ui, _| document_body(p, ui)); +} + +/// The Rulers & Grids section: its header and [`rulers_body`]. +fn rulers_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Rulers & Grids")).show(ui, |ui, _| rulers_body(p, ui)); +} + +/// The Guides section: its header and [`guides_body`]. +fn guides_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Guides")).show(ui, |ui, _| guides_body(p, ui)); +} + +/// The Snap Options section: its header and [`snap_body`]. +fn snap_section(p: &mut SnapProps<'_>, ui: &mut Ui) { + super::section(tl!("Snap Options")).show(ui, |ui, _| snap_body(p, ui)); +} + +/// The Preferences section: its header and [`preferences_body`]. +fn preferences_section(p: &mut PreferencesProps<'_>, ui: &mut Ui) { + super::section(tl!("Preferences")).show(ui, |ui, _| preferences_body(p, ui)); +} + +/// The Quick Actions section: its header and [`quick_actions_body`]. +fn quick_actions_section(p: &mut Language, ui: &mut Ui) { + super::section(tl!("Quick Actions")).show(ui, |ui, _| quick_actions_body(p, ui)); } /// What a section that reads only command states reads besides them: the interface language of its labels. @@ -248,6 +278,47 @@ mod tests { SECTION_RUNS.with(std::cell::Cell::get) } + thread_local! { + /// This thread shows the memoized sections directly, outside their `MemoView`s. + static DIRECT: std::cell::Cell = const { std::cell::Cell::new(false) }; + } + + pub(super) fn shown_directly() -> bool { + DIRECT.with(std::cell::Cell::get) + } + + /// The runs of text the whole Properties panel paints with nothing selected, after idle frames that replay the + /// memoized sections, with the sections shown in their `MemoView`s or, with `direct`, directly. + fn panel_texts(direct: bool) -> Vec<(String, egui::Rect)> { + DIRECT.with(|d| d.set(direct)); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let mut panel = Panel::new(app, super::super::show); + panel.frame(); + let before = runs(); + panel.frame(); + panel.frame(); + if !direct { + assert_eq!(runs(), before, "the last frames replay the memoized sections"); + } + let texts = panel.texts(); + DIRECT.with(|d| d.set(false)); + texts + } + + /// Whole sections shown in `MemoView`s, header and body, land where the same sections shown directly do under the + /// app's `SectionRhythm::Spaced` and `QuietHeader::Heads`: the Document section under the panel's heading draws no + /// rule above it, and each later section keeps the stack's gap. + #[test] + fn memoized_sections_land_where_direct_ones_do() { + let direct = panel_texts(true); + for heading in ["Document", "Rulers & Grids", "Guides", "Snap Options", "Preferences", "Quick Actions", "Snap to Point"] { + assert!(direct.iter().any(|(text, _)| text == heading), "the panel shows {heading:?}: {direct:?}"); + } + let memoized = panel_texts(false); + assert_eq!(memoized, direct, "memoized sections land where direct ones do"); + } + #[test] fn canceling_the_units_popup_leaves_the_document_unchanged() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index f4f02f8627..d3e0f6e1df 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 = "186a229c8da8db5916f8a863dfd894f1879af735"; +const REV: &str = "19805ced1eee99a0667facfc3e02ca909e7df348"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From 7a799a1bc48c16f66957032c21eb01e835e53ddc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 20:21:31 -0800 Subject: [PATCH 11/37] Properties: Document sections below the fold keep their controls A MemoView in a scroll area skips a view that is out of view, so in a Properties panel too short for every Document section, the sections below the fold registered no focus stops or accessibility nodes until the panel scrolled: Tab and a screen reader did not reach Keyboard Increment, Scale Strokes & Effects or Snap to Grid. Each section's MemoView now shows out of view too, as the sections did before they were memoized. sections_below_the_fold_keep_their_controls draws the panel 200 pt high and finds those controls below it. It fails without shown_out_of_view. --- .../panels/properties/document_sections.rs | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/document_sections.rs b/crates/ui-egui/src/panels/properties/document_sections.rs index ca142a9172..d702cbf899 100644 --- a/crates/ui-egui/src/panels/properties/document_sections.rs +++ b/crates/ui-egui/src/panels/properties/document_sections.rs @@ -72,7 +72,8 @@ pub(super) fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { memoized("properties-quick-actions", Language { lang }, quick_actions_section, ui); } -/// Shows `section` in a `MemoView` with `id`, keyed on `props`. Tests can show it directly instead, to compare where +/// Shows `section` in a `MemoView` with `id`, keyed on `props`. A section scrolled out of view still runs or replays, so +/// its controls keep their focus stops and accessibility nodes. Tests can show it directly instead, to compare where /// the memoized sections land with where direct ones do. fn memoized(id: &'static str, props: P, section: fn(&mut P, &mut Ui), ui: &mut Ui) { #[cfg(test)] @@ -81,7 +82,7 @@ fn memoized(id: &'static str, props: P, section: fn(&mut P, &mut U section(&mut props, ui); return; } - let _ = MemoView::new(id, props, section).show(ui); + let _ = MemoView::new(id, props, section).shown_out_of_view().show(ui); } /// The Document section: its header and [`document_body`]. @@ -319,6 +320,22 @@ mod tests { assert_eq!(memoized, direct, "memoized sections land where direct ones do"); } + /// In a panel too short for every section, the sections below the fold still register their controls, so Tab + /// and a screen reader reach them before the panel scrolls. + #[test] + fn sections_below_the_fold_keep_their_controls() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let mut panel = Panel::new(app, super::super::show); + panel.room(egui::vec2(300.0, 200.0)); + panel.frame(); + panel.frame(); + for name in ["Keyboard Increment", "Scale Strokes & Effects", "Snap to Grid"] { + assert!(panel.shows(name), "the panel registers {name:?} below the fold"); + assert!(panel.rect(name).top() > 200.0, "{name:?} is below the fold of a 200 pt panel"); + } + } + #[test] fn canceling_the_units_popup_leaves_the_document_unchanged() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); From d9609ce53ca8085c8013de84779852e2beeef5e7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 20:45:12 -0800 Subject: [PATCH 12/37] Dependencies: pin craft-libs 5190e08ab, current main craft-libs main took eight more pull requests after 19805ced1e (raster 3D, mesh ops, SVG group ancestry, image dimensions, footer bar wrapping). Every craft-libs rev, the craft-web-api line and the rev `cargo xtask pdf-deps` checks move to it. Its egui and winit revs are the ones VectorCraft already pins, and Cargo.lock changes only the craft-libs source lines. --- Cargo.lock | 170 ++++++++++++++++---------------- Cargo.toml | 74 +++++++------- apps/vectorcraft-web/Cargo.toml | 2 +- xtask/src/pdf_deps.rs | 2 +- 4 files changed, 124 insertions(+), 124 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1e38ca2a4f..fbe934ae2c 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "egui", ] @@ -1381,7 +1381,7 @@ dependencies = [ [[package]] name = "craft-cms" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "rayon", ] @@ -1444,7 +1444,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "serde", ] @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "gif", ] @@ -1619,7 +1619,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", ] @@ -1627,7 +1627,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" 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=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "chrono", "craft-codepage", @@ -1822,7 +1822,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-keymap", @@ -1838,7 +1838,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", "serde", @@ -1849,7 +1849,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1861,7 +1861,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "async-channel", "async-io", @@ -1894,7 +1894,7 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "kurbo 0.13.1", "thiserror 2.0.21", @@ -1903,7 +1903,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -1927,7 +1927,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1938,7 +1938,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-eps", "flate2", @@ -1952,7 +1952,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "encoding_rs", "flate2", @@ -1963,7 +1963,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "dispatch2", "egui", @@ -1976,7 +1976,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "base64 0.23.1", "craft-behavior", @@ -1995,7 +1995,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-atomic", "craft-host", @@ -2012,7 +2012,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "fax", "hayro-ccitt", @@ -2023,7 +2023,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2044,7 +2044,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2056,7 +2056,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2081,7 +2081,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2096,7 +2096,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-atomic", "craft-behavior", @@ -2111,7 +2111,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2121,7 +2121,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "serde", "thiserror 2.0.21", @@ -2130,7 +2130,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-keymap", @@ -2145,12 +2145,12 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2164,7 +2164,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-i18n", @@ -2180,7 +2180,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "accesskit", "craft-behavior", @@ -2218,7 +2218,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2229,7 +2229,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2247,7 +2247,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2268,7 +2268,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2289,7 +2289,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-behavior", "craft-host", @@ -2308,7 +2308,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "base64 0.22.1", "chrono", @@ -2340,7 +2340,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", "serde", @@ -2351,7 +2351,7 @@ dependencies = [ [[package]] name = "craft-wayland" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "raw-window-handle", "wayland-backend", @@ -2361,7 +2361,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "js-sys", "serde_json", @@ -2372,7 +2372,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "winsafe", ] @@ -2380,7 +2380,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "craft-appkit", "craft-atomic", @@ -2412,7 +2412,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "quick-xml 0.41.0", "serde", @@ -3767,7 +3767,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "brotli 8.0.4", "hayro-postscript", @@ -3776,7 +3776,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3794,7 +3794,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3812,12 +3812,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "flate2", "hayro-ccitt", @@ -4800,7 +4800,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "base64 0.22.1", "bumpalo", @@ -4957,7 +4957,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=19805ced1eee99a0667facfc3e02ca909e7df348#19805ced1eee99a0667facfc3e02ca909e7df348" +source = "git+https://github.com/storytold/craft-libs?rev=5190e08ab8ef93c0abdfce2790a34cc0c377b3b6#5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index 4ec887ba19..0c31608537 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,49 +10,49 @@ license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", default-features = false, features = ["interpret", "write"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", default-features = false, features = ["interpret", "write"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # Language packs: the Craft apps' shared font store installs them (#4936). -craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # 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 = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # `.pcraft` documents: their manifest, full-size composite, preview, layer pixels and ICC profile. -craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", features = ["pcraft-pixels"] } +craft-doc = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", features = ["pcraft-pixels"] } # Native Affinity documents (craft-libs#914). -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). -craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348", default-features = false, features = ["read", "write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", default-features = false, features = ["read", "write"] } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # 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 = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # 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 = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } # Nightly profile isolation, launch protocol, and security fence. craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # internal @@ -194,13 +194,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "19805ced1eee99a0667facfc3e02ca909e7df348" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 98a00a7ca6..e72a7f26ed 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 = "19805ced1eee99a0667facfc3e02ca909e7df348", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6", version = "0.1.0" } wasm-bindgen = "0.2" serde_json = { workspace = true } diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index d3e0f6e1df..668abfea2e 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 = "19805ced1eee99a0667facfc3e02ca909e7df348"; +const REV: &str = "5190e08ab8ef93c0abdfce2790a34cc0c377b3b6"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV), From dcdbd3cc1b3f7747e63d1ae96d6338905074f4ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 02:38:02 -0800 Subject: [PATCH 13/37] CI: declare the files each crate reads in other crates, for test selection Test selection in the shared gate (`select-tests`) runs the tests of the crates a change reaches. A crate that compiles or reads another crate's files lists them under `[package.metadata.craft]` in its Cargo.toml: - vectorcraft-plugins sets `reads-every-member = true`, because `tests/grant_sites.rs` reads the sources of every crate. - vectorcraft-cli, vectorcraft-affinity, vectorcraft-engine, vectorcraft-mcp, vectorcraft-ui-egui and xtask list the files they compile through `#[path]` or read with `include_str!`/`include_bytes!` or from `CARGO_MANIFEST_DIR`. Cargo ignores this table. Only the gate's selection step reads it, and that step fails when a read is missing from it. --- apps/vectorcraft-cli/Cargo.toml | 11 +++++++++++ crates/affinity/Cargo.toml | 4 ++++ crates/engine/Cargo.toml | 11 +++++++++++ crates/mcp/Cargo.toml | 4 ++++ crates/plugins/Cargo.toml | 4 ++++ crates/ui-egui/Cargo.toml | 4 ++++ xtask/Cargo.toml | 4 ++++ 7 files changed, 42 insertions(+) diff --git a/apps/vectorcraft-cli/Cargo.toml b/apps/vectorcraft-cli/Cargo.toml index 376f431903..25cffe599e 100644 --- a/apps/vectorcraft-cli/Cargo.toml +++ b/apps/vectorcraft-cli/Cargo.toml @@ -48,3 +48,14 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std" tempfile = "3" vectorcraft-testkit = { workspace = true } serde_json = { workspace = true } + +# The files of other crates that this crate compiles or its tests read, for CI's test selection. +[package.metadata.craft] +reads = [ + "apps/vectorcraft/src/mac_fonts.rs", + "apps/vectorcraft/src/prefs_dir.rs", + "apps/vectorcraft/src/profile.rs", + "apps/vectorcraft/src/system_fonts.rs", + "apps/vectorcraft/src/windows_cores.rs", + "crates/plugins/tests/fixtures/desaturate.wasm", +] diff --git a/crates/affinity/Cargo.toml b/crates/affinity/Cargo.toml index 92977884cf..80876c409a 100644 --- a/crates/affinity/Cargo.toml +++ b/crates/affinity/Cargo.toml @@ -24,3 +24,7 @@ craft-image-codecs = { workspace = true } # tests/it's `import_limits`, `outline_limits` and `text` modules need `synth`, also when this crate # is tested without vectorcraft-engine (`cargo xtask ci shard`). vectorcraft-affinity = { path = ".", features = ["synth"] } + +# The files of other crates that this crate's tests compile or read, for CI's test selection. +[package.metadata.craft] +reads = ["xtask/affinity-corpus.sha256", "xtask/src/sha256.rs"] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 027ae10251..1e74ecb5d2 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -143,3 +143,14 @@ ruzstd = { workspace = true } vectorcraft-js = { workspace = true } # A bundled font's own glyph boxes, for the glyph bounds tests. skrifa = { workspace = true } + +# The files of other crates that this crate compiles or its tests read, for CI's test selection. +[package.metadata.craft] +reads = [ + "crates/affinity/tests/support/corpus.rs", + "crates/affinity/tests/support/text_fixture.rs", + "crates/apischema/src/conformance.rs", + "crates/plugins/tests/fixtures/desaturate.wasm", + "xtask/affinity-corpus.sha256", + "xtask/src/sha256.rs", +] diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 8aa221b4a6..b5544b958c 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -33,3 +33,7 @@ craft-image-codecs = { workspace = true } vectorcraft-testkit = { workspace = true } proptest = { workspace = true } socket2 = { workspace = true } + +# The files of other crates that this crate's tests compile, for CI's test selection. +[package.metadata.craft] +reads = ["crates/apischema/src/conformance.rs"] diff --git a/crates/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 621f5e79bc..aecb0bd533 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -44,3 +44,7 @@ vectorcraft-plugins = { path = ".", features = ["test-steady"] } [features] # `vectorcraft_plugins::steady` for other crates' tests (dev-dependencies only). test-steady = [] + +# For CI's test selection: `tests/grant_sites.rs` reads the sources of every crate. +[package.metadata.craft] +reads-every-member = true diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 95487e91c0..d0bb345b44 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -109,3 +109,7 @@ wat = { workspace = true } [build-dependencies] serde_json = { workspace = true } 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"] diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 6d935ae8fd..7a5c83e8b5 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -10,3 +10,7 @@ workspace = true [dependencies] serde_json = { workspace = true } + +# The files of other crates that this crate compiles, for CI's test selection. +[package.metadata.craft] +reads = ["crates/text/build/web_fonts.rs"] From f553ddfa67646ffd711f89eb783b88c15aa3b841 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:12:48 -0800 Subject: [PATCH 14/37] xtask: test-lint fails on weak tests in the lines a change touches `cargo xtask test-lint` reads the Rust files changed since a base and fails on tests that a wrong result can pass: `.all()` with no length or emptiness check, only is_ok/is_some/non-empty checks, `assert_eq!(x, x)`, a process test that checks only the exit status, no assertion and no asserting helper, a silent early return on a value from the code under test, `#[ignore]` without a reason, an environment variable that no CI leg sets, `thread::sleep` in test code, and test code that reads Rust source outside the listed source audits. Only hits on changed lines, or in a test with a changed line for the rules about a whole test, fail it; older hits in the same files are counted. The base is --base or TEST_LINT_BASE, the first parent of the checked-out commit in CI (a shallow checkout fetches it), else the merge base with upstream/main or origin/main. `// test-lint: allow ` exempts a line. `--all` lists every hit by crate and rule and does not fail. `cargo xtask ci` runs it after cursors, so it runs in the checks shard. --- docs/development.md | 4 + xtask/src/main.rs | 9 +- xtask/src/test_lint.rs | 2574 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 2586 insertions(+), 1 deletion(-) create mode 100644 xtask/src/test_lint.rs diff --git a/docs/development.md b/docs/development.md index 5a1b6efd95..26058129e7 100644 --- a/docs/development.md +++ b/docs/development.md @@ -349,6 +349,10 @@ The app decides which cursors exist; whoever draws them works from the list. For `cargo xtask brands` (part of `cargo xtask ci`) fails when user-visible text names another vendor's products or company: string literals in Rust sources (command labels and params docs, menus, panels, MCP tool definitions), `Cargo.toml` descriptions and packaging files. Comments, test files and `#[cfg(test)]` modules are not checked. Say "the reference app" or name the feature itself. A line that must keep an old name, such as an alias that files or preferences from earlier versions still use, or a name another project defines, such as a shared MIME type, carries a `brand-ok` comment. In the Linux desktop entry, whose comments take whole lines, the comment goes on the `#` line just above it; `MARK_ABOVE` in `xtask/src/brands.rs` lists the files that accept a mark there. +## Test lint + +`cargo xtask test-lint` (part of `cargo xtask ci`) fails on tests that a wrong result can pass, in the lines and tests changed since a base: `assert!(….all(…))` with no length or emptiness check, a test whose only checks are `is_ok`, `is_some` or `!is_empty`, `assert_eq!(x, x)`, 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, `#[ignore]` without a reason, an environment variable that no CI leg sets, `thread::sleep` in test code, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. 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. + ## Tests - `cargo xtask test` runs the workspace's unit and integration tests with diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 08a55df09a..f48f088aa8 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -18,6 +18,7 @@ mod sha256; mod shards; mod stats; mod test262; +mod test_lint; mod ui_commands; mod version; mod web_fonts; @@ -32,6 +33,10 @@ commands: assets check that every icon/image/font/asset is attributed in ASSETS.md brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) + test-lint [--base ] [--all] + fail on weak tests (unguarded .all(), only is_ok/is_some checks, no assertion, early + returns, unset env gates, sleeps...) in the lines changed since the base + (xtask/src/test_lint.rs); --all lists every hit by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) ui-commands regenerate crates/mcp/src/ui_catalog.rs from desktop UI_COMMANDS; --check fails on drift @@ -39,7 +44,7 @@ commands: layers enforce the crate dependency layering (plan/architecture.md §3) wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates, the web app and its plug-in worker test the workspace tests (cargo nextest when installed, else cargo test), then the doctests - ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), ui-commands --check, layers, wasm (stops at first failure) + ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure) ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs the tests and doctests of its crates, the last shard the other steps ci warm build what every shard builds, without running it (fills the gate's cache); with @@ -74,6 +79,7 @@ fn main() -> ExitCode { Some("assets") => assets::run(&root()), Some("brands") => brands::run(&root()), Some("cursors") => cursors::run(&root()), + Some("test-lint") => test_lint::run(&root(), &rest), Some("i18n-report") => cmd_i18n_report(), Some("ui-commands") => ui_commands::run(&root(), rest.contains(&"--check")), Some("layers") => cmd_layers(), @@ -515,6 +521,7 @@ fn ci_steps() -> Vec { ("assets", Box::new(|| assets::run(&root()))), ("brands", Box::new(|| brands::run(&root()))), ("cursors", Box::new(|| cursors::run(&root()))), + ("test-lint", Box::new(|| test_lint::run(&root(), &[]))), ("i18n-report", Box::new(cmd_ci_i18n_report)), ("ui-commands", Box::new(|| ui_commands::run(&root(), true))), ("layers", Box::new(cmd_layers)), diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs new file mode 100644 index 0000000000..8664403997 --- /dev/null +++ b/xtask/src/test_lint.rs @@ -0,0 +1,2574 @@ +//! `cargo xtask test-lint`: tests that a wrong result can pass, in the tests a change touches. +//! +//! Rules, checked in `#[test]` functions (and `#[tokio::test]`, `#[test_case]`, +//! `#[wasm_bindgen_test]`, and `#[test]` inside `proptest!`): +//! * `all-unguarded`: `assert!(….all(…))` in a test that neither checks a length, emptiness, +//! count, first item or `any` in an assertion's condition or compared operands, nor takes a +//! first item by indexing, unwrapping or a panicking `let … else`: `.all()` is true for an empty +//! collection (negated `.all(…)`, including `== false`, and predicates saying that no item +//! matches, with whole negations or `!=` comparisons joined only by `&&`, are left out). An earlier +//! `assert_eq!`, `debug_assert_eq!` or `prop_assert_eq!` comparing a plain local receiver +//! (optionally borrowed or viewed through `.as_slice()` or `[..]`) with a non-empty array +//! literal or `vec![…]` guards only that receiver. Non-empty array literals and plain local +//! names bound to them in the test, optionally through `.map(…)`, are also left out. Empty arrays +//! still count. A change anywhere in the test counts as a change to the hit; +//! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the +//! test calls no asserting helper; +//! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that +//! expression calls nothing with arguments (two calls with arguments check determinism); +//! * `exit-status-only`: a test that runs a process and checks only its exit status, reading no +//! output, with a status check in any condition or compared operand of a standard assertion; +//! * `no-assertion`: no assertion macro, `panic!`, `unwrap_err`, `expect_err` or asserting helper, +//! and no `#[should_panic]`; +//! * `early-return`: a silent bare `return` before the end of the test whose guard tests a value +//! from the code under test. Left out: a return after an assertion in its block, one whose +//! statement or line has a comment or a printed note saying why, and guards on files, fonts, +//! corpora, environment variables, the platform or a child process; +//! * `ignore-without-reason`: `#[ignore]` with no `= "reason"`; +//! * `env-gate-unset`: `env::var("NAME")` in a test where no CI workflow, the shared gate or the +//! file itself sets `NAME`; workflow mapping keys and `NAME=` assignments count, but comments +//! and variable reads do not; +//! * `sleep`: `thread::sleep` in test code; +//! * `reads-source`: test code that reads Rust source (`include_str!` of a `.rs` file, or a walk +//! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]. +//! +//! Test code is a test file (`tests.rs`, `tests_*.rs`, `*_tests.rs`, a file in a `tests` or +//! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]`, or a test function. +//! +//! An asserting helper is a function or macro in the crate's test code (or in `crates/testkit`) +//! that asserts, panics or calls one that does, or a call whose name starts with `assert`, +//! `check`, `verify`, `ensure` or `expect_`. +//! +//! `// test-lint: allow ` exempts the line it is on and the line below it; for the +//! rules about a whole test it can be on any line from the line above the test attribute to the +//! `fn` line. An allow without a reason exempts nothing. +//! +//! `cargo xtask test-lint` fails on the hits in the lines and tests changed since a base: `--base +//! ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge +//! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as +//! 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::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::path::Path; +use std::process::Command; + +/// Test files that read Rust source on purpose: they audit the source tree. +pub const SOURCE_AUDITS: &[&str] = &[ + "crates/plugins/tests/grant_sites.rs", + "crates/ui-egui/src/i18n/tests.rs", + "crates/ui-egui/src/icons.rs", + "crates/eps/src/import/tests_generators.rs", +]; + +/// Variables the shared gate workflow and its setup action set on every leg, besides those named +/// in `.github/workflows/*.yml`. +const SHARED_GATE_ENV: &[&str] = + &["CRAFT_FONTS_DIR", "CRAFT_FONTS_REQUIRED", "GATE_SHARD", "GATE_SHARDS", "NEXTEST_PARTITION", "NEXTEST_ARCHIVE_FILE"]; + +/// Variables the runner, the operating system or cargo set. +const SYSTEM_ENV: &[&str] = &[ + "HOME", + "PATH", + "USER", + "USERNAME", + "LOGNAME", + "TMPDIR", + "TEMP", + "TMP", + "APPDATA", + "LOCALAPPDATA", + "USERPROFILE", + "PROGRAMDATA", + "PROGRAMFILES", + "WINDIR", + "SYSTEMROOT", + "CI", + "LANG", + "SHELL", + "PWD", + "OUT_DIR", +]; +const SYSTEM_ENV_PREFIXES: &[&str] = &["CARGO_", "NEXTEST", "RUST", "GITHUB_", "RUNNER_", "XDG_"]; + +/// Larger source files are refused rather than read. +const MAX_FILE: u64 = 16 << 20; + +/// The marker of an exemption comment. +const ALLOW: &str = "test-lint: allow "; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Rule { + AllUnguarded, + OnlyWeak, + SelfCompare, + ExitStatusOnly, + NoAssertion, + EarlyReturn, + IgnoreWithoutReason, + EnvGateUnset, + Sleep, + ReadsSource, +} + +impl Rule { + pub const ALL: [Rule; 10] = [ + Rule::AllUnguarded, + Rule::OnlyWeak, + Rule::SelfCompare, + Rule::ExitStatusOnly, + Rule::NoAssertion, + Rule::EarlyReturn, + Rule::IgnoreWithoutReason, + Rule::EnvGateUnset, + Rule::Sleep, + Rule::ReadsSource, + ]; + + pub fn id(self) -> &'static str { + match self { + Rule::AllUnguarded => "all-unguarded", + Rule::OnlyWeak => "only-weak", + Rule::SelfCompare => "self-compare", + Rule::ExitStatusOnly => "exit-status-only", + Rule::NoAssertion => "no-assertion", + Rule::EarlyReturn => "early-return", + Rule::IgnoreWithoutReason => "ignore-without-reason", + Rule::EnvGateUnset => "env-gate-unset", + Rule::Sleep => "sleep", + Rule::ReadsSource => "reads-source", + } + } + + fn advice(self) -> &'static str { + match self { + Rule::AllUnguarded => "also assert the expected length (or that the collection is not empty)", + Rule::OnlyWeak => "assert the value itself (assert_eq! on the result), not only that there is one", + Rule::SelfCompare => "compare with an expected value written out, or with a second, independent computation", + Rule::ExitStatusOnly => "also check the output (stdout, stderr or the files written)", + Rule::NoAssertion => "assert what the code returns or changes", + Rule::EarlyReturn => "assert the condition instead of returning, so a wrong value fails the test", + Rule::IgnoreWithoutReason => "write #[ignore = \"why\"]", + Rule::EnvGateUnset => "set the variable in a CI leg, or make the test run without it", + Rule::Sleep => "wait on a handshake (channel, barrier) or a controllable clock", + Rule::ReadsSource => "test the behavior, or add the file to SOURCE_AUDITS in xtask/src/test_lint.rs if it audits the source tree", + } + } + + fn from_id(id: &str) -> Option { + Rule::ALL.into_iter().find(|r| r.id() == id) + } +} + +/// A rule broken in a file. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Hit { + pub path: String, + /// 1-based: the line of the finding, or of `fn` for a rule about a whole test. + pub line: usize, + pub rule: Rule, + /// The test it is in; empty for test code outside a test function. + pub test: String, + pub note: String, + /// The first and last line of what the hit covers: the test, from its attribute to its closing + /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for + /// `self-compare`, else `line`. This span controls changed-line detection; `all-unguarded` + /// and `self-compare` exemptions still apply only near `line`. + pub first: usize, + pub last: usize, +} + +impl Hit { + fn show(&self) -> String { + let test = if self.test.is_empty() { String::new() } else { format!(" `{}`", self.test) }; + format!("{}:{}: [{}]{test}: {}", self.path, self.line, self.rule.id(), self.note) + } +} + +/// What the rules need beyond the file: asserting helper names by crate and the variables CI sets. +pub struct Ctx { + pub helpers: HashMap>, + pub ci_env: HashSet, +} + +pub fn run(root: &Path, args: &[&str]) -> Result<(), String> { + let opts = Options::parse(args)?; + let repo = crate::repo_files(root)?; + let ci_env = ci_env(root, &repo)?; + let files: Vec = repo.into_iter().filter(|p| is_scanned(p)).collect(); + if opts.all { + let sources = read_all(root, &files)?; + let ctx = Ctx { helpers: asserting_helpers(&sources), ci_env }; + let hits: Vec = sources.iter().flat_map(|(p, s)| lint_file(p, s, &ctx)).collect(); + print!("{}", report(&hits, sources.len())); + return Ok(()); + } + let base = resolve_base(root, opts.base)?; + let changed = changed_lines(root, &base)?; + let changed: BTreeMap>> = changed.into_iter().filter(|(p, _)| is_scanned(p)).collect(); + 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 ctx = Ctx { helpers: asserting_helpers(&read_all(root, &helper_files)?), ci_env }; + let present: Vec = changed.keys().filter(|p| root.join(p).is_file()).cloned().collect(); + let (mut counted, mut older) = (vec![], 0usize); + for (path, src) in read_all(root, &present)? { + for hit in lint_file(&path, &src, &ctx) { + if touches(&hit, changed.get(&path).and_then(Option::as_ref)) { + counted.push(hit); + } else { + older += 1; + } + } + } + finish(&counted, older, present.len(), &base) +} + +/// The command line: `--all`, `--base `. +#[derive(Debug, Default, PartialEq)] +struct Options { + all: bool, + base: Option, +} + +impl Options { + fn parse(args: &[&str]) -> Result { + let mut opts = Options::default(); + let mut it = args.iter(); + while let Some(&arg) = it.next() { + match arg { + "--all" if !opts.all => opts.all = true, + "--base" if opts.base.is_none() => match it.next() { + Some(rev) if !rev.is_empty() && !rev.starts_with('-') => opts.base = Some((*rev).to_owned()), + _ => return Err("test-lint: --base takes a revision".into()), + }, + _ => return Err(format!("test-lint: unexpected argument `{arg}` (usage: cargo xtask test-lint [--all] [--base ])")), + } + } + if opts.all && opts.base.is_some() { + return Err("test-lint: --all checks every file and takes no --base".into()); + } + Ok(opts) + } +} + +fn finish(counted: &[Hit], older: usize, files: usize, base: &str) -> Result<(), String> { + let older = if older == 0 { String::new() } else { format!("; {older} hit(s) on unchanged lines of those files are not counted") }; + if counted.is_empty() { + println!("test-lint: no hits in the changed lines of {files} Rust file(s) since {base}{older}"); + return Ok(()); + } + let mut out: Vec = counted.iter().map(Hit::show).collect(); + let rules: BTreeSet = counted.iter().map(|h| h.rule).collect(); + out.extend(rules.iter().map(|r| format!("{}: {}", r.id(), r.advice()))); + Err(format!( + "{} test-lint hit(s) in the lines changed since {base}{older} (exempt a line with `// {ALLOW} `):\n {}", + counted.len(), + out.join("\n ") + )) +} + +/// `--all`: counts by crate and rule, then every hit. +fn report(hits: &[Hit], files: usize) -> String { + let mut by_crate: BTreeMap> = BTreeMap::new(); + for h in hits { + *by_crate.entry(crate_of(&h.path)).or_default().entry(h.rule).or_default() += 1; + } + let mut out = format!("test-lint --all: {} hit(s) in {files} Rust file(s)\n\nby rule:\n", hits.len()); + for rule in Rule::ALL { + out += &format!(" {:<22} {}\n", rule.id(), hits.iter().filter(|h| h.rule == rule).count()); + } + out += "\nby crate:\n"; + for (krate, rules) in &by_crate { + let list: Vec = rules.iter().map(|(r, n)| format!("{} {n}", r.id())).collect(); + out += &format!(" {krate}: {}\n", list.join(", ")); + } + out += "\nhits:\n"; + for h in hits { + out += &format!(" {}\n", h.show()); + } + out +} + +/// Rust files the lint reads. +fn is_scanned(path: &str) -> bool { + path.ends_with(".rs") && ["crates/", "apps/", "xtask/"].iter().any(|d| path.starts_with(d)) +} + +/// `crates/` or `apps/` for a file in one, else its first path component. +fn crate_of(path: &str) -> String { + let parts: Vec<&str> = path.split('/').collect(); + match parts.as_slice() { + [top @ ("crates" | "apps"), name, _, ..] => format!("{top}/{name}"), + [first, ..] => (*first).to_owned(), + [] => String::new(), + } +} + +fn read_all(root: &Path, paths: &[String]) -> Result, String> { + paths + .iter() + .map(|p| { + let full = root.join(p); + let len = std::fs::metadata(&full).map_err(|e| format!("{p}: {e}"))?.len(); + if len > MAX_FILE { + return Err(format!("{p}: {len} bytes, over test-lint's limit of {MAX_FILE}")); + } + Ok((p.clone(), std::fs::read_to_string(&full).map_err(|e| format!("{p}: {e}"))?)) + }) + .collect() +} + +// ---- Git: the base and the changed lines ---- + +fn git(root: &Path, args: &[&str]) -> Result { + let out = Command::new("git").current_dir(root).args(args).output().map_err(|e| format!("git {}: {e}", args.join(" ")))?; + if !out.status.success() { + return Err(format!("git {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim())); + } + Ok(String::from_utf8_lossy(&out.stdout).trim().to_owned()) +} + +fn resolve_base(root: &Path, explicit: Option) -> Result { + if let Some(rev) = explicit.or_else(|| std::env::var("TEST_LINT_BASE").ok().filter(|v| !v.is_empty())) { + return git(root, &["rev-parse", "--verify", "--quiet", &format!("{rev}^{{commit}}")]) + .map_err(|_| format!("test-lint: base `{rev}` is not a commit")); + } + if std::env::var_os("GITHUB_ACTIONS").is_some() { + if let Ok(parent) = git(root, &["rev-parse", "--verify", "--quiet", "HEAD^1^{commit}"]) { + return Ok(parent); + } + let head = git(root, &["rev-parse", "HEAD"])?; + git(root, &["fetch", "--no-tags", "--quiet", "--depth=2", "origin", &head])?; + return git(root, &["rev-parse", "--verify", "--quiet", "HEAD^1^{commit}"]) + .map_err(|_| "test-lint: HEAD has no parent to compare with (set TEST_LINT_BASE)".into()); + } + for main in ["upstream/main", "origin/main"] { + if let Ok(base) = git(root, &["merge-base", "HEAD", main]) { + return Ok(base); + } + } + Err("test-lint: no upstream/main or origin/main to compare with; pass --base or set TEST_LINT_BASE".into()) +} + +/// The changed files since `base` with their changed lines (new numbering); `None` for a file that +/// is new or untracked. A pure deletion marks the lines before and after it, or line 1 at the top +/// of the file. +fn changed_lines(root: &Path, base: &str) -> Result>>, String> { + let diff = git( + root, + &["-c", "core.quotepath=off", "diff", "-U0", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", base, "--", "*.rs"], + )?; + let mut out = parse_diff(&diff); + for path in git(root, &["-c", "core.quotepath=off", "ls-files", "--others", "--exclude-standard", "--", "*.rs"])?.lines() { + out.insert(path.to_owned(), None); + } + Ok(out) +} + +/// The changed new-side lines in each file. A pure deletion includes its anchor and the following +/// line, or just line 1 when the anchor is 0. +fn parse_diff(diff: &str) -> BTreeMap>> { + let mut out: BTreeMap>> = BTreeMap::new(); + let mut current: Option = None; + // Inside a file's header (from `diff --git` to its first hunk), where `+++ ` names the file. + let (mut header, mut new_file) = (false, false); + for line in diff.lines() { + if line.starts_with("diff --git ") { + (header, new_file) = (true, false); + } else if header && line.starts_with("new file mode") { + new_file = true; + } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { + current = path.strip_prefix("b/").map(str::to_owned); + if let Some(p) = ¤t { + out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); + } + } else if let (Some(hunk), Some(path)) = (line.strip_prefix("@@ "), ¤t) { + header = false; + if let (Some((start, count)), Some(Some(lines))) = (hunk_range(hunk), out.get_mut(path)) { + if count == 0 { + lines.extend(start.max(1)..=start.saturating_add(1)); + } else { + lines.extend(start..start + count); + } + } + } + } + out +} + +/// `(start, count)` of the new side of a hunk header's `-a,b +c,d @@`. A pure deletion has count 0 +/// and sits between lines c and c + 1; c = 0 places it before line 1. +fn hunk_range(hunk: &str) -> Option<(usize, usize)> { + let new = hunk.split_whitespace().find(|w| w.starts_with('+'))?.trim_start_matches('+'); + match new.split_once(',') { + Some((s, c)) => Some((s.parse().ok()?, c.parse().ok()?)), + None => Some((new.parse().ok()?, 1)), + } +} + +/// Whether `hit` covers a changed line (`None`: the whole file is new). +fn touches(hit: &Hit, changed: Option<&BTreeSet>) -> bool { + changed.is_none_or(|lines| lines.range(hit.first..=hit.last).next().is_some()) +} + +// ---- What CI sets ---- + +fn ci_env(root: &Path, files: &[String]) -> Result, String> { + let mut names: HashSet = SHARED_GATE_ENV.iter().map(|s| (*s).to_owned()).collect(); + for path in files.iter().filter(|p| p.starts_with(".github/workflows/") && (p.ends_with(".yml") || p.ends_with(".yaml"))) { + let text = std::fs::read_to_string(root.join(path)).map_err(|e| format!("{path}: {e}"))?; + names.extend(upper_words(&text)); + } + Ok(names) +} + +/// Workflow mapping keys and assignments with capitalized environment variable names. +fn upper_words(text: &str) -> impl Iterator + '_ { + text.lines().flat_map(|line| { + let line = workflow_code(line); + let start = line.trim_start().strip_prefix("- ").unwrap_or(line.trim_start()).trim_start(); + let mapping = + start.split_once(':').filter(|(name, rest)| env_assignment_name(name) && (rest.is_empty() || rest.starts_with(char::is_whitespace))); + let assignments = line.match_indices('=').filter_map(move |(at, _)| { + let name = line[..at].rsplit(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')).next().unwrap_or_default(); + let from = at - name.len(); + let boundary = from == 0 || line.as_bytes().get(from - 1).is_some_and(|c| c.is_ascii_whitespace() || matches!(c, b'\'' | b'"' | b';')); + (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>'])).then(|| name.to_owned()) + }); + mapping.map(|(name, _)| name.to_owned()).into_iter().chain(assignments) + }) +} + +fn env_assignment_name(name: &str) -> bool { + name.len() > 1 + && name.starts_with(|c: char| c.is_ascii_uppercase()) + && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') +} + +/// Removes comment text outside quotes from a workflow line. +fn workflow_code(line: &str) -> &str { + let (mut quote, mut escaped) = (None, false); + for (at, c) in line.char_indices() { + if escaped { + escaped = false; + } else if c == '\\' && quote != Some('\'') { + escaped = true; + } else if quote == Some(c) { + quote = None; + } else if quote.is_none() { + match c { + '\'' | '"' => quote = Some(c), + '#' => return &line[..at], + _ => {} + } + } + } + line +} + +fn set_by_system(name: &str) -> bool { + SYSTEM_ENV.contains(&name) || SYSTEM_ENV_PREFIXES.iter().any(|p| name.starts_with(p)) +} + +// ---- Lexing ---- + +fn is_ident(c: u8) -> bool { + c.is_ascii_alphanumeric() || c == b'_' +} + +/// `src` with the text of comments and of string and character literals replaced by spaces (line +/// breaks and quotes kept), at the same byte offsets. +fn mask(src: &str) -> Vec { + mask_with(src, true) +} + +/// [`mask`], keeping comments when `comments` is false. +fn mask_with(src: &str, comments: bool) -> Vec { + mask_parts(src, comments, true) +} + +/// Blanks comments while keeping code and literal contents at the same byte offsets. +fn mask_comments(src: &str) -> Vec { + mask_parts(src, true, false) +} + +/// Blanks the selected comments and literal contents, preserving line breaks and literal quotes. +fn mask_parts(src: &str, comments: bool, literals: bool) -> Vec { + let b = src.as_bytes(); + let mut out = b.to_vec(); + let mut i = 0; + while i < b.len() { + let next = match b[i] { + b'/' if b.get(i + 1) == Some(&b'/') => { + let end = find(b, b"\n", i).unwrap_or(b.len()); + if comments { + blank(&mut out, i, end); + } + end + } + b'/' if b.get(i + 1) == Some(&b'*') => { + let end = block_comment_end(b, i); + if comments { + blank(&mut out, i, end); + } + end + } + b'"' => { + let end = string_end(b, i + 1); + if literals { + blank(&mut out, i + 1, end.saturating_sub(1)); + } + end + } + b'\'' => { + let end = after_char_or_lifetime(src, i); + if literals { + blank(&mut out, i + 1, end.saturating_sub(1).max(i + 1)); + } + end + } + c if c.is_ascii_alphabetic() || c == b'_' => after_ident(b, &mut out, i, literals), + _ => i + 1, + }; + i = next.max(i + 1); + } + out +} + +fn blank(out: &mut [u8], from: usize, to: usize) { + for c in out.iter_mut().take(to).skip(from) { + if *c != b'\n' { + *c = b' '; + } + } +} + +fn block_comment_end(b: &[u8], mut i: usize) -> usize { + let mut nest = 0usize; + while i < b.len() { + if b[i..].starts_with(b"/*") { + nest += 1; + i += 2; + } else if b[i..].starts_with(b"*/") { + nest = nest.saturating_sub(1); + i += 2; + if nest == 0 { + return i; + } + } else { + i += 1; + } + } + b.len() +} + +/// The index after the closing quote of a `"…"` literal whose body starts at `i`. +fn string_end(b: &[u8], mut i: usize) -> usize { + while i < b.len() && b[i] != b'"' { + i += if b[i] == b'\\' { 2 } else { 1 }; + } + (i + 1).min(b.len()) +} + +/// The index after a char literal (`'x'`, `'\n'`, `'\u{…}'`) at `i`, or after the quote of a +/// lifetime or label. +fn after_char_or_lifetime(src: &str, i: usize) -> usize { + let b = src.as_bytes(); + if b.get(i + 1) == Some(&b'\\') { + let close = (i + 3..b.len()).find(|&j| b[j] == b'\'').unwrap_or(b.len()); + return (close + 1).min(b.len()); + } + match src.get(i + 1..).and_then(|s| s.chars().next()) { + Some(c) if b.get(i + 1 + c.len_utf8()) == Some(&b'\'') => i + 2 + c.len_utf8(), + _ => i + 1, + } +} + +/// Skips the identifier at `start`; a raw string prefix (`r`, `br`, `cr`) also skips the raw +/// string after it and blanks its contents when `literals` is true. +fn after_ident(b: &[u8], out: &mut [u8], start: usize, literals: bool) -> usize { + let mut i = start; + while i < b.len() && is_ident(b[i]) { + i += 1; + } + if start > 0 && is_ident(b[start - 1]) { + return i; + } + let hashes = b[i..].iter().take_while(|&&h| h == b'#').count(); + if !matches!(&b[start..i], b"r" | b"br" | b"cr") || b.get(i + hashes) != Some(&b'"') { + return i; + } + let body = i + hashes + 1; + let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(b, &close, body).unwrap_or(b.len()); + if literals { + blank(out, body, end); + } + (end + close.len()).min(b.len()) +} + +fn find(hay: &[u8], needle: &[u8], from: usize) -> Option { + if needle.is_empty() || from >= hay.len() { + return None; + } + hay[from..].windows(needle.len()).position(|w| w == needle).map(|p| p + from) +} + +fn contains(hay: &[u8], needle: &[u8]) -> bool { + find(hay, needle, 0).is_some() +} + +fn skip_ws(b: &[u8], mut i: usize) -> usize { + while i < b.len() && b[i].is_ascii_whitespace() { + i += 1; + } + i +} + +/// Every start of `word` in `b[from..to]` with no identifier character on either side. +fn words(b: &[u8], word: &[u8], from: usize, to: usize) -> Vec { + let mut out = vec![]; + let mut i = from; + while let Some(at) = find(&b[..to.min(b.len())], word, i) { + let before = at.checked_sub(1).and_then(|j| b.get(j)).copied().is_some_and(is_ident); + let after = b.get(at + word.len()).copied().is_some_and(is_ident); + if !before && !after { + out.push(at); + } + i = at + 1; + } + out +} + +/// The index of the bracket closing the one at `open`. +fn matching(m: &[u8], open: usize) -> Option { + let (o, c) = match m.get(open)? { + b'(' => (b'(', b')'), + b'[' => (b'[', b']'), + b'{' => (b'{', b'}'), + _ => return None, + }; + let mut depth = 0usize; + for (j, &ch) in m.iter().enumerate().skip(open) { + if ch == o { + depth += 1; + } else if ch == c { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(j); + } + } + } + None +} + +/// The ranges of the top-level comma-separated parts of `m[from..to]`. +fn split_args(m: &[u8], from: usize, to: usize) -> Vec<(usize, usize)> { + let (mut out, mut depth, mut start) = (vec![], 0i32, from); + let mut angles = 0usize; + for (j, &ch) in m.iter().enumerate().take(to).skip(from) { + match ch { + b'(' | b'[' | b'{' => depth += 1, + b')' | b']' | b'}' => depth -= 1, + b'<' if angles > 0 || m[from..j].trim_ascii_end().ends_with(b"::") => angles += 1, + b'>' if angles > 0 => angles -= 1, + b',' if depth == 0 && angles == 0 => { + out.push((start, j)); + start = j + 1; + } + _ => {} + } + } + if m[start..to].iter().any(|c| !c.is_ascii_whitespace()) { + out.push((start, to)); + } + out +} + +/// `b` without whitespace. +fn norm(b: &[u8]) -> String { + String::from_utf8_lossy(&b.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect::>()).into_owned() +} + +/// Line starts, to turn byte offsets into 1-based lines. +struct Lines(Vec); + +impl Lines { + fn new(src: &str) -> Lines { + Lines(std::iter::once(0).chain(src.match_indices('\n').map(|(i, _)| i + 1)).collect()) + } + + fn of(&self, pos: usize) -> usize { + self.0.partition_point(|&s| s <= pos) + } +} + +// ---- Tests and calls ---- + +/// A test function: its name, the offsets of its first attribute and `fn`, and its body's braces. +#[derive(Debug)] +struct TestFn { + name: String, + /// The first attribute of the function (`#[should_panic]` can come before `#[test]`). + attr: usize, + fn_at: usize, + open: usize, + close: usize, +} + +fn is_test_attr(path: &[u8]) -> bool { + matches!(path, b"test" | b"wasm_bindgen_test" | b"test_case") || path.ends_with(b"::test") || path.ends_with(b"::test_case") +} + +/// The test functions of masked source `m`. +fn tests_in(m: &[u8]) -> Vec { + let mut out: Vec = vec![]; + let mut i = 0; + while let Some(at) = find(m, b"#[", i) { + i = at + 2; + let start = skip_ws(m, at + 2); + let end = start + m[start..].iter().take_while(|&&c| is_ident(c) || c == b':').count(); + if !is_test_attr(&m[start..end]) || !matches!(m.get(skip_ws(m, end)), Some(b']' | b'(')) { + continue; + } + let Some(t) = fn_after(m, at, end) else { continue }; + if out.iter().any(|o| o.fn_at == t.fn_at) { + continue; + } + i = t.open; + out.push(t); + } + out +} + +/// The function an attribute at `attr` (ending at `from`) belongs to. +fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { + let limit = (from + 800).min(m.len()); + let fn_at = *words(m, b"fn", from, limit).first()?; + if m[from..fn_at].iter().any(|&c| c == b'{' || c == b';') { + return None; + } + let name_start = skip_ws(m, fn_at + 2); + let name_end = name_start + m[name_start..].iter().take_while(|&&c| is_ident(c)).count(); + if name_end == name_start { + return None; + } + let open = name_end + m[name_end..].iter().position(|&c| c == b'{' || c == b';')?; + if m[open] != b'{' { + return None; + } + let close = matching(m, open)?; + // The item starts after the previous item or block opening; comments before it are masked. + let item = m[..attr].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let attr = skip_ws(m, item).min(attr); + Some(TestFn { name: String::from_utf8_lossy(&m[name_start..name_end]).into_owned(), attr, fn_at, open, close }) +} + +/// A macro call in a test: its name, offset and argument ranges. +struct MacroCall { + name: String, + at: usize, + args: Vec<(usize, usize)>, +} + +/// The macro calls (`name!(…)`, `name![…]`, `name!{…}`) in `m[from..to]`. +fn macro_calls(m: &[u8], from: usize, to: usize) -> Vec { + let mut out = vec![]; + let mut i = from; + while let Some(bang) = find(&m[..to], b"!", i) { + i = bang + 1; + let start = (from..bang).rev().take_while(|&j| is_ident(m[j])).last().unwrap_or(bang); + let open = skip_ws(m, bang + 1); + if start == bang || start.checked_sub(1).is_some_and(|j| is_ident(m[j])) || !matches!(m.get(open), Some(b'(' | b'[' | b'{')) { + continue; + } + let Some(close) = matching(m, open).filter(|&c| c < to) else { continue }; + out.push(MacroCall { name: String::from_utf8_lossy(&m[start..bang]).into_owned(), at: start, args: split_args(m, open + 1, close) }); + } + out +} + +fn is_assert_macro(name: &str) -> bool { + ["assert", "debug_assert", "prop_assert"].iter().any(|p| name.starts_with(p)) +} + +const KEYWORDS: &[&str] = &["if", "while", "match", "for", "loop", "return", "fn", "in", "as", "let", "else", "move", "Some", "Ok", "Err"]; + +/// Names that helper detection ignores: too common to tell a helper from the code under test. +const COMMON: &[&str] = &[ + "new", "default", "from", "into", "get", "set", "run", "apply", "build", "make", "open", "load", "save", "parse", "read", "write", "draw", + "render", "len", "clone", "push", "vec", "format", "json", "Box", "Arc", "Vec", "String", "main", +]; + +/// The names called in `m[from..to]`: functions (`name(`, also through a path), methods +/// (`.name(`), including calls with turbofish arguments, and macros (`name!`). +fn calls(m: &[u8], from: usize, to: usize) -> Vec<(String, bool)> { + let m = &m[..to]; + let mut out = vec![]; + let mut i = from; + while i < to { + if !(m[i].is_ascii_alphabetic() || m[i] == b'_') || (i > 0 && is_ident(m[i - 1])) { + i += 1; + continue; + } + let end = i + m[i..to].iter().take_while(|&&c| is_ident(c)).count(); + let bang = m.get(end) == Some(&b'!'); + let after = skip_ws(m, end + usize::from(bang)); + let after = if bang { after } else { skip_turbofish(m, after) }; + if matches!(m.get(after), Some(b'(' | b'[' | b'{')) && (bang || m[after] == b'(') { + let name = String::from_utf8_lossy(&m[i..end]).into_owned(); + let method = i > 0 && m[i - 1] == b'.'; + if !KEYWORDS.contains(&name.as_str()) { + out.push((if bang { format!("{name}!") } else { name }, method)); + } + } + i = end; + } + out +} + +/// Skips optional `::<…>` arguments and the whitespace after them. +fn skip_turbofish(m: &[u8], at: usize) -> usize { + if !m[at..].starts_with(b"::") { + return at; + } + let open = skip_ws(m, at + 2); + if m.get(open) != Some(&b'<') { + return at; + } + let (mut i, mut depth) = (open + 1, 1usize); + while i < m.len() { + match m[i] { + b'<' => depth += 1, + b'>' if m[i - 1] != b'-' => { + depth -= 1; + if depth == 0 { + return skip_ws(m, i + 1); + } + } + b'(' | b'[' | b'{' => i = matching(m, i).unwrap_or(m.len()), + _ => {} + } + i += 1; + } + m.len() +} + +/// Whether `name` (a call in a test) is an asserting helper. +fn is_helper_call(name: &str, method: bool, helpers: &HashSet) -> bool { + let base = name.trim_end_matches('!'); + let named = ["assert", "check", "verify", "ensure", "expect_"].iter().any(|p| base.starts_with(p)); + named || (!method && !COMMON.contains(&base) && helpers.contains(name)) +} + +/// Whether the masked text checks something itself: an assertion, `panic!`, `unwrap_err` or +/// `expect_err`. +fn checks_itself(m: &[u8], from: usize, to: usize) -> bool { + let body = &m[from..to]; + contains(body, b"panic!") + || contains(body, b".unwrap_err()") + || contains(body, b".expect_err(") + || macro_calls(m, from, to).iter().any(|c| is_assert_macro(&c.name)) +} + +/// `tests.rs`, `tests_*.rs`, `*_tests.rs`, files in a `tests` or `benches` folder, and +/// `crates/testkit`. +fn is_test_file(path: &str) -> bool { + let mut parts = path.split('/').rev(); + let file = parts.next().unwrap_or_default(); + file == "tests.rs" + || file.starts_with("tests_") + || file.ends_with("_tests.rs") + || parts.any(|d| d == "tests" || d == "benches") + || path.starts_with("crates/testkit/") +} + +/// The byte ranges of test code in a file: all of a test file, else each item under +/// `#[cfg(test)]` that has a body in the file, and each test function. +fn test_regions(path: &str, m: &[u8], tests: &[TestFn]) -> Vec<(usize, usize)> { + if is_test_file(path) { + return vec![(0, m.len())]; + } + let mut out: Vec<(usize, usize)> = tests.iter().map(|t| (t.attr, t.close)).collect(); + for at in words(m, b"cfg", 0, m.len()) { + let attr = skip_ws(m, at + "cfg".len()); + if !m[..at].ends_with(b"#[") || !m[attr..].starts_with(b"(test)]") { + continue; + } + // The item's body: the first `{` before any `;` (`mod tests;` has none here). + let after = attr + "(test)]".len(); + let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; + if let (b'{', Some(close)) = (m[open], matching(m, open)) { + out.push((at, close)); + } + } + out +} + +fn in_regions(regions: &[(usize, usize)], pos: usize) -> bool { + regions.iter().any(|&(from, to)| from <= pos && pos <= to) +} + +/// A function or macro in test code: its name (`name!` for a macro), whether it checks something +/// itself, and the names it calls. +type Def = (String, bool, Vec); + +/// For each crate of `files` ([`crate_of`]), the names of the functions and macros in its test +/// code, or in `crates/testkit`'s, that assert, panic or call one that does. +pub fn asserting_helpers(files: &[(String, String)]) -> HashMap> { + let mut defs: HashMap> = HashMap::new(); + for (path, src) in files { + let m = mask(src); + let regions = test_regions(path, &m, &tests_in(&m)); + let crate_defs = defs.entry(crate_of(path)).or_default(); + for at in words(&m, b"fn", 0, m.len()).into_iter().chain(words(&m, b"macro_rules", 0, m.len())) { + if in_regions(®ions, at) { + crate_defs.extend(definition(&m, at)); + } + } + } + let testkit = defs.get(TESTKIT).cloned().unwrap_or_default(); + defs.iter().map(|(krate, own)| (krate.clone(), checking(own.iter().chain(if krate == TESTKIT { &[][..] } else { &testkit[..] })))).collect() +} + +/// The crate whose test helpers every crate can call. +const TESTKIT: &str = "crates/testkit"; + +/// The names among `defs` that check something, directly or through another of `defs`. +fn checking<'a>(defs: impl Iterator + Clone) -> HashSet { + let mut known: HashSet = defs.clone().filter(|d| d.1).map(|d| d.0.clone()).collect(); + loop { + let more: Vec = + defs.clone().filter(|d| !known.contains(&d.0) && d.2.iter().any(|c| known.contains(c))).map(|d| d.0.clone()).collect(); + if more.is_empty() { + return known; + } + known.extend(more); + } +} + +/// The `fn` or `macro_rules!` at `at`. +fn definition(m: &[u8], at: usize) -> Option { + let is_macro = m[at..].starts_with(b"macro_rules"); + let mut start = skip_ws(m, at + if is_macro { "macro_rules".len() } else { 2 }); + if is_macro { + start = skip_ws(m, start + usize::from(m.get(start) == Some(&b'!'))); + } + let end = start + m[start..].iter().take_while(|&&c| is_ident(c)).count(); + if end == start { + return None; + } + let open = end + m[end..].iter().position(|&c| c == b'{' || c == b';')?; + if m[open] != b'{' { + return None; + } + let close = matching(m, open)?; + let name = String::from_utf8_lossy(&m[start..end]).into_owned(); + let called = calls(m, open, close).into_iter().filter(|(_, method)| !method).map(|(n, _)| n).collect(); + Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) +} + +// ---- The rules ---- + +/// The source, its masked copy and its tests. +struct File<'a> { + path: &'a str, + src: &'a [u8], + m: Vec, + lines: Lines, + tests: Vec, + /// The test code ([`test_regions`]). + regions: Vec<(usize, usize)>, +} + +impl File<'_> { + fn hit(&self, at: usize, rule: Rule, test: &str, note: String) -> Hit { + let line = self.lines.of(at); + Hit { path: self.path.to_owned(), line, rule, test: test.to_owned(), note, first: line, last: line } + } + + fn test_at(&self, pos: usize) -> &str { + self.tests.iter().find(|t| t.open <= pos && pos <= t.close).map_or("", |t| t.name.as_str()) + } + + /// The source of `from..to` without whitespace and comments between tokens; string and + /// character literals keep their text. + fn src_norm(&self, (from, to): (usize, usize)) -> String { + let mut out = Vec::with_capacity(to - from); + let mut in_literal = false; + for i in from..to { + let (s, m) = (self.src[i], self.m[i]); + if m == b'"' || (m == b'\'' && !in_literal && self.m.get(i + 1) == Some(&b' ')) { + in_literal = !in_literal; + } else if m == b'\'' && in_literal { + in_literal = false; + } + if in_literal || (m == s && !s.is_ascii_whitespace()) { + out.push(s); + } + } + String::from_utf8_lossy(&out).into_owned() + } +} + +/// Every hit in one file, exemptions applied. +pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { + let m = mask(src); + let tests = tests_in(&m); + let regions = test_regions(path, &m, &tests); + let file = File { path, src: src.as_bytes(), m, lines: Lines::new(src), tests, regions }; + let mut hits: Vec = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); + hits.extend(ignore_hits(&file)); + hits.extend(sleep_hits(&file)); + hits.extend(reads_source_hits(&file)); + let allows = allows(src, &file.m); + hits.retain(|h| { + let first = if h.rule == Rule::AllUnguarded { h.line } else { h.first }; + !allows.iter().any(|&(line, rule)| rule == h.rule && line + 1 >= first && line <= h.line) + }); + hits.sort(); + hits +} + +/// `(line, rule)` of each exemption comment that names a rule and a reason. +/// A marker counts only inside a comment: masked (`m`) there, and kept when only literals are +/// masked. +fn allows(src: &str, m: &[u8]) -> Vec<(usize, Rule)> { + let literals = mask_with(src, false); + let lines = Lines::new(src); + src.match_indices(ALLOW) + .filter(|&(p, _)| m[p] == b' ' && literals[p] == b't') + .filter_map(|(p, _)| { + let rest = src[p + ALLOW.len()..].lines().next()?; + let mut words = rest.split_whitespace(); + let rule = Rule::from_id(words.next()?)?; + words.next().map(|_| (lines.of(p), rule)) + }) + .collect() +} + +/// What the rules read of one test. +struct View<'a> { + file: &'a File<'a>, + t: &'a TestFn, + asserts: Vec, + delegates: bool, + checks: bool, + should_panic: bool, +} + +fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { + let m = &file.m; + let asserts: Vec = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect(); + let none = HashSet::new(); + let helpers = ctx.helpers.get(&crate_of(file.path)).unwrap_or(&none); + let delegates = calls(m, t.open, t.close) + .iter() + .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); + let checks = checks_itself(m, t.open, t.close); + let should_panic = contains(&m[t.attr..t.fn_at], b"should_panic"); + let v = View { file, t, asserts, delegates, checks, should_panic }; + let mut hits = all_unguarded(&v); + hits.extend(self_compare(&v)); + hits.extend(early_returns(&v)); + hits.extend(env_gates(&v, ctx)); + hits.extend([only_weak(&v), exit_status_only(&v), no_assertion(&v)].into_iter().flatten()); + hits +} + +impl View<'_> { + fn hit(&self, at: usize, rule: Rule, note: String) -> Hit { + self.file.hit(at, rule, &self.t.name, note) + } + + /// A hit for the whole test, on its `fn` line. + fn whole(&self, rule: Rule, note: String) -> Hit { + let mut h = self.hit(self.t.fn_at, rule, note); + h.first = self.file.lines.of(self.t.attr); + h.last = self.file.lines.of(self.t.close); + h + } + + fn body(&self) -> &[u8] { + &self.file.m[self.t.open..self.t.close] + } + + /// The masked body with assertion failure-message arguments replaced by spaces. + fn body_without_messages(&self) -> Vec { + let mut body = self.body().to_vec(); + for a in &self.asserts { + for &(from, to) in a.args.iter().skip(guard_arg_count(&a.name)) { + blank(&mut body, from - self.t.open, to - self.t.open); + } + } + body + } + + /// The first argument of an assertion, masked, without whitespace. + fn first_arg(&self, a: &MacroCall) -> String { + a.args.first().map(|&(f, t)| norm(&self.file.m[f..t])).unwrap_or_default() + } +} + +const PLAIN_ASSERTS: &[&str] = &["assert", "debug_assert", "prop_assert"]; + +fn all_unguarded(v: &View) -> Vec { + let mut body = v.body_without_messages(); + strip_all_predicates(&mut body); + let checked = v.asserts.iter().any(|a| { + a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { + let arg = norm(&body[from - v.t.open..to - v.t.open]); + [".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"].iter().any(|g| arg.contains(g)) + }) + }); + if checked || first_item_guard(&body) { + return vec![]; + } + v.asserts + .iter() + .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && unguarded_all(&v.first_arg(a), &v.file.m[v.t.open..a.at])) + .map(|a| { + let mut h = v.hit(a.at, Rule::AllUnguarded, format!("{}!(…all(…)) with no length or emptiness check in the test", a.name)); + h.first = v.file.lines.of(v.t.attr); + h.last = v.file.lines.of(v.t.close); + h + }) + .collect() +} + +/// The number of condition or compared operands in a standard assertion macro. +fn guard_arg_count(name: &str) -> usize { + match name { + "assert" | "debug_assert" | "prop_assert" => 1, + "assert_eq" | "assert_ne" | "debug_assert_eq" | "debug_assert_ne" | "prop_assert_eq" | "prop_assert_ne" => 2, + _ => 0, + } +} + +/// Blanks `.all(…)` predicates so their checks do not guard the collection. +fn strip_all_predicates(body: &mut [u8]) { + for at in words(body, b"all", 0, body.len()) { + let method = body[..at].trim_ascii_end().ends_with(b"."); + let open = skip_ws(body, at + 3); + let Some(close) = (method && body.get(open) == Some(&b'(')).then(|| matching(body, open)).flatten() else { continue }; + blank(body, at, close + 1); + } +} + +/// Whether test code accesses a first item in a way that fails on an empty collection. +fn first_item_guard(body: &[u8]) -> bool { + let compact = norm(body); + let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; + let indexed = compact.match_indices("[0]").any(|(at, _)| !on_array_literal(&compact[..at + 3])); + indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body) +} + +/// Whether a `let Some(…) = ….first() else { panic!(…) }` binding checks for an item. +fn panicking_first_binding(body: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let rest = &body[at + 3..]; + let Some(otherwise) = words(rest, b"else", 0, rest.len()).first().copied() else { return false }; + let binding = norm(&rest[..otherwise]); + let Some(close) = binding.strip_prefix("Some(").and_then(|_| matching(binding.as_bytes(), 4)) else { return false }; + let Some(value) = binding[close + 1..].strip_prefix('=') else { return false }; + let first = value.ends_with(".first()") || value.ends_with(".next()"); + first && !value.contains([';', '{', '}']) && norm(&rest[otherwise + 4..]).starts_with("{panic!(") + }) +} + +/// Whether a (masked, whitespace-free) condition holds an `.all(…)` that an empty collection would +/// pass by mistake. Left out: a negated result, a closure that says no item matches (whole +/// negations or `!=` comparisons joined only by `&&`), and a non-empty array literal or a local +/// name bound to or previously compared equal to one. +fn unguarded_all(cond: &str, body: &[u8]) -> bool { + all_with_polarity(cond, true, body) +} + +/// Tracks negation through boolean operands and comparisons with `false`. +fn all_with_polarity(cond: &str, positive: bool, body: &[u8]) -> bool { + if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) { + return all_with_polarity(&cond[1..cond.len() - 1], positive, body); + } + if let Some(at) = boolean_split(cond) { + return all_with_polarity(&cond[..at], positive, body) || all_with_polarity(&cond[at + 2..], positive, body); + } + if let Some(expr) = cond.strip_suffix("==false").or_else(|| cond.strip_prefix("false==")) { + return all_with_polarity(expr, !positive, body); + } + if let Some(expr) = cond.strip_prefix('!') { + return all_with_polarity(expr, !positive, body); + } + positive && positive_all(cond, body) +} + +/// Finds a boolean operator outside parentheses, brackets and braces. +fn boolean_split(cond: &str) -> Option { + let b = cond.as_bytes(); + let mut at = 0; + while at < b.len() { + if b[at..].starts_with(b"&&") || b[at..].starts_with(b"||") { + return Some(at); + } + at = if matches!(b[at], b'(' | b'[' | b'{') { matching(b, at)? + 1 } else { at + 1 }; + } + None +} + +fn positive_all(cond: &str, test_body: &[u8]) -> bool { + cond.match_indices(".all(").any(|(i, _)| { + let rest = &cond[i + ".all(".len()..]; + let arg = &rest[..arg_end(rest)]; + let body = arg.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(arg, |(_, body)| body); + let none_match = not_equal_conjunction(body); + !none_match && !on_array_literal(&cond[..i]) && !on_bound_array(&cond[..i], test_body) && !on_equal_array(&cond[..i], test_body) + }) +} + +/// Whether every boolean operand is a whole negation or `!=` comparison joined only by `&&`. +fn not_equal_conjunction(body: &str) -> bool { + if body.starts_with('(') && matching(body.as_bytes(), 0) == Some(body.len() - 1) { + return not_equal_conjunction(&body[1..body.len() - 1]); + } + if let Some(at) = boolean_split(body) { + return body[at..].starts_with("&&") && not_equal_conjunction(&body[..at]) && not_equal_conjunction(&body[at + 2..]); + } + if whole_negation(body) { + return true; + } + let (mut at, mut comparisons) = (0, 0); + let b = body.as_bytes(); + while at < b.len() { + if b[at..].starts_with(b"!=") { + comparisons += 1; + at += 2; + } else if matches!(b[at], b'=' | b'<' | b'>' | b'&' | b'|') { + return false; + } else if matches!(b[at], b'(' | b'[' | b'{') { + let Some(close) = matching(b, at) else { return false }; + at = close + 1; + } else { + at += 1; + } + } + comparisons == 1 +} + +/// Whether `!` negates the whole operand rather than one side of a binary expression. +fn whole_negation(body: &str) -> bool { + let Some(rest) = body.strip_prefix('!') else { return false }; + let rest = rest.trim_start_matches(['!', '*', '&']); + let b = rest.as_bytes(); + let mut at = 0; + while at < b.len() { + if matches!(b[at], b'=' | b'<' | b'>' | b'&' | b'|' | b'+' | b'-' | b'*' | b'/' | b'%' | b'^') { + return false; + } + at = if matches!(b[at], b'(' | b'[' | b'{') { + let Some(close) = matching(b, at) else { return false }; + close + 1 + } else { + at + 1 + }; + } + !rest.is_empty() +} + +/// Whether an earlier equality assertion compares this plain local receiver with a non-empty literal. +fn on_equal_array(receiver: &str, body: &[u8]) -> bool { + let name = array_receiver(receiver); + if name.is_empty() || name.as_bytes()[0].is_ascii_digit() || !name.bytes().all(is_ident) { + return false; + } + macro_calls(body, 0, body.len()).iter().any(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { + return false; + } + let Some(&(lf, lt)) = a.args.first() else { return false }; + let Some(&(rf, rt)) = a.args.get(1) else { return false }; + let (left, right) = (norm(&body[lf..lt]), norm(&body[rf..rt])); + (collection_operand(&left) == name && non_empty_literal(&right)) || (collection_operand(&right) == name && non_empty_literal(&left)) + }) +} + +/// Removes one borrow and a slice view from a compared operand. +fn collection_operand(operand: &str) -> &str { + let operand = operand.strip_prefix('&').unwrap_or(operand); + operand.strip_suffix(".as_slice()").or_else(|| operand.strip_suffix("[..]")).unwrap_or(operand) +} + +/// Whether the whole operand is a non-empty array literal or `vec![…]`. +fn non_empty_literal(operand: &str) -> bool { + let b = operand.strip_prefix("vec!").unwrap_or(operand).as_bytes(); + b.first() == Some(&b'[') && matching(b, 0) == Some(b.len() - 1) && non_empty_array(&b[1..b.len() - 1]) +} + +/// The length of a call's arguments in `rest`, the text after its `(`: up to its closing bracket. +fn arg_end(rest: &str) -> usize { + let mut depth = 0i32; + rest.bytes() + .position(|c| { + depth += match c { + b'(' | b'[' | b'{' => 1, + b')' | b']' | b'}' => -1, + _ => 0, + }; + depth < 0 + }) + .unwrap_or(rest.len()) +} + +/// Whether `receiver` (the text before `.all(`) ends with a non-empty array literal, through `.iter()` or +/// `.into_iter()`. +fn on_array_literal(receiver: &str) -> bool { + let r = array_receiver(receiver); + let b = r.as_bytes(); + if b.last() != Some(&b']') { + return false; + } + let mut depth = 0usize; + for (j, &c) in b.iter().enumerate().rev() { + match c { + b']' => depth += 1, + b'[' => { + depth = depth.saturating_sub(1); + if depth == 0 { + let literal = !j.checked_sub(1).and_then(|k| b.get(k)).is_some_and(|&p| is_ident(p) || matches!(p, b')' | b']' | b'.')); + return literal && non_empty_array(&b[j + 1..b.len() - 1]); + } + } + _ => {} + } + } + false +} + +/// Removes the iterator method from an array receiver. +fn array_receiver(receiver: &str) -> &str { + receiver.strip_suffix(".iter()").or_else(|| receiver.strip_suffix(".into_iter()")).unwrap_or(receiver) +} + +/// Whether a plain local receiver's latest preceding binding initializes a non-empty array. +fn on_bound_array(receiver: &str, body: &[u8]) -> bool { + let name = array_receiver(receiver).as_bytes(); + if name.is_empty() || name[0].is_ascii_digit() || !name.iter().copied().all(is_ident) { + return false; + } + words(body, b"let", 0, body.len()).into_iter().rev().find_map(|at| array_binding(&body[at + 3..], name)).unwrap_or(false) +} + +/// Checks a named binding, allowing `mut` and an array type annotation. +fn array_binding(mut rest: &[u8], name: &[u8]) -> Option { + rest = rest.trim_ascii_start(); + if rest.starts_with(b"mut") && rest.get(3).is_some_and(u8::is_ascii_whitespace) { + rest = rest[3..].trim_ascii_start(); + } + let end = rest.iter().copied().take_while(|&c| is_ident(c)).count(); + if &rest[..end] != name { + return None; + } + rest = rest[end..].trim_ascii_start(); + if let Some(annotation) = rest.strip_prefix(b":") { + let annotation = annotation.trim_ascii_start(); + let close = (annotation.first() == Some(&b'[')).then(|| matching(annotation, 0)).flatten(); + let Some(close) = close else { return Some(false) }; + rest = annotation[close + 1..].trim_ascii_start(); + } + Some(rest.strip_prefix(b"=").is_some_and(array_initializer)) +} + +/// Whether an initializer is a non-empty array literal, optionally followed by one `.map(…)`. +fn array_initializer(rest: &[u8]) -> bool { + let rest = rest.trim_ascii_start(); + let Some(close) = (rest.first() == Some(&b'[')).then(|| matching(rest, 0)).flatten() else { return false }; + if !non_empty_array(&rest[1..close]) { + return false; + } + let tail = rest[close + 1..].trim_ascii_start(); + if tail.starts_with(b";") { + return true; + } + let compact = norm(tail); + if !compact.starts_with(".map(") { + return false; + } + let Some(close) = matching(compact.as_bytes(), 4) else { return false }; + compact[close + 1..].starts_with(';') +} + +/// Whether an array's masked contents have an element and, for repetition, a positive literal count. +fn non_empty_array(contents: &[u8]) -> bool { + let mut at = 0; + while at < contents.len() { + match contents[at] { + b';' => return norm(&contents[at + 1..]).parse::().is_ok_and(|count| count > 0), + b'(' | b'[' | b'{' => { + let Some(close) = matching(contents, at) else { return false }; + at = close + 1; + } + _ => at += 1, + } + } + !contents.trim_ascii().is_empty() +} + +/// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. +fn is_weak(cond: &str) -> bool { + let (negated, expr) = match cond.strip_prefix('!') { + Some(rest) => (true, rest), + None => (false, cond), + }; + let plain = |rest: &str| !["&&", "||", "==", "!=", "<", ">"].iter().any(|op| rest.contains(op)); + let suffix = |s: &str| expr.strip_suffix(s).is_some_and(plain); + if negated { + return suffix(".is_empty()"); + } + suffix(".is_ok()") || suffix(".is_some()") || suffix(".len()>0") || suffix(".len()!=0") || suffix(".len()>=1") +} + +fn only_weak(v: &View) -> Option { + let all_weak = v.asserts.iter().all(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && is_weak(&v.first_arg(a))); + let other = contains(v.body(), b"panic!") || contains(v.body(), b".unwrap_err()") || contains(v.body(), b".expect_err("); + if v.asserts.is_empty() || !all_weak || other || v.delegates || v.should_panic { + return None; + } + Some(v.whole(Rule::OnlyWeak, format!("its {} assertion(s) only check is_ok/is_some/non-empty", v.asserts.len()))) +} + +fn self_compare(v: &View) -> Vec { + v.asserts + .iter() + .filter(|a| a.name.ends_with("_eq") || a.name.ends_with("_ne")) + .filter_map(|a| { + let right = *a.args.get(1)?; + let (l, r) = (v.file.src_norm(*a.args.first()?), v.file.src_norm(right)); + let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); + let calls_with_args = l.replace("()", "").contains(['(', '!']); + (l == r && !l.is_empty() && !calls_with_args).then(|| { + let mut h = v.hit(a.at, Rule::SelfCompare, format!("{}! compares `{l}` with itself", a.name)); + let end = right.0 + v.file.m[right.0..right.1].trim_ascii_end().len(); + h.last = v.file.lines.of(end.saturating_sub(1)); + h + }) + }) + .collect() +} + +fn exit_status_only(v: &View) -> Option { + let mut body = norm(&v.body_without_messages()).into_bytes(); + let runs = contains(&body, b"Command::new") || contains(&body, b".output()") || contains(&body, b".status()"); + strip_stream_configuration(&mut body); + let reads = + ["stdout", "stderr", "fs::read", "read_to_string", "from_slice", "from_str", "contains("].iter().any(|w| contains(&body, w.as_bytes())); + let status_only = |a: &MacroCall| { + a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { + let c = norm(&v.file.m[from..to]); + c.contains(".success()") || c.contains(".code()") + }) + }; + if !runs || reads || v.asserts.is_empty() || !v.asserts.iter().all(status_only) || v.delegates { + return None; + } + Some(v.whole(Rule::ExitStatusOnly, "runs a process and checks only its exit status".into())) +} + +/// Blanks stream method names that configure a process with `Stdio` in whitespace-free text. +fn strip_stream_configuration(body: &mut [u8]) { + for stream in ["stdout", "stderr", "stdin"] { + for at in words(body, stream.as_bytes(), 0, body.len()) { + let rest = &body[at + stream.len()..]; + let config = rest.starts_with(b"(Stdio::") || rest.starts_with(b"(std::process::Stdio::"); + if body[..at].ends_with(b".") && config { + blank(body, at, at + stream.len()); + } + } + } +} + +fn no_assertion(v: &View) -> Option { + if v.checks || v.delegates || v.should_panic { + return None; + } + Some(v.whole(Rule::NoAssertion, "no assertion and no asserting helper".into())) +} + +/// Guards that mark a skip for a missing resource or another platform, or a test that runs itself +/// in a child process, matched case-sensitively on the guard without whitespace. +const SKIP_GUARDS: &[&str] = &[ + "in_own_process", + "OWN_PROCESS", + "_TEST_CHILD", + "current_exe()", + "skip_without_craft_fonts", + "CRAFT_FONTS", + "japanese_fonts", + "craft_fonts", + "env::var", + "cfg!(", + "target_os", + "geteuid", + "Command::new", + "File::open", + "fs::read", + "read_dir(", + ".exists()", + "which(", +]; + +/// The same, matched without regard to case. +const SKIP_GUARDS_ANY_CASE: &[&str] = &[ + "installed_family", + "kufi", + "library/fonts", + "default_font(", + "arabic_face", + "arabic_test_face", + "devanagari_test_face", + "joiner_test_faces", + "mark_text(", + "arabic_style", + "has_family", + "variable_font", + "fontdb", + ".face(", + "covers(", + "thai", + "cjk", + "corpus", + "suite_dir", + "json2_file", + "read_fixture", + "samples(", + "pinned(", + "platform()", + "is_mac", + "/system/library", +]; + +fn early_returns(v: &View) -> Vec { + let (m, t) = (&v.file.m, v.t); + words(m, b"return", t.open, t.close) + .into_iter() + .filter_map(|at| { + let end = bare_return_end(m, at + "return".len())?; + let rest_empty = m[end..t.close].iter().all(|c| c.is_ascii_whitespace() || matches!(c, b';' | b'}')); + if rest_empty || nested(m, t.open, at) || skip_guard(v.file, t.open, at, end) { + return None; + } + Some(v.hit(at, Rule::EarlyReturn, "returns early on a value from the code under test".into())) + }) + .collect() +} + +/// The end of a bare `return` (`return;`, `return }`, `return Ok(());`) whose keyword ends at `i`. +fn bare_return_end(m: &[u8], i: usize) -> Option { + let mut j = skip_ws(m, i); + if m[j..].starts_with(b"Ok") { + j += 2; + for c in *b"(())" { + j = skip_ws(m, j); + if m.get(j) != Some(&c) { + return None; + } + j += 1; + } + j = skip_ws(m, j); + } + match m.get(j)? { + b';' => Some(j + 1), + b'}' | b',' => Some(j), + _ => None, + } +} + +/// Whether `pos` is inside a closure or a nested function in the body opened at `open`. +fn nested(m: &[u8], open: usize, pos: usize) -> bool { + let mut stack: Vec = vec![]; + for i in open..pos { + match m[i] { + b'{' => stack.push(i > open && opens_closure_or_fn(m, open, i)), + b'}' => { + stack.pop(); + } + _ => {} + } + } + stack.contains(&true) +} + +fn opens_closure_or_fn(m: &[u8], open: usize, brace: usize) -> bool { + let from = brace.saturating_sub(160).max(open + 1); + let head = &m[from..brace]; + let start = head.iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + let head = String::from_utf8_lossy(&head[start..]).into_owned(); + let head = head.trim_end(); + let closure = head.ends_with('|') || head.rfind("->").is_some_and(|p| head[..p].trim_end().ends_with('|')); + closure || !words(head.as_bytes(), b"fn", 0, head.len()).is_empty() +} + +/// Whether the return at `at..end` is not a silent skip on a value: the block it ends asserts +/// first; a comment or a printed note from the start of its statement to the end of its line says +/// why it returns; or its guard skips for a resource, a platform or a child process. +fn skip_guard(file: &File, open: usize, at: usize, end: usize) -> bool { + let m = &file.m; + let block = m[open..at].iter().rposition(|&c| c == b'{').map_or(open, |p| p + open); + let stmt = m[open..block].iter().rposition(|&c| c == b';' || c == b'}').map_or(open, |p| p + open); + let line_end = find(m, b"\n", end).unwrap_or(m.len()); + let asserted = macro_calls(m, block, at).iter().any(|c| is_assert_macro(&c.name)); + let printed = macro_calls(m, stmt, at).iter().any(|c| c.name.ends_with("print") || c.name.ends_with("println")); + let commented = (stmt..line_end).any(|i| file.src[i..].starts_with(b"//") && m[i] == b' '); + if asserted || printed || commented { + return true; + } + let guard = norm(&file.src[stmt..end]); + let lower = guard.to_ascii_lowercase(); + let wide = &file.src[stmt.saturating_sub(250).max(open)..end]; + SKIP_GUARDS.iter().any(|g| guard.contains(g)) + || SKIP_GUARDS_ANY_CASE.iter().any(|g| lower.contains(g)) + || (lower.contains("fs::write(") && lower.contains(".is_err()")) + || ["in_own_process", "OWN_PROCESS", "_TEST_CHILD", "current_exe()"].iter().any(|g| contains(wide, g.as_bytes())) + || !words(wide, b"CHILD", 0, wide.len()).is_empty() +} + +fn env_gates(v: &View, ctx: &Ctx) -> Vec { + let (m, src, t) = (&v.file.m, v.file.src, v.t); + let mut out = vec![]; + for at in words(m, b"var", t.open, t.close).into_iter().chain(words(m, b"var_os", t.open, t.close)) { + if !m[..at].ends_with(b"env::") { + continue; + } + let Some(name) = env_name(m, src, at) else { continue }; + if ctx.ci_env.contains(&name) || set_by_system(&name) { + continue; + } + // The whole file is masked and searched only for a name that CI and the system leave unset. + let file = norm(&mask_comments(&String::from_utf8_lossy(src))); + let set_here = file.contains(&format!(".env(\"{name}\"")) + || file.contains(&format!("=\"{name}\";")) + || file.match_indices(&format!("set_var(\"{name}\"")).any(|(at, _)| at == 0 || !is_ident(file.as_bytes()[at - 1])); + if !set_here { + out.push(v.hit(at, Rule::EnvGateUnset, format!("reads {name}, which no CI leg sets"))); + } + } + out +} + +/// The literal name in `env::var("NAME")` whose `var` is at `at`. +fn env_name(m: &[u8], src: &[u8], at: usize) -> Option { + let open = skip_ws(m, at + m[at..].iter().take_while(|&&c| is_ident(c)).count()); + if m.get(open) != Some(&b'(') { + return None; + } + let quote = skip_ws(m, open + 1); + if m.get(quote) != Some(&b'"') { + return None; + } + let end = string_end(src, quote + 1).saturating_sub(1); + let name = std::str::from_utf8(&src[quote + 1..end]).ok()?; + (!name.is_empty() && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')).then(|| name.to_owned()) +} + +fn ignore_hits(file: &File) -> Vec { + let m = &file.m; + let mut out = vec![]; + for at in words(m, b"ignore", 0, m.len()) { + if !m[..at].ends_with(b"#[") { + continue; + } + let j = skip_ws(m, at + "ignore".len()); + let reason = match m.get(j) { + Some(b'=') => { + let q = skip_ws(m, j + 1); + ignore_reason(&file.src[q..]).is_some_and(|body| body.iter().any(|c| !c.is_ascii_whitespace())) + } + _ => false, + }; + if !reason { + let test = file.tests.iter().find(|t| t.fn_at > at).map_or("", |t| t.name.as_str()); + out.push(file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into())); + } + } + out +} + +/// The body of an ordinary or raw string literal used as an ignore reason. +fn ignore_reason(src: &[u8]) -> Option<&[u8]> { + if src.first() == Some(&b'"') { + return src.get(1..string_end(src, 1).saturating_sub(1)); + } + let raw = src.strip_prefix(b"r")?; + let hashes = raw.iter().take_while(|&&c| c == b'#').count(); + if raw.get(hashes) != Some(&b'"') { + return None; + } + let body = hashes + 2; + let close: Vec = std::iter::once(b'"').chain(std::iter::repeat_n(b'#', hashes)).collect(); + let end = find(src, &close, body)?; + src.get(body..end) +} + +fn sleep_hits(file: &File) -> Vec { + let m = &file.m; + words(m, b"sleep", 0, m.len()) + .into_iter() + .filter(|&at| { + if !in_regions(&file.regions, at) { + return false; + } + let before = m[..at].iter().rposition(|c| !c.is_ascii_whitespace()); + let method = before.is_some_and(|b| m[b] == b'.'); + let definition = m[..at].trim_ascii_end().ends_with(b"fn"); + !method && !definition && m.get(skip_ws(m, at + "sleep".len())) == Some(&b'(') + }) + .map(|at| file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into())) + .collect() +} + +fn reads_source_hits(file: &File) -> Vec { + if SOURCE_AUDITS.contains(&file.path) { + return vec![]; + } + let m = &file.m; + let mut out = vec![]; + for (word, note) in [(&b"include_str"[..], "includes a .rs file as text"), (&b"ends_with"[..], "keeps files ending in .rs")] { + for at in words(m, word, 0, m.len()).into_iter().filter(|&at| in_regions(&file.regions, at)) { + let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); + let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; + let arg = norm(&file.src[open + 1..close]); + let rs = if word == b"ends_with" { arg == "\".rs\"" } else { arg.ends_with(".rs\"") }; + if rs { + out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ctx() -> Ctx { + Ctx { helpers: HashMap::new(), ci_env: ["SET_IN_CI".to_owned()].into_iter().collect() } + } + + /// The rule ids of `src`'s hits, as `(line, rule)`. + fn hits(src: &str) -> Vec<(usize, &'static str)> { + hits_in("crates/x/src/tests.rs", src, &ctx()) + } + + fn hits_in(path: &str, src: &str, ctx: &Ctx) -> Vec<(usize, &'static str)> { + lint_file(path, src, ctx).into_iter().map(|h| (h.line, h.rule.id())).collect() + } + + #[test] + fn all_needs_a_non_empty_guard() { + let bad = "#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(bad), [(4, "all-unguarded")]); + let good = "#[test]\nfn t() {\n let xs = f();\n assert_eq!(xs.len(), 3);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(good), []); + let inner = "#[test]\nfn t() {\n assert!(rows().iter().all(|r| r.len() == 3));\n}\n"; + assert_eq!(hits(inner), [(3, "all-unguarded")], "a length inside the predicate is about each item"); + let none = "#[test]\nfn t() {\n assert!(warnings().iter().all(|w| !w.contains(\"lost\")), \"no warning\");\n}\n"; + assert_eq!(hits(none), [], "all(|w| !…) says that no item matches"); + let other = "#[test]\nfn t() {\n assert!(listed().iter().all(|e| e[\"id\"] != id));\n assert!([0, 4, 20].iter().all(|&i| glow[i].a() == 0));\n}\n"; + assert_eq!(hits(other), [], "one != comparison, and an array literal"); + let indexed = "#[test]\nfn t() {\n assert!(rows()[2].iter().all(|r| r.ok && r.n != 0));\n assert!(f().iter().all(|x| x.0 != 1 && x.1 != 2));\n}\n"; + assert_eq!(hits(indexed), [(3, "all-unguarded")]); + let mixed = "#[test]\nfn t() {\n assert!(f().iter().all(|x| x.0 != 1 && x.1 > 2));\n}\n"; + assert_eq!(hits(mixed), [(3, "all-unguarded")]); + } + + #[test] + fn all_equality_guards_match_each_receiver() { + for assertion in ["assert_eq", "debug_assert_eq", "prop_assert_eq"] { + for operand in ["xs", "&xs", "xs.as_slice()", "&xs.as_slice()", "xs[..]", "&xs[..]"] { + for literal in ["[1]", "[1, 2,]", "[1; 2]", "vec![1, 2]", "vec![1; 2]", "[\"[;]\", name]"] { + for (left, right) in [(operand, literal), (literal, operand)] { + let src = format!( + "#[test]\nfn t() {{\n {assertion}!({left}, {right}, \"items\");\n assert!(xs.iter().all(|x| valid(x)));\n assert!(ys.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{assertion}!({left}, {right})"); + let combined = src.replace("valid(x)));\n assert!(ys", "valid(x)) && ys"); + assert_eq!(hits(&combined), [(4, "all-unguarded")], "another receiver in the same condition"); + } + } + } + } + } + + #[test] + fn all_equality_guards_require_non_empty_literals() { + for expected in ["[]", "[1; 0]", "vec![]", "vec![1; 0]", "expected", "items()", "[1].map(f)", "vec![1].clone()"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!(xs, {expected});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{expected}"); + } + for operand in ["ys", "xs_other", "other.xs", "other::xs", "xs()", "xs.clone()", "xs[1..]", "&&xs"] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{operand}"); + } + } + + #[test] + fn all_equality_guards_require_earlier_compared_operands_in_the_test() { + for assertion in ["assert_ne", "debug_assert_ne", "prop_assert_ne"] { + let src = format!("#[test]\nfn t() {{\n {assertion}!(xs, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{assertion}"); + } + let later = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n assert_eq!(xs, [1]);\n}\n"; + assert_eq!(hits(later), [(3, "all-unguarded")]); + let outside = "fn helper() { assert_eq!(xs, [1]); }\n#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(outside), [(4, "all-unguarded")]); + let message = "#[test]\nfn t() {\n assert_eq!(a, b, \"items {:?} {:?}\", xs, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(message), [(4, "all-unguarded")]); + } + + #[test] + fn all_skips_conjunctions_of_not_equal_comparisons() { + for predicate in [ + "|(id, _)| id != \"action.batch\" && id != \"flattener.preview\"", + "|x| x.0 != 1 && x.1 != 2", + "|x| x != 1 && x != 2 && x != 3", + "|x| (x != 1) && ((x != 2) && x != 3)", + "|x| value(x) != expected(1, 2) && *x != 3", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(names.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [], "{predicate}"); + let mixed = src.replace("));\n", ") && ys.iter().all(|y| valid(y)));\n"); + assert_eq!(hits(&mixed), [(3, "all-unguarded")], "another positive predicate beside {predicate}"); + } + } + + #[test] + fn all_reports_conjunctions_with_other_predicates() { + for predicate in [ + "|x| x != 1 && x == 2", + "|x| x != 1 && x < 2", + "|x| x.0 != 1 && x.1 > 2", + "|x| x != 1 && valid(x)", + "|x| valid(x) && x != 1", + "|x| x != 1 || x != 2", + "|x| x != 1 && x != 2 || x != 3", + "|x| x != 1 && (x != 2 || x != 3)", + "|x| (x != 1 && x > 2) && x != 3", + "|x| valid(x != 1) && x != 2", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(names.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{predicate}"); + } + } + + #[test] + fn all_skips_only_whole_negations_and_not_equal_conjunctions() { + for predicate in [ + "|x| !x.contains(\"lost\")", + "|x| !blocked!(x)", + "|x| !(blocked(x) && invalid(x))", + "|x| !a(x) && !b(x)", + "|x| !a(x) && x != 1", + "|x| x != 1 && (!a(x) && !(b(x)))", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(xs.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [], "{predicate}"); + } + for predicate in [ + "|x| !blocked(x) && valid(x)", + "|x| valid(x) && !blocked(x)", + "|x| !a(x) || b(x)", + "|x| !a(x) == b(x)", + "|x| (!a(x) == b(x)) && x != 1", + "|x| !a(x) && (!b(x) || c(x))", + "|x| !a(x) ^ b(x)", + ] { + let src = format!("#[test]\nfn t() {{\n assert!(xs.iter().all({predicate}));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{predicate}"); + } + } + + #[test] + fn all_skips_locally_bound_non_empty_arrays() { + for binding in [ + "let xs = [1, 2];", + "let mut xs = [1, 2];", + "let xs: [u8; 2] = [1, 2];", + "let mut xs: [u8; 2] = [1, 2];", + "let xs = [1; 2];", + "let xs = [[1, 2], [3, 4]];", + "let xs = [\"[\", \";\", \"bad ] brackets [\"].map(|s| s.trim());", + "let xs = [1, 2].map(|x| { let pair = [x, x]; pair });", + "let xs /* items */ : [u8; 2] = [1, 2] . map (|x| x + 1);", + ] { + for method in ["iter", "into_iter"] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding} through {method}"); + let mixed = src.replace("valid(x)))", "valid(x)) && ys.iter().all(|y| valid(y)))"); + assert_eq!(hits(&mixed), [(4, "all-unguarded")], "another collection beside {binding}"); + } + } + } + + #[test] + fn all_reports_empty_arrays_and_other_initializers() { + for value in [ + "[]", + "[1; 0]", + "[1; 0].map(|x| x + 1)", + "vec![1, 2]", + "items()", + "items().collect()", + "[1, 2].into_iter().collect()", + "[1, 2].map(|x| x + 1).into_iter().collect()", + "[1, 2].map(|x| x + 1).map(|x| x + 1)", + ] { + for binding in [format!("let xs = {value};"), format!("let mut xs = {value};"), format!("let xs: [u8; 0] = {value};")] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{binding}"); + } + } + } + + #[test] + fn all_array_bindings_match_only_plain_preceding_local_names() { + for (binding, receiver) in [ + ("let xs_other = [1, 2];", "xs"), + ("let other_xs = [1, 2];", "xs"), + ("let (xs, ys) = ([1, 2], items());", "xs"), + ("let xs = [1, 2]; let xs = items();", "xs"), + ("let xs = [1, 2];", "other.xs"), + ("let xs = [1, 2];", "other::xs"), + ("let xs = [1, 2];", "xs()"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!({receiver}.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{binding} with {receiver}"); + } + let later = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n let xs = [1, 2];\n}\n"; + assert_eq!(hits(later), [(3, "all-unguarded")], "a later binding does not initialize the receiver"); + let outside = "fn helper() { let xs = [1, 2]; }\n#[test]\nfn t() {\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(outside), [(4, "all-unguarded")], "a binding outside the test does not count"); + } + + #[test] + fn all_direct_array_literals_must_be_non_empty() { + for method in ["iter", "into_iter"] { + for array in ["[]", "[1; 0]", "[items(); 0]", "[1; 0usize]"] { + let src = format!("#[test]\nfn t() {{\n assert!({array}.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(3, "all-unguarded")], "{array} through {method}"); + } + for array in ["[1]", "[1, 2]", "[1; 2]", "[[1; 0]]", "[\"[;]\"]"] { + let src = format!("#[test]\nfn t() {{\n assert!({array}.{method}().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{array} through {method}"); + } + } + } + + #[test] + fn all_skips_mapped_arrays_of_named_rectangles() { + for (name, labels, message) in [ + ("chips", "[\"Color (, or Shift+,)\", \"Gradient (. or Shift+.)\", \"None (/)\"]", "one line"), + ("modes", "[\"Draw Normal (Shift+D)\", \"Draw Behind (Shift+D)\", \"Draw Inside (Shift+D)\"]", "side by side"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let {name} = {labels}.map(|label| named_rect(&nodes, label));\n assert!({name}.iter().all(|r| (r.top() - {name}[0].top()).abs() < 0.5), \"{message}: {{{name}:?}}\");\n}}\n" + ); + assert_eq!(hits(&src), [], "{name}"); + let empty = src.replace(labels, "[]"); + assert_eq!(hits(&empty), [(4, "all-unguarded")], "an empty {name} still passes vacuously"); + } + } + + #[test] + fn all_respects_condition_polarity() { + for condition in [ + "!xs.iter().all(|x| *x > 0)", + "!(xs.iter().all(|x| *x > 0))", + "ready() && !xs.iter().all(|x| *x > 0)", + "!xs.iter().all(|x| *x > 0) && ready()", + "xs.iter().all(|x| *x > 0) == false", + "ready() && (xs.iter().all(|x| *x > 0) == false)", + "false == xs.iter().all(|x| *x > 0)", + ] { + let good = format!("#[test]\nfn t() {{\n assert!({condition});\n}}\n"); + assert_eq!(hits(&good), [], "{condition}"); + let bad = format!("#[test]\nfn t() {{\n assert!(({condition}) && ys.iter().all(|y| *y > 0));\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "a positive operand beside {condition}"); + } + } + + #[test] + fn all_reports_positive_boolean_operands() { + for condition in [ + "xs.iter().all(|x| *x > 0)", + "ready() && xs.iter().all(|x| *x > 0)", + "xs.iter().all(|x| *x > 0) && ready()", + "ready() || xs.iter().all(|x| *x > 0)", + "xs.iter().all(|x| *x > 0) || ready()", + "!!xs.iter().all(|x| *x > 0)", + "!xs.iter().all(|x| *x > 0) == false", + "!(xs.iter().all(|x| *x > 0) == false)", + ] { + let bad = format!("#[test]\nfn t() {{\n assert!({condition});\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "{condition}"); + let good = bad.replace(" assert!", " assert_eq!(xs.len(), 3);\n assert!"); + assert_eq!(hits(&good), [], "a length check guards {condition}"); + } + } + + #[test] + fn all_guards_use_assertion_operands_and_skip_messages() { + for name in ["assert", "debug_assert", "prop_assert"] { + let good = format!("#[test]\nfn t() {{\n {name}!(xs.len() > 0);\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{name} condition"); + let bad = format!("#[test]\nfn t() {{\n {name}!(ready(), \"length {{}}\", xs.len());\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "{name} message"); + } + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + for (left, right) in [("xs.len()", "3"), ("3", "xs.len()")] { + let good = format!("#[test]\nfn t() {{\n {name}!({left}, {right});\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{name} operands"); + } + let bad = format!("#[test]\nfn t() {{\n {name}!(a, b, \"length {{}}\", xs.len());\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "{name} message"); + } + } + + #[test] + fn all_guards_require_checks_of_collection_properties() { + for expr in ["xs.len()", "xs.is_empty()", "xs.iter().count()", "xs.first()", "xs.iter().any(|x| *x > 0)", "xs.iter().next()", "xs.last()"] { + let bad = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&bad), [(4, "all-unguarded")], "unused {expr}"); + let good = format!("#[test]\nfn t() {{\n assert_eq!({expr}, expected);\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "checked {expr}"); + } + } + + #[test] + fn all_guards_accept_first_item_access_that_fails_when_empty() { + for expr in ["xs[0]", "xs.first().unwrap()", "xs.first().expect(\"item\")", "xs.iter().next().unwrap()", "xs.iter().next().expect(\"item\")"] + { + let good = format!("#[test]\nfn t() {{\n let _ = {expr};\n assert!(xs.iter().all(|x| *x > 0));\n}}\n"); + assert_eq!(hits(&good), [], "{expr} fails when empty"); + let inner = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| {expr} > 0));\n}}\n"); + assert_eq!(hits(&inner), [(3, "all-unguarded")], "{expr} inside the predicate"); + let message = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| *x > 0), \"item {{:?}}\", {expr});\n}}\n"); + assert_eq!(hits(&message), [(3, "all-unguarded")], "{expr} inside the message"); + } + let literal = "#[test]\nfn t() {\n let _ = [0];\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(literal), [(4, "all-unguarded")], "an array literal does not access an item"); + } + + #[test] + fn all_guards_accept_panicking_first_item_bindings() { + let good = "#[test]\nfn t() {\n let Some(x) = xs.first() else { panic!(\"empty\") };\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(good), []); + let bad = "#[test]\nfn t() {\n let Some(x) = xs.first() else { skip(); };\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(bad), [(4, "all-unguarded")]); + } + + #[test] + fn all_hits_count_changes_anywhere_in_their_test() { + let src = "#[should_panic]\n#[test]\nfn t() {\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\nfn other() {}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 1); + assert_eq!(found[0].line, 5); + let guarded = src.replace(" assert!(xs.iter()", " assert!(!xs.is_empty());\n assert!(xs.iter()"); + assert_eq!(hits(&guarded), [], "the guard prevents the finding before deletion"); + for line in [1, 2, 3, 4, 5, 6] { + assert!(touches(&found[0], Some(&[line].into_iter().collect())), "test line {line}"); + } + assert!(!touches(&found[0], Some(&[7].into_iter().collect())), "another function is outside the test"); + let diff = "diff --git a/crates/x/src/tests.rs b/crates/x/src/tests.rs\n--- a/crates/x/src/tests.rs\n+++ b/crates/x/src/tests.rs\n@@ -5 +4,0 @@\n- assert!(!xs.is_empty());\n"; + let changed = parse_diff(diff); + assert!(touches(&found[0], changed["crates/x/src/tests.rs"].as_ref()), "removing a guard changes the test"); + } + + #[test] + fn all_allow_comments_stay_near_the_finding() { + let distant = "#[test]\nfn t() {\n // test-lint: allow all-unguarded empty input is allowed\n let xs = f();\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(distant), [(5, "all-unguarded")]); + let adjacent = "#[test]\nfn t() {\n let xs = f();\n // test-lint: allow all-unguarded empty input is allowed\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(adjacent), []); + let same = "#[test]\nfn t() {\n assert!(xs.iter().all(|x| *x > 0)); // test-lint: allow all-unguarded empty input is allowed\n}\n"; + assert_eq!(hits(same), []); + } + + #[test] + fn only_weak_checks_are_reported_once_per_test() { + let bad = "#[test]\nfn t() {\n assert!(parse(\"a\").is_ok());\n assert!(!list().is_empty());\n}\n"; + assert_eq!(hits(bad), [(2, "only-weak")]); + let good = "#[test]\nfn t() {\n assert!(parse(\"a\").is_ok());\n assert_eq!(parse(\"a\").unwrap(), 1);\n}\n"; + assert_eq!(hits(good), []); + let refusal = "#[test]\nfn t() {\n assert!(parse(\"\").is_err());\n}\n"; + assert_eq!(hits(refusal), [], "is_err is not on the plan's list"); + let compound = "#[test]\nfn t() {\n assert!(a.is_some() && a == Some(2));\n}\n"; + assert_eq!(hits(compound), []); + } + + #[test] + fn self_compare_needs_the_same_plain_expression() { + let bad = "#[test]\nfn t() {\n let x = f();\n assert_eq!(x.len(), x.len());\n assert_eq!(&x, x);\n}\n"; + assert_eq!(hits(bad), [(4, "self-compare"), (5, "self-compare")]); + let good = "#[test]\nfn t() {\n assert_eq!(write(&doc), write(&doc), \"deterministic\");\n assert_eq!(f(\"a\"), f(\"b\"));\n assert_ne!(\"a b\", \"ab\");\n assert_ne!(x /* one */, x.y);\n assert_ne!(' ', ':');\n}\n"; + assert_eq!(hits(good), [], "literal text, including its spaces, is compared"); + } + + #[test] + fn self_compare_counts_changes_through_the_second_operand() { + let src = "#[test]\nfn t() {\n assert_eq!(\n actual,\n actual,\n \"comparison\"\n );\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 1); + let hit = &found[0]; + assert_eq!(hit.rule, Rule::SelfCompare); + assert_eq!((hit.line, hit.first, hit.last), (3, 3, 5)); + for line in [3, 4, 5] { + assert!(touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + for line in [2, 6, 7] { + assert!(!touches(hit, Some(&[line].into_iter().collect())), "changed line {line}"); + } + assert_eq!(hits(&src.replacen(" actual,", " expected,", 1)), []); + } + + #[test] + fn self_compare_keeps_exemptions_near_the_macro_opening() { + let src = "#[test]\nfn t() {\n assert_eq!( // MARKER\n actual, // OPERAND\n actual\n );\n}\n"; + let allow = "test-lint: allow self-compare checks the lint"; + assert_eq!(hits(&src.replace("MARKER", allow)), []); + assert_eq!(hits(&src.replace(" assert_eq!", &format!(" // {allow}\n assert_eq!"))), []); + assert_eq!(hits(&src.replace("OPERAND", allow)), [(3, "self-compare")]); + } + + #[test] + fn a_process_test_must_read_its_output() { + let bad = "#[test]\nfn t() {\n let out = Command::new(bin()).arg(\"x\").output().unwrap();\n assert!(out.status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = "#[test]\nfn t() {\n let out = Command::new(bin()).output().unwrap();\n assert!(out.status.success());\n assert_eq!(out.stdout, b\"ok\\n\");\n}\n"; + assert_eq!(hits(good), []); + } + + #[test] + fn process_status_checks_accept_every_comparison_assertion() { + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {name}!(out.status.code(), Some(0), \"{{:?}}\", out.stderr);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{name}"); + let good = bad.replace("Some(0)", "parse_code(&out.stdout)"); + assert_eq!(hits(&good), [], "{name} reads output in its second operand"); + } + } + + #[test] + fn process_status_checks_accept_either_compared_operand() { + for name in ["assert_eq", "assert_ne", "debug_assert_eq", "debug_assert_ne", "prop_assert_eq", "prop_assert_ne"] { + for (expected, status) in [("Some(0)", "out.status.code()"), ("true", "out.status.success()")] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {name}!({expected}, {status}, \"{{:?}}\", out.stdout);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{name} with {status} on the right"); + let good = bad.replace(expected, "parse_status(&out.stderr)"); + assert_eq!(hits(&good), [], "{name} reads output in its first operand"); + let message = bad.replace(status, "expected_status"); + assert_eq!(hits(&message), [], "{name} has no status check in its operands"); + } + } + } + + #[test] + fn process_output_in_failure_messages_does_not_count_as_reading() { + for assertion in ["assert!(out.status.success()", "debug_assert!(out.status.success()", "prop_assert!(out.status.success()"] { + let bad = + format!("#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {assertion}, \"{{:?}}\", out.stderr);\n}}\n"); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}"); + let good = bad.replace("out.status.success()", "out.status.success() && out.stdout == expected"); + assert_eq!(hits(&good), [], "output in the condition of {assertion}"); + } + for assertion in ["assert_eq", "assert_ne"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n {assertion}!(out.status.code(), f::(), \"{{:?}}\", out.stderr);\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{assertion}"); + let good = bad.replace("f::()", "from_slice(&out.stdout)"); + assert_eq!(hits(&good), [], "output in the second operand of {assertion}"); + } + } + + #[test] + fn stream_configuration_does_not_count_as_reading_output() { + for stream in ["stdout", "stderr", "stdin"] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).{stream}(Stdio::piped()).output().unwrap();\n assert!(out.status.success());\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{stream} configuration"); + let good = bad.replace(" assert!", " let _ = out.stderr;\n assert!"); + assert_eq!(hits(&good), [], "reading a field after {stream} configuration"); + } + let bad = "#[test]\nfn t() {\n let out = Command::new(bin()).stdout (std::process::Stdio::piped()).output().unwrap();\n assert!(out.status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = bad.replace("std::process::Stdio::piped()", "output.stdout"); + assert_eq!(hits(&good), [], "a field read in a builder argument counts"); + } + + #[test] + fn output_inspection_counts_outside_failure_messages() { + for read in [ + "out.stdout", + "out.stderr", + "String::from_utf8(out.stdout)", + "fs::read(path)", + "read_to_string(path)", + "from_slice(data)", + "from_str(text)", + "text.contains(needle)", + ] { + let bad = format!( + "#[test]\nfn t() {{\n let out = Command::new(bin()).output().unwrap();\n assert!(out.status.success(), \"{{:?}}\", {read});\n}}\n" + ); + assert_eq!(hits(&bad), [(2, "exit-status-only")], "{read} in a message"); + let good = bad.replace(" assert!", &format!(" let _ = {read};\n assert!")); + assert_eq!(hits(&good), [], "{read} outside a message"); + } + } + + #[test] + fn failure_messages_are_removed_for_every_standard_assertion() { + for name in [ + "assert", + "debug_assert", + "prop_assert", + "assert_eq", + "assert_ne", + "debug_assert_eq", + "debug_assert_ne", + "prop_assert_eq", + "prop_assert_ne", + ] { + let operands = if guard_arg_count(name) == 1 { "true" } else { "left, right" }; + let bad = format!("#[test]\nfn t() {{\n assert!(xs.iter().all(|x| *x > 0));\n {name}!({operands}, \"{{:?}}\", xs[0]);\n}}\n"); + assert_eq!(hits(&bad), [(3, "all-unguarded")], "{name} message"); + let good = bad.replace(" assert!", " let _ = xs[0];\n assert!"); + assert_eq!(hits(&good), [], "access outside the {name} message"); + } + } + + #[test] + fn assertion_arguments_keep_turbofish_groups_and_split_comparisons() { + for operand in ["f::()", "f::>()", "f :: ()"] { + let src = format!("{operand}, expected, message"); + let m = mask(&src); + let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| src[from..to].trim()).collect(); + assert_eq!(args, [operand, "expected", "message"], "{operand}"); + let comparison = format!("a < b, {operand} > c, message"); + let m = mask(&comparison); + let args: Vec<&str> = split_args(&m, 0, m.len()).into_iter().map(|(from, to)| comparison[from..to].trim()).collect(); + assert_eq!(args, ["a < b", &format!("{operand} > c"), "message"], "comparisons around {operand}"); + } + } + + #[test] + fn a_test_needs_an_assertion_or_an_asserting_helper() { + let bad = "#[test]\nfn t() {\n let d = open(\"x\").unwrap();\n d.save();\n}\n"; + assert_eq!(hits(bad), [(2, "no-assertion")]); + let panics = "fn f() {}\n/// Panics.\n#[should_panic(expected = \"x\")]\n#[test]\nfn p() {\n f();\n}\n"; + assert_eq!(hits(panics), [], "#[should_panic] before #[test]"); + let src = "fn same(a: u8, b: u8) {\n assert_eq!(a, b);\n}\nfn twice(a: u8) {\n same(a, a);\n}\n#[test]\nfn t() {\n twice(f());\n}\n#[test]\n#[should_panic]\nfn p() {\n f();\n}\n#[test]\nfn q() {\n check_round_trip(f());\n}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); + assert!(helpers["crates/x"].contains("twice"), "{helpers:?}"); + let ctx = Ctx { helpers, ci_env: HashSet::new() }; + assert_eq!(hits_in("crates/x/tests/it.rs", src, &ctx), []); + assert_eq!(hits_in("crates/y/tests/it.rs", src, &ctx), [(8, "no-assertion")], "another crate's helper does not count"); + let kit = asserting_helpers(&[("crates/testkit/src/lib.rs".to_owned(), src.to_owned()), ("crates/y/src/lib.rs".to_owned(), String::new())]); + assert!(kit["crates/y"].contains("twice"), "testkit helpers count in every crate: {kit:?}"); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers: HashMap::new(), ci_env: HashSet::new() }), [(8, "no-assertion")]); + } + + #[test] + fn generic_asserting_calls_count_for_functions_and_methods() { + for call in ["check_round_trip::()", "check_round_trip::>(x)", "value.check::()", "value.check :: >> ()"] { + let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); + assert_eq!(hits(&src), [], "{call}"); + } + for expression in ["check_round_trip::", "value.check::", "round_trip::()", "value.round_trip::()"] { + let src = format!("#[test]\nfn t() {{\n let _ = {expression};\n}}\n"); + assert_eq!(hits(&src), [(2, "no-assertion")], "{expression}"); + } + } + + #[test] + fn generic_crate_helpers_count_through_other_helpers() { + let defs = "fn same(a: T, b: T) { assert_eq!(a, b); }\nfn twice(a: T) { same::(a, a); }\nfn idle() {}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/helpers.rs".to_owned(), defs.to_owned())]); + assert!(helpers["crates/x"].contains("same")); + assert!(helpers["crates/x"].contains("twice")); + assert!(!helpers["crates/x"].contains("idle")); + let ctx = Ctx { helpers, ci_env: HashSet::new() }; + for call in ["same::(a, b)", "twice::>>(x)"] { + let src = format!("#[test]\nfn t() {{\n {call};\n}}\n"); + assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [], "{call}"); + assert_eq!(hits_in("crates/y/tests/it.rs", &src, &ctx), [(2, "no-assertion")], "{call} in another crate"); + } + for expression in ["idle::()", "same::", "value.same::()"] { + let src = format!("#[test]\nfn t() {{\n let _ = {expression};\n}}\n"); + assert_eq!(hits_in("crates/x/tests/it.rs", &src, &ctx), [(2, "no-assertion")], "{expression}"); + } + } + + #[test] + fn early_returns_on_values_are_reported_and_resource_skips_are_not() { + let bad = "#[test]\nfn t() {\n let Some(n) = find() else { return };\n assert_eq!(n, 2);\n}\n"; + assert_eq!(hits(bad), [(3, "early-return")]); + let fonts = "#[test]\nfn t() {\n let Some(face) = installed_family(\"Kufi\") else { return; };\n assert_eq!(face.n, 2);\n}\n"; + assert_eq!(hits(fonts), []); + let closure = "#[test]\nfn t() {\n let f = |x: u8| { if x == 0 { return; } g(x) };\n assert_eq!(f(1), ());\n}\n"; + assert_eq!(hits(closure), []); + let last = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n if g() { return; }\n}\n"; + assert_eq!(hits(last), []); + let value = "#[test]\nfn t() -> Result<(), String> {\n if f()? == 0 { return Ok(()); }\n assert_eq!(g(), 1);\n Ok(())\n}\n"; + assert_eq!(hits(value), [(3, "early-return")]); + let checked = "#[test]\nfn t() {\n for _ in 0..9 {\n if g() == 1 {\n assert_eq!(f(), 2);\n return;\n }\n }\n panic!(\"never stable\");\n}\n"; + assert_eq!(hits(checked), [], "a return after an assertion in its block"); + let said = "#[test]\nfn t() {\n if !link(\"a\") {\n eprintln!(\"skipped: no links here\");\n return;\n }\n assert_eq!(f(), 2);\n}\n"; + assert_eq!(hits(said), [], "a return after a printed skip note"); + let commented = "#[test]\nfn t() {\n let Some(w) = width() else { return }; // no wide font here\n assert_eq!(w, 2);\n}\n"; + assert_eq!(hits(commented), [], "a return whose line says why"); + let quiet = "#[test]\nfn t() {\n if !link(\"a\") {\n return;\n }\n assert_eq!(f(), 2);\n}\n"; + assert_eq!(hits(quiet), [(4, "early-return")]); + } + + #[test] + fn ignore_needs_a_reason() { + let bad = "#[test]\n#[ignore]\nfn t() {\n assert_eq!(f(), 1);\n}\n#[ignore = \" \"]\n#[test]\nfn u() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bad), [(2, "ignore-without-reason"), (6, "ignore-without-reason")]); + let good = "#[test]\n#[ignore = \"a benchmark: run with --ignored\"]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(good), []); + } + + #[test] + fn ignore_accepts_non_empty_raw_string_reasons() { + for hashes in ["", "#", "##", "########"] { + for reason in ["requires an external service", " service ", r"service \ path"] { + let literal = format!("r{hashes}\"{reason}\"{hashes}"); + let src = format!("#[test]\n#[ignore = {literal}]\nfn t() {{ assert_eq!(f(), 1); }}\n"); + assert_eq!(hits(&src), [], "{literal}"); + } + for reason in ["", " ", "\t\n"] { + let literal = format!("r{hashes}\"{reason}\"{hashes}"); + let src = format!("#[test]\n#[ignore = {literal}]\nfn t() {{ assert_eq!(f(), 1); }}\n"); + assert_eq!(hits(&src), [(2, "ignore-without-reason")], "{literal}"); + } + } + } + + #[test] + fn env_gates_need_a_variable_ci_sets() { + let bad = "#[test]\nfn t() {\n let Ok(dir) = std::env::var(\"MY_SAMPLES\") else { return };\n assert_eq!(count(&dir), 3);\n}\n"; + assert_eq!(hits(bad), [(3, "env-gate-unset")]); + let ci = "#[test]\nfn t() {\n if std::env::var(\"SET_IN_CI\").is_ok() { assert_eq!(f(), 1); }\n assert_eq!(std::env::var(\"CARGO_PKG_NAME\").unwrap(), \"x\");\n}\n"; + assert_eq!(hits(ci), []); + let child = "const CHILD: &str = \"X_TEST_CHILD\";\n#[test]\nfn t() {\n if std::env::var_os(\"X_TEST_CHILD\").is_some() { assert_eq!(f(), 1); }\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(child), []); + } + + #[test] + fn env_gates_ignore_commented_out_setters() { + for setter in ["cmd.env(\"MY_SAMPLES\", dir);", "std::env::set_var(\"MY_SAMPLES\", \"x\");", "const X: &str = \"MY_SAMPLES\";"] { + for comment in [format!("// {setter}"), format!("/* {setter} */"), format!("/* outer /* {setter} */ end */")] { + let src = + format!("{comment}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [(4, "env-gate-unset")], "{comment}"); + } + } + } + + #[test] + fn env_gates_keep_code_setters_and_literal_contents() { + for setter in [ + "cmd . env ( \"MY_SAMPLES\", dir);", + "std::env::set_var ( \"MY_SAMPLES\", \"x\");", + "set_var(\"MY_SAMPLES\", \"x\");", + "use std::env::set_var; fn setup() { set_var(\"MY_SAMPLES\", \"x\"); }", + "cmd.set_var(\"MY_SAMPLES\", \"x\");", + "const X: &str = \"MY_SAMPLES\";", + "cmd.env(/* name */ \"MY_SAMPLES\", dir);", + ] { + let src = format!("{setter}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [], "{setter}"); + assert_eq!(hits(&src.replacen("MY_SAMPLES", "OTHER_SAMPLES", 1)), [(4, "env-gate-unset")], "{setter}"); + } + let src = "let a = \"https://host/*path*/\"; /* removed */ let b = r#\"// kept /* kept */\"#; // removed\nlet c = '/';"; + let masked = String::from_utf8(mask_comments(src)).unwrap(); + assert!(masked.contains("\"https://host/*path*/\"")); + assert!(masked.contains("r#\"// kept /* kept */\"#")); + assert!(masked.contains("let c = '/';")); + assert!(!masked.contains("removed")); + } + + #[test] + fn env_gates_require_setter_call_boundaries() { + for reader in [ + "read_env(\"MY_SAMPLES\");", + "cmd.read_env(\"MY_SAMPLES\");", + "env(\"MY_SAMPLES\", dir);", + "my_set_var(\"MY_SAMPLES\", \"x\");", + "std::env::my_set_var(\"MY_SAMPLES\", \"x\");", + "cmd.my_set_var(\"MY_SAMPLES\", \"x\");", + ] { + let src = format!("{reader}\n#[test]\nfn t() {{\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(dir, expected);\n}}\n"); + assert_eq!(hits(&src), [(4, "env-gate-unset")], "{reader}"); + } + } + + #[test] + fn sleep_in_test_code_is_reported() { + let bad = "fn wait() {\n std::thread::sleep(Duration::from_millis(5));\n}\n#[test]\nfn t() {\n thread::sleep(D);\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bad), [(2, "sleep"), (6, "sleep")]); + let good = "fn sleep(d: D) {}\n#[test]\nfn t() {\n run(\"$.sleep(250)\");\n clock.sleep(D);\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(good), []); + let shipped = "pub fn wait() {\n std::thread::sleep(D);\n}\n#[cfg(test)]\nmod tests {}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", shipped, &ctx()), [], "code before #[cfg(test)] is not test code"); + assert_eq!(hits_in("xtask/src/test_lint.rs", shipped, &ctx()), [], "a name that only starts with test is not a test file"); + let after = "#[cfg(test)]\nmod tests {\n fn w() { thread::sleep(D); }\n}\npub fn later() {\n thread::sleep(D);\n}\n"; + assert_eq!(hits_in("crates/x/src/lib.rs", after, &ctx()), [(3, "sleep")], "code after a #[cfg(test)] module is not test code"); + for test_file in [ + "crates/x/src/tests.rs", + "crates/x/src/tests_wheel.rs", + "crates/x/src/widget_tests.rs", + "crates/x/tests/it/a.rs", + "crates/testkit/src/lib.rs", + ] { + assert_eq!(hits_in(test_file, shipped, &ctx()), [(2, "sleep")], "{test_file}"); + } + } + + #[test] + fn reading_rust_source_is_reported_outside_the_audits() { + let bad = "#[test]\nfn t() {\n let src = include_str!(\"../lib.rs\");\n assert_eq!(src.matches(\"x\").count(), 1);\n}\n"; + assert_eq!(hits(bad), [(3, "reads-source")]); + let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(\".rs\")).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(hits(walk), [(3, "reads-source")]); + 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), []); + } + + #[test] + fn allow_comments_need_the_rule_and_a_reason() { + let src = "#[test]\nfn t() {\n // test-lint: allow sleep the file clock has a 2 ms step\n thread::sleep(D);\n thread::sleep(D); // test-lint: allow sleep same\n assert_eq!(f(), 1);\n thread::sleep(D); // test-lint: allow sleep\n thread::sleep(D); // test-lint: allow early-return wrong rule\n}\n// test-lint: allow no-assertion a smoke test of the panic-free reader\n#[test]\nfn u() {\n let _ = read(b\"junk\");\n}\n"; + assert_eq!(hits(src), [(7, "sleep"), (8, "sleep")], "an allow covers its own line and the next, and needs a reason"); + let strings = "#[test]\nfn t() {\n let s = \"test-lint: allow sleep in a string\"; thread::sleep(D);\n let r = r#\"test-lint: allow sleep raw\"#; thread::sleep(D);\n /* test-lint: allow sleep a block comment */ thread::sleep(D);\n assert_eq!(s, r);\n}\n"; + assert_eq!(hits(strings), [(3, "sleep"), (4, "sleep")], "a marker in a literal is not an exemption"); + } + + #[test] + fn comments_and_strings_are_not_code() { + let src = "#[test]\nfn t() {\n // assert!(x.iter().all(|y| y))\n let s = \"thread::sleep(d); #[ignore]\";\n let r = r#\"env::var(\"NOPE\")\"#;\n let c = '\"';\n assert_eq!(s, r);\n}\n"; + assert_eq!(hits(src), []); + } + + #[test] + fn tests_are_found_by_their_attributes() { + let src = "#[cfg(test)]\nmod tests {\n #[tokio::test]\n async fn a() {}\n #[test_case(1)]\n fn b(n: u8) {}\n proptest! {\n #[test]\n fn c(x in 0..9u8) {}\n }\n #[test]\n fn d() -> Result<(), String> { Ok(()) }\n fn not_a_test() {}\n}\n"; + let names: Vec = tests_in(&mask(src)).into_iter().map(|t| t.name).collect(); + assert_eq!(names, ["a", "b", "c", "d"]); + } + + #[test] + fn changed_lines_come_from_the_new_side_of_each_hunk() { + let diff = "diff --git a/crates/x/src/a.rs b/crates/x/src/a.rs\nindex 1..2 100644\n--- a/crates/x/src/a.rs\n+++ b/crates/x/src/a.rs\n@@ -3,0 +4,2 @@ fn f() {\n+a\n+b\n@@ -10 +12 @@\n-c\n+d\n@@ -20,2 +21,0 @@\n-e\ndiff --git a/crates/x/src/n.rs b/crates/x/src/n.rs\nnew file mode 100644\n--- /dev/null\n+++ b/crates/x/src/n.rs\n@@ -0,0 +1,3 @@\n"; + let got = parse_diff(diff); + assert_eq!(got.len(), 2); + assert_eq!(got["crates/x/src/a.rs"], Some([4, 5, 12, 21, 22].into_iter().collect())); + assert_eq!(got["crates/x/src/n.rs"], None); + } + + #[test] + fn deleting_the_first_attribute_changes_the_remaining_test() { + let path = "crates/x/src/tests.rs"; + for (prefix, anchor) in [("", 0), ("fn before() {}\n", 1)] { + let src = format!("{prefix}#[test]\nfn t() {{}}\n#[test]\nfn other() {{}}\n"); + let before = src.replacen("#[test]", "#[should_panic]\n#[test]", 1); + assert!(lint_file(path, &before, &ctx()).iter().all(|h| h.test != "t"), "the attribute prevents the finding"); + let found = lint_file(path, &src, &ctx()); + assert_eq!(found.len(), 2); + let old = anchor + 1; + let diff = format!("diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -{old} +{anchor},0 @@\n-#[should_panic]\n"); + let changed = parse_diff(&diff); + let expected = if anchor == 0 { vec![1] } else { vec![anchor, anchor + 1] }; + assert_eq!(changed[path], Some(expected.into_iter().collect())); + assert_eq!(found[0].rule, Rule::NoAssertion); + assert_eq!(found[0].test, "t"); + assert!(touches(&found[0], changed[path].as_ref()), "the deletion changes the remaining test"); + assert!(!touches(&found[1], changed[path].as_ref()), "the following test is unchanged"); + } + } + + #[test] + fn only_hits_on_changed_lines_count() { + let src = "#[test]\nfn old() {\n f();\n}\n#[test]\nfn new() {\n g();\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.len(), 2); + let changed: BTreeSet = [7].into_iter().collect(); + let counted: Vec<&str> = found.iter().filter(|h| touches(h, Some(&changed))).map(|h| h.test.as_str()).collect(); + assert_eq!(counted, ["new"]); + assert_eq!(found.iter().filter(|h| touches(h, None)).count(), 2); + assert_eq!(found.iter().filter(|h| touches(h, Some(&BTreeSet::new()))).count(), 0); + } + + #[test] + fn options_reject_unknown_and_repeated_arguments() { + assert_eq!(Options::parse(&[]), Ok(Options::default())); + assert_eq!(Options::parse(&["--base", "abc"]), Ok(Options { all: false, base: Some("abc".into()) })); + assert_eq!(Options::parse(&["--all"]), Ok(Options { all: true, base: None })); + for bad in [&["--base"][..], &["--base", "--all"], &["--all", "--all"], &["--fix"], &["--all", "--base", "x"]] { + assert!(Options::parse(bad).unwrap_err().starts_with("test-lint:"), "{bad:?}"); + } + } + + #[test] + fn workflow_variables_count_as_set() { + let names: Vec = upper_words("env:\n AFFINITY_CORPUS_REQUIRED: 1\n run: X=1 cargo test # A\n").collect(); + assert_eq!(names, ["AFFINITY_CORPUS_REQUIRED"]); + assert!(set_by_system("CARGO_MANIFEST_DIR") && set_by_system("HOME") && !set_by_system("MY_SAMPLES")); + } + + #[test] + fn workflow_mapping_keys_count_without_reads_or_comments() { + let assigned: Vec = upper_words("env:\n MY_SAMPLES: fixtures\n - OTHER_SAMPLES: fixtures\n EMPTY_SAMPLES:\n").collect(); + assert_eq!(assigned, ["MY_SAMPLES", "OTHER_SAMPLES", "EMPTY_SAMPLES"]); + let reads = "# MY_SAMPLES: fixtures\nif: env.MY_SAMPLES != ''\nrun: echo $OTHER_SAMPLES ${EMPTY_SAMPLES}\nvalue: ${{ env.MY_SAMPLES }}\n"; + assert_eq!(upper_words(reads).collect::>(), Vec::::new()); + } + + #[test] + fn workflow_script_assignments_count_without_reads_or_comments() { + for assignment in [ + " MY_SAMPLES=value", + " export MY_SAMPLES=value", + " run: MY_SAMPLES=value cargo test", + " echo \"MY_SAMPLES=value\" >> \"$GITHUB_ENV\"", + " echo 'MY_SAMPLES=value' >> \"$GITHUB_ENV\"", + " MY_SAMPLES=value # OTHER_SAMPLES=value", + " MY_SAMPLES=\"#value\"", + " MY_SAMPLES=", + " - MY_SAMPLES=value", + ] { + assert_eq!(upper_words(assignment).collect::>(), ["MY_SAMPLES"], "{assignment}"); + let commented = format!("# {assignment}"); + assert_eq!(upper_words(&commented).collect::>(), Vec::::new(), "{commented}"); + } + let reads = "env.MY_SAMPLES=value\n${{ env.MY_SAMPLES }}\n$MY_SAMPLES\n${MY_SAMPLES}\nMY_SAMPLES==value\n"; + assert_eq!(upper_words(reads).collect::>(), Vec::::new()); + } + + #[test] + fn workflow_mentions_do_not_suppress_unset_gates() { + let src = "#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + for workflow in ["if: env.MY_SAMPLES != ''", "run: echo $MY_SAMPLES", "# MY_SAMPLES=value"] { + let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [(3, "env-gate-unset")], "{workflow}"); + } + for workflow in ["env:\n MY_SAMPLES: fixtures", "run: |\n export MY_SAMPLES=fixtures", "with:\n env: |\n MY_SAMPLES=fixtures"] { + let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words(workflow).collect() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [], "{workflow}"); + } + } +} From f677523787f00ad35282422242e369c860aeb6c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 03:23:37 -0800 Subject: [PATCH 15/37] Menus: the keymap test counts only runs the catalogs held still through A font, plug-in, script or proof setup change from a test running alongside rebuilds the menus, so the test now holds the fonts and plug-ins steady and runs again on a new app, at most 20 times, until the catalogs held still, as the Selection move test in canvas/tests.rs does. --- crates/ui-egui/src/menus/model.rs | 70 +++++++++++++++++++++---------- 1 file changed, 48 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/menus/model.rs b/crates/ui-egui/src/menus/model.rs index 3095b74794..ced219084f 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -743,7 +743,9 @@ mod tests { /// A new window keymap with nothing else changed (the framework builds the first one after the first frame's /// menus) sets the panel rows' shortcuts from it, in the bar and in the laid-out bar, without building the menus - /// again. + /// again. The menus are also built again when a process-wide catalog changes, so the fonts and plug-ins are held + /// steady against tests running alongside, and the steps run again on a new app, at most 20 times, until the + /// other catalogs held still through them. #[test] fn a_new_keymap_alone_sets_the_shortcuts_without_a_rebuild() { fn clear(nodes: &mut [Node]) { @@ -761,28 +763,52 @@ mod tests { .filter(|it| it.command.id == "window.panel" && it.command.params["toggle"] == true && it.shortcut.is_some()) .count() } - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); - app.run("file.new", json!({})).unwrap(); - let ctx = crate::testing::ui_context(); - for _ in 0..2 { - crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default()); - } - let shown = panel_chords(&app.menus.bar); + let fonts = vectorcraft_text::FontDb::global(); + let _steady = (vectorcraft_text::test_fonts::steady_fonts(fonts), vectorcraft_plugins::steady::steady_plugins()); + let catalogs = || { + ( + crate::menus::plugin_revision(), + fonts.generation(), + fonts.installed_fonts_ready(), + crate::scripts_menu::revision(), + crate::dialogs::proof_setup::saved_revision(), + ) + }; + let run = || { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let ctx = crate::testing::ui_context(); + for _ in 0..2 { + crate::testing::app_frame(&mut app, &ctx, egui::RawInput::default()); + } + let shown = panel_chords(&app.menus.bar); + // The menus as a refresh before the window's keymap leaves them. + app.menus.keymap = None; + for menu in &mut app.menus.bar.menus { + clear(&mut menu.children); + } + app.menus.laid.edit(|laid| laid.menus.iter_mut().for_each(|menu| clear(&mut menu.children))); + let (rebuilds, refreshes) = (app.menus.rebuilds, app.menus.shortcut_refreshes); + refresh(&mut app, &ctx); + let first = (app.menus.rebuilds - rebuilds, app.menus.shortcut_refreshes - refreshes); + let chords = (panel_chords(&app.menus.bar), panel_chords(&app.menus.laid)); + refresh(&mut app, &ctx); + let second = (app.menus.rebuilds - rebuilds, app.menus.shortcut_refreshes - refreshes); + (shown, first, chords, second) + }; + let (shown, first, chords, second) = (0..20) + .find_map(|_| { + let before = catalogs(); + let out = run(); + (catalogs() == before).then_some(out) + }) + .unwrap_or_else(|| panic!("tests running alongside kept changing the font and plug-in catalogs")); assert!(shown > 0, "the panel rows show their shortcuts' chords"); - // The menus as a refresh before the window's keymap leaves them. - app.menus.keymap = None; - for menu in &mut app.menus.bar.menus { - clear(&mut menu.children); - } - app.menus.laid.edit(|laid| laid.menus.iter_mut().for_each(|menu| clear(&mut menu.children))); - let (rebuilds, refreshes) = (app.menus.rebuilds, app.menus.shortcut_refreshes); - refresh(&mut app, &ctx); - assert_eq!(app.menus.rebuilds, rebuilds, "a new keymap alone does not build the menus again"); - assert_eq!(app.menus.shortcut_refreshes, refreshes + 1, "the new keymap sets the shortcuts"); - assert_eq!(panel_chords(&app.menus.bar), shown, "the panel rows show their chords again"); - assert_eq!(panel_chords(&app.menus.laid), shown, "the laid-out bar shows them too"); - refresh(&mut app, &ctx); - assert_eq!((app.menus.rebuilds, app.menus.shortcut_refreshes), (rebuilds, refreshes + 1), "the same keymap sets nothing again"); + assert_eq!(first.0, 0, "a new keymap alone does not build the menus again"); + assert_eq!(first.1, 1, "the new keymap sets the shortcuts"); + assert_eq!(chords.0, shown, "the panel rows show their chords again"); + assert_eq!(chords.1, shown, "the laid-out bar shows them too"); + assert_eq!(second, (0, 1), "the same keymap sets nothing again"); } /// A rebuild runs the check of a command that many rows share once: Effect's dialogs, Window's panels, the From 25756e1b8d38fc93ef8b6c5989253b4a00fc4fd3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 04:43:33 -0800 Subject: [PATCH 16/37] xtask: test-lint fails on four rules; all-unguarded skips collections that cannot be empty Replayed over the last 300 merges of main, all-unguarded failed good pull requests on collections that cannot be empty. It now leaves out: - plain locals bound to an array type of a positive length, to a non-empty array literal or vec![...], or to a literal range followed only by methods that keep an item (map, iter, rev, collect into a known collection ...); counts may be consts of the file - locals filled by a push or insert on every pass of a loop over such a source - fields and const or static items the file declares only as arrays of a positive length - collections compared with a non-empty literal through such methods, directly or through a local built from them, and assertions on a local bound to a count or length - .windows(k) and .chunks_exact(k) when the collection has k items Later code that may remove items or replace the collection cancels the exemption. Only only-weak, self-compare, ignore-without-reason and sleep fail the check now. The other rules list their hits on changed lines without failing. On the same 300 merges, 1 would fail (an only-weak test), and the 3 all-unguarded hits are tests an empty result passes. On main at 07037afda8, all-unguarded lists 392 hits instead of 433. --- docs/development.md | 2 +- xtask/src/main.rs | 7 +- xtask/src/test_lint.rs | 1164 ++++++++++++++++++++++++++++++++++++---- 3 files changed, 1065 insertions(+), 108 deletions(-) diff --git a/docs/development.md b/docs/development.md index 26058129e7..cfd02bacc8 100644 --- a/docs/development.md +++ b/docs/development.md @@ -351,7 +351,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`) fails on tests that a wrong result can pass, in the lines and tests changed since a base: `assert!(….all(…))` with no length or emptiness check, a test whose only checks are `is_ok`, `is_some` or `!is_empty`, `assert_eq!(x, x)`, 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, `#[ignore]` without a reason, an environment variable that no CI leg sets, `thread::sleep` in test code, and test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. 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 a test whose only checks are `is_ok`, `is_some` or `!is_empty` (`only-weak`), `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: `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 test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. 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. ## Tests diff --git a/xtask/src/main.rs b/xtask/src/main.rs index f48f088aa8..addf9cb7e1 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -34,9 +34,10 @@ commands: brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) test-lint [--base ] [--all] - fail on weak tests (unguarded .all(), only is_ok/is_some checks, no assertion, early - returns, unset env gates, sleeps...) in the lines changed since the base - (xtask/src/test_lint.rs); --all lists every hit by crate and never fails + weak tests in the lines changed since the base: fail on only is_ok/is_some checks, + self-compares, reasonless #[ignore] and sleeps; list unguarded .all(), no assertion, + early returns, unset env gates... (xtask/src/test_lint.rs); --all lists every hit + by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a broken scan; ci runs it too) ui-commands regenerate crates/mcp/src/ui_catalog.rs from desktop UI_COMMANDS; --check fails on drift diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 8664403997..60363000fd 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -9,9 +9,15 @@ //! matches, with whole negations or `!=` comparisons joined only by `&&`, are left out). An earlier //! `assert_eq!`, `debug_assert_eq!` or `prop_assert_eq!` comparing a plain local receiver //! (optionally borrowed or viewed through `.as_slice()` or `[..]`) with a non-empty array -//! literal or `vec![…]` guards only that receiver. Non-empty array literals and plain local -//! names bound to them in the test, optionally through `.map(…)`, are also left out. Empty arrays -//! still count. A change anywhere in the test counts as a change to the hit; +//! literal or `vec![…]` guards only that receiver, and so does an assertion on a local bound to a +//! count, length or emptiness check. Collections that cannot be empty are also left out: +//! non-empty array literals; plain locals of the test bound to an array type of a positive length, +//! to a non-empty array literal or `vec![…]` or a literal range (lengths and repetition counts may +//! be `const`s of the file) followed only by methods that keep an item (`map`, `iter`, `rev`, +//! `collect` …), or filled by a `push` or `insert` on every pass of a loop over one, unless later +//! code may shrink or replace them; and fields the file declares only as arrays of a positive +//! length. `.windows(k)` and `.chunks_exact(k)` need `k` items. Empty arrays still count. A change +//! anywhere in the test counts as a change to the hit; //! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the //! test calls no asserting helper; //! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that @@ -50,6 +56,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::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::Path; use std::process::Command; @@ -156,6 +163,11 @@ impl Rule { } } + /// Whether a hit on a changed line fails the command. The other rules only report. + pub fn fails(self) -> bool { + matches!(self, Rule::OnlyWeak | Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep) + } + fn from_id(id: &str) -> Option { Rule::ALL.into_iter().find(|r| r.id() == id) } @@ -254,20 +266,33 @@ impl Options { fn finish(counted: &[Hit], older: usize, files: usize, base: &str) -> Result<(), String> { let older = if older == 0 { String::new() } else { format!("; {older} hit(s) on unchanged lines of those files are not counted") }; - if counted.is_empty() { - println!("test-lint: no hits in the changed lines of {files} Rust file(s) since {base}{older}"); + let (failing, reported): (Vec<&Hit>, Vec<&Hit>) = counted.iter().partition(|h| h.rule.fails()); + if !reported.is_empty() { + println!( + "test-lint: {} hit(s) of report-only rules in the lines changed since {base} (they do not fail the check):\n {}", + reported.len(), + listing(&reported).join("\n ") + ); + } + if failing.is_empty() { + println!("test-lint: no failing hits in the changed lines of {files} Rust file(s) since {base}{older}"); return Ok(()); } - let mut out: Vec = counted.iter().map(Hit::show).collect(); - let rules: BTreeSet = counted.iter().map(|h| h.rule).collect(); - out.extend(rules.iter().map(|r| format!("{}: {}", r.id(), r.advice()))); Err(format!( "{} test-lint hit(s) in the lines changed since {base}{older} (exempt a line with `// {ALLOW} `):\n {}", - counted.len(), - out.join("\n ") + failing.len(), + listing(&failing).join("\n ") )) } +/// Each hit, then the advice for each rule they break. +fn listing(hits: &[&Hit]) -> Vec { + let mut out: Vec = hits.iter().map(|h| h.show()).collect(); + let rules: BTreeSet = hits.iter().map(|h| h.rule).collect(); + out.extend(rules.iter().map(|r| format!("{}: {}", r.id(), r.advice()))); + out +} + /// `--all`: counts by crate and rule, then every hit. fn report(hits: &[Hit], files: usize) -> String { let mut by_crate: BTreeMap> = BTreeMap::new(); @@ -1113,21 +1138,26 @@ impl View<'_> { const PLAIN_ASSERTS: &[&str] = &["assert", "debug_assert", "prop_assert"]; +/// Calls whose result says how many items a collection has. +const SIZE_CHECKS: &[&str] = &[".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"]; + fn all_unguarded(v: &View) -> Vec { let mut body = v.body_without_messages(); strip_all_predicates(&mut body); + let locals = bindings(&body); let checked = v.asserts.iter().any(|a| { a.args.iter().take(guard_arg_count(&a.name)).any(|&(from, to)| { - let arg = norm(&body[from - v.t.open..to - v.t.open]); - [".len()", ".is_empty()", ".count()", ".first()", ".any(", ".next()", ".last()"].iter().any(|g| arg.contains(g)) + let (from, to) = (from - v.t.open, to - v.t.open); + SIZE_CHECKS.iter().any(|g| norm(&body[from..to]).contains(g)) || reads_counted_local(&body, &locals, from, to) }) }); - if checked || first_item_guard(&body) { + let sizes = Sizes { file: &v.file.m, consts: OnceCell::new() }; + if checked || first_item_guard(&body, &sizes) { return vec![]; } v.asserts .iter() - .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && unguarded_all(&v.first_arg(a), &v.file.m[v.t.open..a.at])) + .filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && unguarded_all(&v.first_arg(a), &v.file.m[v.t.open..a.at], &sizes)) .map(|a| { let mut h = v.hit(a.at, Rule::AllUnguarded, format!("{}!(…all(…)) with no length or emptiness check in the test", a.name)); h.first = v.file.lines.of(v.t.attr); @@ -1157,10 +1187,10 @@ fn strip_all_predicates(body: &mut [u8]) { } /// Whether test code accesses a first item in a way that fails on an empty collection. -fn first_item_guard(body: &[u8]) -> bool { +fn first_item_guard(body: &[u8], sizes: &Sizes) -> bool { let compact = norm(body); let unwrapped = [".first().unwrap()", ".first().expect(", ".next().unwrap()", ".next().expect("]; - let indexed = compact.match_indices("[0]").any(|(at, _)| !on_array_literal(&compact[..at + 3])); + let indexed = compact.match_indices("[0]").any(|(at, _)| array_literal_len(&compact[..at + 3], sizes).is_none_or(|n| n == 0)); indexed || unwrapped.iter().any(|g| compact.contains(g)) || panicking_first_binding(body) } @@ -1179,27 +1209,27 @@ fn panicking_first_binding(body: &[u8]) -> bool { /// Whether a (masked, whitespace-free) condition holds an `.all(…)` that an empty collection would /// pass by mistake. Left out: a negated result, a closure that says no item matches (whole -/// negations or `!=` comparisons joined only by `&&`), and a non-empty array literal or a local -/// name bound to or previously compared equal to one. -fn unguarded_all(cond: &str, body: &[u8]) -> bool { - all_with_polarity(cond, true, body) +/// negations or `!=` comparisons joined only by `&&`), and a collection the test shows cannot be +/// empty ([`least_items`]). +fn unguarded_all(cond: &str, body: &[u8], sizes: &Sizes) -> bool { + all_with_polarity(cond, true, body, sizes) } /// Tracks negation through boolean operands and comparisons with `false`. -fn all_with_polarity(cond: &str, positive: bool, body: &[u8]) -> bool { +fn all_with_polarity(cond: &str, positive: bool, body: &[u8], sizes: &Sizes) -> bool { if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) { - return all_with_polarity(&cond[1..cond.len() - 1], positive, body); + return all_with_polarity(&cond[1..cond.len() - 1], positive, body, sizes); } if let Some(at) = boolean_split(cond) { - return all_with_polarity(&cond[..at], positive, body) || all_with_polarity(&cond[at + 2..], positive, body); + return all_with_polarity(&cond[..at], positive, body, sizes) || all_with_polarity(&cond[at + 2..], positive, body, sizes); } if let Some(expr) = cond.strip_suffix("==false").or_else(|| cond.strip_prefix("false==")) { - return all_with_polarity(expr, !positive, body); + return all_with_polarity(expr, !positive, body, sizes); } if let Some(expr) = cond.strip_prefix('!') { - return all_with_polarity(expr, !positive, body); + return all_with_polarity(expr, !positive, body, sizes); } - positive && positive_all(cond, body) + positive && positive_all(cond, body, sizes) } /// Finds a boolean operator outside parentheses, brackets and braces. @@ -1215,13 +1245,14 @@ fn boolean_split(cond: &str) -> Option { None } -fn positive_all(cond: &str, test_body: &[u8]) -> bool { +fn positive_all(cond: &str, test_body: &[u8], sizes: &Sizes) -> bool { cond.match_indices(".all(").any(|(i, _)| { let rest = &cond[i + ".all(".len()..]; let arg = &rest[..arg_end(rest)]; let body = arg.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(arg, |(_, body)| body); let none_match = not_equal_conjunction(body); - !none_match && !on_array_literal(&cond[..i]) && !on_bound_array(&cond[..i], test_body) && !on_equal_array(&cond[..i], test_body) + let (receiver, need) = receiver_need(&cond[..i], sizes); + !none_match && least_items(receiver, test_body, sizes) < need }) } @@ -1274,33 +1305,217 @@ fn whole_negation(body: &str) -> bool { !rest.is_empty() } -/// Whether an earlier equality assertion compares this plain local receiver with a non-empty literal. -fn on_equal_array(receiver: &str, body: &[u8]) -> bool { - let name = array_receiver(receiver); - if name.is_empty() || name.as_bytes()[0].is_ascii_digit() || !name.bytes().all(is_ident) { - return false; - } - macro_calls(body, 0, body.len()).iter().any(|a| { - if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { - return false; +/// The fewest items the test shows `receiver` (the text before `.all(`, without its iterator +/// method) to have: a non-empty array literal, a plain local bound to one or to a sized +/// initializer ([`expr_len`]) or filled by a loop ([`loop_fill_len`]), a plain local an earlier +/// equality assertion compares with a non-empty literal, or a field the file declares as an +/// array of a positive length. 0 when the test does not show it. +fn least_items(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { + let literal = array_literal_len(receiver, sizes).unwrap_or(0); + let derived = derived_locals(receiver, body).iter().map(|(d, from)| equal_len(d, body, sizes, Some(*from))).max().unwrap_or(0); + literal + .max(bound_len(receiver, body, sizes)) + .max(equal_len(receiver, body, sizes, None)) + .max(derived) + .max(field_len(receiver, sizes)) + .max(if binds(body, array_receiver(receiver).as_bytes()) { 0 } else { item_len(receiver, sizes) }) +} + +/// Whether `body` has a `let` binding of `name`. +fn binds(body: &[u8], name: &[u8]) -> bool { + words(body, b"let", 0, body.len()).into_iter().any(|at| { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); } - let Some(&(lf, lt)) = a.args.first() else { return false }; - let Some(&(rf, rt)) = a.args.get(1) else { return false }; - let (left, right) = (norm(&body[lf..lt]), norm(&body[rf..rt])); - (collection_operand(&left) == name && non_empty_literal(&right)) || (collection_operand(&right) == name && non_empty_literal(&left)) + body[start..].starts_with(name) && !body.get(start + name.len()).copied().is_some_and(is_ident) }) } +/// Methods that give at least one item for each distinct item they are given, and none from none, +/// with `collect` restricted to known collection targets. +const KEEPING: &[&str] = &["map", "iter", "into_iter", "cloned", "copied", "enumerate", "rev", "collect", "to_vec", "to_owned", "clone"]; + +/// Whether a normalized type names a collection that keeps an item of a non-empty iterator. +fn known_collection(ty: &str) -> bool { + let (name, args) = ty.split_once('<').map_or((ty, None), |(name, args)| (name, args.strip_suffix('>'))); + match name { + "Vec" | "std::vec::Vec" | "String" | "std::string::String" => true, + "Box" | "std::boxed::Box" => args.is_some_and(|args| { + args.starts_with('[') && matching(args.as_bytes(), 0) == Some(args.len() - 1) && !has_top_level(&args.as_bytes()[1..args.len() - 1], b';') + }), + _ => matches!( + name.strip_prefix("std::collections::").unwrap_or(name), + "VecDeque" | "HashSet" | "BTreeSet" | "HashMap" | "BTreeMap" | "BinaryHeap" | "LinkedList" + ), + } +} + +/// `operand` (masked, whitespace-free) without trailing calls of [`KEEPING`] methods: the +/// collection a compared or bound value was built from. Only the final call may use an +/// inferred `collect` target, when the caller knows it is a collection. +fn keeping_base(operand: &str, inferred_collect: bool) -> &str { + let mut op = operand; + while op.ends_with(')') { + let b = op.as_bytes(); + let mut depth = 0usize; + let Some(open) = (0..b.len()).rev().find(|&i| { + match b[i] { + b')' | b']' | b'}' => depth += 1, + b'(' | b'[' | b'{' => depth = depth.saturating_sub(1), + _ => {} + } + depth == 0 + }) else { + break; + }; + let mut head = &op[..open]; + let mut target = None; + if head.ends_with('>') { + let Some(turbofish) = head.rfind("::<") else { break }; + target = Some(&head[turbofish + 3..head.len() - 1]); + head = &head[..turbofish]; + } + let Some((rest, method)) = head.rsplit_once('.') else { break }; + if !KEEPING.contains(&method) || (method == "collect" && !target.map_or(inferred_collect && op.len() == operand.len(), known_collection)) { + break; + } + op = rest; + } + op +} + +/// Plain locals of the test bound (`let name = …;`, latest binding) to `receiver` through +/// [`KEEPING`] methods only, so they have no more distinct items than it, when no later code may +/// shrink or replace `receiver` ([`may_shrink`]), paired with the end of each binding. +fn derived_locals(receiver: &str, body: &[u8]) -> Vec<(String, usize)> { + let name = array_receiver(receiver); + if !plain_local(name) { + return vec![]; + } + let mut latest: HashMap = HashMap::new(); + for at in words(body, b"let", 0, body.len()) { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + let end = start + body[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || body[start].is_ascii_digit() { + continue; + } + let stop = statement_end(body, end); + let stmt = norm(&body[end..stop]); + let (annotation, from) = stmt.split_once('=').unwrap_or(("", "")); + let inferred_collect = annotation.strip_prefix(':').is_some_and(known_collection); + let base = keeping_base(from, inferred_collect); + let derived = base != from && collection_operand(base) == name && !may_shrink(body, name.as_bytes(), stop); + latest.insert(String::from_utf8_lossy(&body[start..end]).into_owned(), (derived, stop)); + } + latest.into_iter().filter(|&(_, (derived, _))| derived).map(|(n, (_, stop))| (n, stop)).collect() +} + +/// The length a `const` or `static` item of the file declares for a plain name +/// (`const NAME: [T; N]`), taking the smallest length across all declarations of that name, +/// or 0 when any declaration has an unknown or non-array type. +fn item_len(receiver: &str, sizes: &Sizes) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let file = sizes.file; + let mut len = None; + for at in words(file, name.as_bytes(), 0, file.len()) { + let before = file[..at].trim_ascii_end(); + let before = before.strip_suffix(b"mut").map_or(before, |b| b.trim_ascii_end()); + let keyword = |w: &[u8]| before.ends_with(w) && !before.len().checked_sub(w.len() + 1).is_some_and(|j| is_ident(before[j])); + if !keyword(b"const") && !keyword(b"static") { + continue; + } + let colon = skip_ws(file, at + name.len()); + let ty = skip_ws(file, colon + 1); + if file.get(colon) != Some(&b':') || file.get(ty) != Some(&b'[') { + return 0; + } + let Some(close) = matching(file, ty) else { return 0 }; + let count = repeat_count(&file[ty + 1..close], sizes).unwrap_or(0); + len = Some(len.map_or(count, |n: usize| n.min(count))); + } + len.unwrap_or(0) +} + +/// The receiver without its iterator method and the items it needs for `.all(…)` to see one: +/// `.windows(k)` and `.chunks_exact(k)` need `k`, anything else one. An unknown `k` needs more +/// than any collection has. +fn receiver_need<'a>(receiver: &'a str, sizes: &Sizes) -> (&'a str, usize) { + let r = array_receiver(receiver); + for (method, exact) in [(".windows(", true), (".chunks_exact(", true), (".chunks(", false)] { + let Some(at) = r.rfind(method) else { continue }; + let open = at + method.len() - 1; + if matching(r.as_bytes(), open) != Some(r.len() - 1) { + continue; + } + let need = match sizes.count(&r[open + 1..r.len() - 1]) { + Some(k) if k > 0 => { + if exact { + k + } else { + 1 + } + } + _ => usize::MAX, + }; + return (array_receiver(&r[..at]), need); + } + (r, 1) +} + +/// The length of the non-empty literal an earlier equality assertion compares this plain local +/// receiver with, or 0. For a derived local, its binding must reach the assertion unchanged. +fn equal_len(receiver: &str, body: &[u8], sizes: &Sizes, binding: Option) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; + } + let lens = macro_calls(body, 0, body.len()).into_iter().filter_map(|a| { + if !["assert_eq", "debug_assert_eq", "prop_assert_eq"].contains(&a.name.as_str()) { + return None; + } + let &(lf, lt) = a.args.first()?; + let &(rf, rt) = a.args.get(1)?; + if binding.is_some_and(|from| lf < from || may_change(&body[..lf], name.as_bytes(), from, false)) { + return None; + } + let end = a.args.last().map_or(rt, |&(_, to)| to); + if may_shrink(body, name.as_bytes(), end) { + return None; + } + let (left, right) = (norm(&body[lf..lt]), norm(&body[rf..rt])); + if collection_operand(keeping_base(&left, true)) == name { + Some(literal_len(&right, sizes)) + } else if collection_operand(keeping_base(&right, true)) == name { + Some(literal_len(&left, sizes)) + } else { + None + } + }); + lens.max().unwrap_or(0) +} + +/// Whether `name` is a plain local name: an identifier that does not start with a digit. +fn plain_local(name: &str) -> bool { + !name.is_empty() && !name.as_bytes()[0].is_ascii_digit() && name.bytes().all(is_ident) +} + /// Removes one borrow and a slice view from a compared operand. fn collection_operand(operand: &str) -> &str { let operand = operand.strip_prefix('&').unwrap_or(operand); operand.strip_suffix(".as_slice()").or_else(|| operand.strip_suffix("[..]")).unwrap_or(operand) } -/// Whether the whole operand is a non-empty array literal or `vec![…]`. -fn non_empty_literal(operand: &str) -> bool { +/// The length of an operand that is wholly an array literal or `vec![…]`, else 0. +fn literal_len(operand: &str, sizes: &Sizes) -> usize { let b = operand.strip_prefix("vec!").unwrap_or(operand).as_bytes(); - b.first() == Some(&b'[') && matching(b, 0) == Some(b.len() - 1) && non_empty_array(&b[1..b.len() - 1]) + if b.first() == Some(&b'[') && matching(b, 0) == Some(b.len() - 1) { array_len(&b[1..b.len() - 1], sizes) } else { 0 } } /// The length of a call's arguments in `rest`, the text after its `(`: up to its closing bracket. @@ -1318,13 +1533,13 @@ fn arg_end(rest: &str) -> usize { .unwrap_or(rest.len()) } -/// Whether `receiver` (the text before `.all(`) ends with a non-empty array literal, through `.iter()` or -/// `.into_iter()`. -fn on_array_literal(receiver: &str) -> bool { +/// The length of the array literal `receiver` (the text before `.all(`) ends with, through +/// `.iter()` or `.into_iter()`, or `None` when it does not end with one. +fn array_literal_len(receiver: &str, sizes: &Sizes) -> Option { let r = array_receiver(receiver); let b = r.as_bytes(); if b.last() != Some(&b']') { - return false; + return None; } let mut depth = 0usize; for (j, &c) in b.iter().enumerate().rev() { @@ -1334,13 +1549,13 @@ fn on_array_literal(receiver: &str) -> bool { depth = depth.saturating_sub(1); if depth == 0 { let literal = !j.checked_sub(1).and_then(|k| b.get(k)).is_some_and(|&p| is_ident(p) || matches!(p, b')' | b']' | b'.')); - return literal && non_empty_array(&b[j + 1..b.len() - 1]); + return literal.then(|| array_len(&b[j + 1..b.len() - 1], sizes)); } } _ => {} } } - false + None } /// Removes the iterator method from an array receiver. @@ -1348,68 +1563,455 @@ fn array_receiver(receiver: &str) -> &str { receiver.strip_suffix(".iter()").or_else(|| receiver.strip_suffix(".into_iter()")).unwrap_or(receiver) } -/// Whether a plain local receiver's latest preceding binding initializes a non-empty array. -fn on_bound_array(receiver: &str, body: &[u8]) -> bool { - let name = array_receiver(receiver).as_bytes(); - if name.is_empty() || name[0].is_ascii_digit() || !name.iter().copied().all(is_ident) { - return false; +/// The fewest items a plain local receiver has after its latest preceding binding: from the +/// binding ([`array_binding`]) or a loop that fills it ([`loop_fill_len`]), and 0 when a later +/// statement may shrink or replace it ([`may_shrink`]). +fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { + let name = array_receiver(receiver); + if !plain_local(name) { + return 0; } - words(body, b"let", 0, body.len()).into_iter().rev().find_map(|at| array_binding(&body[at + 3..], name)).unwrap_or(false) + let name = name.as_bytes(); + let Some((len, end)) = words(body, b"let", 0, body.len()).into_iter().rev().find_map(|at| array_binding(body, at, name, sizes)) else { + return 0; + }; + if may_shrink(body, name, end) { + return 0; + } + len.max(loop_fill_len(body, name, end, sizes)) } -/// Checks a named binding, allowing `mut` and an array type annotation. -fn array_binding(mut rest: &[u8], name: &[u8]) -> Option { - rest = rest.trim_ascii_start(); - if rest.starts_with(b"mut") && rest.get(3).is_some_and(u8::is_ascii_whitespace) { - rest = rest[3..].trim_ascii_start(); +/// For a `let` at `at` that binds `name` (allowing `mut`): the fewest items its array type +/// annotation gives (which decides when there is one), else its initializer gives ([`expr_len`]), +/// and where the statement ends. `None` for a binding of another name. +fn array_binding(body: &[u8], at: usize, name: &[u8], sizes: &Sizes) -> Option<(usize, usize)> { + let mut at = skip_ws(body, at + 3); + if body[at..].starts_with(b"mut") && body.get(at + 3).is_some_and(u8::is_ascii_whitespace) { + at = skip_ws(body, at + 3); } - let end = rest.iter().copied().take_while(|&c| is_ident(c)).count(); - if &rest[..end] != name { + let end = at + body[at..].iter().copied().take_while(|&c| is_ident(c)).count(); + if &body[at..end] != name { return None; } - rest = rest[end..].trim_ascii_start(); - if let Some(annotation) = rest.strip_prefix(b":") { - let annotation = annotation.trim_ascii_start(); - let close = (annotation.first() == Some(&b'[')).then(|| matching(annotation, 0)).flatten(); - let Some(close) = close else { return Some(false) }; - rest = annotation[close + 1..].trim_ascii_start(); + let stop = statement_end(body, end); + let stmt = &body[end..stop]; + let eq = (0..stmt.len()).find(|&i| { + stmt[i] == b'=' + && !matches!(stmt.get(i + 1), Some(b'=' | b'>')) + && !matches!(i.checked_sub(1).map(|j| stmt[j]), Some(b'=' | b'!' | b'<' | b'>')) + }); + let (annotation, init) = match eq { + Some(eq) => (&stmt[..eq], Some(&stmt[eq + 1..])), + None => (stmt, None), + }; + let annotation = norm(annotation); + if let Some(ty) = annotation.strip_prefix(':') + && ty.starts_with('[') + && matching(ty.as_bytes(), 0) == Some(ty.len() - 1) + { + return Some((repeat_count(&ty.as_bytes()[1..ty.len() - 1], sizes).unwrap_or(0), stop)); } - Some(rest.strip_prefix(b"=").is_some_and(array_initializer)) + Some((init.map_or(0, |init| expr_len(&norm(init), sizes, annotation.strip_prefix(':').unwrap_or(""))), stop)) } -/// Whether an initializer is a non-empty array literal, optionally followed by one `.map(…)`. -fn array_initializer(rest: &[u8]) -> bool { - let rest = rest.trim_ascii_start(); - let Some(close) = (rest.first() == Some(&b'[')).then(|| matching(rest, 0)).flatten() else { return false }; - if !non_empty_array(&rest[1..close]) { - return false; - } - let tail = rest[close + 1..].trim_ascii_start(); - if tail.starts_with(b";") { - return true; - } - let compact = norm(tail); - if !compact.starts_with(".map(") { - return false; - } - let Some(close) = matching(compact.as_bytes(), 4) else { return false }; - compact[close + 1..].starts_with(';') -} - -/// Whether an array's masked contents have an element and, for repetition, a positive literal count. -fn non_empty_array(contents: &[u8]) -> bool { - let mut at = 0; - while at < contents.len() { - match contents[at] { - b';' => return norm(&contents[at + 1..]).parse::().is_ok_and(|count| count > 0), - b'(' | b'[' | b'{' => { - let Some(close) = matching(contents, at) else { return false }; - at = close + 1; - } +/// The index of the `;` that ends the statement starting at `from`, outside brackets, or the +/// end of `body`. +fn statement_end(body: &[u8], from: usize) -> usize { + let mut at = from; + while at < body.len() { + match body[at] { + b';' => return at, + b'(' | b'[' | b'{' => match matching(body, at) { + Some(close) => at = close + 1, + None => return body.len(), + }, _ => at += 1, } } - !contents.trim_ascii().is_empty() + body.len() +} + +/// The fewest items a (masked, whitespace-free) expression yields: an array literal or `vec![…]`, +/// a literal range, either followed only by methods that keep at least one item of a non-empty +/// input (`map`, `iter`, `into_iter`, `cloned`, `copied`, `enumerate`, `rev`, `chain`, `to_vec`, +/// `to_owned`, `clone`, and `collect` into a known collection or `step_by`, after which at least +/// one is known). Only a final `collect` without a turbofish can use the binding's type. 0 for +/// anything else. +fn expr_len(e: &str, sizes: &Sizes, binding_type: &str) -> usize { + let e = e.strip_prefix("vec!").unwrap_or(e); + let b = e.as_bytes(); + let (mut n, mut rest) = match b.first() { + Some(b'[') => { + let Some(close) = matching(b, 0) else { return 0 }; + (array_len(&b[1..close], sizes), &e[close + 1..]) + } + Some(b'(') => { + let Some(close) = matching(b, 0) else { return 0 }; + (range_len(&e[1..close], sizes), &e[close + 1..]) + } + _ => return range_len(e, sizes), + }; + while !rest.is_empty() { + let Some(tail) = rest.strip_prefix('.') else { return 0 }; + let end = tail.bytes().take_while(|&c| is_ident(c)).count(); + let method = &tail[..end]; + let mut open = end; + if tail[open..].starts_with("::<") { + let mut depth = 0usize; + let Some(close) = tail[open + 2..].bytes().position(|c| { + depth = match c { + b'<' => depth + 1, + b'>' => depth.saturating_sub(1), + _ => depth, + }; + depth == 0 + }) else { + return 0; + }; + open += 2 + close + 1; + } + if tail.as_bytes().get(open) != Some(&b'(') { + return 0; + } + let Some(close) = matching(tail.as_bytes(), open) else { return 0 }; + match method { + "map" | "iter" | "into_iter" | "cloned" | "copied" | "enumerate" | "rev" | "chain" | "to_vec" | "to_owned" | "clone" => {} + "collect" => { + let target = if open > end { + &tail[end + 3..open - 1] + } else if close + 1 == tail.len() { + binding_type + } else { + "" + }; + if !known_collection(target) { + return 0; + } + n = n.min(1); + } + "step_by" => n = n.min(1), + _ => return 0, + } + rest = &tail[close + 1..]; + } + n +} + +/// The number of items in a range of integer literals or constants (`a..b`, `a..=b`); 0 for +/// anything else, an open range included. +fn range_len(e: &str, sizes: &Sizes) -> usize { + let (lo, hi, inclusive) = match e.split_once("..=") { + Some((lo, hi)) => (lo, hi, true), + None => match e.split_once("..") { + Some((lo, hi)) => (lo, hi, false), + None => return 0, + }, + }; + let value = |t: &str| match t.strip_prefix('-') { + Some(t) => sizes.count(t).and_then(|v| i128::try_from(v).ok()).map(|v| -v), + None => sizes.count(t).and_then(|v| i128::try_from(v).ok()), + }; + let (Some(lo), Some(hi)) = (value(lo), value(hi)) else { return 0 }; + let len = hi - lo + i128::from(inclusive); + usize::try_from(len).unwrap_or(0) +} + +/// The number of items in an array literal's masked contents: the count of a repetition, or the +/// elements of a list. +fn array_len(contents: &[u8], sizes: &Sizes) -> usize { + if let Some(count) = repeat_count(contents, sizes) { + return count; + } + if has_top_level(contents, b';') { + return 0; + } + split_args(contents, 0, contents.len()).len() +} + +/// The count of a repetition `[x; N]` (a literal or a `const` of the file), from its masked +/// contents; `None` when they are not a repetition, `Some(0)` when the count is not known. +fn repeat_count(contents: &[u8], sizes: &Sizes) -> Option { + let mut at = 0; + while at < contents.len() { + match contents[at] { + b';' => return Some(sizes.count(&norm(&contents[at + 1..])).unwrap_or(0)), + b'(' | b'[' | b'{' => at = matching(contents, at)? + 1, + _ => at += 1, + } + } + None +} + +/// Whether `c` occurs in `b` outside brackets. +fn has_top_level(b: &[u8], c: u8) -> bool { + let mut at = 0; + while at < b.len() { + match b[at] { + x if x == c => return true, + b'(' | b'[' | b'{' => match matching(b, at) { + Some(close) => at = close + 1, + None => return true, + }, + _ => at += 1, + } + } + false +} + +/// The fewest items a `for` loop after `from`, in the same block, adds to `name`: a loop over a +/// sized source ([`expr_len`]) whose own block (not a nested one) pushes or inserts into `name` +/// on every pass, with no `break`, `continue`, `return` or `?` in the loop. 0 when there is none. +fn loop_fill_len(body: &[u8], name: &[u8], from: usize, sizes: &Sizes) -> usize { + let mut best = 0; + for at in words(body, b"for", from, body.len()) { + if block_depth(&body[from..at]) != Some(0) { + continue; + } + let Some(&in_at) = words(body, b"in", at + 3, body.len()).first() else { continue }; + let Some(open) = (in_at + 2..body.len()).find(|&i| body[i] == b'{' && !has_open_bracket(&body[in_at + 2..i])) else { continue }; + let Some(close) = matching(body, open) else { continue }; + let source = expr_len(&norm(&body[in_at + 2..open]), sizes, ""); + let block = &body[open + 1..close]; + let exits = [&b"break"[..], b"continue", b"return"].iter().any(|w| !words(block, w, 0, block.len()).is_empty()) || contains(block, b"?"); + if source == 0 || exits { + continue; + } + let pushes = words(block, name, 0, block.len()).into_iter().any(|p| { + let before = block[..p].trim_ascii_end(); + let statement = matches!(before.last(), None | Some(b';' | b'{' | b'}')); + let call = norm(&block[p + name.len()..block.len().min(p + name.len() + 16)]); + statement && block_depth(&block[..p]) == Some(0) && [".push(", ".push_back(", ".insert("].iter().any(|m| call.starts_with(m)) + }); + if pushes { + best = best.max(source); + } + } + best +} + +/// The brace depth at the end of `b`, or `None` when it closes a block it did not open. +fn block_depth(b: &[u8]) -> Option { + let mut depth = 0usize; + for &c in b { + match c { + b'{' => depth += 1, + b'}' => depth = depth.checked_sub(1)?, + _ => {} + } + } + Some(depth) +} + +/// Whether `b` leaves a `(` or `[` open. +fn has_open_bracket(b: &[u8]) -> bool { + let mut depth = 0i32; + for &c in b { + match c { + b'(' | b'[' => depth += 1, + b')' | b']' => depth -= 1, + _ => {} + } + } + depth > 0 +} + +/// Whether code after `from` may remove items from `name` or replace it. +fn may_shrink(body: &[u8], name: &[u8], from: usize) -> bool { + may_change(body, name, from, true) +} + +/// Whether code after `from` may change the item count of `name`: an unknown method call, +/// an assignment, or a `&mut` borrow. Growth is harmless only for the source collection. +fn may_change(body: &[u8], name: &[u8], from: usize, allow_growth: bool) -> bool { + const PRESERVING: &[&str] = &[ + "iter", + "iter_mut", + "into_iter", + "len", + "is_empty", + "contains", + "get", + "get_mut", + "first", + "last", + "first_mut", + "last_mut", + "as_slice", + "as_ref", + "clone", + "to_vec", + "to_owned", + "windows", + "chunks", + "chunks_exact", + "sort", + "sort_by", + "sort_by_key", + "sort_unstable", + "sort_unstable_by", + "sort_unstable_by_key", + "reverse", + "binary_search", + "binary_search_by", + "binary_search_by_key", + "starts_with", + "ends_with", + "map", + "concat", + "join", + "keys", + "values", + ]; + const ADDING: &[&str] = &["push", "push_back", "push_front", "insert", "extend"]; + words(body, name, from, body.len()).into_iter().any(|p| { + let after = &body[skip_ws(body, p + name.len())..]; + let assigned = (after.starts_with(b"=") && !after.starts_with(b"==") && !after.starts_with(b"=>")) + || ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="].iter().any(|op| after.starts_with(op.as_bytes())); + let before = body[from..p].trim_ascii_end(); + let borrowed = before.strip_suffix(b"mut").is_some_and(|b| b.trim_ascii_end().ends_with(b"&")); + let called = if after.first() == Some(&b'.') { + let start = skip_ws(after, 1); + let end = start + after[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + let rest = &after[skip_ws(after, end)..]; + let method = &after[start..end]; + (rest.starts_with(b"(") || rest.starts_with(b"::<")) + && !PRESERVING.iter().any(|m| method == m.as_bytes()) + && !(allow_growth && ADDING.iter().any(|m| method == m.as_bytes())) + } else { + false + }; + assigned || borrowed || called + }) +} + +/// The length of a field the file declares as an array of a positive length (`name: [T; N]`), +/// for a receiver `….name`. 0 when any other `name:` in the file may start a type: anything but +/// an array, a lowercase name that is not a path or a primitive type (a value in a struct +/// expression), or a literal. +fn field_len(receiver: &str, sizes: &Sizes) -> usize { + let Some((owner, field)) = receiver.rsplit_once('.') else { return 0 }; + if owner.is_empty() || !plain_local(field) { + return 0; + } + const PRIMITIVE: &[&str] = &[ + "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32", "f64", "bool", "char", "str", "dyn", "impl", + "fn", "mut", "crate", "self", "super", + ]; + let file = sizes.file; + let mut least: Option = None; + for at in words(file, field.as_bytes(), 0, file.len()) { + let colon = skip_ws(file, at + field.len()); + if file.get(colon) != Some(&b':') || file.get(colon + 1) == Some(&b':') || at.checked_sub(1).is_some_and(|j| file[j] == b':') { + continue; + } + let ty = skip_ws(file, colon + 1); + let word_end = ty + file[ty..].iter().copied().take_while(|&c| is_ident(c)).count(); + let word = &file[ty..word_end]; + let value = match file.get(ty) { + Some(b'[') => false, + Some(c) if c.is_ascii_digit() || matches!(c, b'"' | b'\'' | b'-') => true, + Some(c) if c.is_ascii_lowercase() || *c == b'_' => { + let path = file[skip_ws(file, word_end)..].starts_with(b"::"); + !path && !PRIMITIVE.iter().any(|p| p.as_bytes() == word) + } + _ => return 0, + }; + if value { + continue; + } + let Some(close) = matching(file, ty) else { return 0 }; + match repeat_count(&file[ty + 1..close], sizes) { + Some(n) if n > 0 => least = Some(least.map_or(n, |l| l.min(n))), + Some(_) => return 0, + None => {} + } + } + least.unwrap_or(0) +} + +/// What the rules know about collection sizes in one masked file: its `const` counts, read on first use. +struct Sizes<'a> { + file: &'a [u8], + consts: OnceCell>, +} + +impl Sizes<'_> { + /// An unsigned integer literal (with `_` and an integer suffix allowed) or a `const` of the + /// file whose value is one. + fn count(&self, text: &str) -> Option { + int_literal(text).or_else(|| self.consts.get_or_init(|| file_consts(self.file)).get(text).copied()) + } +} + +fn int_literal(text: &str) -> Option { + let digits = text.bytes().take_while(|c| c.is_ascii_digit() || *c == b'_').count(); + let suffix = &text[digits..]; + let suffixes = ["", "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize"]; + if digits == 0 || !text.as_bytes()[0].is_ascii_digit() || !suffixes.contains(&suffix) { + return None; + } + text[..digits].replace('_', "").parse().ok() +} + +/// `const NAME: T = ;` in a masked file; a name declared more than once keeps +/// its smallest value, and 0 when one of its values is not a literal. +fn file_consts(file: &[u8]) -> HashMap { + let mut out: HashMap = HashMap::new(); + for at in words(file, b"const", 0, file.len()) { + let start = skip_ws(file, at + 5); + let end = start + file[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || skip_ws(file, end) >= file.len() || file[skip_ws(file, end)] != b':' { + continue; + } + let stop = statement_end(file, end); + let stmt = norm(&file[end..stop]); + let Some((_, value)) = stmt.split_once('=') else { continue }; + let value = int_literal(value).unwrap_or(0); + let name = String::from_utf8_lossy(&file[start..end]).into_owned(); + let slot = out.entry(name).or_insert(value); + *slot = (*slot).min(value); + } + out +} + +/// A `let` of a plain name: the name, where the statement ends, and whether it binds an expression +/// that checks a size ([`SIZE_CHECKS`]). +struct Binding { + name: Vec, + end: usize, + counts: bool, +} + +/// Every `let` of a plain name in `body`, in order. +fn bindings(body: &[u8]) -> Vec { + words(body, b"let", 0, body.len()) + .into_iter() + .filter_map(|at| { + let mut start = skip_ws(body, at + 3); + if body[start..].starts_with(b"mut") && body.get(start + 3).is_some_and(u8::is_ascii_whitespace) { + start = skip_ws(body, start + 3); + } + let end = start + body[start..].iter().copied().take_while(|&c| is_ident(c)).count(); + if end == start || body[start].is_ascii_digit() { + return None; + } + let stop = statement_end(body, end); + let stmt = norm(&body[end..stop]); + let counts = stmt.split_once('=').is_some_and(|(_, init)| SIZE_CHECKS.iter().any(|g| init.contains(g))); + Some(Binding { name: body[start..end].to_vec(), end: stop, counts }) + }) + .collect() +} + +/// Whether `body[from..to]` (an assertion operand) reads a local whose binding reaching that +/// point checks a size and was not assigned since. +fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> bool { + all.iter().filter(|b| b.counts && b.name != b"_").any(|b| { + words(body, &b.name, from, to).into_iter().any(|p| { + let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p); + reaching.is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end)) + }) + }) } /// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. @@ -1803,7 +2405,7 @@ mod tests { let src = format!("#[test]\nfn t() {{\n assert_eq!(xs, {expected});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); assert_eq!(hits(&src), [(4, "all-unguarded")], "{expected}"); } - for operand in ["ys", "xs_other", "other.xs", "other::xs", "xs()", "xs.clone()", "xs[1..]", "&&xs"] { + for operand in ["ys", "xs_other", "other.xs", "other::xs", "xs()", "xs.filter(f)", "xs.iter().filter(f).collect()", "xs[1..]", "&&xs"] { let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [1]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); assert_eq!(hits(&src), [(4, "all-unguarded")], "{operand}"); } @@ -1913,12 +2515,23 @@ mod tests { "[]", "[1; 0]", "[1; 0].map(|x| x + 1)", - "vec![1, 2]", + "vec![]", + "vec![1; 0]", + "vec![1; n]", "items()", "items().collect()", + "items().collect::>()", + "(0..0).collect::>()", + "(3..1).collect::>()", + "(0..n).collect::>()", + "(0..).take(3).collect::>()", + "[1, 2].iter().filter(|x| keep(x)).collect::>()", + "[1, 2].into_iter().zip(ys).collect::>()", + "[None::].into_iter().collect::>>()", + "[Err::(error())].into_iter().collect::, E>>()", "[1, 2].into_iter().collect()", - "[1, 2].map(|x| x + 1).into_iter().collect()", - "[1, 2].map(|x| x + 1).map(|x| x + 1)", + "[1, 2].into_iter().collect::()", + "[1, 2].into_iter().collect::>()", ] { for binding in [format!("let xs = {value};"), format!("let mut xs = {value};"), format!("let xs: [u8; 0] = {value};")] { let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); @@ -1976,6 +2589,333 @@ mod tests { } } + #[test] + fn all_skips_bindings_with_sized_initializers() { + let consts = "const N: usize = 3;\nconst NONE: usize = 0;\n"; + for binding in [ + "let xs = vec![1, 2];", + "let mut xs = vec![[1, 2]; 2];", + "let xs: Vec<_> = [1, 2].into_iter().collect();", + "let xs = [1, 2].map(|x| x + 1).map(|x| x + 1);", + "let xs: Vec = [1, 2].iter().copied().rev().collect();", + "let xs: Vec = (0..40u8).map(|n| px(n)).collect();", + "let xs = (1..=3).collect::>();", + "let xs = (-2..1).step_by(2).collect::>();", + "let xs: Vec<_> = (0..N).collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::>().into_iter().collect();", + "let xs = [0.0; N];", + "let xs: [u8; 3] = items();", + "let xs: [u8; N] = items();", + ] { + let src = format!("{consts}#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(7, "all-unguarded")], "{binding} then cleared"); + } + for binding in [ + "let xs = (0..NONE).collect::>();", + "let xs = [0.0; NONE];", + "let xs: [u8; NONE] = [1];", + "let xs = (0..M).collect::>();", + "let xs = [None::].into_iter().collect::>>();", + "let xs = [Err::(error())].into_iter().collect::, E>>();", + "let xs: Option> = [1].into_iter().collect();", + "let xs: Result, E> = [1].into_iter().collect();", + "let xs = [1, 2].into_iter().collect();", + "let xs: Items = [1, 2].into_iter().collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect().clone();", + "let xs: Vec<_> = [1, 2].into_iter().collect().into_iter().collect();", + "let xs: Vec<_> = [None::].into_iter().collect::>>().into_iter().collect();", + "let xs: Vec<_> = [1, 2].into_iter().collect::();", + ] { + let src = format!("{consts}#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(6, "all-unguarded")], "{binding}"); + } + for later in [ + "xs.retain(|x| keep(x));", + "xs = items();", + "take(&mut xs);", + "xs.truncate(0);", + "xs.pop();", + "xs.resize(0, 0);", + "xs.resize_with(0, f);", + "xs.pop_front();", + "xs.pop_back();", + "xs.unknown_method_that_may_shrink();", + "xs . unknown::();", + ] { + let src = format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n {later}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{later}"); + } + for op in ["+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>="] { + let src = + format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n xs {op} other;\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{op}"); + } + for later in [ + "xs[0] = 5; use_it(&xs);", + "xs[1] = 5; use_it(&xs);", + "use_it(&xs);", + "use_it(xs);", + "use_it(xs == other);", + "match other { xs => use_it(xs), _ => () };", + "xs.push(3); xs.push_back(4); xs.push_front(5); xs.insert(0, 6); xs.extend(other);", + "xs.sort(); xs.sort_by(f); xs.sort_by_key(f); xs.sort_unstable(); xs.reverse();", + "use_it(xs.iter()); use_it(xs.iter_mut()); use_it(xs.into_iter());", + "use_it(xs.len()); use_it(xs.is_empty()); use_it(xs.contains(&1));", + "use_it(xs.get(0)); use_it(xs.get_mut(0)); use_it(xs.first()); use_it(xs.last());", + "use_it(xs.first_mut()); use_it(xs.last_mut()); use_it(xs.as_slice()); use_it(xs.as_ref());", + "use_it(xs.clone()); use_it(xs.to_vec()); use_it(xs.windows(2)); use_it(xs.chunks(2));", + "use_it(xs.binary_search(&1)); use_it(xs.starts_with(&[1])); use_it(xs.ends_with(&[2]));", + "use_it(xs.map(f)); use_it(xs.concat()); use_it(xs.join(sep)); use_it(xs.keys()); use_it(xs.values());", + ] { + let src = format!("#[test]\nfn t() {{\n let mut xs = vec![1, 2];\n {later}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{later}"); + } + } + + #[test] + fn all_collects_require_known_collection_targets() { + for target in [ + "Vec<_>", + "std::vec::Vec<_>", + "VecDeque<_>", + "std::collections::VecDeque<_>", + "HashSet<_>", + "std::collections::HashSet<_>", + "BTreeSet<_>", + "std::collections::BTreeSet<_>", + "HashMap<_, _>", + "std::collections::HashMap<_, _>", + "BTreeMap<_, _>", + "std::collections::BTreeMap<_, _>", + "BinaryHeap<_>", + "std::collections::BinaryHeap<_>", + "LinkedList<_>", + "std::collections::LinkedList<_>", + "String", + "std::string::String", + "Box<[_]>", + "std::boxed::Box<[_]>", + ] { + let source = if target.contains("Map") { "[(1, 2)]" } else { "['a', 'b']" }; + for binding in [ + format!("let xs = {source}.into_iter().collect::<{target}>();"), + format!("let xs: {target} = {source}.into_iter().collect();"), + format!("let xs = {source}.into_iter().collect::<{target}>().into_iter().collect::>();"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + } + } + } + + #[test] + fn all_skips_collections_every_pass_of_a_sized_loop_fills() { + for (source, fill) in [ + ("[1, 2, 3]", "xs.push(i);"), + ("0..3", "xs.push(i);"), + ("[[0, 1], [1, 0]]", "let s = Fill { a: 1 }.span(i);\n xs.push(s);"), + ("[1, 2].iter().enumerate()", "for j in items() { use_it(j); }\n xs.insert(i);"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let mut xs = vec![];\n for i in {source} {{\n {fill}\n }}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [], "{source}: {fill}"); + let after = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&after), [(line + 1, "all-unguarded")], "{source} then cleared"); + } + for (source, fill) in [ + ("items()", "xs.push(i);"), + ("0..0", "xs.push(i);"), + ("0..n", "xs.push(i);"), + ("[1, 2]", "if keep(i) { xs.push(i); }"), + ("[1, 2]", "if !keep(i) { continue; }\n xs.push(i);"), + ("[1, 2]", "let v = get(i)?;\n xs.push(v);"), + ("[1, 2]", "ys.iter().for_each(|y| xs.push(*y));"), + ("[1, 2]", "ys.push(i);"), + ("[1, 2]", "let mut xs = vec![];\n xs.push(i);"), + ("[1, 2].iter().filter(|x| keep(x))", "xs.push(i);"), + ] { + let src = format!( + "#[test]\nfn t() {{\n let mut xs = vec![];\n for i in {source} {{\n {fill}\n }}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [(line, "all-unguarded")], "{source}: {fill}"); + } + let nested = "#[test]\nfn t() {\n let mut xs = vec![];\n if ready() {\n for i in [1, 2] {\n xs.push(i);\n }\n }\n assert!(xs.iter().all(|x| valid(x)));\n}\n"; + assert_eq!(hits(nested), [(9, "all-unguarded")], "a loop that may not run"); + } + + #[test] + fn all_skips_fields_the_file_declares_as_arrays() { + let test = "#[test]\nfn t() {\n let c = parse();\n assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v)));\n}\n"; + for decl in [ + "struct C { rgb: [f32; 3] }\n", + "const N: usize = 3;\nstruct C { pub rgb: [f32; N], alpha: Option }\n", + "struct C { rgb: [f32; 3] }\nfn c() -> C { C { rgb: rgb_of(\"x\"), alpha: 1 } }\n", + ] { + let src = format!("{decl}{test}"); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [], "{decl}"); + let other = format!("{decl}struct D {{ rgb: Vec }}\n{test}"); + assert_eq!(hits(&other), [(line + 1, "all-unguarded")], "another struct's rgb can be empty"); + } + for decl in + ["struct C { rgb: [f32; 0] }\n", "struct C { rgb: &'static [f32] }\n", "struct C { rgb: [f32; LEN] }\n", "struct C { other: [f32; 3] }\n"] + { + let src = format!("{decl}{test}"); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{decl}"); + } + for other in ["std::vec::Vec", "Pixels", "u8", "(f32, f32)", "T"] { + let src = format!("struct C {{ rgb: [f32; 3] }}\nstruct D {{ rgb: {other} }}\n{test}"); + assert_eq!(hits(&src), [(6, "all-unguarded")], "another struct's rgb is {other}"); + } + let local = "struct C { rgb: [f32; 3] }\n#[test]\nfn t() {\n let rgb = parse();\n assert!(rgb.iter().all(|v| valid(v)));\n}\n"; + assert_eq!(hits(local), [(5, "all-unguarded")], "a local name is not the field"); + } + + #[test] + fn all_equality_guards_follow_methods_that_keep_items() { + for operand in [ + "xs.clone()", + "xs.iter().map(|l| l.0).collect()", + "xs.iter().copied().collect::>().into_iter().collect()", + "xs.iter().map(|l| l.0).collect::>()", + "&xs.iter().copied().rev().collect::>()", + ] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({operand}, vec![0, 7]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{operand}"); + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(5, "all-unguarded")], "{operand} then cleared"); + } + for (binding, compared) in [ + ("let ids: Vec<&str> = xs.iter().map(|l| l.id()).collect();", "assert_eq!(ids, [\"a\", \"b\"]);"), + ("let ids = xs.iter().cloned().collect::>();", "assert_eq!([\"a\"], ids);"), + ("let ids = xs.iter().copied().collect::>();", "assert_eq!(ids, [1]);"), + ("let ids: Vec<_> = xs.iter().copied().collect::>().into_iter().collect();", "assert_eq!(ids, [1]);"), + ] { + let src = format!("#[test]\nfn t() {{\n {binding}\n {compared}\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [], "{binding}"); + let filtered = src.replace(binding, &binding.replace(".iter()", ".iter().filter(|x| keep(x))")); + assert_eq!(hits(&filtered), [(5, "all-unguarded")], "{binding} through a filter"); + let rebound = src.replace(&format!(" {compared}\n"), &format!(" let ids = other();\n {compared}\n")); + assert_eq!(hits(&rebound), [(6, "all-unguarded")], "{binding} then bound again"); + for change in ["ids = vec![1];", "ids.clear();", "reset(&mut ids);", "ids.push(1);"] { + let reassigned = + src.replace("let ids", "let mut ids").replace(&format!(" {compared}\n"), &format!(" {change}\n {compared}\n")); + assert_eq!(hits(&reassigned), [(6, "all-unguarded")], "{binding} then {change}"); + } + let cleared = src.replace("\n assert!", "\n xs.clear();\n assert!"); + assert_eq!(hits(&cleared), [(6, "all-unguarded")], "{binding} then the source cleared"); + } + } + + #[test] + fn all_equality_guards_stop_at_other_collect_targets() { + for operand in [ + "xs.iter().copied().collect().into_iter().collect::>()", + "xs.iter().copied().collect().into_iter().collect()", + "xs.iter().copied().collect().clone()", + ] { + for compared in [format!("{operand}, [vec![]]"), format!("[vec![]], {operand}")] { + let src = format!("#[test]\nfn t() {{\n assert_eq!({compared});\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&src), [(4, "all-unguarded")], "{compared}"); + } + } + for binding in [ + "let ids: Option> = xs.iter().copied().collect();", + "let ids: Result, E> = xs.iter().copied().collect();", + "let ids: Items = xs.iter().copied().collect();", + "let ids = xs.iter().copied().collect();", + "let ids: Vec<_> = xs.iter().copied().collect().into_iter().collect();", + "let ids: Vec<_> = xs.iter().copied().collect().into_iter().collect::>();", + "let ids: Vec<_> = xs.iter().copied().collect().clone();", + ] { + let src = format!( + "#[test]\nfn t() {{\n {binding}\n assert_eq!(ids.into_iter().collect::>(), [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&src), [(5, "all-unguarded")], "{binding}"); + } + for target in ["Option>", "Result, E>", "Items"] { + let operand = format!("xs.iter().copied().collect::<{target}>().iter().collect::>()"); + let direct = format!("#[test]\nfn t() {{\n assert_eq!({operand}, [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n"); + assert_eq!(hits(&direct), [(4, "all-unguarded")], "{target} compared directly"); + let derived = format!( + "#[test]\nfn t() {{\n let ids = {operand};\n assert_eq!(ids, [vec![]]);\n assert!(xs.iter().all(|x| valid(x)));\n}}\n" + ); + assert_eq!(hits(&derived), [(5, "all-unguarded")], "{target} through a local"); + } + } + + #[test] + fn all_skips_const_and_static_arrays_of_the_file() { + let test = "#[test]\nfn t() {\n assert!(NAMES.iter().all(|n| valid(n)));\n}\n"; + for decl in [ + "const NAMES: [&str; 2] = [\"a\", \"b\"];\n", + "static NAMES: [u8; N] = [0; N];\nconst N: usize = 4;\n", + "pub(crate) static mut NAMES: [u8; 1] = [0];\n", + ] { + let src = format!("{decl}{test}"); + assert_eq!(hits(&src), [], "{decl}"); + } + for decl in ["const NAMES: [&str; 0] = [];\n", "const NAMES: &[&str] = &[\"a\"];\n", "fn my_const() {}\nlet NAMES: [u8; 2] = f();\n", ""] { + let src = format!("{decl}{test}"); + let line = src.lines().position(|l| l.contains("assert!")).map_or(0, |p| p + 1); + assert_eq!(hits(&src), [(line, "all-unguarded")], "{decl}"); + } + let shadowed = "const NAMES: [&str; 2] = [\"a\", \"b\"];\n#[test]\nfn t() {\n let NAMES = items();\n assert!(NAMES.iter().all(|n| valid(n)));\n}\n"; + assert_eq!(hits(shadowed), [(5, "all-unguarded")], "a local of the same name"); + for (other_type, other_value, found) in [("[u8; 0]", "[]", true), ("&[u8]", "&[]", true), ("[u8; 3]", "[0; 3]", false)] { + for (first_type, first_value, second_type, second_value) in + [("[u8; 2]", "[0; 2]", other_type, other_value), (other_type, other_value, "[u8; 2]", "[0; 2]")] + { + let src = format!( + "mod a {{ const CASES: {first_type} = {first_value}; }}\nmod b {{\nconst CASES: {second_type} = {second_value};\n#[test]\nfn t() {{\n assert!(CASES.iter().all(|n| valid(n)));\n}}\n}}\n" + ); + let want: &[(usize, &str)] = if found { &[(6, "all-unguarded")] } else { &[] }; + assert_eq!(hits(&src), want, "{first_type} and {second_type}"); + } + } + } + + #[test] + fn all_windows_need_as_many_items_as_their_size() { + for (array, method, found) in [ + ("[a, b, c, d]", "windows(2)", false), + ("[a, b]", "windows(2)", false), + ("[a]", "windows(2)", true), + ("[a, b]", "windows(k)", true), + ("[a]", "chunks(3)", false), + ("[a, b]", "chunks_exact(3)", true), + ("[a, b, c]", "chunks_exact(3)", false), + ] { + let src = + format!("#[test]\nfn t() {{\n let xs = {array}.map(|s| node(s));\n assert!(xs.{method}.all(|w| w[0].y == w[1].y));\n}}\n"); + let want: &[(usize, &str)] = if found { &[(4, "all-unguarded")] } else { &[] }; + assert_eq!(hits(&src), want, "{array}.{method}"); + } + } + + #[test] + fn all_guards_accept_asserted_locals_that_count() { + let src = "#[test]\nfn t() {\n let row = cards.iter().filter(|c| first_row(c)).count();\n assert_eq!(row, 4, \"four cards\");\n assert!(cards.iter().all(|c| c.x < 10));\n}\n"; + assert_eq!(hits(src), []); + let summed = src.replace(".count()", ".map(|c| c.w).sum::()"); + assert_eq!(hits(&summed), [(5, "all-unguarded")], "a sum does not count items"); + let message = src.replace("assert_eq!(row, 4, \"four cards\")", "assert_eq!(a, b, \"{}\", row)"); + assert_eq!(hits(&message), [(5, "all-unguarded")], "a count in a failure message checks nothing"); + let unused = src.replace(" assert_eq!(row, 4, \"four cards\");\n", ""); + assert_eq!(hits(&unused), [(4, "all-unguarded")], "a count no assertion reads checks nothing"); + for change in ["let row = 4;", "row = 4;", "reset(&mut row);"] { + let changed = src.replace(" assert_eq!(row", &format!(" {change}\n assert_eq!(row")); + assert_eq!(hits(&changed), [(6, "all-unguarded")], "{change} before the assertion"); + } + let later = src.replace(" assert_eq!(row, 4, \"four cards\");\n", " assert_eq!(row, 4);\n let row = 4;\n"); + assert_eq!(hits(&later), [], "the count reaches the assertion before it is bound again"); + } + #[test] fn all_respects_condition_polarity() { for condition in [ @@ -2513,6 +3453,22 @@ mod tests { assert_eq!(found.iter().filter(|h| touches(h, Some(&BTreeSet::new()))).count(), 0); } + #[test] + fn only_failing_rules_fail_the_check() { + let failing: Vec<&str> = Rule::ALL.into_iter().filter(|r| r.fails()).map(Rule::id).collect(); + assert_eq!(failing, ["only-weak", "self-compare", "ignore-without-reason", "sleep"]); + let weak = "#[test]\nfn weak() {\n assert!(f().is_ok());\n}\n"; + let unguarded = "#[test]\nfn all() {\n assert!(f().iter().all(|x| valid(x)));\n}\n"; + let hits_of = |src: &str| lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(finish(&hits_of(unguarded), 0, 1, "base"), Ok(()), "all-unguarded only reports"); + let both = hits_of(&format!("{weak}{unguarded}")); + assert_eq!(both.len(), 2); + let Err(message) = finish(&both, 0, 1, "base") else { panic!("only-weak fails the check") }; + assert!(message.starts_with("1 test-lint hit(s)"), "{message}"); + assert!(message.contains("[only-weak] `weak`") && !message.contains("[all-unguarded]"), "{message}"); + assert_eq!(finish(&[], 3, 1, "base"), Ok(())); + } + #[test] fn options_reject_unknown_and_repeated_arguments() { assert_eq!(Options::parse(&[]), Ok(Options::default())); From 747593d0dd6524ed3789940a590ed9e5d8039cfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:10:17 -0800 Subject: [PATCH 17/37] xtask: test-lint reads quoted paths, test_case tests and literal setters correctly - Changed mode decodes `+++` labels (the tab after a path with a space, C-quoted paths), and the file inventories read `git ls-files -z`, so files with spaces, quotes or non-ASCII names are linted. - `#[test_case(1; "one")]` arguments and other attributes no longer end the item before its `fn`, and an inner `#![...]` attribute before the first test is not part of that test's span. - A helper name counts as asserting only when every function of that name in the crate's test code asserts. - `.stdout(file)` and other stream builder calls count as configuration whatever their argument, so `exit-status-only` still reports. - A `return` inside `async { ... }` or `async move { ... }` ends the future, not the test, for `early-return`. - `env-gate-unset` looks for setters in code only, not in string literals, ignores `echo` and `printf` output that is not written to `$GITHUB_ENV`, and its span reaches the variable name on a later line. - `sleep` reports `thread::sleep`, or a bare `sleep(...)` only where the file imports `thread::sleep`. - `reads-source` checks raw string paths in `include_str!` and `ends_with`. - A test pins that a collection changed after its `assert_eq!` loses that guard for `all-unguarded`. --- xtask/src/main.rs | 4 +- xtask/src/test_lint.rs | 288 +++++++++++++++++++++++++++++++++++------ 2 files changed, 247 insertions(+), 45 deletions(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index addf9cb7e1..3a0c854486 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -125,13 +125,13 @@ pub fn root() -> PathBuf { pub fn repo_files(root: &Path) -> Result, String> { let out = Command::new("git") .current_dir(root) - .args(["ls-files", "--cached", "--others", "--exclude-standard"]) + .args(["ls-files", "-z", "--cached", "--others", "--exclude-standard"]) .output() .map_err(|e| format!("git ls-files: {e}"))?; if !out.status.success() { return Err(format!("git ls-files failed: {}", String::from_utf8_lossy(&out.stderr).trim())); } - Ok(String::from_utf8_lossy(&out.stdout).lines().filter(|l| root.join(l).exists()).map(str::to_owned).collect()) + Ok(String::from_utf8_lossy(&out.stdout).split('\0').filter(|l| !l.is_empty() && root.join(l).exists()).map(str::to_owned).collect()) } /// A `cargo` command (the one running xtask, else `cargo` on the PATH) run in the workspace root. diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 60363000fd..a0e8f8040a 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -32,9 +32,10 @@ //! corpora, environment variables, the platform or a child process; //! * `ignore-without-reason`: `#[ignore]` with no `= "reason"`; //! * `env-gate-unset`: `env::var("NAME")` in a test where no CI workflow, the shared gate or the -//! file itself sets `NAME`; workflow mapping keys and `NAME=` assignments count, but comments -//! and variable reads do not; -//! * `sleep`: `thread::sleep` in test code; +//! file's code sets `NAME`; workflow mapping keys and `NAME=` assignments count, but comments, +//! string literals, `echo` or `printf` output that is not written to `$GITHUB_ENV`, and variable +//! 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, or a walk //! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]. //! @@ -42,8 +43,8 @@ //! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]`, or a test function. //! //! An asserting helper is a function or macro in the crate's test code (or in `crates/testkit`) -//! that asserts, panics or calls one that does, or a call whose name starts with `assert`, -//! `check`, `verify`, `ensure` or `expect_`. +//! that asserts, panics or calls one that does (every one of that name, when there are several), +//! or a call whose name starts with `assert`, `check`, `verify`, `ensure` or `expect_`. //! //! `// test-lint: allow ` exempts the line it is on and the line below it; for the //! rules about a whole test it can be on any line from the line above the test attribute to the @@ -185,8 +186,9 @@ pub struct Hit { pub note: String, /// The first and last line of what the hit covers: the test, from its attribute to its closing /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for - /// `self-compare`, else `line`. This span controls changed-line detection; `all-unguarded` - /// and `self-compare` exemptions still apply only near `line`. + /// `self-compare`, through the variable's name for `env-gate-unset`, else `line`. This span + /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply + /// only near `line`. pub first: usize, pub last: usize, } @@ -385,7 +387,7 @@ fn changed_lines(root: &Path, base: &str) -> Result BTreeMap>> { } else if header && line.starts_with("new file mode") { new_file = true; } else if let Some(path) = line.strip_prefix("+++ ").filter(|_| header) { - current = path.strip_prefix("b/").map(str::to_owned); + current = patch_path(path).and_then(|p| p.strip_prefix("b/").map(str::to_owned)); if let Some(p) = ¤t { out.insert(p.clone(), if new_file { None } else { Some(BTreeSet::new()) }); } @@ -422,6 +424,41 @@ fn parse_diff(diff: &str) -> BTreeMap>> { out } +/// The path in a `+++ ` label: git ends a label that contains a space with a tab, and writes a +/// path with a quote, a backslash or a control character as a C-style quoted string. +fn patch_path(label: &str) -> Option { + let label = label.strip_suffix('\t').unwrap_or(label); + let Some(quoted) = label.strip_prefix('"') else { return Some(label.to_owned()) }; + let body = quoted.strip_suffix('"')?.as_bytes(); + let (mut out, mut i) = (Vec::with_capacity(body.len()), 0); + while i < body.len() { + if body[i] != b'\\' { + out.push(body[i]); + i += 1; + continue; + } + let c = *body.get(i + 1)?; + let octal = body.get(i + 1..i + 4).filter(|d| d.iter().all(|c| (b'0'..=b'7').contains(c))); + if let Some(digits) = octal { + out.push(digits.iter().fold(0u8, |n, d| n.wrapping_mul(8).wrapping_add(d - b'0'))); + i += 4; + continue; + } + out.push(match c { + b'a' => 7, + b'b' => 8, + b't' => b'\t', + b'n' => b'\n', + b'v' => 11, + b'f' => 12, + b'r' => b'\r', + other => other, + }); + i += 2; + } + String::from_utf8(out).ok() +} + /// `(start, count)` of the new side of a hunk header's `-a,b +c,d @@`. A pure deletion has count 0 /// and sits between lines c and c + 1; c = 0 places it before line 1. fn hunk_range(hunk: &str) -> Option<(usize, usize)> { @@ -459,12 +496,20 @@ fn upper_words(text: &str) -> impl Iterator + '_ { let name = line[..at].rsplit(|c: char| !(c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')).next().unwrap_or_default(); let from = at - name.len(); let boundary = from == 0 || line.as_bytes().get(from - 1).is_some_and(|c| c.is_ascii_whitespace() || matches!(c, b'\'' | b'"' | b';')); - (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>'])).then(|| name.to_owned()) + (boundary && env_assignment_name(name) && !line[at + 1..].starts_with(['=', '>']) && !printed(line, from)).then(|| name.to_owned()) }); mapping.map(|(name, _)| name.to_owned()).into_iter().chain(assignments) }) } +/// Whether the text at `from` is an argument of `echo` or `printf` in its shell command, on a line +/// that does not write to `$GITHUB_ENV`. +fn printed(line: &str, from: usize) -> bool { + let command = line[..from].rsplit([';', '&', '|']).next().unwrap_or_default().as_bytes(); + let prints = ["echo", "printf"].iter().any(|w| !words(command, w.as_bytes(), 0, command.len()).is_empty()); + prints && !line.contains("GITHUB_ENV") +} + fn env_assignment_name(name: &str) -> bool { name.len() > 1 && name.starts_with(|c: char| c.is_ascii_uppercase()) @@ -513,11 +558,6 @@ fn mask_with(src: &str, comments: bool) -> Vec { mask_parts(src, comments, true) } -/// Blanks comments while keeping code and literal contents at the same byte offsets. -fn mask_comments(src: &str) -> Vec { - mask_parts(src, true, false) -} - /// Blanks the selected comments and literal contents, preserving line breaks and literal quotes. fn mask_parts(src: &str, comments: bool, literals: bool) -> Vec { let b = src.as_bytes(); @@ -769,6 +809,11 @@ fn tests_in(m: &[u8]) -> Vec { /// The function an attribute at `attr` (ending at `from`) belongs to. fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { + // The attribute's arguments, and the attributes after it, can hold `;` (`#[test_case(1; "one")]`). + let mut from = from.max(matching(m, attr + 1)? + 1); + while m[skip_ws(m, from)..].starts_with(b"#[") { + from = matching(m, skip_ws(m, from) + 1)? + 1; + } let limit = (from + 800).min(m.len()); let fn_at = *words(m, b"fn", from, limit).first()?; if m[from..fn_at].iter().any(|&c| c == b'{' || c == b';') { @@ -785,7 +830,11 @@ fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { } let close = matching(m, open)?; // The item starts after the previous item or block opening; comments before it are masked. - let item = m[..attr].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + // Inner attributes (`#![…]`) there belong to the enclosing module or crate. + let mut item = m[..attr].iter().rposition(|&c| matches!(c, b';' | b'{' | b'}')).map_or(0, |p| p + 1); + while m[skip_ws(m, item)..].starts_with(b"#![") && skip_ws(m, item) < attr { + item = matching(m, skip_ws(m, item) + 2)? + 1; + } let attr = skip_ws(m, item).min(attr); Some(TestFn { name: String::from_utf8_lossy(&m[name_start..name_end]).into_owned(), attr, fn_at, open, close }) } @@ -960,12 +1009,22 @@ pub fn asserting_helpers(files: &[(String, String)]) -> HashMap(defs: impl Iterator + Clone) -> HashSet { - let mut known: HashSet = defs.clone().filter(|d| d.1).map(|d| d.0.clone()).collect(); + let mut by_name: HashMap<&str, Vec<&Def>> = HashMap::new(); + for d in defs { + by_name.entry(d.0.as_str()).or_default().push(d); + } + let mut known: HashSet = HashSet::new(); loop { - let more: Vec = - defs.clone().filter(|d| !known.contains(&d.0) && d.2.iter().any(|c| known.contains(c))).map(|d| d.0.clone()).collect(); + let checks = |d: &Def| d.1 || d.2.iter().any(|c| known.contains(c)); + let more: Vec = by_name + .iter() + .filter(|(name, same)| !known.contains(**name) && same.iter().all(|d| checks(d))) + .map(|(name, _)| (*name).to_owned()) + .collect(); if more.is_empty() { return known; } @@ -2074,13 +2133,12 @@ fn exit_status_only(v: &View) -> Option { Some(v.whole(Rule::ExitStatusOnly, "runs a process and checks only its exit status".into())) } -/// Blanks stream method names that configure a process with `Stdio` in whitespace-free text. +/// Blanks the names of builder calls that set a process's streams (`.stdout(…)`, whatever the +/// argument) in whitespace-free text. Reads of the output fields (`out.stdout`) stay. fn strip_stream_configuration(body: &mut [u8]) { for stream in ["stdout", "stderr", "stdin"] { for at in words(body, stream.as_bytes(), 0, body.len()) { - let rest = &body[at + stream.len()..]; - let config = rest.starts_with(b"(Stdio::") || rest.starts_with(b"(std::process::Stdio::"); - if body[..at].ends_with(b".") && config { + if body[..at].ends_with(b".") && body[at + stream.len()..].starts_with(b"(") { blank(body, at, at + stream.len()); } } @@ -2205,7 +2263,9 @@ fn opens_closure_or_fn(m: &[u8], open: usize, brace: usize) -> bool { let head = String::from_utf8_lossy(&head[start..]).into_owned(); let head = head.trim_end(); let closure = head.ends_with('|') || head.rfind("->").is_some_and(|p| head[..p].trim_end().ends_with('|')); - closure || !words(head.as_bytes(), b"fn", 0, head.len()).is_empty() + let block = head.strip_suffix("move").unwrap_or(head).trim_end(); + let future = block.ends_with("async") && !block[..block.len() - "async".len()].ends_with(|c: char| c.is_ascii_alphanumeric() || c == '_'); + closure || future || !words(head.as_bytes(), b"fn", 0, head.len()).is_empty() } /// Whether the return at `at..end` is not a silent skip on a value: the block it ends asserts @@ -2239,24 +2299,50 @@ fn env_gates(v: &View, ctx: &Ctx) -> Vec { if !m[..at].ends_with(b"env::") { continue; } - let Some(name) = env_name(m, src, at) else { continue }; + let Some((name, end)) = env_name(m, src, at) else { continue }; if ctx.ci_env.contains(&name) || set_by_system(&name) { continue; } - // The whole file is masked and searched only for a name that CI and the system leave unset. - let file = norm(&mask_comments(&String::from_utf8_lossy(src))); - let set_here = file.contains(&format!(".env(\"{name}\"")) - || file.contains(&format!("=\"{name}\";")) - || file.match_indices(&format!("set_var(\"{name}\"")).any(|(at, _)| at == 0 || !is_ident(file.as_bytes()[at - 1])); - if !set_here { - out.push(v.hit(at, Rule::EnvGateUnset, format!("reads {name}, which no CI leg sets"))); + if !set_in_file(m, src, &name) { + // The hit sits on `var`; its span reaches the name, which can be on a later line. + let mut hit = v.hit(at, Rule::EnvGateUnset, format!("reads {name}, which no CI leg sets")); + hit.last = v.file.lines.of(end); + out.push(hit); } } out } -/// The literal name in `env::var("NAME")` whose `var` is at `at`. -fn env_name(m: &[u8], src: &[u8], at: usize) -> Option { +/// Whether the file's code (masked `m`, outside comments and literals) sets `name`: `.env("NAME", …)`, +/// `set_var("NAME", …)`, or a constant `= "NAME";`. The name is read from the source. +fn set_in_file(m: &[u8], src: &[u8], name: &str) -> bool { + let call = |word: &[u8], method: bool| { + words(m, word, 0, m.len()).into_iter().any(|at| { + let dot = m[..at].trim_ascii_end().ends_with(b"."); + (dot || !method) && env_name(m, src, at).is_some_and(|(n, _)| n == name) + }) + }; + let constant = find_all(src, name.as_bytes()).any(|p| { + let (open, close) = (p.wrapping_sub(1), p + name.len()); + let (Some(b'"'), Some(b'"')) = (m.get(open), m.get(close)) else { return false }; + m[..open].trim_ascii_end().ends_with(b"=") && m.get(skip_ws(m, close + 1)) == Some(&b';') + }); + call(b"env", true) || call(b"set_var", false) || constant +} + +/// Every start of `needle` in `hay`. +fn find_all<'a>(hay: &'a [u8], needle: &'a [u8]) -> impl Iterator + 'a { + let mut from = 0; + std::iter::from_fn(move || { + let at = find(hay, needle, from)?; + from = at + 1; + Some(at) + }) +} + +/// The literal name in `env::var("NAME")` whose `var` is at `at`, and the offset of its closing +/// quote. +fn env_name(m: &[u8], src: &[u8], at: usize) -> Option<(String, usize)> { let open = skip_ws(m, at + m[at..].iter().take_while(|&&c| is_ident(c)).count()); if m.get(open) != Some(&b'(') { return None; @@ -2267,7 +2353,7 @@ fn env_name(m: &[u8], src: &[u8], at: usize) -> Option { } let end = string_end(src, quote + 1).saturating_sub(1); let name = std::str::from_utf8(&src[quote + 1..end]).ok()?; - (!name.is_empty() && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')).then(|| name.to_owned()) + (!name.is_empty() && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_')).then(|| (name.to_owned(), end)) } fn ignore_hits(file: &File) -> Vec { @@ -2311,16 +2397,24 @@ fn ignore_reason(src: &[u8]) -> Option<&[u8]> { fn sleep_hits(file: &File) -> Vec { let m = &file.m; + // A bare `sleep(…)` counts only where a `use` brings in `thread::sleep`. + let imported = words(m, b"use", 0, m.len()).into_iter().any(|u| { + let item = norm(&m[u..statement_end(m, u)]); + item.contains("thread::sleep") + || item.split_once("thread::{").is_some_and(|(_, list)| !words(list.as_bytes(), b"sleep", 0, list.len()).is_empty()) + }); words(m, b"sleep", 0, m.len()) .into_iter() .filter(|&at| { - if !in_regions(&file.regions, at) { + if !in_regions(&file.regions, at) || m.get(skip_ws(m, at + "sleep".len())) != Some(&b'(') { return false; } - let before = m[..at].iter().rposition(|c| !c.is_ascii_whitespace()); - let method = before.is_some_and(|b| m[b] == b'.'); - let definition = m[..at].trim_ascii_end().ends_with(b"fn"); - !method && !definition && m.get(skip_ws(m, at + "sleep".len())) == Some(&b'(') + let before = m[..at].trim_ascii_end(); + let path = before.strip_suffix(b"::").map(<[u8]>::trim_ascii_end); + match path { + Some(p) => p.ends_with(b"thread") && !p.ends_with(b"_thread"), + None => imported && !before.ends_with(b".") && !before.ends_with(b"fn"), + } }) .map(|at| file.hit(at, Rule::Sleep, file.test_at(at), "sleeps in test code".into())) .collect() @@ -2337,7 +2431,10 @@ fn reads_source_hits(file: &File) -> Vec { let open = skip_ws(m, at + word.len() + usize::from(m.get(at + word.len()) == Some(&b'!'))); let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue }; let arg = norm(&file.src[open + 1..close]); - let rs = if word == b"ends_with" { arg == "\".rs\"" } else { arg.ends_with(".rs\"") }; + // An ordinary or raw string literal: `".rs"`, `r".rs"`, `r#"…/lib.rs"#`. + let raw = arg.strip_prefix('r').map(|a| a.trim_matches('#')).filter(|a| a.starts_with('"')); + let literal = raw.unwrap_or(&arg); + let rs = if word == b"ends_with" { literal == "\".rs\"" } else { arg.trim_end_matches('#').ends_with(".rs\"") }; if rs { out.push(file.hit(at, Rule::ReadsSource, file.test_at(at), note.into())); } @@ -3335,7 +3432,7 @@ mod tests { assert_eq!(hits(&src.replacen("MY_SAMPLES", "OTHER_SAMPLES", 1)), [(4, "env-gate-unset")], "{setter}"); } let src = "let a = \"https://host/*path*/\"; /* removed */ let b = r#\"// kept /* kept */\"#; // removed\nlet c = '/';"; - let masked = String::from_utf8(mask_comments(src)).unwrap(); + let masked = String::from_utf8(mask_parts(src, true, false)).unwrap(); assert!(masked.contains("\"https://host/*path*/\"")); assert!(masked.contains("r#\"// kept /* kept */\"#")); assert!(masked.contains("let c = '/';")); @@ -3527,4 +3624,109 @@ mod tests { assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), [], "{workflow}"); } } + + #[test] + fn printed_workflow_assignments_do_not_count() { + for line in + ["run: echo \"MY_SAMPLES=fixtures\"", " echo MY_SAMPLES=fixtures", " printf 'MY_SAMPLES=x\\n'", " true && echo \"MY_SAMPLES=x\""] + { + assert_eq!(upper_words(line).collect::>(), Vec::::new(), "{line}"); + } + for line in [" echo hi; MY_SAMPLES=x cargo test", " printf 'MY_SAMPLES=x\\n' >> \"$GITHUB_ENV\""] { + assert_eq!(upper_words(line).collect::>(), ["MY_SAMPLES"], "{line}"); + } + } + + #[test] + fn patch_labels_are_decoded_before_filtering() { + let diff = "diff --git a/crates/x/tests/two words.rs b/crates/x/tests/two words.rs\n--- a/crates/x/tests/two words.rs\t\n+++ b/crates/x/tests/two words.rs\t\n@@ -1 +1 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/q\\\"t.rs\" \"b/crates/x/tests/q\\\"t.rs\"\n--- \"a/crates/x/tests/q\\\"t.rs\"\n+++ \"b/crates/x/tests/q\\\"t.rs\"\n@@ -2 +2 @@\n-a\n+b\ndiff --git \"a/crates/x/tests/caf\\303\\251.rs\" \"b/crates/x/tests/caf\\303\\251.rs\"\n--- \"a/crates/x/tests/caf\\303\\251.rs\"\n+++ \"b/crates/x/tests/caf\\303\\251.rs\"\n@@ -3 +3 @@\n-a\n+b\n"; + let got = parse_diff(diff); + assert_eq!(got.get("crates/x/tests/two words.rs"), Some(&Some([1].into_iter().collect())), "{got:?}"); + assert_eq!(got.get("crates/x/tests/q\"t.rs"), Some(&Some([2].into_iter().collect())), "{got:?}"); + assert_eq!(got.get("crates/x/tests/caf\u{e9}.rs"), Some(&Some([3].into_iter().collect())), "{got:?}"); + assert!(got.keys().all(|p| is_scanned(p)), "{got:?}"); + } + + #[test] + fn test_case_arguments_and_inner_attributes_do_not_hide_tests() { + let cases = "#[test_case(1; \"one\")]\n#[test_case(2; \"two\")]\nfn t(n: u8) {}\n"; + assert_eq!(hits(cases), [(3, "no-assertion")]); + let inner = "#![allow(dead_code)]\n\n#[should_panic]\n#[test]\nfn t() {\n f();\n}\n#[test]\nfn u() {\n g();\n}\n"; + let found = lint_file("crates/x/src/tests.rs", &inner.replace("#[should_panic]\n", ""), &ctx()); + assert_eq!(found.iter().map(|h| (h.first, h.last)).collect::>(), [(3, 6), (7, 10)], "{found:?}"); + assert_eq!(hits(inner), [(9, "no-assertion")], "#[should_panic] before #[test] still belongs to the test"); + } + + #[test] + fn helpers_with_a_shared_name_count_only_when_each_asserts() { + let src = "mod a {\n pub fn exercise() { assert_eq!(f(), 1); }\n}\nmod b {\n pub fn exercise() { f(); }\n}\n#[test]\nfn t() {\n b::exercise();\n}\n"; + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), src.to_owned())]); + assert!(!helpers["crates/x"].contains("exercise"), "{helpers:?}"); + assert_eq!(hits_in("crates/x/tests/it.rs", src, &Ctx { helpers, ci_env: HashSet::new() }), [(8, "no-assertion")]); + let both = src.replace("{ f(); }", "{ assert!(f()); }"); + let helpers = asserting_helpers(&[("crates/x/tests/it.rs".to_owned(), both.clone())]); + assert_eq!(hits_in("crates/x/tests/it.rs", &both, &Ctx { helpers, ci_env: HashSet::new() }), []); + } + + #[test] + fn a_changed_collection_loses_its_equality_guard() { + let src = "#[test]\nfn t() {\n let mut xs = f();\n assert_eq!(xs, vec![1]);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + for change in ["xs.clear();", "xs.retain(|x| *x > 5);", "xs = vec![];"] { + let changed = src.replace("\n assert!", &format!("\n {change}\n assert!")); + assert_eq!(hits(&changed), [(6, "all-unguarded")], "{change}"); + } + } + + #[test] + fn stream_redirection_to_any_target_is_configuration() { + let bad = "#[test]\nfn t() {\n let status = Command::new(bin()).stdout(file).stderr(log.try_clone().unwrap()).status().unwrap();\n assert!(status.success());\n}\n"; + assert_eq!(hits(bad), [(2, "exit-status-only")]); + let good = bad.replace(" assert!", " assert_eq!(fs::read(path).unwrap(), b\"ok\");\n assert!"); + assert_eq!(hits(&good), []); + } + + #[test] + fn async_blocks_end_their_own_returns() { + let src = "#[test]\nfn t() {\n block_on(async { if missing() { return; } work().await; });\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(src), []); + assert_eq!(hits(&src.replace("async {", "async move {")), []); + let own = "#[tokio::test]\nasync fn t() {\n if missing() { return; }\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(own), [(3, "early-return")], "a return from the test's own body"); + } + + #[test] + fn env_setters_in_literals_do_not_count_and_spans_reach_the_name() { + let src = "#[test]\nfn t() {\n let _example = r#\"cmd.env(\"MY_SAMPLES\", dir)\"#;\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(src), [(4, "env-gate-unset")]); + let constant = "const X: &str = r#\"= \"MY_SAMPLES\";\"#;\n#[test]\nfn t() {\n let dir = std::env::var(\"MY_SAMPLES\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(constant), [(4, "env-gate-unset")]); + let multiline = "#[test]\nfn t() {\n let dir = std::env::var(\n \"MY_SAMPLES\",\n );\n assert_eq!(f(dir), 3);\n}\n"; + let found = lint_file("crates/x/src/tests.rs", multiline, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::>(), [(Rule::EnvGateUnset, 3, 3, 4)]); + assert!(touches(&found[0], Some(&[4].into_iter().collect())), "a change to the name alone"); + } + + #[test] + fn sleep_needs_the_thread_function() { + let local = "fn sleep() -> u8 { 42 }\n#[test]\nfn t() {\n assert_eq!(sleep(), 42);\n}\n"; + assert_eq!(hits(local), []); + for import in ["use std::thread::sleep;", "use std::thread::{self, sleep};"] { + let src = format!("{import}\n#[test]\nfn t() {{\n sleep(D);\n assert_eq!(f(), 42);\n}}\n"); + assert_eq!(hits(&src), [(4, "sleep")], "{import}"); + } + assert_eq!(hits("#[test]\nfn t() {\n std :: thread :: sleep(D);\n assert_eq!(f(), 1);\n}\n"), [(3, "sleep")]); + } + + #[test] + fn raw_include_str_paths_are_checked() { + for literal in ["r\"../lib.rs\"", "r#\"../lib.rs\"#", "r##\"../lib.rs\"##"] { + let src = format!("#[test]\nfn t() {{\n let src = include_str!({literal});\n assert_eq!(src.len(), 1);\n}}\n"); + assert_eq!(hits(&src), [(3, "reads-source")], "{literal}"); + assert_eq!(hits(&src.replace(".rs", ".svg")), [], "{literal} with a fixture"); + assert_eq!(hits_in(SOURCE_AUDITS[0], &src, &ctx()), [], "{literal} in an audit"); + } + let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(r#\".rs\"#)).count();\n assert_eq!(n, 4);\n}\n"; + assert_eq!(hits(walk), [(3, "reads-source")]); + } } From b851ac2c8d118022643616ecbd3240c91520664d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:16:23 -0800 Subject: [PATCH 18/37] CI: drop the cache prune watcher job; cache-prune.yml prunes after each run ci.yml's `cache prune` job held a runner beside the whole gate on every main push and nightly run, only to delete the rolling entry that the `cache warm` leg replaced. cache-prune.yml already runs that prune once every CI attempt on main ends, and the warm leg is the last job to finish, so the old entry now goes a few seconds after the save instead of during it. The nightly cold run's `cold cache clear` job stays. Its script used the `cache prune` job to tell "Re-run all jobs" from a re-run of failed jobs. It now looks for `gate / select legs` instead, which only "Re-run all jobs" lists once the warm leg has succeeded, and it waits 5 minutes for that job to appear before it treats the warm leg as finished in an earlier attempt. --- .github/workflows/cache-prune.yml | 11 +++++---- .github/workflows/ci.yml | 30 ++----------------------- scripts/ci-clear-rolling-cache-tests.py | 24 +++++++++++++------- scripts/ci-clear-rolling-cache.py | 23 ++++++++++++------- 4 files changed, 38 insertions(+), 50 deletions(-) diff --git a/.github/workflows/cache-prune.yml b/.github/workflows/cache-prune.yml index a79f1ed907..c1b1e73ae3 100644 --- a/.github/workflows/cache-prune.yml +++ b/.github/workflows/cache-prune.yml @@ -1,11 +1,10 @@ name: Cache prune -# A pass of the cache prune after every CI attempt on main. ci.yml's `cache prune` job prunes while -# a run's jobs save their entries, but "Re-run failed jobs" re-runs only the failed jobs: a re-run -# `cache warm` leg saves a new entry, and the prune job, which succeeded in the first attempt, does -# not run again. The entry it replaced would stay until the next main run, and with it the cache -# would be over its 10 GB budget, where GitHub evicts entries a run still needs. This runs once -# after every attempt, re-runs and canceled runs included (craft-common-actions actions/cache-prune). +# Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache +# budget, where GitHub evicts entries a run still needs. Each main CI attempt's `cache warm` leg +# saves a new rolling entry; this deletes the entry it replaced once the attempt ends. It runs once +# after every attempt, re-runs of failed jobs and canceled runs included (craft-common-actions +# actions/cache-prune). on: workflow_run: workflows: [CI] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0954b5c35c..9937d6165c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,8 +50,8 @@ jobs: # The dependency cache also keeps the compiled workspace crates and test executables, so a # pull request's shards rebuild only the crates its changes reach. Each main run's `cache # warm` leg saves a rolling entry of its own, every leg restores the newest one, and - # `cache-prune` below deletes the one it replaced. The nightly run restores nothing and - # builds everything from source. + # cache-prune.yml deletes the one it replaced after each attempt. The nightly run restores + # nothing and builds everything from source. cache-workspace-crates: true cold-build: ${{ github.event_name == 'schedule' }} packages: >- @@ -59,32 +59,6 @@ jobs: libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev - # Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache - # budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A - # failed prune warns instead of failing the run, and cache-prune.yml prunes again after every - # attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's - # `timeout-minutes`, so the watch outlasts a cold `cache warm` leg. - cache-prune: - name: cache prune - if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' - runs-on: ubuntu-24.04 - timeout-minutes: 170 - permissions: - actions: write - steps: - - name: Harden runner - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 - with: - egress-policy: audit - - name: Prune replaced cache entries - uses: storytold/craft-common-actions/actions/cache-prune@main - continue-on-error: true - with: - watch: true - watch-minutes: 160 - saving-jobs: | - ^gate( / cache warm \(.*\))?$ - # The nightly cold run never restores the rolling crates entry, so the old entry is only overlap # while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the # 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py index a284579d16..250fd92b1c 100644 --- a/scripts/ci-clear-rolling-cache-tests.py +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -129,18 +129,26 @@ class Jobs(unittest.TestCase): jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"}, {"name": WARM}] self.assertEqual(clear.warm_job(jobs), jobs[2]) - def test_a_rerun_of_this_job_alone_skips_a_leg_that_succeeded(self): - self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success")})) - self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success"), 2: [{"name": "cold cache clear"}]})) - self.assertTrue(clear.not_in_attempt(ME, {1: earlier("failure"), 2: [{"name": "cold cache clear"}], 3: earlier("success")})) + def test_a_rerun_of_failed_jobs_skips_a_leg_that_succeeded(self): + grace = clear.RERUN_GRACE_SECONDS + failed_shard = [{"name": "gate / test 3/6 (ubuntu-24.04)", "status": "in_progress"}] + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success")}, grace)) + self.assertTrue(clear.not_in_attempt(ME + failed_shard, {1: earlier("success")}, grace)) + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success"), 2: [{"name": "cold cache clear"}]}, grace)) + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("failure"), 2: [{"name": "cold cache clear"}], 3: earlier("success")}, grace)) + + def test_an_attempt_is_watched_for_the_grace_period_first(self): + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success")}, clear.RERUN_GRACE_SECONDS - 1)) def test_a_leg_that_did_not_succeed_is_waited_for(self): - self.assertFalse(clear.not_in_attempt(ME, {1: earlier("cancelled")})) - self.assertFalse(clear.not_in_attempt(ME, {})) - self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success"), 2: earlier("failure")})) + grace = clear.RERUN_GRACE_SECONDS + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("cancelled")}, grace)) + self.assertFalse(clear.not_in_attempt(ME, {}, grace)) + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success"), 2: earlier("failure")}, grace)) def test_a_rerun_of_all_jobs_is_waited_for(self): - self.assertFalse(clear.not_in_attempt(ME + [{"name": "cache prune", "status": "in_progress"}], {1: earlier("success")})) + select = [{"name": "gate / select legs", "status": "queued"}] + self.assertFalse(clear.not_in_attempt(ME + select, {1: earlier("success")}, clear.GIVE_UP_SECONDS)) def test_a_failed_select_or_build_stops_the_wait(self): done = lambda n, c: {"name": n, "status": "completed", "conclusion": c} diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py index 3b913d68f7..e285fef70b 100644 --- a/scripts/ci-clear-rolling-cache.py +++ b/scripts/ci-clear-rolling-cache.py @@ -18,9 +18,10 @@ were deleted leaves no rolling entry, so the next run starts cold, and this exit in a later post step does not count once the save step has succeeded. This also exits 1 when the leg has not started START_SECONDS after this script started, and when the leg has not reached its save, or its save has not finished, GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only -when the most recent earlier attempt that lists it reports success and the current attempt lists -no `cache prune` job, which runs from the start of "Re-run all jobs". Otherwise this keeps polling -because reusable-workflow dependencies may still be scheduling it. +when the most recent earlier attempt that lists it reports success and the current attempt still +lists no `gate / select legs` job RERUN_GRACE_SECONDS after this script started: "Re-run all +jobs" lists that job from its start, and "Re-run failed jobs" after a successful leg does not. +Otherwise this keeps polling because reusable-workflow dependencies may still be scheduling it. """ from datetime import datetime, timezone @@ -36,7 +37,12 @@ WARM_JOB = re.compile(r'^gate / cache warm \(') # The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of # them fails or is canceled, the legs are skipped and no warm leg is listed. NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \()') -PRUNE_JOB = 'cache prune' +# The gate's first job. "Re-run all jobs" lists it; "Re-run failed jobs" lists it only when it +# failed, and then no warm leg succeeded before. +SELECT_JOB = 'gate / select legs' +# How long an attempt that does not list SELECT_JOB is watched before the warm leg counts as +# finished in an earlier attempt. +RERUN_GRACE_SECONDS = 5 * 60 ROLLING = '-gate-crates-' # The gate-setup action's post step, which saves the dependency cache (craft-common-actions # actions/gate-setup, under the gate's `Setup` step). @@ -135,9 +141,10 @@ def legs_stopped(jobs): return any(NEEDED_JOBS.match(j['name']) and j['status'] == 'completed' and j.get('conclusion') in STOPPED for j in jobs) -def not_in_attempt(jobs, earlier_jobs): - """True when no prune job is listed and the most recent earlier warm leg succeeded.""" - if any(j['name'] == PRUNE_JOB for j in jobs): +def not_in_attempt(jobs, earlier_jobs, waited): + """True when SELECT_JOB is not listed `waited` seconds after this script started, at least + RERUN_GRACE_SECONDS, and the most recent earlier warm leg succeeded.""" + if waited < RERUN_GRACE_SECONDS or any(j['name'] == SELECT_JOB for j in jobs): return False for attempt in sorted(earlier_jobs, reverse=True): job = warm_job(earlier_jobs[attempt]) @@ -185,7 +192,7 @@ def main(): earlier_jobs[earlier] = previous.get('jobs', []) if warm_job(earlier_jobs[earlier]) is not None: break - if not_in_attempt(jobs.get('jobs', []), earlier_jobs): + if not_in_attempt(jobs.get('jobs', []), earlier_jobs, (datetime.now(timezone.utc) - began).total_seconds()): print('the cache warm leg is not part of this attempt (it succeeded in an earlier one); nothing deleted') return if legs_stopped(jobs.get('jobs', [])): From 28f33ca04c29a0e6c75d256ad873099ff3ce9e0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:20:08 -0800 Subject: [PATCH 19/37] xtask: test-lint scopes bindings, spans ignore reasons and names its failing rules - The module docs and docs/development.md name the four rules that fail the check, and describe `only-weak` and `self-compare` by what they match (`len() > 0`, `assert_ne!`). - The changed-lines diff passes `--inter-hunk-context=0`, so a clone's `diff.interHunkContext` cannot mark unchanged lines between two edits. - Single-letter workflow variables count as set. - Test names with non-ASCII letters are read whole. - An allow in a block comment needs a reason before `*/`. - `all-unguarded` uses only a binding still in scope at the assertion, treats a `const` declared with different values as unknown, and drops a counted local once its collection may shrink or be replaced. - `only-weak` ignores `unwrap_err`, `expect_err` and `panic!` in failure messages. - `self-compare` leaves out operands that call a method returning the next value each time (`next`, `pop_front`, `recv` and others). - An `ignore-without-reason` span reaches the attribute's `]`, so a change to a reason on the next line counts. --- docs/development.md | 2 +- xtask/src/test_lint.rs | 174 +++++++++++++++++++++++++++++++++++------ 2 files changed, 149 insertions(+), 27 deletions(-) diff --git a/docs/development.md b/docs/development.md index cfd02bacc8..efb554b561 100644 --- a/docs/development.md +++ b/docs/development.md @@ -351,7 +351,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 a test whose only checks are `is_ok`, `is_some` or `!is_empty` (`only-weak`), `assert_eq!(x, x)` (`self-compare`), `#[ignore]` without a reason (`ignore-without-reason`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: `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 test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. 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 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`), 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`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: `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 test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. 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. ## Tests diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index a0e8f8040a..f442c9681d 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -21,7 +21,8 @@ //! * `only-weak`: every assertion is `is_ok()`, `is_some()`, `!is_empty()` or `len() > 0`, and the //! test calls no asserting helper; //! * `self-compare`: `assert_eq!(x, x)` or `assert_ne!(x, x)` on the same expression, when that -//! expression calls nothing with arguments (two calls with arguments check determinism); +//! expression calls nothing with arguments (two calls with arguments check determinism) and no +//! method that returns the next value each time ([`ADVANCING`], such as `next`); //! * `exit-status-only`: a test that runs a process and checks only its exit status, reading no //! output, with a status check in any condition or compared operand of a standard assertion; //! * `no-assertion`: no assertion macro, `panic!`, `unwrap_err`, `expect_err` or asserting helper, @@ -50,8 +51,9 @@ //! rules about a whole test it can be on any line from the line above the test attribute to the //! `fn` line. An allow without a reason exempts nothing. //! -//! `cargo xtask test-lint` fails on the hits in the lines and tests changed since a base: `--base -//! ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! `cargo xtask test-lint` fails on hits of `only-weak`, `self-compare`, `ignore-without-reason` +//! and `sleep` in the lines and tests changed since a base, and lists the other rules' hits there +//! without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's //! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge //! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the @@ -186,7 +188,8 @@ pub struct Hit { pub note: String, /// The first and last line of what the hit covers: the test, from its attribute to its closing /// brace, for a rule about a whole test or `all-unguarded`, through the second operand for - /// `self-compare`, through the variable's name for `env-gate-unset`, else `line`. This span + /// `self-compare`, through the variable's name for `env-gate-unset`, through the attribute's + /// `]` for `ignore-without-reason`, else `line`. This span /// controls changed-line detection; `all-unguarded` and `self-compare` exemptions still apply /// only near `line`. pub first: usize, @@ -384,7 +387,20 @@ fn resolve_base(root: &Path, explicit: Option) -> Result fn changed_lines(root: &Path, base: &str) -> Result>>, String> { let diff = git( root, - &["-c", "core.quotepath=off", "diff", "-U0", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", base, "--", "*.rs"], + &[ + "-c", + "core.quotepath=off", + "diff", + "-U0", + "--inter-hunk-context=0", + "--no-color", + "--no-ext-diff", + "--src-prefix=a/", + "--dst-prefix=b/", + base, + "--", + "*.rs", + ], )?; let mut out = parse_diff(&diff); for path in git(root, &["ls-files", "-z", "--others", "--exclude-standard", "--", "*.rs"])?.split('\0').filter(|p| !p.is_empty()) { @@ -511,9 +527,7 @@ fn printed(line: &str, from: usize) -> bool { } fn env_assignment_name(name: &str) -> bool { - name.len() > 1 - && name.starts_with(|c: char| c.is_ascii_uppercase()) - && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') + name.starts_with(|c: char| c.is_ascii_uppercase()) && name.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == b'_') } /// Removes comment text outside quotes from a workflow line. @@ -820,7 +834,8 @@ fn fn_after(m: &[u8], attr: usize, from: usize) -> Option { return None; } let name_start = skip_ws(m, fn_at + 2); - let name_end = name_start + m[name_start..].iter().take_while(|&&c| is_ident(c)).count(); + // Identifiers may hold non-ASCII letters (`échec`); their UTF-8 bytes are all 0x80 or above. + let name_end = name_start + m[name_start..].iter().take_while(|&&c| is_ident(c) || c >= 0x80).count(); if name_end == name_start { return None; } @@ -1124,7 +1139,8 @@ fn allows(src: &str, m: &[u8]) -> Vec<(usize, Rule)> { src.match_indices(ALLOW) .filter(|&(p, _)| m[p] == b' ' && literals[p] == b't') .filter_map(|(p, _)| { - let rest = src[p + ALLOW.len()..].lines().next()?; + // The reason ends with the line, or with the block comment that holds the marker. + let rest = src[p + ALLOW.len()..].lines().next()?.split("*/").next()?; let mut words = rest.split_whitespace(); let rule = Rule::from_id(words.next()?)?; words.next().map(|_| (lines.of(p), rule)) @@ -1622,7 +1638,7 @@ fn array_receiver(receiver: &str) -> &str { receiver.strip_suffix(".iter()").or_else(|| receiver.strip_suffix(".into_iter()")).unwrap_or(receiver) } -/// The fewest items a plain local receiver has after its latest preceding binding: from the +/// The fewest items a plain local receiver has after its latest preceding binding still in scope: from the /// binding ([`array_binding`]) or a loop that fills it ([`loop_fill_len`]), and 0 when a later /// statement may shrink or replace it ([`may_shrink`]). fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { @@ -1631,7 +1647,8 @@ fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { return 0; } let name = name.as_bytes(); - let Some((len, end)) = words(body, b"let", 0, body.len()).into_iter().rev().find_map(|at| array_binding(body, at, name, sizes)) else { + let mut in_scope = words(body, b"let", 0, body.len()).into_iter().rev().filter(|&at| open_at_end(body, at)); + let Some((len, end)) = in_scope.find_map(|at| array_binding(body, at, name, sizes)) else { return 0; }; if may_shrink(body, name, end) { @@ -1640,6 +1657,21 @@ fn bound_len(receiver: &str, body: &[u8], sizes: &Sizes) -> usize { len.max(loop_fill_len(body, name, end, sizes)) } +/// Whether the block holding offset `at` of `body` is still open at the end of `body`: a binding +/// there is still in scope. +fn open_at_end(body: &[u8], at: usize) -> bool { + let mut depth = 0usize; + for &c in &body[at..] { + match c { + b'{' => depth += 1, + b'}' if depth == 0 => return false, + b'}' => depth -= 1, + _ => {} + } + } + true +} + /// For a `let` at `at` that binds `name` (allowing `mut`): the fewest items its array type /// annotation gives (which decides when there is one), else its initializer gives ([`expr_len`]), /// and where the statement ends. `None` for a binding of another name. @@ -2012,10 +2044,11 @@ fn int_literal(text: &str) -> Option { text[..digits].replace('_', "").parse().ok() } -/// `const NAME: T = ;` in a masked file; a name declared more than once keeps -/// its smallest value, and 0 when one of its values is not a literal. +/// `const NAME: T = ;` in a masked file. A name declared more than once with +/// different values, or with a value that is not a literal, is left out (its value is unknown). fn file_consts(file: &[u8]) -> HashMap { - let mut out: HashMap = HashMap::new(); + // `None` for a name declared with a value that is not a literal or with different values. + let mut out: HashMap> = HashMap::new(); for at in words(file, b"const", 0, file.len()) { let start = skip_ws(file, at + 5); let end = start + file[start..].iter().copied().take_while(|&c| is_ident(c)).count(); @@ -2025,12 +2058,14 @@ fn file_consts(file: &[u8]) -> HashMap { let stop = statement_end(file, end); let stmt = norm(&file[end..stop]); let Some((_, value)) = stmt.split_once('=') else { continue }; - let value = int_literal(value).unwrap_or(0); + let value = int_literal(value); let name = String::from_utf8_lossy(&file[start..end]).into_owned(); let slot = out.entry(name).or_insert(value); - *slot = (*slot).min(value); + if *slot != value { + *slot = None; + } } - out + out.into_iter().filter_map(|(name, value)| Some((name, value?))).collect() } /// A `let` of a plain name: the name, where the statement ends, and whether it binds an expression @@ -2039,6 +2074,8 @@ struct Binding { name: Vec, end: usize, counts: bool, + /// The local whose method the initializer calls (`xs` in `let n = xs.len()`). + source: Option>, } /// Every `let` of a plain name in `body`, in order. @@ -2056,19 +2093,24 @@ fn bindings(body: &[u8]) -> Vec { } let stop = statement_end(body, end); let stmt = norm(&body[end..stop]); - let counts = stmt.split_once('=').is_some_and(|(_, init)| SIZE_CHECKS.iter().any(|g| init.contains(g))); - Some(Binding { name: body[start..end].to_vec(), end: stop, counts }) + let init = stmt.split_once('=').map_or("", |(_, init)| init); + let counts = SIZE_CHECKS.iter().any(|g| init.contains(g)); + let ident = init.bytes().take_while(|&c| is_ident(c)).count(); + let source = (ident > 0 && init[ident..].starts_with('.')).then(|| init.as_bytes()[..ident].to_vec()); + Some(Binding { name: body[start..end].to_vec(), end: stop, counts, source }) }) .collect() } /// Whether `body[from..to]` (an assertion operand) reads a local whose binding reaching that -/// point checks a size and was not assigned since. +/// point checks a size and was not assigned since, of a collection that no later code may shrink +/// or replace. fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> bool { all.iter().filter(|b| b.counts && b.name != b"_").any(|b| { words(body, &b.name, from, to).into_iter().any(|p| { let reaching = all.iter().rfind(|o| o.name == b.name && o.end <= p); - reaching.is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end)) + reaching + .is_some_and(|r| r.counts && !may_shrink(&body[..p], &r.name, r.end) && r.source.as_ref().is_none_or(|s| !may_shrink(body, s, r.end))) }) }) } @@ -2089,13 +2131,20 @@ fn is_weak(cond: &str) -> bool { fn only_weak(v: &View) -> Option { let all_weak = v.asserts.iter().all(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && is_weak(&v.first_arg(a))); - let other = contains(v.body(), b"panic!") || contains(v.body(), b".unwrap_err()") || contains(v.body(), b".expect_err("); + // Failure messages run only after an assertion has failed, so a check there does not count. + let body = v.body_without_messages(); + let other = contains(&body, b"panic!") || contains(&body, b".unwrap_err()") || contains(&body, b".expect_err("); if v.asserts.is_empty() || !all_weak || other || v.delegates || v.should_panic { return None; } Some(v.whole(Rule::OnlyWeak, format!("its {} assertion(s) only check is_ok/is_some/non-empty", v.asserts.len()))) } +/// Methods that return the next value of something each time (`assert_ne!(it.next(), it.next())` +/// compares two items). +const ADVANCING: &[&str] = + &["next", "next_back", "pop", "pop_front", "pop_back", "recv", "try_recv", "read_line", "take", "tick", "step", "advance", "now", "elapsed"]; + fn self_compare(v: &View) -> Vec { v.asserts .iter() @@ -2105,7 +2154,8 @@ fn self_compare(v: &View) -> Vec { let (l, r) = (v.file.src_norm(*a.args.first()?), v.file.src_norm(right)); let (l, r) = (l.trim_start_matches('&'), r.trim_start_matches('&')); let calls_with_args = l.replace("()", "").contains(['(', '!']); - (l == r && !l.is_empty() && !calls_with_args).then(|| { + let advances = ADVANCING.iter().any(|m| l.contains(&format!(".{m}()"))); + (l == r && !l.is_empty() && !calls_with_args && !advances).then(|| { let mut h = v.hit(a.at, Rule::SelfCompare, format!("{}! compares `{l}` with itself", a.name)); let end = right.0 + v.file.m[right.0..right.1].trim_ascii_end().len(); h.last = v.file.lines.of(end.saturating_sub(1)); @@ -2373,7 +2423,10 @@ fn ignore_hits(file: &File) -> Vec { }; if !reason { let test = file.tests.iter().find(|t| t.fn_at > at).map_or("", |t| t.name.as_str()); - out.push(file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into())); + // The hit sits on `#[ignore`; its span reaches the attribute's `]`, past a reason on a later line. + let mut hit = file.hit(at - 2, Rule::IgnoreWithoutReason, test, "#[ignore] gives no reason".into()); + hit.last = matching(m, at - 1).map_or(hit.line, |close| file.lines.of(close)); + out.push(hit); } } out @@ -3579,7 +3632,7 @@ mod tests { #[test] fn workflow_variables_count_as_set() { let names: Vec = upper_words("env:\n AFFINITY_CORPUS_REQUIRED: 1\n run: X=1 cargo test # A\n").collect(); - assert_eq!(names, ["AFFINITY_CORPUS_REQUIRED"]); + assert_eq!(names, ["AFFINITY_CORPUS_REQUIRED", "X"]); assert!(set_by_system("CARGO_MANIFEST_DIR") && set_by_system("HOME") && !set_by_system("MY_SAMPLES")); } @@ -3729,4 +3782,73 @@ mod tests { let walk = "#[test]\nfn t() {\n let n = files().filter(|p| p.ends_with(r#\".rs\"#)).count();\n assert_eq!(n, 4);\n}\n"; assert_eq!(hits(walk), [(3, "reads-source")]); } + + #[test] + fn single_letter_variables_set_in_ci_count() { + let src = "#[test]\nfn t() {\n let dir = std::env::var(\"X\");\n assert_eq!(f(dir), 3);\n}\n"; + assert_eq!(hits(src), [(3, "env-gate-unset")]); + let ctx = Ctx { helpers: HashMap::new(), ci_env: upper_words("env:\n X: 1\n").collect() }; + assert_eq!(hits_in("crates/x/src/tests.rs", src, &ctx), []); + } + + #[test] + fn tests_with_non_ascii_names_are_checked() { + let src = "#[test]\nfn échec() {\n assert!(f().is_ok());\n}\n"; + assert_eq!(lint_file("crates/x/src/tests.rs", src, &ctx()).iter().map(|h| (h.line, h.test.as_str())).collect::>(), [(2, "échec")]); + } + + #[test] + fn block_comment_allows_need_a_reason_before_the_closing_delimiter() { + let bare = "#[test]\nfn t() {\n thread::sleep(D); /* test-lint: allow sleep */\n assert_eq!(f(), 1);\n}\n"; + assert_eq!(hits(bare), [(3, "sleep")]); + assert_eq!(hits(&bare.replace("sleep */", "sleep the clock has a 2 ms step */")), []); + } + + #[test] + fn bindings_out_of_scope_do_not_guard_all() { + let src = "#[test]\nfn t() {\n let xs: Vec = vec![];\n {\n let xs = vec![1];\n use_it(&xs);\n }\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), [(8, "all-unguarded")]); + let inside = "#[test]\nfn t() {\n let xs: Vec = vec![];\n {\n let xs = vec![1];\n assert!(xs.iter().all(|x| *x > 0));\n }\n use_it(&xs);\n}\n"; + assert_eq!(hits(inside), []); + } + + #[test] + fn constants_with_several_values_are_unknown() { + let src = "mod a { const START: usize = 0; }\nmod b {\nconst START: usize = 2;\nconst END: usize = 2;\n#[test]\nfn t() {\n let xs: Vec = (START..END).collect();\n assert!(xs.iter().all(|x| *x > 0));\n}\n}\n"; + assert_eq!(hits(src), [(8, "all-unguarded")]); + assert_eq!(hits(&src.replace("mod a { const START: usize = 0; }\n", "").replace("END: usize = 2", "END: usize = 4")), []); + } + + #[test] + fn a_count_stops_guarding_when_its_collection_changes() { + let src = + "#[test]\nfn t() {\n let mut xs = f();\n let n = xs.len();\n assert_eq!(n, 1);\n assert!(xs.iter().all(|x| *x > 0));\n}\n"; + assert_eq!(hits(src), []); + let cleared = src.replace(" assert_eq!(n, 1);", " xs.clear();\n assert_eq!(n, 1);"); + assert_eq!(hits(&cleared), [(7, "all-unguarded")]); + } + + #[test] + fn checks_in_failure_messages_do_not_end_only_weak() { + let src = "#[test]\nfn t() {\n assert!(parse(input).is_ok(), \"{:?}\", probe().unwrap_err());\n}\n"; + assert_eq!(hits(src), [(2, "only-weak")]); + assert_eq!(hits(&src.replace(" assert!", " let _ = probe().unwrap_err();\n assert!")), []); + } + + #[test] + fn advancing_calls_are_not_self_comparisons() { + for operand in ["it.next()", "q.pop_front()", "rx.recv()"] { + let src = format!("#[test]\nfn t() {{\n assert_ne!({operand}, {operand});\n}}\n"); + assert_eq!(hits(&src), [], "{operand}"); + } + assert_eq!(hits("#[test]\nfn t() {\n assert_eq!(x.len(), x.len());\n}\n"), [(3, "self-compare")]); + } + + #[test] + fn ignore_spans_reach_a_reason_on_the_next_line() { + let src = "#[test]\n#[ignore =\n \"\"]\nfn t() {\n assert_eq!(f(), 1);\n}\n"; + let found = lint_file("crates/x/src/tests.rs", src, &ctx()); + assert_eq!(found.iter().map(|h| (h.rule, h.line, h.first, h.last)).collect::>(), [(Rule::IgnoreWithoutReason, 2, 2, 3)]); + assert!(touches(&found[0], Some(&[3].into_iter().collect())), "a change to the reason alone"); + } } From 7aee17deaaf7f00cd078ffff57cfde8299258b82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:25:15 -0800 Subject: [PATCH 20/37] Tests: the 3D face-limit and gray-level smoothing tests check the same cases with small inputs The two Extrude & Bevel tests of the faces an object's solids keep together built members and strokes from 16,384-corner polygons until they passed MAX_OBJECT_FACES. They took 230 s and 23.5 s on CI. The solids code now reads the limit through object_face_limit(), which tests can lower on their own thread (OBJECT_FACE_LIMIT), and both tests build 64-corner polygons against a limit of exactly three members' or three strokes' faces. The limit is now met exactly, so the tests also check that a solid at the limit still draws. Outside the crate's own tests, object_face_limit() is MAX_OBJECT_FACES. The smoothing test of every pair of gray levels ran the filter on 262,144 one-pixel-pair images, and each pass along a column started two threads. It now puts every pair in one 2-pixel-wide image and one 2-pixel-high image, so it checks the same 65,536 pairs in four passes. --- crates/effects/src/solids.rs | 37 +++++++++++++++++++------- crates/effects/src/solids/tests.rs | 34 ++++++++++++++++++----- crates/effects/src/solids/wireframe.rs | 6 ++--- crates/trace/src/smooth.rs | 30 +++++++++++++++------ 4 files changed, 80 insertions(+), 27 deletions(-) diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index ef1608a5d9..83bb1ca9f7 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -600,9 +600,9 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { } let (parts, bounds) = solid_parts(shapes, b); if !cast { - return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())); + return built_solids(id, p, &parts, bounds, object_face_limit()).try_for_each(|r| r.map(|_| ())); } - let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, false, None) + let built = built_solids_cast(id, p, &parts, bounds, object_face_limit(), true, false, None) .map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces))) .collect::, String>>()?; cast_built(id, p, shapes, built).map(|_| ()) @@ -1025,13 +1025,30 @@ thread_local! { /// [`built_solids`] have built on this thread, for the tests. The solids built to cast a shadow /// ([`cast_shadow`]) count too. static SOLID_GEOMETRY_BUILT: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The limit [`object_face_limit`] gives on this thread: [`MAX_OBJECT_FACES`] unless a test sets + /// a lower one, so that a test of the limit builds small solids. + pub(crate) static OBJECT_FACE_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_OBJECT_FACES) }; +} + +/// Most faces the Extrude & Bevel or Inflate solids of one effect on one object keep together: +/// [`MAX_OBJECT_FACES`]. +#[cfg(not(test))] +fn object_face_limit() -> usize { + MAX_OBJECT_FACES +} + +/// Most faces the Extrude & Bevel or Inflate solids of one effect on one object keep together: +/// [`MAX_OBJECT_FACES`], or the lower limit a test set in [`OBJECT_FACE_LIMIT`]. +#[cfg(test)] +fn object_face_limit() -> usize { + OBJECT_FACE_LIMIT.with(std::cell::Cell::get) } /// The solids Extrude & Bevel (Classic included) or Inflate `id` with parameters `p` builds from /// `parts` ([`solid_parts`]) about `bounds`, one result for each part in order, each built only as /// the iterator reaches it. A stroke's solid past its own limits is `None` (left out of the art, its /// faces not counted); a fill's is an error. The faces of the solids kept count together: once they -/// pass `limit` ([`MAX_OBJECT_FACES`] for the art) the result is an error, and +/// pass `limit` ([`object_face_limit`] for the art) the result is an error, and /// no later part is built. An error ends the iterator. fn built_solids<'a>( id: &'a str, @@ -1211,7 +1228,7 @@ fn rects_overlap(a: Rect, b: Rect) -> bool { /// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces /// and whose paint copies take `paint_bytes` so far: as many as keep the faces within -/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as +/// [`object_face_limit`] and the copies within the allowance, each added face counted as /// [`MAX_FACET_COPIES`] copies of the costliest stroke's paint. fn cut_room<'a>(items: impl Iterator, faces: usize, paint_bytes: usize) -> usize { let per_face = items @@ -1225,7 +1242,7 @@ fn cut_room<'a>(items: impl Iterator, faces: usize, p .unwrap_or(0) .max(1); let affordable = crate::revolve::MAX_PAINT_COPIES.saturating_sub(paint_bytes) / per_face; - MAX_OBJECT_FACES.saturating_sub(faces).min(affordable) + object_face_limit().saturating_sub(faces).min(affordable) } /// In `solids`, each solid's part ([`Paints`]), its shape's index and its faces, cut each face of a @@ -2403,7 +2420,7 @@ fn surfaces_with( let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE); let mut layouts: Vec = vec![]; let mut surfaces_before = 0usize; - let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane, carrier); + let made = built_solids_cast(&fx.id, &p, &parts, bounds, object_face_limit(), cast, membrane, carrier); for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() { let item: &AppearanceItem = item; let layout = map_art.as_ref().map(|_| { @@ -2471,7 +2488,7 @@ fn surfaces_with( if solids.iter().any(|s| ordered(s.4)) { // A stroke face that passes through a fill wall or another stroke's face is cut where it // does. The pieces count against the limits as the faces did: cutting stops before the - // faces pass MAX_OBJECT_FACES or their paint copies pass the allowance, so an effect that + // faces pass object_face_limit() or their paint copies pass the allowance, so an effect that // draws uncut still draws. let counts: Vec = solids.iter().map(|(.., f, _)| f.len()).collect(); let room = cut_room(solids.iter().map(|(item, ..)| *item), counts.iter().sum(), paint_bytes); @@ -2940,7 +2957,7 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' // their handles. A stroke left out places none of its own. When a fill's solid can't be // built, or the solids together pass the limit, the art draws its source and no piece // places a handle. - let built: Vec = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true, None) + let built: Vec = built_solids_cast(INFLATE, &p, &parts, bounds, object_face_limit(), false, true, None) .collect::, String>>() .map(|solids| solids.into_iter().flatten().flat_map(|(f, _)| f).collect()) .unwrap_or_default(); @@ -3065,7 +3082,7 @@ pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option, in let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default(); let facets = vectorcraft_three_d::extrude(area, *rule, bounds, options, view).unwrap_or_default(); kept = kept.saturating_add(facets.len()); - if kept > MAX_OBJECT_FACES { + if kept > object_face_limit() { return None; } listed(&surfaces, &facets, &mut out); @@ -3309,7 +3326,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) Err(e) => return Err(e), }; kept = kept.saturating_add(solid.facets.len()); - if kept > MAX_OBJECT_FACES { + if kept > object_face_limit() { return Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()); } match solid.mesh() { diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 49c301dd75..504fe1d777 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1642,17 +1642,36 @@ fn polygon_node(id: u64, corners: usize) -> Node { Node::path(NodeId(id), path, Appearance::basic(Paint::solid(RED), Paint::None, 0.0)) } +/// Sets the faces the solids of one object keep together ([`OBJECT_FACE_LIMIT`]) to a lower limit +/// on this thread, and sets [`MAX_OBJECT_FACES`] again when dropped, so that a test of the limit +/// builds small solids. +struct FaceLimit(usize); + +impl FaceLimit { + fn set(limit: usize) -> Self { + Self(OBJECT_FACE_LIMIT.with(|l| l.replace(limit))) + } +} + +impl Drop for FaceLimit { + fn drop(&mut self) { + OBJECT_FACE_LIMIT.with(|l| l.set(self.0)); + } +} + /// A group whose members' solids each fit, but not all of them together, draws its source art, and /// the commands that check the effect report the error, as do its mesh and its wireframe; one -/// member fewer, within the limit, draws. +/// member fewer, exactly at the limit, draws. The limit is lowered to three members' faces. #[test] fn a_groups_solids_together_past_the_limit_draw_the_source() { - let member = polygon_node(1, 16_384); + let member = polygon_node(1, 64); let mut alone = member.clone(); alone.appearance.effects.push(fx(EXTRUDE, json!({}))); let [Ok(Some(each))] = solid_faces(EXTRUDE, &alone, MAX_OBJECT_FACES)[..] else { panic!("one solid") }; + let limit = 3 * each; + let _limit = FaceLimit::set(limit); // Members stacked in one place each build the same solid. - let fits = MAX_OBJECT_FACES / each; + let fits = limit / each; let group = |count: usize| { let members = (0..count) .map(|k| { @@ -1703,16 +1722,19 @@ fn an_inflate_frame_places_no_handle_when_a_fill_is_past_the_limits() { } /// A fill and strokes whose solids each fit, but not all of them together, draw the source art, -/// and the strokes after the one past the limit are not left out to make room. +/// and the strokes after the one past the limit are not left out to make room. The limit is +/// lowered to the fill's faces and three strokes'. #[test] fn a_fill_and_strokes_together_past_the_limit_draw_the_source() { - let mut n = polygon_node(1, 16_384); + let mut n = polygon_node(1, 64); n.appearance.effects.push(fx(EXTRUDE, json!({}))); let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(BLUE), 20.0)); n.appearance.items.push(stroke.clone()); // Strokes alike each build the same solid. let [Ok(Some(fill)), Ok(Some(each))] = solid_faces(EXTRUDE, &n, MAX_OBJECT_FACES)[..] else { panic!("a fill's solid and a stroke's") }; - let fits = (MAX_OBJECT_FACES - fill) / each; + let limit = fill + 3 * each; + let _limit = FaceLimit::set(limit); + let fits = (limit - fill) / each; assert!(fits >= 2, "{fill} + {fits} × {each}"); n.appearance.items.extend(std::iter::repeat_n(stroke, fits - 1)); assert!(validate_solid(&n, EXTRUDE, &json!({})).is_ok(), "{fill} + {fits} × {each}"); diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index 65ac8b0f7e..409a5c1dc3 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -12,8 +12,8 @@ use vectorcraft_three_d::Facet; use super::{ CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, - is_three_d, label_of, members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts, - union_bounds, + is_three_d, label_of, members, object_face_limit, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, + solid_parts, union_bounds, }; use crate::{GeomContext, is_geometry}; @@ -258,7 +258,7 @@ pub(crate) fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result = (0..=255u8).flat_map(|p| (0..=255u8).map(move |q| (p, q))).collect(); + let n = pairs.len(); + // The pair of pixel `i` in the output of the pass along rows (`true`) or columns. + let pair_of = |along_rows: bool, i: usize| pairs.get(if along_rows { i / 2 } else { i % n }).copied(); + let first_difference = |along_rows: bool, fast: &[u8], slow: &[u8]| { + if fast.len() != slow.len() { + return Some(format!("lengths {} and {}", fast.len(), slow.len())); } + fast.chunks(4).zip(slow.chunks(4)).position(|(a, b)| a != b).map(|i| format!("pair {:?}", pair_of(along_rows, i))) + }; + // Gray, and a mixed pair: the two pixels made from levels `p` and `q`. + type Kind = fn(u8, u8) -> [[u8; 4]; 2]; + let kinds: [Kind; 2] = [|p, q| [[p, p, p, 255], [q, q, q, 255]], |p, q| [[p, q, p ^ q, 255], [q, p, q ^ 0x5a, 255]]]; + for (k, kind) in kinds.into_iter().enumerate() { + let rows: Vec = pairs.iter().flat_map(|&(p, q)| kind(p, q).into_iter().flatten()).collect(); + let columns: Vec = (0..2).flat_map(|side| pairs.iter().flat_map(move |&(p, q)| kind(p, q)[side])).collect(); + let fast = pass(&rows, 2, n, true, &weights); + assert_eq!(first_difference(true, &fast, &reference(&rows, 2, n, true)), None, "kind {k}, along rows"); + let fast = pass(&columns, n, 2, false, &weights); + assert_eq!(first_difference(false, &fast, &reference(&columns, n, 2, false)), None, "kind {k}, along columns"); } } From 13b9e22c4c8881cfad9aa1c832b09d70eddac71d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:29:35 -0800 Subject: [PATCH 21/37] Tests: merge two duplicate engine tests, keeping every assertion Two engine tests ran the same inputs as another test and checked them again with a tighter bound or a second check. - commands_that_do_not_wait_for_a_tool_edit_change_no_document ran every junk case of every non-waiting command on the Single and Multi fixtures, which every_command_with_junk_params also runs. The junk sweep now compares tool_edit_state before and after each of those calls as well as its own panic, interaction and invariant checks. The tool-edit test keeps only the cases that turn each option on and off (option_cases), which the junk sweep does not send. - turned_colored_inflate_facets_and_seams_cover_their_edges_once drew the same turned Inflate in the same solid fill as one case of colored_light_surfaces_match_supersampling_at_internal_facet_edges. That case now carries its bound (at most one RGB channel more than 3 levels off, by no more than 4) and the separate test is removed. Each merged test fails on a fault that only the removed check caught before: document.info bumping the revision on a non-object params value fails every_command_with_junk_params ("document.info "str" [Multi]"), and solid_surface drawing every facet as a fill and a seam stroke fails the supersampling test (2 channels off, at most 5). docs/target-app-parity.md and waits_for_tool_edit's doc comment name the tests that now hold these checks. --- crates/engine/src/command_sets.rs | 4 +- crates/engine/tests/command_sweep.rs | 60 +++++++++++++------ crates/engine/tests/it/three_d_light_color.rs | 35 +++-------- docs/target-app-parity.md | 2 +- 4 files changed, 52 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 1346dc40c5..3c7db76afe 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -118,8 +118,8 @@ const WAIT_FOR_TOOL_EDIT: &[&str] = &[ /// Does command `id`, run on its own, first apply the edit the active tool is computing on /// another thread and the input held for it ([`Session::finish_tool_edit`])? Every command that /// can edit, select, save or give a document a new revision does; queries that only read do not -/// (`commands_that_do_not_wait_for_a_tool_edit_change_no_document` in the command sweep checks -/// them). A frontend that adds params from +/// (`every_command_with_junk_params` and `commands_that_do_not_wait_for_a_tool_edit_change_no_document` +/// in the command sweep check them). A frontend that adds params from /// its own state (the active artboard) applies them first itself. pub fn waits_for_tool_edit(id: &str) -> bool { find_command(id).is_some_and(|spec| spec.journal || WAIT_FOR_TOOL_EDIT.contains(&id)) diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 67d9b82f76..0fdb272343 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -30,17 +30,27 @@ fn no_panic(r: Result) -> Result Option { + probe_and_compare(fx, id, params, false).0 +} + +/// Run one call as [`probe`] does, returning its failure description, and with `compare`, also +/// `id params [fixture]` when the call changed the session's [`tool_edit_state`], panic or not. +fn probe_and_compare(fx: Fixture, id: &str, params: &Value, compare: bool) -> (Option, Option) { let mut s = fx.session(); + let before = compare.then(|| tool_edit_state(&s)); let r = catch_quiet(|| no_panic(s.execute(id, params))); - match r { + let changed = before.filter(|b| tool_edit_state(&s) != *b).map(|_| format!("{id} {params} [{fx:?}]")); + let failure = match r { Err(msg) => Some(format!("PANIC {id} {params} [{fx:?}]: {msg}")), Ok(_) => { if s.in_interaction() { - return Some(format!("{id} {params} [{fx:?}]: left an interaction open")); + Some(format!("{id} {params} [{fx:?}]: left an interaction open")) + } else { + check_session(&s).err().map(|e| format!("{id} {params} [{fx:?}]: {e}")) } - check_session(&s).err().map(|e| format!("{id} {params} [{fx:?}]: {e}")) } - } + }; + (failure, changed) } #[test] @@ -223,31 +233,43 @@ fn junk_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { cases } +/// Every command with every junk case in every fixture: no panic, no interaction left open and no +/// broken invariant ([`probe`]). In `Single` and `Multi`, every command that runs at once while the +/// active tool computes an edit on another thread (it does not `waits_for_tool_edit`) also leaves +/// the documents' revisions and selections, the active document and the current paint as they were +/// ([`tool_edit_state`]), as `commands_that_do_not_wait_for_a_tool_edit_change_no_document` checks +/// for the cases that turn each option on and off. #[test] fn every_command_with_junk_params() { let dir = vectorcraft_testkit::TempDir::new("sweep"); let path = safe_path(&dir); let mut failures = vec![]; + let mut changed = vec![]; let mut calls = 0usize; for fx in Fixture::ALL { for c in command_specs() { + let compare = matches!(fx, Fixture::Single | Fixture::Multi) && !vectorcraft_engine::waits_for_tool_edit(c.id); let cases = junk_cases(c, &path); for p in &cases { calls += 1; - if let Some(f) = probe(fx, c.id, p) { - failures.push(f); - } + let (failure, change) = probe_and_compare(fx, c.id, p, compare); + failures.extend(failure); + changed.extend(change); } } } assert!(calls > 5_000, "only {calls} calls"); failures.sort(); failures.dedup(); + changed.sort(); + changed.dedup_by(|a, b| a.split(' ').next() == b.split(' ').next()); assert!( - failures.is_empty(), - "{} failures (of {calls} calls):\n{}", + failures.is_empty() && changed.is_empty(), + "{} failures (of {calls} calls):\n{}\n{} commands change a document without waiting for a tool edit:\n{}", failures.len(), - failures.iter().take(60).cloned().collect::>().join("\n") + failures.iter().take(60).cloned().collect::>().join("\n"), + changed.len(), + changed.join("\n") ); } @@ -262,10 +284,11 @@ fn tool_edit_state(s: &Session) -> ToolEditState { (docs, s.active_index(), s.paint.clone()) } -/// The params the tool-edit sweep sends `c`: junk params, then each documented key turned on and -/// off, with a string under a file or folder key replaced by a location inside `path`'s folder. -fn tool_edit_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { - let mut cases = junk_cases(c, path); +/// The params the tool-edit sweep sends `c` beyond its junk cases, which the junk sweep checks: +/// each documented key turned on and off, with a string under a file or folder key replaced by a +/// location inside `path`'s folder. +fn option_cases(c: &vectorcraft_engine::CommandSpec, path: &str) -> Vec { + let mut cases = vec![]; for k in command_param_keys(c) { for v in [json!(true), json!(false), json!(1), json!("on")] { cases.push(json!({ k.as_str(): safe_value_for_command(c, &k, &v, path) })); @@ -333,7 +356,7 @@ fn sweep_cases_name_files_only_inside_the_temp_folder() { } } let mut cases = junk_params_for_command(c, &path); - cases.extend(tool_edit_cases(c, &path)); + cases.extend(option_cases(c, &path)); cases.extend(serializable_cases(c, &path)); for p in &cases { let Some(o) = p.as_object() else { continue }; @@ -485,8 +508,9 @@ fn sweep_cases_send_the_file_keys_of_the_command_catalog() { /// Every command that runs at once while the active tool computes an edit on another thread (a /// Shape Builder merge), rather than applying the edit first (`waits_for_tool_edit`), leaves the /// documents' revisions and selections, the active document and the current paint as they were, -/// with `{}`, junk params and params that turn its options on and off: the edit, computed for the -/// document as it was, still applies after it. +/// with params that turn its options on and off ([`option_cases`]; `every_command_with_junk_params` +/// checks the same with the junk cases): the edit, computed for the document as it was, still +/// applies after it. #[test] fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() { let dir = vectorcraft_testkit::TempDir::new("sweep"); @@ -494,7 +518,7 @@ fn commands_that_do_not_wait_for_a_tool_edit_change_no_document() { let mut failures = vec![]; for fx in [Fixture::Single, Fixture::Multi] { for c in command_specs().iter().filter(|c| !vectorcraft_engine::waits_for_tool_edit(c.id)) { - let cases = tool_edit_cases(c, &path); + let cases = option_cases(c, &path); for p in &cases { let mut s = fx.session(); let before = tool_edit_state(&s); diff --git a/crates/engine/tests/it/three_d_light_color.rs b/crates/engine/tests/it/three_d_light_color.rs index be06539537..0a6e438a75 100644 --- a/crates/engine/tests/it/three_d_light_color.rs +++ b/crates/engine/tests/it/three_d_light_color.rs @@ -533,7 +533,8 @@ fn seams_against_supersampled(d: &Document, image: &vectorcraft_render::Rendered /// opacity once over the surface. Inflate seen straight on, one layer of facets, has no alpha off, and /// in opaque fills no RGB channel more than 3 levels off. Inflate turned so facets narrow to slivers /// at the edges, and Revolve with a cap over its body, draw facets over other facets, and have no -/// alpha off. +/// alpha off. In the turned Inflate's opaque solid fill, each facet and its seam cover an edge pixel +/// once together, so at most one RGB channel is more than 3 levels off, by no more than 4. #[test] fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { let lights = json!([ @@ -556,20 +557,21 @@ fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { let (mut s, _) = setup("threeD.inflate"); let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":rotation.0,"rotationY":rotation.1}}); s.execute("effect.setParams", &change).unwrap(); - cases.push((format!("inflate {rotation:?}"), s, fills([100, 150], [200, 150]), rotation == (0, 0))); + cases.push((format!("inflate {rotation:?}"), s, fills([100, 150], [200, 150]), rotation == (0, 0), rotation == (50, 35))); } let (mut s, _) = capped_profile(); s.execute("effect.setParams", &json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights}})).unwrap(); - cases.push(("revolve".into(), s, fills([80, 200], [240, 200]), false)); + cases.push(("revolve".into(), s, fills([80, 200], [240, 200]), false, false)); let mut failures = vec![]; - for (name, mut s, fills, one_layer) in cases { + for (name, mut s, fills, one_layer, turned) in cases { for fill in fills { s.execute("paint.setFill", &fill).unwrap(); let image = render(doc(&s)); let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image); assert!(measured > 2_000, "{name} {fill}: {measured} pixels inside"); let opaque = !fill.to_string().contains("opacity"); - if holes > 0 || (one_layer && opaque && color > 0) { + let edges_once = turned && fill.get("color").is_some(); + if holes > 0 || (one_layer && opaque && color > 0) || (edges_once && (color > 1 || max > 4)) { failures.push(format!( "{name} {fill}: of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}" )); @@ -579,29 +581,6 @@ fn colored_light_surfaces_match_supersampling_at_internal_facet_edges() { assert!(failures.is_empty(), "{failures:#?}"); } -/// Inflate turned so its facets narrow to slivers at the edges, in an opaque solid fill under two -/// colored lights, against 3x averaged down ([`seams_against_supersampled`]): each facet and its -/// seam cover an edge pixel once together, so at most one RGB channel is more than 3 levels off, by -/// no more than 4, and no alpha is off. -#[test] -fn turned_colored_inflate_facets_and_seams_cover_their_edges_once() { - let lights = json!([ - {"color":"#ff0000","rotation":135,"height":35,"intensity":70}, - {"color":"#0000ff","rotation":-35,"height":25,"intensity":65} - ]); - let (mut s, _) = setup("threeD.inflate"); - let change = json!({"index":0,"item":null,"params":{"ambient":10,"lights":lights,"rotationX":50,"rotationY":35}}); - s.execute("effect.setParams", &change).unwrap(); - s.execute("paint.setFill", &json!({"color":"#ffcc66"})).unwrap(); - let image = render(doc(&s)); - let (measured, color, max, holes, worst) = seams_against_supersampled(doc(&s), &image); - assert!(measured > 2_000, "{measured} pixels inside"); - assert!( - holes == 0 && color <= 1 && max <= 4, - "of {measured} pixels, {color} channels off by more than 3 (at most {max}), {holes} alphas off: {worst:?}" - ); -} - /// The closed facet edges of colored-light surfaces survive SVG and PDF, read back and drawn at /// 1:1, and Expand Appearance: inside the art, every pixel stays opaque and within 6 levels of the /// live art. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4df379b998..b62372f326 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2896,7 +2896,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Evidence for the shared light Color: geometry tests in `tests_lighting`, effect paint tests, command/save/undo/expand and SVG/PDF checks in `three_d_light_color`, and headless picker/reset/preview tests in `tests_revolve`. Revolve keeps smooth colored vector ramps and continuous flat-lit caps. Inflate geometry tests check spherical lighting, shared vertex/edge continuity, concave cell coverage, puffed backs at perspective and legacy single-light/list equivalence; rendered command/export regressions cover smooth shading and editable expansion. Four legacy white-light PNGs matched main byte for byte when this was measured (2026-10-17); since every 3D seam took round joins (2026-11-12), white-light output is expected to differ from them at facet corners ([Seams](three-d.md#seams)); the four scenes were not exported again to measure it; [release measurements](3d-lighting-performance.md) record the colored solid-fill batch and the remaining source-gradient cost. Colored Inflate's facets lie over an underlay of themselves under one clip, so their shared edges show neither the black channel backdrop nor the background ([Seams](three-d.md#seams)); `three_d_light_color::colored_light_surfaces_match_supersampling_at_internal_facet_edges` compares 1:1 with 3x averaged down, and `colored_light_seams_stay_closed_in_svg_pdf_and_expansion` checks SVG, PDF and Expand Appearance. Colored Revolve's faces lie over an underlay of themselves the same way, run by run in a group and with mapped graphics kept after their faces; `colored_revolve_faces_leave_no_alpha_holes_at_one_to_one` checks that no pixel inside the art lets the background through at 1:1 where 3x averaged down is opaque, live, read back from SVG and PDF, and expanded. -Colored Inflate's composited facets that are simple polygons are each one filled path of the facet and its round seam, so a facet edge pixel is covered once instead of by a fill and then a same-color stroke ([Seams](three-d.md#seams)); `three_d_light_color::turned_colored_inflate_facets_and_seams_cover_their_edges_once` bounds the turned (X 50°, Y 35°) solid fill against 3x averaged down, and `lighting::tests::seamed_fill_covers_a_polygon_and_its_seam_once` checks the path's coverage and the facets that keep a fill and a stroke. +Colored Inflate's composited facets that are simple polygons are each one filled path of the facet and its round seam, so a facet edge pixel is covered once instead of by a fill and then a same-color stroke ([Seams](three-d.md#seams)); `three_d_light_color::colored_light_surfaces_match_supersampling_at_internal_facet_edges` bounds the turned (X 50°, Y 35°) solid fill against 3x averaged down, and `lighting::tests::seamed_fill_covers_a_polygon_and_its_seam_once` checks the path's coverage and the facets that keep a fill and a stroke. ## Eyedropper character dimensions (2026-11-11) From ebb84ec16c32313c4590d18e3d8b867b56977c81 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:40:53 -0800 Subject: [PATCH 22/37] xtask: test-lint reports only-weak hits instead of failing on them Replayed over the last 300 merges to main, only-weak would have failed 3 merges on 4 hits, and all 4 were tests where an is_ok or is_some check is the behavior under test (a lease or start file that can be taken again, a never-panic property test, a label found by a search with the row's position in its predicate). Of the 39 only-weak hits in the whole workspace, most are the same kinds: registry and label lookups, still-imports and never-panic tests. only-weak now lists its hits without failing, like all-unguarded. The check fails on self-compare, ignore-without-reason and sleep. With this change the replay fails 0 of 272 merges that change Rust files. --- docs/development.md | 2 +- xtask/src/main.rs | 4 ++-- xtask/src/test_lint.rs | 20 +++++++++++--------- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/development.md b/docs/development.md index efb554b561..604c363dba 100644 --- a/docs/development.md +++ b/docs/development.md @@ -351,7 +351,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 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`), 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`) and `thread::sleep` in test code (`sleep`). It lists the hits of the other rules without failing: `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 test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. 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`) and `thread::sleep` in test code (`sleep`). 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 test code that reads Rust source outside the audits listed in `SOURCE_AUDITS`. 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. ## Tests diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 3a0c854486..6f4347e952 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -34,8 +34,8 @@ commands: brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails) test-lint [--base ] [--all] - weak tests in the lines changed since the base: fail on only is_ok/is_some checks, - self-compares, reasonless #[ignore] and sleeps; list unguarded .all(), no assertion, + weak tests in the lines changed since the base: fail on self-compares, reasonless + #[ignore] and sleeps; list only is_ok/is_some checks, unguarded .all(), no assertion, early returns, unset env gates... (xtask/src/test_lint.rs); --all lists every hit by crate and never fails i18n-report list the strings each language's catalog lacks, shown in English (fails only on a diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index f442c9681d..45ae3566d3 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -51,9 +51,8 @@ //! rules about a whole test it can be on any line from the line above the test attribute to the //! `fn` line. An allow without a reason exempts nothing. //! -//! `cargo xtask test-lint` fails on hits of `only-weak`, `self-compare`, `ignore-without-reason` -//! and `sleep` in the lines and tests changed since a base, and lists the other rules' hits there -//! without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's +//! `cargo xtask test-lint` fails on hits of `self-compare`, `ignore-without-reason` and `sleep` in +//! the lines and tests changed since a base, and lists the other rules' hits there without failing. The base is `--base ` or `TEST_LINT_BASE`; in GitHub Actions the first parent of `HEAD` (a pull request's //! merge commit is checked out, and a shallow checkout fetches that parent); elsewhere the merge //! base of `HEAD` and `upstream/main` or `origin/main`. Uncommitted and untracked files count as //! changed. Hits on unchanged lines are counted but do not fail it. `--all` lists every hit in the @@ -168,7 +167,7 @@ impl Rule { /// Whether a hit on a changed line fails the command. The other rules only report. pub fn fails(self) -> bool { - matches!(self, Rule::OnlyWeak | Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep) + matches!(self, Rule::SelfCompare | Rule::IgnoreWithoutReason | Rule::Sleep) } fn from_id(id: &str) -> Option { @@ -3606,16 +3605,19 @@ mod tests { #[test] fn only_failing_rules_fail_the_check() { let failing: Vec<&str> = Rule::ALL.into_iter().filter(|r| r.fails()).map(Rule::id).collect(); - assert_eq!(failing, ["only-weak", "self-compare", "ignore-without-reason", "sleep"]); + assert_eq!(failing, ["self-compare", "ignore-without-reason", "sleep"]); let weak = "#[test]\nfn weak() {\n assert!(f().is_ok());\n}\n"; let unguarded = "#[test]\nfn all() {\n assert!(f().iter().all(|x| valid(x)));\n}\n"; + let skipped = "#[test]\n#[ignore]\nfn skipped() {\n assert_eq!(f(), 1);\n}\n"; let hits_of = |src: &str| lint_file("crates/x/src/tests.rs", src, &ctx()); assert_eq!(finish(&hits_of(unguarded), 0, 1, "base"), Ok(()), "all-unguarded only reports"); - let both = hits_of(&format!("{weak}{unguarded}")); - assert_eq!(both.len(), 2); - let Err(message) = finish(&both, 0, 1, "base") else { panic!("only-weak fails the check") }; + assert_eq!(finish(&hits_of(weak), 0, 1, "base"), Ok(()), "only-weak only reports"); + let all = hits_of(&format!("{weak}{unguarded}{skipped}")); + assert_eq!(all.len(), 3); + let Err(message) = finish(&all, 0, 1, "base") else { panic!("ignore-without-reason fails the check") }; assert!(message.starts_with("1 test-lint hit(s)"), "{message}"); - assert!(message.contains("[only-weak] `weak`") && !message.contains("[all-unguarded]"), "{message}"); + assert!(message.contains("[ignore-without-reason] `skipped`"), "{message}"); + assert!(!message.contains("[only-weak]") && !message.contains("[all-unguarded]"), "{message}"); assert_eq!(finish(&[], 3, 1, "base"), Ok(())); } From fbcc1627c41afd7391e668d42f3ec3a943351545 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:46:34 -0800 Subject: [PATCH 23/37] xtask: test-lint counts items under cfg(all(test, ...)) as test code test_regions matched only the exact `#[cfg(test)]`, so helpers in a module under `#[cfg(all(test, windows))]` or `#[cfg(all(test, not(target_arch = "wasm32")))]` (as in apps/vectorcraft-web/src/file_drops.rs) were not test code: a sleep in such a helper passed the check, and its asserting helpers were not found. A cfg predicate now counts when it is `test` or an `all(...)` with such a predicate among its arguments, at any depth and with any spacing. `any(test, ...)`, `not(test)` and `feature = "test"` do not count. --- xtask/src/test_lint.rs | 53 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index 45ae3566d3..bfa4f4728c 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -41,7 +41,8 @@ //! that keeps files ending in `.rs`), outside the source audits in [`SOURCE_AUDITS`]. //! //! Test code is a test file (`tests.rs`, `tests_*.rs`, `*_tests.rs`, a file in a `tests` or -//! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]`, or a test function. +//! `benches` folder, `crates/testkit`), an item under `#[cfg(test)]` or `#[cfg(all(test, …))]`, +//! or a test function. //! //! An asserting helper is a function or macro in the crate's test code (or in `crates/testkit`) //! that asserts, panics or calls one that does (every one of that name, when there are several), @@ -972,20 +973,52 @@ fn is_test_file(path: &str) -> bool { || path.starts_with("crates/testkit/") } -/// The byte ranges of test code in a file: all of a test file, else each item under -/// `#[cfg(test)]` that has a body in the file, and each test function. +/// Whether a `cfg` predicate holds only in test builds: `test`, or an `all(…)` with such a +/// predicate among its arguments. +fn cfg_requires_test(pred: &[u8]) -> bool { + let pred: Vec = pred.iter().copied().filter(|c| !c.is_ascii_whitespace()).collect(); + if pred == b"test" { + return true; + } + let Some(args) = pred.strip_prefix(b"all(").and_then(|a| a.strip_suffix(b")")) else { return false }; + let mut depth = 0usize; + let mut start = 0; + for (i, &c) in args.iter().enumerate() { + match c { + b'(' => depth += 1, + b')' => depth = depth.saturating_sub(1), + b',' if depth == 0 => { + if cfg_requires_test(&args[start..i]) { + return true; + } + start = i + 1; + } + _ => {} + } + } + cfg_requires_test(&args[start..]) +} + +/// The byte ranges of test code in a file: all of a test file, else each item under a `#[cfg(…)]` +/// that holds only in test builds ([`cfg_requires_test`]) and has a body in the file, and each +/// test function. fn test_regions(path: &str, m: &[u8], tests: &[TestFn]) -> Vec<(usize, usize)> { if is_test_file(path) { return vec![(0, m.len())]; } let mut out: Vec<(usize, usize)> = tests.iter().map(|t| (t.attr, t.close)).collect(); for at in words(m, b"cfg", 0, m.len()) { - let attr = skip_ws(m, at + "cfg".len()); - if !m[..at].ends_with(b"#[") || !m[attr..].starts_with(b"(test)]") { + let open = skip_ws(m, at + "cfg".len()); + if !m[..at].ends_with(b"#[") || m.get(open) != Some(&b'(') { + continue; + } + let Some(close) = matching(m, open) else { continue }; + let end = skip_ws(m, close + 1); + if m.get(end) != Some(&b']') || !cfg_requires_test(&m[open + 1..close]) { continue; } // The item's body: the first `{` before any `;` (`mod tests;` has none here). - let after = attr + "(test)]".len(); + let after = end + 1; let Some(open) = m[after..].iter().position(|&c| c == b'{' || c == b';').map(|p| p + after) else { continue }; if let (b'{', Some(close)) = (m[open], matching(m, open)) { out.push((at, close)); @@ -3517,6 +3550,14 @@ mod tests { assert_eq!(hits_in("xtask/src/test_lint.rs", shipped, &ctx()), [], "a name that only starts with test is not a test file"); let after = "#[cfg(test)]\nmod tests {\n fn w() { thread::sleep(D); }\n}\npub fn later() {\n thread::sleep(D);\n}\n"; assert_eq!(hits_in("crates/x/src/lib.rs", after, &ctx()), [(3, "sleep")], "code after a #[cfg(test)] module is not test code"); + for gate in ["all(test, windows)", "all( test , not(target_arch = \"wasm32\") )", "all(feature = \"x\", all(unix, test))"] { + let gated = format!("#[cfg({gate})]\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{gate} holds only in tests"); + } + for gate in ["any(test, feature = \"x\")", "not(test)", "all(unix, not(test))", "feature = \"test\""] { + let gated = format!("#[cfg({gate})]\nmod helpers {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [], "{gate} also holds outside tests"); + } for test_file in [ "crates/x/src/tests.rs", "crates/x/src/tests_wheel.rs", From 050634b6ad44ddefe938b4e636cc9f925bbc5b2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:19:05 -0800 Subject: [PATCH 24/37] xtask: test-lint skips declared-only items and unapplied should_panic - Functions and macros declared inside a test no longer count as its assertions or calls; a call to one still counts as a helper call. - `should_panic` exempts a test only as an applied attribute: `#[should_panic]`, or inside `#[cfg_attr(test, ...)]`. - `only-weak` strips parentheses around the whole condition, so `assert!((x.is_ok()))` is classified like `assert!(x.is_ok())`. - `#[ cfg(test)]` and attributes with comments between `#`, `[` and `cfg` mark test code like the compact form. --- xtask/src/test_lint.rs | 114 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 104 insertions(+), 10 deletions(-) diff --git a/xtask/src/test_lint.rs b/xtask/src/test_lint.rs index bfa4f4728c..8609ace2f5 100644 --- a/xtask/src/test_lint.rs +++ b/xtask/src/test_lint.rs @@ -1009,7 +1009,9 @@ fn test_regions(path: &str, m: &[u8], tests: &[TestFn]) -> Vec<(usize, usize)> { let mut out: Vec<(usize, usize)> = tests.iter().map(|t| (t.attr, t.close)).collect(); for at in words(m, b"cfg", 0, m.len()) { let open = skip_ws(m, at + "cfg".len()); - if !m[..at].ends_with(b"#[") || m.get(open) != Some(&b'(') { + // Whitespace and comments (masked to spaces) may separate `#`, `[` and `cfg`. + let outer_attr = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + if !outer_attr || m.get(open) != Some(&b'(') { continue; } let Some(close) = matching(m, open) else { continue }; @@ -1079,8 +1081,8 @@ fn checking<'a>(defs: impl Iterator + Clone) -> HashSet } } -/// The `fn` or `macro_rules!` at `at`. -fn definition(m: &[u8], at: usize) -> Option { +/// The name, kind (`true` for a macro) and body braces of the `fn` or `macro_rules!` at `at`. +fn item_at(m: &[u8], at: usize) -> Option<(&[u8], bool, usize, usize)> { let is_macro = m[at..].starts_with(b"macro_rules"); let mut start = skip_ws(m, at + if is_macro { "macro_rules".len() } else { 2 }); if is_macro { @@ -1094,8 +1096,13 @@ fn definition(m: &[u8], at: usize) -> Option { if m[open] != b'{' { return None; } - let close = matching(m, open)?; - let name = String::from_utf8_lossy(&m[start..end]).into_owned(); + Some((&m[start..end], is_macro, open, matching(m, open)?)) +} + +/// The `fn` or `macro_rules!` at `at`. +fn definition(m: &[u8], at: usize) -> Option { + let (name, is_macro, open, close) = item_at(m, at)?; + let name = String::from_utf8_lossy(name).into_owned(); let called = calls(m, open, close).into_iter().filter(|(_, method)| !method).map(|(n, _)| n).collect(); Some((if is_macro { format!("{name}!") } else { name }, checks_itself(m, open, close), called)) } @@ -1107,6 +1114,9 @@ struct File<'a> { path: &'a str, src: &'a [u8], m: Vec, + /// [`File::m`] with the functions and macros declared inside each test blanked: declaring + /// one does not run its body ([`executed`]). + exec: Vec, lines: Lines, tests: Vec, /// The test code ([`test_regions`]). @@ -1148,7 +1158,8 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { let m = mask(src); let tests = tests_in(&m); let regions = test_regions(path, &m, &tests); - let file = File { path, src: src.as_bytes(), m, lines: Lines::new(src), tests, regions }; + let exec = executed(&m, &tests); + let file = File { path, src: src.as_bytes(), m, exec, lines: Lines::new(src), tests, regions }; let mut hits: Vec = file.tests.iter().flat_map(|t| test_hits(&file, t, ctx)).collect(); hits.extend(ignore_hits(&file)); hits.extend(sleep_hits(&file)); @@ -1162,6 +1173,20 @@ pub fn lint_file(path: &str, src: &str, ctx: &Ctx) -> Vec { hits } +/// `m` with each `fn` and `macro_rules!` declared inside a test's body replaced by spaces, from +/// its keyword to its closing brace. A call to one stays, so it can still count as a helper call. +fn executed(m: &[u8], tests: &[TestFn]) -> Vec { + let mut out = m.to_vec(); + for t in tests { + for at in words(m, b"fn", t.open, t.close).into_iter().chain(words(m, b"macro_rules", t.open, t.close)) { + if let Some((_, _, _, close)) = item_at(m, at).filter(|&(_, _, _, close)| close < t.close) { + blank(&mut out, at, close + 1); + } + } + } + out +} + /// `(line, rule)` of each exemption comment that names a rule and a reason. /// A marker counts only inside a comment: masked (`m`) there, and kept when only literals are /// masked. @@ -1191,7 +1216,7 @@ struct View<'a> { } fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { - let m = &file.m; + let m = &file.exec; let asserts: Vec = macro_calls(m, t.open, t.close).into_iter().filter(|c| is_assert_macro(&c.name)).collect(); let none = HashSet::new(); let helpers = ctx.helpers.get(&crate_of(file.path)).unwrap_or(&none); @@ -1199,7 +1224,7 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { .iter() .any(|(n, method)| n != &t.name && !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers)); let checks = checks_itself(m, t.open, t.close); - let should_panic = contains(&m[t.attr..t.fn_at], b"should_panic"); + let should_panic = should_panic_attr(m, t.attr, t.fn_at); let v = View { file, t, asserts, delegates, checks, should_panic }; let mut hits = all_unguarded(&v); hits.extend(self_compare(&v)); @@ -1209,6 +1234,27 @@ fn test_hits(file: &File, t: &TestFn, ctx: &Ctx) -> Vec { hits } +/// Whether the attributes in `m[from..to]` include an applied `should_panic`: `#[should_panic]`, +/// `#[should_panic(…)]`, or one inside `#[cfg_attr(test, …)]`. Another `cfg_attr` predicate may +/// not hold, so it does not count. +fn should_panic_attr(m: &[u8], from: usize, to: usize) -> bool { + let attached = words(m, b"should_panic", from, to).into_iter().any(|at| { + let before = m[..at].trim_ascii_end().strip_suffix(b"[").is_some_and(|b| b.trim_ascii_end().ends_with(b"#")); + before && matches!(m.get(skip_ws(m, at + "should_panic".len())), Some(b']' | b'(')) + }); + attached + || words(m, b"cfg_attr", from, to).into_iter().any(|at| { + let open = skip_ws(m, at + "cfg_attr".len()); + let Some(close) = matching(m, open).filter(|&c| m[open] == b'(' && c < to) else { return false }; + let args = split_args(m, open + 1, close); + let name = |&(f, t): &(usize, usize)| { + let a = norm(&m[f..t]); + a == "should_panic" || a.starts_with("should_panic(") + }; + args.first().is_some_and(|&(f, t)| norm(&m[f..t]) == "test") && args.iter().skip(1).any(name) + }) +} + impl View<'_> { fn hit(&self, at: usize, rule: Rule, note: String) -> Hit { self.file.hit(at, rule, &self.t.name, note) @@ -1223,7 +1269,7 @@ impl View<'_> { } fn body(&self) -> &[u8] { - &self.file.m[self.t.open..self.t.close] + &self.file.exec[self.t.open..self.t.close] } /// The masked body with assertion failure-message arguments replaced by spaces. @@ -2149,8 +2195,9 @@ fn reads_counted_local(body: &[u8], all: &[Binding], from: usize, to: usize) -> /// Whether an assertion's (masked, whitespace-free) condition only says that there is a value. fn is_weak(cond: &str) -> bool { + let cond = unparenthesized(cond); let (negated, expr) = match cond.strip_prefix('!') { - Some(rest) => (true, rest), + Some(rest) => (true, unparenthesized(rest)), None => (false, cond), }; let plain = |rest: &str| !["&&", "||", "==", "!=", "<", ">"].iter().any(|op| rest.contains(op)); @@ -2161,6 +2208,14 @@ fn is_weak(cond: &str) -> bool { suffix(".is_ok()") || suffix(".is_some()") || suffix(".len()>0") || suffix(".len()!=0") || suffix(".len()>=1") } +/// `expr` without the balanced parentheses around all of it (`((a.is_ok()))` gives `a.is_ok()`). +fn unparenthesized(mut expr: &str) -> &str { + while expr.starts_with('(') && matching(expr.as_bytes(), 0) == Some(expr.len() - 1) { + expr = &expr[1..expr.len() - 1]; + } + expr +} + fn only_weak(v: &View) -> Option { let all_weak = v.asserts.iter().all(|a| PLAIN_ASSERTS.contains(&a.name.as_str()) && is_weak(&v.first_arg(a))); // Failure messages run only after an assertion has failed, so a check there does not count. @@ -3223,6 +3278,41 @@ mod tests { assert_eq!(hits(refusal), [], "is_err is not on the plan's list"); let compound = "#[test]\nfn t() {\n assert!(a.is_some() && a == Some(2));\n}\n"; assert_eq!(hits(compound), []); + for cond in ["(parse(\"x\").is_ok())", "((parse(\"x\").is_ok()))", "!(list().is_empty())", "(!list().is_empty())"] { + let src = format!("#[test]\nfn t() {{\n assert!({cond});\n}}\n"); + assert_eq!(hits(&src), [(2, "only-weak")], "{cond}"); + } + let grouped = "#[test]\nfn t() {\n assert!((a.is_some()) && (a == Some(2)));\n}\n"; + assert_eq!(hits(grouped), [], "parentheses around one side of a comparison stay"); + } + + #[test] + fn functions_declared_in_a_test_count_only_when_called() { + let unused = "#[test]\nfn t() {\n fn unused() {\n assert_eq!(1, 1);\n }\n assert!(parse(\"x\").is_ok());\n}\n"; + assert_eq!(hits(unused), [(2, "only-weak")], "a declared function's assertion does not run"); + let macro_only = "#[test]\nfn t() {\n macro_rules! check {\n () => { assert_eq!(1, 1) };\n }\n f();\n}\n"; + assert_eq!(hits(macro_only), [(2, "no-assertion")], "a declared macro's assertion does not run"); + let called = unused.replace(" assert!(parse", " unused();\n assert!(parse"); + let files = [("crates/x/src/tests.rs".to_owned(), called.clone())]; + let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() }; + assert_eq!(hits_in("crates/x/src/tests.rs", &called, &with_helpers), [], "a call to it checks"); + } + + #[test] + fn should_panic_counts_only_when_applied() { + let weak = "#[test]\nfn t() {\n assert!(parse(\"x\").is_ok());\n}\n"; + for attr in [ + "#[should_panic]", + "#[ should_panic(expected = \"x\") ]", + "#[cfg_attr(test, should_panic)]", + "#[cfg_attr( test , should_panic(expected = \"x\"))]", + ] { + assert_eq!(hits(&format!("{attr}\n{weak}")), [], "{attr}"); + } + for attr in ["#[cfg_attr(any(), should_panic)]", "#[cfg_attr(windows, should_panic)]", "#[doc = \"should_panic\"]", "#[allow(should_panic)]"] + { + assert_eq!(hits(&format!("{attr}\n{weak}")), [(3, "only-weak")], "{attr}"); + } } #[test] @@ -3554,6 +3644,10 @@ mod tests { let gated = format!("#[cfg({gate})]\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{gate} holds only in tests"); } + for attr in ["#[ cfg(all(test, unix))]", "#[/* test-only */cfg(test)]", "# [cfg (test)]"] { + let gated = format!("{attr}\nmod tests {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); + assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [(3, "sleep")], "{attr}"); + } for gate in ["any(test, feature = \"x\")", "not(test)", "all(unix, not(test))", "feature = \"test\""] { let gated = format!("#[cfg({gate})]\nmod helpers {{\n fn w() {{ thread::sleep(D); }}\n}}\n"); assert_eq!(hits_in("crates/x/src/lib.rs", &gated, &ctx()), [], "{gate} also holds outside tests"); From 81cc0fc7973c71bbb5b52c41461669d099088fea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 05:49:09 -0800 Subject: [PATCH 25/37] Tests: nine engine integration test files join the tests/it binary blend_render_consistency, direct_handle_mirror, ellipse_drag_anchors, eraser_open_fill, group3_reference, path_fill_hits, pen_space_handle, preflight and scissors_snap were each a test binary of their own. They now are modules of crates/engine/tests/it, with their tests unchanged, so the engine's tests link nine fewer binaries. The files that stay separate change process-wide state (installed plug-ins, Safe Mode, the font database, color settings, the working directory), are run by name from CI or xtask (the Affinity corpus tests, script_corpus, import_fuzz), or compile for about a minute on their own (command_sweep), which would make every edit to tests/it rebuild it. Docs that named the old paths name the new ones, and the preflight command in docs/production-preflight.md runs `--test it preflight::`. --- crates/engine/Cargo.toml | 2 +- .../{ => it}/blend_render_consistency.rs | 1 - .../tests/{ => it}/direct_handle_mirror.rs | 1 - .../tests/{ => it}/ellipse_drag_anchors.rs | 1 - .../engine/tests/{ => it}/eraser_open_fill.rs | 2 -- .../engine/tests/{ => it}/group3_reference.rs | 0 crates/engine/tests/it/main.rs | 9 ++++++++ .../engine/tests/{ => it}/path_fill_hits.rs | 1 - .../engine/tests/{ => it}/pen_space_handle.rs | 2 -- crates/engine/tests/{ => it}/preflight.rs | 2 -- crates/engine/tests/{ => it}/scissors_snap.rs | 1 - docs/gaps.md | 10 ++++----- docs/production-preflight.md | 2 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 22 +++++++++---------- docs/ui-parity.md | 14 ++++++------ 16 files changed, 35 insertions(+), 37 deletions(-) rename crates/engine/tests/{ => it}/blend_render_consistency.rs (99%) rename crates/engine/tests/{ => it}/direct_handle_mirror.rs (99%) rename crates/engine/tests/{ => it}/ellipse_drag_anchors.rs (99%) rename crates/engine/tests/{ => it}/eraser_open_fill.rs (99%) rename crates/engine/tests/{ => it}/group3_reference.rs (100%) rename crates/engine/tests/{ => it}/path_fill_hits.rs (99%) rename crates/engine/tests/{ => it}/pen_space_handle.rs (99%) rename crates/engine/tests/{ => it}/preflight.rs (99%) rename crates/engine/tests/{ => it}/scissors_snap.rs (99%) diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 027ae10251..406851393a 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -116,7 +116,7 @@ zune-core = { workspace = true } # JPEG XL files for the import fuzz tests (tests/import_fuzz.rs). craft-jxl = { workspace = true } # vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference -# tests/group3_reference.rs compares it with. +# tests/it/group3_reference.rs compares it with. hayro-ccitt = { workspace = true } craft-stream-codecs = { workspace = true } vectorcraft-affinity = { workspace = true, features = ["synth"] } diff --git a/crates/engine/tests/blend_render_consistency.rs b/crates/engine/tests/it/blend_render_consistency.rs similarity index 99% rename from crates/engine/tests/blend_render_consistency.rs rename to crates/engine/tests/it/blend_render_consistency.rs index fdc2fb3b93..fa69885ad7 100644 --- a/crates/engine/tests/blend_render_consistency.rs +++ b/crates/engine/tests/it/blend_render_consistency.rs @@ -1,5 +1,4 @@ //! Blend edits invalidate every pixel they change, including keys aligned to a curved spine. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::sync::Arc; diff --git a/crates/engine/tests/direct_handle_mirror.rs b/crates/engine/tests/it/direct_handle_mirror.rs similarity index 99% rename from crates/engine/tests/direct_handle_mirror.rs rename to crates/engine/tests/it/direct_handle_mirror.rs index 30326d8e74..bfe8db75a0 100644 --- a/crates/engine/tests/direct_handle_mirror.rs +++ b/crates/engine/tests/it/direct_handle_mirror.rs @@ -1,5 +1,4 @@ //! Temporary Cmd/Control symmetry while Direct Selection drags an existing handle. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; use vectorcraft_doc::{Node, NodeId}; diff --git a/crates/engine/tests/ellipse_drag_anchors.rs b/crates/engine/tests/it/ellipse_drag_anchors.rs similarity index 99% rename from crates/engine/tests/ellipse_drag_anchors.rs rename to crates/engine/tests/it/ellipse_drag_anchors.rs index afce996136..1e278505ed 100644 --- a/crates/engine/tests/ellipse_drag_anchors.rs +++ b/crates/engine/tests/it/ellipse_drag_anchors.rs @@ -1,5 +1,4 @@ //! Ellipse arrow keys edit the anchor count of the shape actually being dragged. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; use vectorcraft_doc::{LiveShape, Node, NodeId}; diff --git a/crates/engine/tests/eraser_open_fill.rs b/crates/engine/tests/it/eraser_open_fill.rs similarity index 99% rename from crates/engine/tests/eraser_open_fill.rs rename to crates/engine/tests/it/eraser_open_fill.rs index a0ab760660..a5f6e60956 100644 --- a/crates/engine/tests/eraser_open_fill.rs +++ b/crates/engine/tests/it/eraser_open_fill.rs @@ -1,6 +1,4 @@ //! Fill-only open-path Eraser regressions through the public engine and CPU renderer. -// Integration tests may unwrap and panic on failure (AGENTS.md). -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; diff --git a/crates/engine/tests/group3_reference.rs b/crates/engine/tests/it/group3_reference.rs similarity index 100% rename from crates/engine/tests/group3_reference.rs rename to crates/engine/tests/it/group3_reference.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index ff4a5c22ab..2be85215bb 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -12,13 +12,18 @@ mod affinity_local; mod align_automatic_reference; mod artboard_click; mod beyond_canvas; +mod blend_render_consistency; mod clear_commands; mod compound_attributes; mod copy_direct_selection; mod delete_path_pieces; mod dimensions; +mod direct_handle_mirror; +mod ellipse_drag_anchors; +mod eraser_open_fill; mod eyedropper_sources; mod find_replace_paras; +mod group3_reference; mod inline_text; mod js_lexer_vs_scriptcheck; mod known_bugs; @@ -27,12 +32,16 @@ mod model_based; mod param_keys; mod paste_many; mod pasted_clipping_path; +mod path_fill_hits; mod pen_click_after_smooth; mod pen_endpoint_picking; mod pen_rubber_band; +mod pen_space_handle; +mod preflight; mod ruler_guide_nodes; mod ruler_guide_perf; mod ruler_origin; +mod scissors_snap; mod script_host_vs_scriptcheck; mod selection_commands; mod several_handles; diff --git a/crates/engine/tests/path_fill_hits.rs b/crates/engine/tests/it/path_fill_hits.rs similarity index 99% rename from crates/engine/tests/path_fill_hits.rs rename to crates/engine/tests/it/path_fill_hits.rs index f8dfebafaf..28ab79e36b 100644 --- a/crates/engine/tests/path_fill_hits.rs +++ b/crates/engine/tests/it/path_fill_hits.rs @@ -1,5 +1,4 @@ //! Path fill hit testing follows the visible paint stack while transparent paint remains selectable. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use std::sync::Arc; diff --git a/crates/engine/tests/pen_space_handle.rs b/crates/engine/tests/it/pen_space_handle.rs similarity index 99% rename from crates/engine/tests/pen_space_handle.rs rename to crates/engine/tests/it/pen_space_handle.rs index 5e37ca8a11..9bb8a0b8c8 100644 --- a/crates/engine/tests/pen_space_handle.rs +++ b/crates/engine/tests/it/pen_space_handle.rs @@ -1,6 +1,4 @@ //! Pen lends Direct Selection for one handle gesture; Space repositions that handle's owner. -// Integration tests may unwrap and panic (AGENTS.md, Robustness). -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::json; use vectorcraft_doc::NodeId; diff --git a/crates/engine/tests/preflight.rs b/crates/engine/tests/it/preflight.rs similarity index 99% rename from crates/engine/tests/preflight.rs rename to crates/engine/tests/it/preflight.rs index e656596d71..73f6066bd3 100644 --- a/crates/engine/tests/preflight.rs +++ b/crates/engine/tests/it/preflight.rs @@ -1,5 +1,3 @@ -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - //! Production preflight must find actual delivery problems and clear them after repairs. use serde_json::{Value, json}; diff --git a/crates/engine/tests/scissors_snap.rs b/crates/engine/tests/it/scissors_snap.rs similarity index 99% rename from crates/engine/tests/scissors_snap.rs rename to crates/engine/tests/it/scissors_snap.rs index 6d12bd6457..b81ac05bab 100644 --- a/crates/engine/tests/scissors_snap.rs +++ b/crates/engine/tests/it/scissors_snap.rs @@ -1,5 +1,4 @@ //! Scissors receives the view's Smart Guides setting and keeps the split endpoint selected. -#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] use serde_json::json; use vectorcraft_doc::NodeId; diff --git a/docs/gaps.md b/docs/gaps.md index 9130e782f1..01b62dc5d6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -29,7 +29,7 @@ OpenType panel feature-row context menus (part of G12): a secondary click on a f Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. Appearance panel row context menus (part of G12): right-clicking stroke and fill rows offers Duplicate Stroke / Duplicate Fill, Delete Stroke / Delete Fill, and Hide Stroke/Show Stroke / Hide Fill/Show Fill; effect rows offer Edit Effect…, Duplicate Effect, Delete Effect, and Hide Effect / Show Effect; the root object row offers Clear Appearance and Reduce to Basic Appearance. Right-clicking an unselected row targets that row before presenting the menu. Item actions run in one undo step. Evidence: `panels::tests_appearance::right_clicking_a_stroke_row_selects_it_and_exposes_context_menu`, `panels::tests_appearance::clicking_duplicate_stroke_duplicates_the_stroke_with_one_undo_step`, `panels::tests_appearance::clicking_delete_effect_removes_the_effect_from_appearance`, and `panels::tests_appearance::right_clicking_root_object_row_exposes_clear_and_reduce_appearance` in `crates/ui-egui/src/panels/tests_appearance.rs`. Scores and estimates unchanged. @@ -185,7 +185,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged, and the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. -- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. @@ -197,7 +197,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Polygon/Star count persistence:** Exact-size placement saves the chosen count for later drags and reopening the existing canvas dialog. Regression coverage includes both tools, repeated drags, switching tools and Cancel. The remaining G1 scope and estimates are unchanged. -- **Ellipse drag anchor count (#7840):** Up/Down changes the remembered Anchors count from 2 to 1000 in the current preview box. The existing click-dialog count starts later drags; Escape restores the earlier count while an explicit `tool.setOption` update is kept. Regression target: `crates/engine/tests/ellipse_drag_anchors.rs`. Broader G1 scope and estimates unchanged. +- **Ellipse drag anchor count (#7840):** Up/Down changes the remembered Anchors count from 2 to 1000 in the current preview box. The existing click-dialog count starts later drags; Escape restores the earlier count while an explicit `tool.setOption` update is kept. Regression target: `crates/engine/tests/it/ellipse_drag_anchors.rs`. Broader G1 scope and estimates unchanged. - **Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. Broader scope and estimates unchanged. @@ -398,8 +398,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G11 Correctness bugs in core tools -- **Resolved redraw-bounds defect (#5179):** a curved-spine blend's renderer bounds include its rotated keys and steps after Replace Spine; `crates/engine/tests/blend_render_consistency.rs` keeps the straight-blend control and checks all changed pixels against the advertised area. Both focused CPU regressions pass; broader G11 scope and estimates unchanged. -- **Improved (#6582), fill-only scope:** the Eraser subtracts its swept area or Alt-drag marquee from filled open contours with no visible painted stroke, preserving fill outside the sweep. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. The result keeps the existing path/compound piece structure and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths deliberately retain the outline-splitting behavior from main. Public reference semantics for those stroked paths were not established, and their fill behavior is not claimed fixed here. Focused engine integration tests cover fixed and varied tips and Alt-drag marquees on fill-only open/closed geometry and pixels, compound holes and self-crossing fill, plus painted-stroke paths that keep the outline route and clipping-mask split, empty-mask and Path Eraser controls. `crates/engine/tests/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Scores and estimates unchanged. +- **Resolved redraw-bounds defect (#5179):** a curved-spine blend's renderer bounds include its rotated keys and steps after Replace Spine; `crates/engine/tests/it/blend_render_consistency.rs` keeps the straight-blend control and checks all changed pixels against the advertised area. Both focused CPU regressions pass; broader G11 scope and estimates unchanged. +- **Improved (#6582), fill-only scope:** the Eraser subtracts its swept area or Alt-drag marquee from filled open contours with no visible painted stroke, preserving fill outside the sweep. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. The result keeps the existing path/compound piece structure and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths deliberately retain the outline-splitting behavior from main. Public reference semantics for those stroked paths were not established, and their fill behavior is not claimed fixed here. Focused engine integration tests cover fixed and varied tips and Alt-drag marquees on fill-only open/closed geometry and pixels, compound holes and self-crossing fill, plus painted-stroke paths that keep the outline route and clipping-mask split, empty-mask and Path Eraser controls. `crates/engine/tests/it/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Scores and estimates unchanged. - **Implemented (#6470):** Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping, following the existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions are in `crates/tools/src/draw2/anchor/tests.rs`; broader G11 scope and estimates unchanged. diff --git a/docs/production-preflight.md b/docs/production-preflight.md index ecc551f0c9..77698662d8 100644 --- a/docs/production-preflight.md +++ b/docs/production-preflight.md @@ -52,7 +52,7 @@ The same read-only report is available through `document.preflight`; see [MCP](m Checked on Windows with Rust 1.99.1, based on `main` at `36b5a5920c`: -- Engine integration tests: 9 passed (`cargo test -p vectorcraft-engine --test preflight`). +- Engine integration tests: 9 passed (`cargo test -p vectorcraft-engine --test it preflight::`). - Panel tests: 5 passed (`cargo test -p vectorcraft-ui-egui --lib preflight`), including pointer selection/zoom, edits and Undo, document switching, external-file polling and explicit Recheck. - Both test commands used `--offline --target-dir target --config profile.test.opt-level=0`. diff --git a/docs/roadmap.md b/docs/roadmap.md index 971ca6eafa..726ecd790b 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -34,7 +34,7 @@ Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged. -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4df379b998..ae083e42e9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -77,7 +77,7 @@ Variables panel row context menus (2026-11-20, G12): Right-click highlights the Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged. -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. `window.panel.float` updates an existing native panel window's supplied position and size (#8391). Positions use the main window's content origin. Omitted coordinates and dimensions keep their current native values, including after an OS window move or resize. Evidence: `panel_docking::native_tests::an_explicit_float_command_updates_an_existing_native_windows_geometry` covers panel, group and column commands. Scores and estimates are unchanged. @@ -346,8 +346,8 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | -| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options; Touch Type (#2469) and the Dimension tool (#1788) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | +| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/it/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options; Touch Type (#2469) and the Dimension tool (#1788) are done; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/it/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged; gradient stop editor color-mode menu (#7918) | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | @@ -692,12 +692,12 @@ since 2026-10-01. - **`.ai` clipping paths grouped in a compound path (#8128):** `clipping_paths_grouped_in_a_compound_path_are_its_subpaths` in `crates/eps/src/import/ai/tests.rs` covers clipping paths grouped in a compound path (`*u u W n … U *U`, also nested in other groups): they are the compound path's subpaths, and the compound clipping path, their union, clips its clipping group however many there are and wherever in the group it is written. Synthetic files written in the test; no fixtures added. Scores and hours unchanged. -**Production Preflight (2026-11-18, VectorCraft addition):** `document.preflight` and Window > Production Preflight reuse the output-aware type walk, Links status probes, `image.info` effective-PPI calculation and saved Print geometry. Findings locate canvas objects (resource findings name their first visible owner). Rechecking follows document identity/revision, output/scope/threshold changes, explicit Recheck and a two-second external-file timer. Print resolution includes the page transform. Resolution in resource art and placed documents is explicitly not checked; this is not exported-file certification. Regression sources: `crates/engine/tests/preflight.rs`, `crates/ui-egui/src/panels/preflight/tests.rs`. Scores and estimates unchanged. +**Production Preflight (2026-11-18, VectorCraft addition):** `document.preflight` and Window > Production Preflight reuse the output-aware type walk, Links status probes, `image.info` effective-PPI calculation and saved Print geometry. Findings locate canvas objects (resource findings name their first visible owner). Rechecking follows document identity/revision, output/scope/threshold changes, explicit Recheck and a two-second external-file timer. Print resolution includes the page transform. Resolution in resource art and placed documents is explicitly not checked; this is not exported-file certification. Regression sources: `crates/engine/tests/it/preflight.rs`, `crates/ui-egui/src/panels/preflight/tests.rs`. Scores and estimates unchanged. - `object.setBounds` uses the same reference point for whole-number integer and floating-point values, including `0` and `0.0`. It rejects negative and fractional indices without changing geometry, selection, or undo history. An omitted or null reference uses the center, and whole-number references above 8 use point 8. Object and direct-anchor selections follow these rules (`tests::bboxrotate::set_bounds_whole_number_references_match_integer_references`, `set_bounds_rejects_invalid_references_without_changes`). - Twist keeps boundary handles tangent to the rotation inside its outer circle. Regressions cover 90, 400, and -720 degree twists, unchanged boundary anchors, and a sampling midpoint that rounds to an endpoint at large coordinates (`twist_boundary_handles_follow_the_inward_tangent` and `a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction`). -- **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged. +- **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/it/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged. - **Guide row highlight (#7344):** `guide_row_highlight_stays_selected_without_hover` in `crates/ui-egui/src/panels/layers/tests.rs` checks selected guide background after the pointer leaves, with unselected guide and ordinary row controls. Guide selection, dragging and deletion are unchanged. Scores and estimates unchanged. - **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`. @@ -716,7 +716,7 @@ since 2026-10-01. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. -**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss with Object Selection by Path Only on or in Outline view, and with it off are picked only when the click hits nothing else there (#9175, below). Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/it/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **Clicks inside unfilled shapes (#9175):** with Object Selection by Path Only off (the default), the Selection, Direct Selection and Group Selection tools, Object Highlighting and a right-click's selection pick a closed path or compound path with no fill by a click inside its closed subpaths, when the click hits no other object there, by its fill, stroke, path or bounds (a symbol instance, for example, is hit anywhere in its bounds); among such paths the topmost is picked, and Select Behind lists them after the objects that paint there. Open paths, guides and clipping paths are still picked by their path only, and Outline view and layers whose Preview is off are unchanged. This is VectorCraft's own rule. Tests: `an_unfilled_closed_path_is_hit_inside_unless_by_path_only_or_in_outline`, `an_open_path_is_not_hit_inside`, `art_inside_an_unfilled_frame_above_it_is_hit_before_the_frame`, `an_unfilled_compound_path_is_hit_inside_its_members_but_not_its_holes`, `guides_and_clipping_paths_are_not_hit_inside`, `a_repeat_is_hit_inside_its_unfilled_copies_but_not_inside_their_masks` and `symbol_art_parts_are_picked_inside_unfilled_frames_after_what_paints` in `crates/doc/src/hit/tests.rs`, and `a_click_inside_an_unfilled_shape_selects_it_unless_by_path_only` (MCP). Scores and estimates unchanged. @@ -727,7 +727,7 @@ since 2026-10-01. - **PDF Indic type (#5235, #6906):** `crates/pdf/src/tests/reshaped.rs` covers a vowel sign the file draws before its consonant (the line keeps the file's glyphs as outlines, with a note), text in reading order (stays type), a mark with no advance (stays on its line, not vertical type of its own), outlined glyphs stroked with different dashes and translucent outlined glyphs (each keeps its own path). Synthetic font only; one real Gujarati file checked by eye on page 1. Indic type in an uninstalled font keeps the file's glyphs as outlines; reordering signs so more lines stay editable is not done. Scores and hours stay at 75% / 10-20 h. -- **Selection — Space during an ordinary path's direction-handle drag (#7237, request 3 only).** Pressing Space during an ordinary path's Direct Selection handle drag translates the owning anchor and both handles; releasing Space while the mouse stays down resumes handle adjustment. The same gesture during the Pen's Cmd/Ctrl loan returns to drawing from the same endpoint. `crates/engine/tests/pen_space_handle.rs` covers first-motion Space, repeated toggles and Pen continuation (`pen_space_first_motion_repeated_toggle_and_pen_continuation`), one-step Undo/Redo (`pen_space_handle_drag_undo_redo_is_one_step`), and cancellation restoring the borrowed gesture (`pen_space_escape_restores_entire_borrowed_gesture`). Live type-on-path Space behavior is outside this increment; blend-spine editing is unchanged. This does not close the issue's separate handle-hover label request or change Cmd snapping or handle-coupling policy. Score and hours unchanged. +- **Selection — Space during an ordinary path's direction-handle drag (#7237, request 3 only).** Pressing Space during an ordinary path's Direct Selection handle drag translates the owning anchor and both handles; releasing Space while the mouse stays down resumes handle adjustment. The same gesture during the Pen's Cmd/Ctrl loan returns to drawing from the same endpoint. `crates/engine/tests/it/pen_space_handle.rs` covers first-motion Space, repeated toggles and Pen continuation (`pen_space_first_motion_repeated_toggle_and_pen_continuation`), one-step Undo/Redo (`pen_space_handle_drag_undo_redo_is_one_step`), and cancellation restoring the borrowed gesture (`pen_space_escape_restores_entire_borrowed_gesture`). Live type-on-path Space behavior is outside this increment; blend-spine editing is unchanged. This does not close the issue's separate handle-hover label request or change Cmd snapping or handle-coupling policy. Score and hours unchanged. - **Selection — disconnected path deletion (#3380, deletion only):** Clear/Delete and Cut turn surviving disconnected pieces of an ordinary contour into independent selected sibling objects. The first keeps its ID; all keep appearance, baked transforms and stacking order. `deletion_split_preserves_gradient_placement` compares rendered survivors with the original paint space and checks linear/radial fill/stroke vectors, already placed gradients and atomic Undo/Redo; connected remainders keep automatic fitting. Existing multi-subpath paths and explicit compound members retain their semantics. Original synthetic regressions in `crates/engine/tests/it/delete_path_pieces.rs` cover styled/transformed rectangles, cubic handles, compound preservation and atomic Undo/Redo; `crates/ui-egui/src/tests/removeanchors.rs` covers real-frame Delete/Backspace and a second Delete removing all survivors. Segment endpoint highlighting remains open. Scores and hours unchanged. - **Selection: deletion on paths with many subpaths:** Clear/Delete, `path.deleteAnchors`, Copy, Cut and Cut Path read each subpath's selected anchors or segments directly from the path's ordered selection, instead of scanning every selected anchor or segment of the path once per subpath. The result is unchanged: `crates/engine/tests/it/delete_path_pieces.rs` checks exact surviving subpaths and their order, open and closed contours, an untouched subpath, references to missing subpaths and indexes, one Undo/Redo step and a second Delete, for anchor and segment selections on one path. Scores and hours unchanged. @@ -834,7 +834,7 @@ since 2026-10-01. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. - **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. -- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/direct_handle_mirror.rs`. +- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/it/direct_handle_mirror.rs`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Commands run during a tool drag:** by VectorCraft's own rule, a command that changes the document while a tool drag is in progress (from a panel, a menu or `run_command`) records its own undo step before the drag's. The drag goes on with the art the command left, Escape cancels only the drag, and Undo takes back the drag first and the command next, with Real-time Drawing on or off. A selection the command makes does not change which objects the drag moves. Commands that keep the drag as a step first (Undo, Redo, `command.batch` and others), a Quick Pen press, and a copy made with `object.transform` during an Alt-drag work as before. Regression tests: `crates/engine/src/tests/interaction_commands.rs` and `tests::drag_commands` in `crates/ui-egui`. @@ -1594,10 +1594,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur VectorCraft's own Anchors field in the Ellipse dialog (a click with the Ellipse tool; `shape.ellipse {anchors}`, part of #7840) sets how many smooth anchors the ellipse has, 4 by default; 4 draws a live ellipse, and any other count from 2 to 1000 draws a plain path with the anchors spaced evenly by angle, fitted to the typed width and height. The count last confirmed stays as the Ellipse tool's `anchors` option, and the next Ellipse dialog opens on it (`ellipse_with_four_anchors_is_the_live_ellipse`, `ellipse_anchors_draw_that_many_anchors_on_the_ellipse`, `ellipse_refuses_a_bad_anchor_count`, `the_ellipse_dialog_draws_and_keeps_its_anchor_count`). In the Ellipse dialog, a click on the word Height copies the Width value into the Height field, so OK draws a circle of that width, as [the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=140) describes for drawing ellipses. The Rectangle and Rounded Rectangle dialogs keep plain labels. VectorCraft's own rules: the word Height is a button that Space or Enter also presses, and that Enter does not press OK (nor does Enter on the Constrain Width and Height Proportions button); with the link on, the link stays on and keeps the circle when a side is typed next; a Width that is empty or not a distance, including one the field refuses as the click leaves it, leaves Height as it is; Cancel discards the copy. Evidence: `dialogs::shapes::tests::{clicking_height_in_the_ellipse_dialog_copies_width_into_height, the_ellipse_height_button_copies_width_from_the_keyboard_and_keeps_the_link_round, enter_on_the_link_button_turns_the_link_on_without_pressing_ok, only_the_ellipse_dialog_has_the_height_button, copying_width_takes_only_a_width_that_reads}`. - The click-dialog field landed in #7964. While an ellipse is dragged out, Up/Down raises or lowers the same remembered Anchors count within 2…1000 (#7840), keeping the preview box and its Shift, Alt and Space behavior. Four anchors keep the live ellipse; other counts use the existing plain-path geometry. Releasing commits one undo step. Escape restores the count from before the drag, unless `tool.setOption` explicitly updated it during the gesture, in which case that value stays. Regression target: `crates/engine/tests/ellipse_drag_anchors.rs` (`ellipse_drag_anchors_`). + The click-dialog field landed in #7964. While an ellipse is dragged out, Up/Down raises or lowers the same remembered Anchors count within 2…1000 (#7840), keeping the preview box and its Shift, Alt and Space behavior. Four anchors keep the live ellipse; other counts use the existing plain-path geometry. Releasing commits one undo step. Escape restores the count from before the drag, unless `tool.setOption` explicitly updated it during the gesture, in which case that value stays. Regression target: `crates/engine/tests/it/ellipse_drag_anchors.rs` (`ellipse_drag_anchors_`). - **Cutting:** Eraser, Scissors, Knife, Mirror & Cut, Line Cut and Rectangle Cut (real geometry, compound paths keep their holes). - The Eraser cuts fill-only open contours as areas (#6582), retaining fill outside its sweep or Alt-drag marquee. An eligible appearance has a visible non-None fill and no visible non-None stroke of positive width. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. Cut pieces keep the existing path/compound representation and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths retain the outline-splitting behavior from main. `crates/engine/tests/eraser_open_fill.rs` covers fixed and varied tips on fill-only open/closed geometry and raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. The same public target includes container-own paint and evaluated-placement regression cases. This deliberately scoped fix does not claim to repair filled-and-stroked open-path fill behavior. Scores and hours are unchanged. - With Alt released, Scissors hover and cuts snap as the Pen does: onto paths and anchors, into alignment and onto intersections (#6470). The hover guides and cut use the same snapped point; the cursor follows the current hover target. The existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options keep their precedence. Pixel Preview turns off Smart Guides through the tool view context; Snap to Point keeps its existing rules. Alt Add Anchor and the cut's endpoint selection below are unchanged. Source: `crates/tools/src/draw2/anchor.rs`. Headless regressions: `scissors_snaps_intersections_with_the_drawing_options`, `scissors_shows_paths_alignment_and_configured_anchor_snaps`, `scissors_cursor_and_press_use_current_snaps` and `scissors_clears_its_snap_when_the_interaction_ends_or_alt_takes_over` in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. + The Eraser cuts fill-only open contours as areas (#6582), retaining fill outside its sweep or Alt-drag marquee. An eligible appearance has a visible non-None fill and no visible non-None stroke of positive width. Fill-only open compound members are cut together under their compound fill rule so holes stay empty. Cut pieces keep the existing path/compound representation and whole appearance. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Path or Compound clipping masks keep every surviving contour in the same mask node; full erasure leaves an empty mask without promoting clipped contents. The mask identity, fill rule, appearance and parent child order are retained. Path Eraser uses the same preservation of the clipping role. Filled-and-stroked open paths retain the outline-splitting behavior from main. `crates/engine/tests/it/eraser_open_fill.rs` covers fixed and varied tips on fill-only open/closed geometry and raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. The same public target includes container-own paint and evaluated-placement regression cases. This deliberately scoped fix does not claim to repair filled-and-stroked open-path fill behavior. Scores and hours are unchanged. + With Alt released, Scissors hover and cuts snap as the Pen does: onto paths and anchors, into alignment and onto intersections (#6470). The hover guides and cut use the same snapped point; the cursor follows the current hover target. The existing Smart Guides, Snap to Point, Snap to Pixel and Snap to Grid options keep their precedence. Pixel Preview turns off Smart Guides through the tool view context; Snap to Point keeps its existing rules. Alt Add Anchor and the cut's endpoint selection below are unchanged. Source: `crates/tools/src/draw2/anchor.rs`. Headless regressions: `scissors_snaps_intersections_with_the_drawing_options`, `scissors_shows_paths_alignment_and_configured_anchor_snaps`, `scissors_cursor_and_press_use_current_snaps` and `scissors_clears_its_snap_when_the_interaction_ends_or_alt_takes_over` in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. A Scissors cut (`path.split`) leaves one of the two new end points selected and the rest of the path unselected, as [Cut paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) and the "Split a path" section of the [CS3 user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describe: the two end points lie on top of each other, and a Direct Selection drag from them moves the selected one with its handles and no other anchor. A closed path cut once stays one open path. The paths a Scissors cut (`path.split`) or Cut Path at Selected Anchor Points (`path.cutAtAnchors`) makes keep the source path's fill and stroke settings, and every stroke's alignment becomes Center in the same undo step, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/split-paths.html) describes. Resetting hidden stroke rows too, centering the strokes of a path's other subpaths and of the compound path a cut member belongs to are VectorCraft's own rules (`scissors_cut_paths_have_their_strokes_centered`, `cut_at_anchors_paths_have_their_strokes_centered`). While Alt is held, the Scissors tool works as the Add Anchor Point tool ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)): a click on a segment adds an anchor point without cutting (`path.insertAnchor`), and the pointer shows the Add Anchor Point cursor. When Alt is let go, a click cuts again. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d131053a67..957cfa9479 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -25,7 +25,7 @@ ## Feature submission evidence -**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged. Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. @@ -204,12 +204,12 @@ tools, never checked side by side) isn't captured row by row. | Pen cursors (new path ×, continue /, close o, add +, delete −, convert ^) | done | the nib is a fountain-pen nib, tip on the hotspot, with the slit widening into the breather hole and the heel clipped square to its axis; bitmap tests at 1× and 2× pin the nib and the new-path asterisk, and in-app screenshots compare the Pen with Direct Selection | | Node-editing cursors: Direct Selection's white arrow with a hollow or filled square over an anchor (path unselected or selected); the Reshape Segment cursor over a curved segment (Direct Selection, Anchor Point, the Pen with Alt); the Anchor Point caret for the Pen with Alt; Group Selection's plus (also Direct Selection with Alt); a filled arrow while dragging that turns hollow on a snap; a double arrowhead for an Alt-drag copy | partial | as the public manual describes them, drawn in code; no cue over handles (none documented) | | Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge | -| Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping (#6470) | implemented | Existing Smart Guides, Snap to Point, pixel and grid options apply; Pixel Preview turns off Smart Guides. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions: `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. | -| Scissors cut-point preview (#8655) | implemented | Native marker at the actual anchor or curve target; current snapping, cut and Alt Add Anchor behavior retained. `crates/tools/src/draw2/anchor/tests.rs`, `crates/engine/tests/scissors_snap.rs`. | +| Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping (#6470) | implemented | Existing Smart Guides, Snap to Point, pixel and grid options apply; Pixel Preview turns off Smart Guides. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions: `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. | +| Scissors cut-point preview (#8655) | implemented | Native marker at the actual anchor or curve target; current snapping, cut and Alt Add Anchor behavior retained. `crates/tools/src/draw2/anchor/tests.rs`, `crates/engine/tests/it/scissors_snap.rs`. | | Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it | | Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview | | Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | -| Eraser: filled open paths and compound holes | partial | Fill-only open paths preserve fill outside sweeps and Alt-drag marquees and keep compound holes under their fill rule (#6582). Path or Compound clipping masks retain all surviving contours or empty geometry in the same node, preserving the mask role; Path Eraser shares this behavior. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Focused engine tests cover fixed and varied tips and Alt-drag marquees on open/closed geometry, raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. `crates/engine/tests/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Filled-and-stroked open paths retain main behavior; that fill behavior is not claimed fixed. See G11 in [gaps.md](gaps.md#g11-correctness-bugs-in-core-tools). | +| Eraser: filled open paths and compound holes | partial | Fill-only open paths preserve fill outside sweeps and Alt-drag marquees and keep compound holes under their fill rule (#6582). Path or Compound clipping masks retain all surviving contours or empty geometry in the same node, preserving the mask role; Path Eraser shares this behavior. Bounds-fitted gradients on ordinary paths, compounds, groups and layers keep their original evaluated placement when it can be reproduced in the stored paint. Effects that draw replacement artwork, effect plug-ins, Rasterize, gradients along or across a stroke, and flattened placements or placements that cannot reproduce the original appearance keep their existing fitted behavior. Hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving a visible gradient. Already placed gradients and live-effect settings are retained; changes to a live effect's geometry can still move its paint. Focused engine tests cover fixed and varied tips and Alt-drag marquees on open/closed geometry, raster output, compound holes and self-crossing fill, plus a painted-stroke outline control and clipping-mask split, empty-mask and Path Eraser cases. `crates/engine/tests/it/eraser_open_fill.rs` also includes container-own paint and evaluated-placement regression cases. Filled-and-stroked open paths retain main behavior; that fill behavior is not claimed fixed. See G11 in [gaps.md](gaps.md#g11-correctness-bugs-in-core-tools). | | Knife cursor | done | a knife, the blade's point on the hotspot, white blade and black handle, for the Knife and the Trim at Crossings Tool; the crosshair with Use Precise Cursors; `the_knife_shows_a_knife_with_its_point_on_the_hotspot`, `drawing_tools_show_their_own_cursor` | | Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). | | Eraser: an Alt-drag draws a marquee and the release erases everything inside it (closed shapes and fill-only open paths lose the rectangle's area, other open paths are cut where they cross its edges); Alt+Shift keeps the marquee square; Escape cancels it, and a click erases nothing | done | `path.eraseRegion {rect}`; [public behavior reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133); `eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle`, `eraser_alt_shift_drag_keeps_the_marquee_square`, `eraser_marquee_click_or_escape_erases_nothing`, `erase_region_rect_erases_everything_inside_it`, `erase_region_rect_refuses_bad_values` | @@ -250,7 +250,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| -| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/path_fill_hits.rs`; hidden-fill and no-fill stroke cap/join CPU regressions passed | +| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/it/path_fill_hits.rs`; hidden-fill and no-fill stroke cap/join CPU regressions passed | | Backquote/~ arrow nudges move selected pattern fills and strokes | done | #7717: Selection, partial-anchor Direct Selection and other idle tools; Keyboard Increment/Shift; geometry, guides and anchor selection stay fixed. Tests: `crates/ui-egui/tests/pattern_only_nudge.rs` | | Deleting segments or anchors that disconnect an ordinary path creates independent selected objects | done | #3380, deletion only: first piece retains its ID, styles and transforms carry over in sibling order, bounds-fitted gradients keep their original placement, and one Undo restores the original. Existing multi-subpath paths and compound members stay intact. `delete_path_pieces` covers transformed/styled rectangles, cubic handles and Undo/Redo. Endpoint highlighting remains open. | | Click/Shift-click anchors; marquee toggles with Shift | done | #483 | @@ -269,7 +269,7 @@ tools, never checked side by side) isn't captured row by row. | Drag a curved segment to bend it, a straight one to move its anchors | done | | | Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 | | Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 | -| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | +| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/it/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | | Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display | | Convert selected anchors to corner/smooth from the Control bar and Properties | done | | | Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | @@ -405,7 +405,7 @@ tools, never checked side by side) isn't captured row by row. | Artboard Options › Display: Show Center Mark and Show Cross Hairs ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/modify-display-settings-of-artboards.html)) | done | Per-artboard checkboxes (`artboard.setProps`/`artboard.new` `showCenterMark`, `showCrossHairs`, one undo step); the canvas draws a cross 12 points across on screen at the center and lines from the middle of each side through it, 1 point wide on screen at any zoom and turned with the view; exports and print leave them out; tests `an_artboard_shows_its_center_mark_and_cross_hairs`, `artboard_options_show_center_mark_and_cross_hairs` | | View › Hide Artboards (Ctrl/Cmd+Shift+H) hides the artboards' edges, bleeds, marks and names and shows the whole canvas as paper (white, or Simulate Colored Paper's colour); the Artboard tool still shows them | done | #4038, `canvas::tests::hidden_artboards_leave_a_paper_canvas_without_edges` | | Artboard Options › Display: Show Video Safe Areas and Video Ruler Pixel Aspect Ratio ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)) | done | #2849; per artboard (`artboard.setProps`/`artboard.new` `showVideoSafeAreas`, `videoRulerPixelAspectRatio` 0.1–10, default 1; one undo step; native format). The page gives no safe-area numbers: our choice is [EBU R 95](https://tech.ebu.ch/docs/r/r095.pdf)'s, the action-safe area 3.5% and the title-safe area 5% in from each edge, outlined 1 point wide on the canvas and turned with the view; exports and print leave them out. Tests `an_artboard_shows_its_video_safe_areas`, `artboard_options_show_video_display_options`, `artboard_video_display_options_*` | -| Shape tools: Shift constrains, Alt from centre, Space moves while dragging, arrows change sides/points/rows and Ellipse anchors | done | #7840: Ellipse Up/Down changes the remembered Anchors count within 2…1000; four anchors keep a live ellipse, other counts a plain path. Release is one undo step; Escape restores the earlier count unless explicitly updated with `tool.setOption`. `crates/engine/tests/ellipse_drag_anchors.rs` | +| Shape tools: Shift constrains, Alt from centre, Space moves while dragging, arrows change sides/points/rows and Ellipse anchors | done | #7840: Ellipse Up/Down changes the remembered Anchors count within 2…1000; four anchors keep a live ellipse, other counts a plain path. Release is one undo step; Escape restores the earlier count unless explicitly updated with `tool.setOption`. `crates/engine/tests/it/ellipse_drag_anchors.rs` | | Eraser: Shift-drag erases along a horizontal, vertical or diagonal line ([public source](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=82)) | done | the line runs from the press point at the 45° step from the Constrain Angle nearest the pointer, taken once the pointer is 3 screen pixels from the press and kept until Shift is released; the tip outline follows the line; released, the drag goes on freehand from the last point on the line, and Shift again takes a new step from the press point (VectorCraft's own rules); `eraser_shift_keeps_the_stroke_on_a_45_degree_line` in `crates/tools/src/draw2/gesture/tests.rs` | | Polygon/Star exact-size placement remembers the chosen sides/points for later drags and dialog openings; Cancel preserves the previous count | done | Session tool options; existing dialog-opening gestures retained; regression in `toolbar.rs` | | Tool double-click opens its options | done | | From 83a8e775d47f0a0bfb693a625badf0fdb7e25d49 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:34:14 -0800 Subject: [PATCH 26/37] Graphics: start on Mesa's software renderer when no adapter can show the window Part of #2654. On Linux and the BSDs, when no graphics adapter could show the window (no wgpu backend started, or the restarts left no adapter), the app ended. It now starts once more with LIBGL_ALWAYS_SOFTWARE=1 and VECTORCRAFT_GPU_SOFTWARE=1 and says in the status bar that it draws on the CPU. When that start also fails, or on Windows and macOS, or with WGPU_BACKEND, WGPU_ADAPTER_NAME or LIBGL_ALWAYS_SOFTWARE set, the error names the backends the driver needs. wgpu draws with Vulkan, OpenGL 3.3 or OpenGL ES 3.0. Intel's Ironlake graphics (8086:0046) has OpenGL 2.1 alone, so the window's surface failed with "Failed to create surface for any enabled backend: {}" before any adapter was listed, and gpu::finish restarted only without an adapter that had been picked. --- apps/vectorcraft/src/gpu.rs | 133 ++++++++++++++++++++++++++---- apps/vectorcraft/src/gpu/tests.rs | 49 +++++++++-- apps/vectorcraft/src/main.rs | 8 +- docs/development.md | 2 + 4 files changed, 169 insertions(+), 23 deletions(-) diff --git a/apps/vectorcraft/src/gpu.rs b/apps/vectorcraft/src/gpu.rs index 198e7dcc85..f71cc434ba 100644 --- a/apps/vectorcraft/src/gpu.rs +++ b/apps/vectorcraft/src/gpu.rs @@ -32,6 +32,12 @@ //! that adapter, as the next one in the order would be tried. Each restart leaves out one more //! adapter, so it ends when none is left. //! +//! When no adapter is picked at all, because none is left or no graphics backend started (wgpu +//! needs Vulkan, OpenGL 3.3 or OpenGL ES 3.0, and the driver of Intel's Ironlake graphics offers +//! none of them, so the window's surface failed "for any enabled backend" with no backend listed, +//! #2654), Linux and the BSDs start once more on Mesa's software renderer ([`Software`]); after +//! that, the error that ends the app says what the graphics driver needs. +//! //! An adapter can also hang instead of failing: on a hybrid laptop with High Performance chosen, //! the discrete GPU never put the window's first frame on the screen, with no error and no panic, //! and the app stayed in the background without a window (#964). [`watch_first_frame`] gives the @@ -853,7 +859,7 @@ pub fn watch_first_frame(startup: Arc) { // The new app records its own start. startup.ended(); skip.push(failed.to_string()); - match restart(&skip.join(",")) { + match restart(&skip.join(","), false) { Ok(()) => std::process::exit(0), Err(e) => { log::error!("starting again failed: {e}"); @@ -950,6 +956,94 @@ fn restart_without<'a>(graphics_failed: bool, frames: u64, picked: Option<&'a st picked.filter(|p| graphics_failed && frames < STARTUP_FRAMES && !skip.iter().any(|s| s == p)) } +/// Whether a start whose window no graphics adapter could show may start again on Mesa's software +/// renderer, which draws OpenGL on the CPU (llvmpipe). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Software { + /// Linux and the BSDs, where Mesa provides OpenGL, and this start isn't on it yet. + Possible, + /// This start already draws on it: the app started again with [`SOFTWARE_ENV`], or the user + /// set `LIBGL_ALWAYS_SOFTWARE`. + Tried, + /// Windows and macOS, or a start that `WGPU_BACKEND` or `WGPU_ADAPTER_NAME` chooses. + Unavailable, +} + +impl Software { + /// This start's [`Software`], from the platform and the environment. + pub fn from_env() -> Self { + if cfg!(any(windows, target_os = "macos")) || explicit_choice() { + Software::Unavailable + } else if software_start() || std::env::var_os("LIBGL_ALWAYS_SOFTWARE").is_some() { + Software::Tried + } else { + Software::Possible + } + } +} + +/// Set by the app when it starts again on Mesa's software renderer because no graphics adapter +/// could show the window (#2654). +pub const SOFTWARE_ENV: &str = "VECTORCRAFT_GPU_SOFTWARE"; + +/// Whether this start is the one the app made on Mesa's software renderer ([`SOFTWARE_ENV`]). +pub fn software_start() -> bool { + std::env::var_os(SOFTWARE_ENV).is_some() +} + +/// The graphics APIs the window can draw with on this platform, for the error that ends the app +/// when no adapter can show it and for the note of a start on Mesa's software renderer. +pub const NEEDS: &str = if cfg!(windows) { + "Direct3D 12, OpenGL 3.3 or OpenGL ES 3.0" +} else if cfg!(target_os = "macos") { + "Metal" +} else { + "Vulkan, OpenGL 3.3 or OpenGL ES 3.0" +}; + +/// What follows the window's run ([`next`]). +#[derive(Debug, PartialEq, Eq)] +enum Next { + /// The window closed normally. + Done, + /// Start again without the adapters in `skip`, on Mesa's software renderer when `software`. + Restart { skip: Vec, software: bool }, + /// End the app with this error. + Stop(String), +} + +/// What follows the window's run: `why` it failed (`None` when it closed normally), whether the +/// graphics failed, the `frames` the UI ran, the adapter `picked`, those left out (`skip`) and +/// whether the software renderer is still to try. A failure on an adapter while starting up starts +/// again without it. When no adapter was picked, because none can show the window or no graphics +/// backend started at all (an old GPU whose driver offers neither Vulkan nor OpenGL 3.3 or OpenGL +/// ES 3.0, such as Intel's Ironlake graphics, #2654), Linux and the BSDs start once more on Mesa's +/// software renderer, and after that the error says what the window needs. +fn next(why: Option, graphics_failed: bool, frames: u64, picked: Option<&str>, mut skip: Vec, software: Software) -> Next { + let Some(why) = why else { return Next::Done }; + if let Some(failed) = restart_without(graphics_failed, frames, picked, &skip) { + log::error!("the window failed on graphics adapter {failed} ({why}): starting again without it"); + skip.push(failed.to_string()); + return Next::Restart { skip, software: false }; + } + if !graphics_failed { + return Next::Stop(why); + } + if picked.is_some() || frames >= STARTUP_FRAMES { + return Next::Stop(format!("{why} ({HELP})")); + } + match software { + Software::Possible => { + log::error!("no graphics adapter could show the window ({why}): starting again on Mesa's software renderer, which draws on the CPU"); + Next::Restart { skip, software: true } + } + Software::Tried => Next::Stop(format!( + "{why}: no graphics adapter could show the window, not even Mesa's software renderer (the graphics driver needs {NEEDS}; {HELP})" + )), + Software::Unavailable => Next::Stop(format!("{why}: no graphics adapter could show the window (the graphics driver needs {NEEDS}; {HELP})")), + } +} + /// After the window's run: `Ok` when it closed normally or the app started again (see the module /// docs), otherwise why it failed. `outcome` is eframe's result, or the message of a panic that /// ended it. @@ -957,28 +1051,35 @@ pub fn finish(outcome: Result, startup: &Startup) -> Res // Whatever follows, this start didn't crash; a new app records its own start. startup.ended(); let (why, graphics_failed) = match outcome { - Ok(Ok(())) => return Ok(()), - Ok(Err(e @ eframe::Error::Wgpu(_))) => (e.to_string(), true), - Ok(Err(e)) => (e.to_string(), false), - Err(panic) => (panic, GRAPHICS_PANIC.load(Ordering::Relaxed)), + Ok(Ok(())) => (None, false), + Ok(Err(e @ eframe::Error::Wgpu(_))) => (Some(e.to_string()), true), + Ok(Err(e)) => (Some(e.to_string()), false), + Err(panic) => (Some(panic), GRAPHICS_PANIC.load(Ordering::Relaxed)), }; let frames = startup.ui.get().map_or(0, egui::Context::cumulative_frame_nr); - let mut skip = skipped(); - let Some(failed) = restart_without(graphics_failed, frames, startup.adapter.get().map(String::as_str), &skip) else { - return Err(if graphics_failed { format!("{why} ({HELP})") } else { why }); - }; - log::error!("the window failed on graphics adapter {failed} ({why}): starting again without it"); - skip.push(failed.to_string()); - restart(&skip.join(",")).map_err(|e| format!("{why}; starting again failed: {e}")) + let picked = startup.adapter.get().map(String::as_str); + match next(why.clone(), graphics_failed, frames, picked, skipped(), Software::from_env()) { + Next::Done => Ok(()), + Next::Stop(e) => Err(e), + Next::Restart { skip, software } => { + let why = why.unwrap_or_default(); + restart(&skip.join(","), software).map_err(|e| format!("{why}; starting again failed: {e}")) + } + } } -/// Start the app again with the same arguments, leaving out the adapters in `skip`. On Unix the -/// new app replaces this process (same process id, so an AppImage keeps its files mounted), and -/// this returns only on failure; on Windows it starts beside this one, which then exits. -fn restart(skip: &str) -> std::io::Result<()> { +/// Start the app again with the same arguments, leaving out the adapters in `skip`, and on Mesa's +/// software renderer when `software` (`LIBGL_ALWAYS_SOFTWARE`, with [`SOFTWARE_ENV`] so it is +/// tried once). On Unix the new app replaces this process (same process id, so an AppImage keeps +/// its files mounted), and this returns only on failure; on Windows it starts beside this one, +/// which then exits. +fn restart(skip: &str, software: bool) -> std::io::Result<()> { log::logger().flush(); let mut c = std::process::Command::new(std::env::current_exe()?); c.args(std::env::args_os().skip(1)).env(SKIP_ENV, skip); + if software { + c.env("LIBGL_ALWAYS_SOFTWARE", "1").env(SOFTWARE_ENV, "1"); + } #[cfg(unix)] { use std::os::unix::process::CommandExt as _; diff --git a/apps/vectorcraft/src/gpu/tests.rs b/apps/vectorcraft/src/gpu/tests.rs index 792518993d..4b660854f6 100644 --- a/apps/vectorcraft/src/gpu/tests.rs +++ b/apps/vectorcraft/src/gpu/tests.rs @@ -602,15 +602,52 @@ fn only_a_graphics_failure_while_starting_up_restarts_without_the_adapter() { fn a_normal_exit_or_another_failure_does_not_restart() { let startup = Startup::default(); assert_eq!(finish(Ok(Ok(())), &startup), Ok(())); - // No adapter was picked (none can show the window): the error is returned, nothing restarts. - let none = eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::CustomNativeAdapterSelectionError("no graphics adapter can show the window".into())); - assert_eq!( - finish(Ok(Err(none)), &startup), - Err(format!("WGPU error: Adapter selection failed: no graphics adapter can show the window ({HELP})")) - ); let _ = startup.adapter.set("Vulkan:1002:164e".into()); GRAPHICS_PANIC.store(false, Ordering::Relaxed); assert_eq!(finish(Err("a bug".into()), &startup), Err("a bug".into())); + // The same, decided without starting anything. + let amd = Some("Vulkan:1002:164e"); + for software in [Software::Possible, Software::Tried, Software::Unavailable] { + assert_eq!(next(None, false, 0, amd, vec![], software), Next::Done); + assert_eq!(next(Some("a bug".into()), false, 0, None, vec![], software), Next::Stop("a bug".into())); + // A failure after start-up, or on an adapter already left out, is not the start's. + assert_eq!(next(Some("lost".into()), true, STARTUP_FRAMES, amd, vec![], software), Next::Stop(format!("lost ({HELP})"))); + let skip = vec!["Vulkan:1002:164e".to_string()]; + assert_eq!(next(Some("lost".into()), true, 0, amd, skip, software), Next::Stop(format!("lost ({HELP})"))); + } + // An adapter that failed while starting up is left out, never with the software renderer. + assert_eq!( + next(Some("lost".into()), true, 0, amd, vec!["Gl:8086:0046".into()], Software::Possible), + Next::Restart { skip: vec!["Gl:8086:0046".into(), "Vulkan:1002:164e".into()], software: false } + ); +} + +/// #2654: on a ThinkPad T510 with Intel's Ironlake graphics, whose driver offers neither Vulkan +/// nor OpenGL 3.3 or OpenGL ES 3.0, wgpu started no backend, so the window's surface failed before +/// any adapter was listed and the app ended; started with `LIBGL_ALWAYS_SOFTWARE=1`, it ran on +/// llvmpipe. With no adapter picked, Linux starts once more on Mesa's software renderer, keeping +/// the adapters already left out, and the error after that says what the driver needs. +#[test] +fn a_start_no_adapter_can_show_tries_the_software_renderer_once() { + let surface = "WGPU error: Failed to create surface for any enabled backend: {}"; + let skip = vec!["Vulkan:8086:0046".to_string()]; + assert_eq!(next(Some(surface.into()), true, 0, None, skip.clone(), Software::Possible), Next::Restart { skip: skip.clone(), software: true }); + // No adapter left that can show the window, after restarts without each. + let none = "WGPU error: Adapter selection failed: no graphics adapter can show the window"; + assert_eq!(next(Some(none.into()), true, 0, None, skip.clone(), Software::Possible), Next::Restart { skip: skip.clone(), software: true }); + // Already on the software renderer: the app ends, saying what the window needs. + let Next::Stop(tried) = next(Some(surface.into()), true, 0, None, skip.clone(), Software::Tried) else { + panic!("a start already on the software renderer starts again") + }; + assert!(tried.starts_with(surface), "{tried}"); + assert!(tried.contains("not even Mesa's software renderer") && tried.contains(NEEDS) && tried.contains(HELP), "{tried}"); + // Windows, macOS or a backend the user chose: no software renderer to start on. + let Next::Stop(unavailable) = next(Some(surface.into()), true, 0, None, skip, Software::Unavailable) else { + panic!("a start without the software renderer starts again") + }; + assert!(unavailable.contains(NEEDS) && unavailable.contains(HELP) && !unavailable.contains("Mesa"), "{unavailable}"); + // A failure outside the graphics never starts again. + assert_eq!(next(Some("a bug".into()), false, 0, None, vec![], Software::Possible), Next::Stop("a bug".into())); } /// A log folder of its own for each test. diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 6ab6778597..b34c3c23d9 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -920,7 +920,13 @@ fn main() -> std::process::ExitCode { let summary = adapter_summary(&rs.adapter.get_info()); log::info!("rendering with {summary} (power preference {power:?})"); created.created(&cc.egui_ctx); - if !gpu::skipped().is_empty() { + if gpu::software_start() { + // No graphics processor could show the window, so Mesa draws it on the CPU (#2654). + app.status(format!( + "No graphics processor could show the window, so VectorCraft started again on {summary}, which draws on the CPU and is slower. Showing it on the graphics processor needs a driver with {}", + gpu::NEEDS + )); + } else if !gpu::skipped().is_empty() { // A processor chosen in Settings can be the one that can't show the window. if chosen_gpu { app.status(format!( diff --git a/docs/development.md b/docs/development.md index 5a1b6efd95..3a1f06fd39 100644 --- a/docs/development.md +++ b/docs/development.md @@ -74,6 +74,7 @@ The canvas is rasterized on the CPU (`vectorcraft-render`, vello_cpu); the GPU ( - **Automatic on Linux and the BSDs** is the GPU that drives the panel or a monitor, then the system's order: Mesa's Vulkan device-select layer puts the GPU the desktop runs on first (the integrated one on hybrid laptops; `DRI_PRIME` and `MESA_VK_DEVICE_SELECT` steer it). A Wayland compositor may not accept frames from another GPU: on a desktop whose compositor ran on an NVIDIA GPU, rendering on the Ryzen's integrated GPU made KWin end the window's connection ("importing the supplied dmabufs failed") and 0.5.0 crashed at startup (#502). - 0.5.0 saved `powerSaving`, its default, for everyone; it reads as `automatic`. - **If the window fails on its adapter while starting up** (an error from wgpu, or a panic inside wgpu or egui-wgpu during the first frames), the app starts again without that adapter and tries the next one, telling which in the status bar; the run that failed keeps its log as `vectorcraft.1.log`. On Unix the new app replaces the process (an AppImage stays mounted); on Windows it starts beside it. Adapters are told apart by backend and PCI ids, or by name where the backend reports no ids (Metal lists every GPU of a dual-GPU Mac as `0000:0000`, #651). The adapters left out travel in `VECTORCRAFT_GPU_SKIP` (`backend:vendor:device`, such as `Vulkan:1002:164e`), one more on each restart, so the restarts end. When no adapter is left, the app logs why and exits with an error instead of panicking. +- **If no graphics adapter can show the window at all** on Linux or a BSD, the app starts once more on Mesa's software renderer (llvmpipe, through `LIBGL_ALWAYS_SOFTWARE=1`), which draws on the CPU and is slower, and says so in the status bar. That covers every adapter left out by the restarts above, and a GPU whose driver offers none of the backends wgpu draws with: Vulkan, OpenGL 3.3 or OpenGL ES 3.0. Intel's Ironlake graphics (PCI id `8086:0046`, in a ThinkPad T510) has OpenGL 2.1 alone, so wgpu started no backend and the window failed with `Failed to create surface for any enabled backend: {}` (#2654). The software start carries `VECTORCRAFT_GPU_SOFTWARE`, so it happens once; when it fails too, or when `WGPU_BACKEND`, `WGPU_ADAPTER_NAME` or `LIBGL_ALWAYS_SOFTWARE` is set, the app exits with an error that names the backends the driver needs. On a laptop with a second GPU, choosing that GPU in the firmware settings may give a driver with one of these backends. - **If the window's first frame never reaches the screen** within 20 seconds of the app being created (the files named at the start opened), the adapter counts as hanging and the app starts again without it in the same way (#964: High Performance on a hybrid laptop left the app running in the background with no window and nothing in the log). A window minimized at the start isn't counted. When the processor that hung was chosen in Preferences, the status bar points to Automatic. - **If the app crashes while the window starts**, as when Intel's Direct3D 12 driver (`igd12umd64.dll`) ended 0.9.0 before its window appeared on an Intel UHD Graphics 605 (#2243), no code in the process runs to start it again, so the next start leaves the adapter out. Each start writes `graphics-start.json` in the log folder before the graphics start and adds the adapter once one is picked; when the first frame reaches the screen or the app ends without crashing, the start is cleared from the file. A start that finds an earlier start still recorded there logs the adapter, leaves it out and shows a note in the status bar. When the crash came while the adapters were being listed (wgpu's Direct3D 12 backend creates a device on each GPU to list it), the next start lists OpenGL's adapters alone; on macOS, where wgpu has no OpenGL adapters, it lists them all. Later starts keep leaving them out until the app version or Preferences › Performance › Graphics Processor changes, a start shows its first frame on the adapter that crashed, or no adapter is left that can show the window. `WGPU_BACKEND` and `WGPU_ADAPTER_NAME` choose regardless of the file: a start with `WGPU_BACKEND=dx12` tries Direct3D 12 again, and when its first frame appears, the crash is cleared. A process ended from outside during the start (Task Manager, `kill`) counts as a crash. Runs without preferences (`VECTORCRAFT_NO_PREFS`) record nothing, and a start made while another copy of the app is starting neither reads nor writes the file. - **To recover from a Graphics Processor choice that doesn't work** without editing files: start once with `WGPU_POWER_PREF=low` (or `WGPU_ADAPTER_NAME=…`), which overrides the preference for that start while settings still save, and set Graphics Processor back to Automatic. `VECTORCRAFT_NO_PREFS=1` also starts without it, but saves nothing. @@ -109,6 +110,7 @@ When the interface thread stays in one part of a frame for 3 s (VectorCraft's ow | `WGPU_ADAPTER_NAME` | Graphics adapter by (part of) its name, any case (see [Desktop graphics processor](#desktop-graphics-processor)) | | `WGPU_BACKEND` | Graphics backends: `vulkan`, `dx12`, `metal`, `gl` | | `VECTORCRAFT_GPU_SKIP` | Set by the app when it starts again without a graphics adapter that failed (see [Desktop graphics processor](#desktop-graphics-processor)) | +| `VECTORCRAFT_GPU_SOFTWARE` | Set by the app, with `LIBGL_ALWAYS_SOFTWARE=1`, when it starts again on Mesa's software renderer because no graphics adapter could show the window (Linux and the BSDs; see [Desktop graphics processor](#desktop-graphics-processor)) | | `RUST_LOG` | Log levels for standard error and the log file (see [Logs](#logs)) | ## macOS: the menu bar From 49344097e40c724d9c5c21fe9a1cd6664f067601 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:39:42 -0800 Subject: [PATCH 27/37] Docs: keep the original preflight test command in the 2026-11-18 record The 2026-11-18 validation ran when preflight was its own test binary, so the record keeps `--test preflight`. A separate line gives the current command, `--test it preflight::`. --- docs/production-preflight.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/production-preflight.md b/docs/production-preflight.md index 77698662d8..cc84d2ef59 100644 --- a/docs/production-preflight.md +++ b/docs/production-preflight.md @@ -52,7 +52,7 @@ The same read-only report is available through `document.preflight`; see [MCP](m Checked on Windows with Rust 1.99.1, based on `main` at `36b5a5920c`: -- Engine integration tests: 9 passed (`cargo test -p vectorcraft-engine --test it preflight::`). +- Engine integration tests: 9 passed (`cargo test -p vectorcraft-engine --test preflight`). - Panel tests: 5 passed (`cargo test -p vectorcraft-ui-egui --lib preflight`), including pointer selection/zoom, edits and Undo, document switching, external-file polling and explicit Recheck. - Both test commands used `--offline --target-dir target --config profile.test.opt-level=0`. @@ -77,6 +77,9 @@ WebAssembly Clippy run also encounters existing target-specific lints in unchang (`drop_non_drop`) and `font_menu.rs` (`unnecessary_lazy_evaluations`); the WebAssembly typecheck and the native Clippy run above pass without source changes for those findings. +The engine preflight tests now live in the `it` test binary. Run them with +`cargo test -p vectorcraft-engine --test it preflight::`. + ### Review follow-up on `main` at `ee60c51fd` The exact-threshold and locked-artboard regressions were first run against the original From 5321337ce845efb5bef7834388b1d01bcb145742 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:42:57 -0800 Subject: [PATCH 28/37] Open: say when a file dialog is already open instead of waiting silently On some Wayland compositors the system file dialog can open as its own window out of sight. Pressing Open again on the Home screen then queued a second picker behind the first and showed nothing, so Open seemed to do nothing at all (#6160). - File > Open, Open With and Install Plug-in refuse a new picker while a file dialog is still open and say so in the status bar. - The Home screen's New, Open, template and Clear Recent buttons report a failed command in the status bar instead of dropping it. - An open picker that fails (the browser could not read the file) says why instead of being taken for a cancel. Part of #6160 --- crates/ui-egui/src/canvas/home.rs | 15 ++++++++++----- crates/ui-egui/src/io/open.rs | 9 ++++++++- crates/ui-egui/src/tests/home.rs | 20 ++++++++++++++++++++ crates/ui-egui/src/tests/picks.rs | 25 +++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas/home.rs b/crates/ui-egui/src/canvas/home.rs index d95cdc02e1..5034e23f17 100644 --- a/crates/ui-egui/src/canvas/home.rs +++ b/crates/ui-egui/src/canvas/home.rs @@ -73,15 +73,20 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { } } -/// What the start screen's user did. +/// What the start screen's user did. A command that fails says why in the status bar (#6160). fn run_action(app: &mut VectorcraftApp, action: StartAction) { + fn run(app: &mut VectorcraftApp, id: &str, params: serde_json::Value) { + if let Err(e) = app.run(id, params) { + app.status(e); + } + } match action { - StartAction::New => drop(app.run("file.newDialog", json!({}))), - StartAction::Open => drop(app.run("file.open", json!({}))), + StartAction::New => run(app, "file.newDialog", json!({})), + StartAction::Open => run(app, "file.open", json!({})), // A failure is reported to the user there. StartAction::OpenRecent(path) => drop(crate::io::open_reporting(app, &path.to_string_lossy())), - StartAction::UseTemplate(name) => drop(app.run("file.new", json!({ "preset": name }))), - StartAction::ClearRecent => drop(app.run("file.clearRecent", json!({}))), + StartAction::UseTemplate(name) => run(app, "file.new", json!({ "preset": name })), + StartAction::ClearRecent => run(app, "file.clearRecent", json!({})), StartAction::RemoveRecent(path) => app.ui.recent_files.retain(|recent| std::path::Path::new(recent) != path), StartAction::RevealRecent(path) => { // PLAN: `io::export` is a private module of `io`; `reveal_path` needs a re-export from io.rs (unowned). diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 673f78af10..e5c59365b1 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -233,13 +233,19 @@ fn open_request<'a>(purpose: &str, folder: Option, filters: impl IntoIte /// Asks for a file to open with `request`; `then` gets its path. The web answers with the file's /// bytes, which open as File › Open opens them (the extension decides). A cancelled picker runs -/// nothing. While it is open the reply is `{pending: "fileDialog"}`. +/// nothing, and a picker that failed (the browser could not read the file) reports why. While it is +/// open the reply is `{pending: "fileDialog"}`. While another file dialog is still open, which can +/// be a window the system placed out of sight, the reply is an error saying so (#6160): a second +/// picker would only wait behind the first. fn ask_open( app: &mut VectorcraftApp, request: PickRequest, owner: Owner, then: impl FnOnce(&mut VectorcraftApp, String) -> Result + 'static, ) -> Result { + if app.file_dialog_open() { + return Err(file_asks::busy().into()); + } Ok(file_asks::ask(app, request, owner, move |app, picked| match picked { Picked::Contents(files) => { for (name, bytes) in &files { @@ -247,6 +253,7 @@ fn ask_open( } Ok(Value::Null) } + Picked::Failed(error) => Err(error), picked => match picked.first_path() { Some(path) => then(app, path.to_string_lossy().into_owned()), None => Err("cancelled".into()), diff --git a/crates/ui-egui/src/tests/home.rs b/crates/ui-egui/src/tests/home.rs index 5ccb6412a9..904de40932 100644 --- a/crates/ui-egui/src/tests/home.rs +++ b/crates/ui-egui/src/tests/home.rs @@ -125,6 +125,26 @@ fn home_screen(app: VectorcraftApp) -> Panel { home } +/// Home's Open while a file dialog is still open (a window the system may have placed out of sight) +/// says so in the status bar and asks for no second picker; once the first answers, Open asks again +/// (#6160). +#[test] +fn home_open_while_a_file_dialog_is_open_says_so() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let picker = crate::tests::picks::scripted(&mut app); + let mut home = home_screen(app); + home.click("Open"); + assert_eq!(picker.requests().len(), 1); + assert!(home.app().ui.status.is_empty()); + home.click("Open"); + assert_eq!(picker.requests().len(), 1, "no second picker waits behind the first"); + assert_eq!(home.app().ui.status, crate::file_asks::busy()); + picker.cancel(); + crate::file_asks::poll(&mut home.app()); + home.click("Open"); + assert_eq!(picker.requests().len(), 2, "Open asks again once the first dialog answered"); +} + /// The Home screen lists the first recent files (#663); opening one that can't be opened says so. #[test] fn home_lists_recent_files_and_a_click_opens_one() { diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index 851d438904..1d521af1c0 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -49,6 +49,10 @@ impl Picker { pub(crate) fn cancel(&self) { self.files.answer(Picked::Cancelled); } + /// The newest open pick fails with `why`, as the browser's picker does when it cannot read the file. + pub(crate) fn fail(&self, why: &str) { + self.files.answer(Picked::Failed(why.into())); + } /// The bytes a save through the service (`Files::save`) wrote to `path`. pub(crate) fn file(&self, path: &str) -> Option> { self.files.file(std::path::Path::new(path)) @@ -197,6 +201,27 @@ fn app() -> VectorcraftApp { VectorcraftApp::new(Session::new(), Services::default()) } +/// File › Open and Install Plug-in ask for no second picker while a file dialog is still open, and +/// say so; an open picker that fails says why, and opens nothing (#6160). +#[test] +fn an_open_picker_is_refused_while_a_dialog_is_open_and_a_failed_one_says_why() { + for command in ["file.open", "ui.installPlugin"] { + let mut app = app(); + let picker = scripted(&mut app); + asks(&mut app, command); + for again in ["file.open", "ui.installPlugin"] { + assert_eq!(app.run(again, json!({})), Err(file_asks::busy().to_string()), "{again} after {command}"); + } + assert_eq!(picker.requests().len(), 1, "no second picker waits behind the first after {command}"); + picker.fail("the file could not be read"); + settle(&mut app); + assert_eq!(app.ui.status, "the file could not be read", "{command}"); + assert!(app.session.documents().is_empty(), "{command}"); + asks(&mut app, command); + assert_eq!(picker.requests().len(), 2, "{command} asks again once the first answered"); + } +} + /// The picks' answers, then the rest of a frame's pumps (Save Changes goes on once its save is written). fn settle(app: &mut VectorcraftApp) { let ctx = app.ui_ctx.clone().unwrap_or_default(); From 0b3cf56b81e34da4fcbe87566043f4bee16615bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 06:59:34 -0800 Subject: [PATCH 29/37] Graphics: closing the window after a lost device no longer panics After the graphics device is lost, a frame the device could not present stays acquired by the window's surface. When the window closed, eframe released the surface, and wgpu's Vulkan backend panicked with "Trying to destroy a SwapchainAcquireSemaphore that is still in use by a SurfaceTexture" (gfx-rs/wgpu#9277), so the app stopped with an error. GraphicsLoss now remembers that a loss happened after the frame handled the report. When the window closes after a loss, the process ends in on_exit once the app has saved what it keeps on quitting, before the window's graphics are torn down, on every platform. This is the exit the macOS accessibility quit already takes (#661); a loss during start-up still goes to the adapter restart (#651). Fixes #6374 --- apps/vectorcraft/src/app.rs | 62 ++++++++++++++++++++++++++++------ crates/ui-egui/src/graphics.rs | 39 +++++++++++++++++++-- 2 files changed, 88 insertions(+), 13 deletions(-) diff --git a/apps/vectorcraft/src/app.rs b/apps/vectorcraft/src/app.rs index b91282e7da..791143bb42 100644 --- a/apps/vectorcraft/src/app.rs +++ b/apps/vectorcraft/src/app.rs @@ -1,4 +1,4 @@ -#[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] +#[cfg(feature = "wgpu")] use super::gpu; use super::nightly_session; use super::prefs::{flush, save_tick}; @@ -107,7 +107,7 @@ impl eframe::App for App { // Plug-ins still loading end before the launch marker does (the macOS exit below skips // dropping the app). self.app.session.cancel_plugin_loads(); - end_before_teardown(self.frames); + end_before_teardown(self.frames, self.graphics_loss.happened()); } } @@ -202,16 +202,58 @@ impl App { /// its own class, which AppKit's Touch Bar support was observing it under, and AppKit aborts the /// app as it quits on Macs with a Touch Bar. On a normal quit, only the launch marker is needed /// after the window, so it is ended here as `main` ends it after the window on other platforms. +/// On every platform, the process also ends here when the window's graphics device was lost +/// (`device_lost`, #6374). A frame the lost device could not present stays acquired, and releasing +/// the window's surface as eframe tears it down then panics in wgpu (gfx-rs/wgpu#9277). /// Not while the window is still starting up (`frames` below [`gpu::STARTUP_FRAMES`]): a graphics /// failure then starts the app again on another adapter (#651). -#[allow(unused_variables)] -fn end_before_teardown(frames: u64) { - #[cfg(all(target_os = "macos", feature = "accessibility", feature = "wgpu"))] - if frames >= gpu::STARTUP_FRAMES { - safe_mode::end_launch(); - log::info!("quitting"); - log::logger().flush(); - std::process::exit(0); +fn end_before_teardown(frames: u64, device_lost: bool) { + if !ends_before_teardown(frames, device_lost) { + return; + } + if device_lost { + log::info!("the graphics device was lost: quitting before the window's graphics are torn down"); + } + // `main` does these after the window, which this exit skips. + #[cfg(not(target_os = "macos"))] + single_instance::resign(); + safe_mode::end_launch(); + log::info!("quitting"); + log::logger().flush(); + std::process::exit(0); +} + +/// Whether [`end_before_teardown`] ends the process: after the window's start-up, on macOS with +/// accessibility, or once the graphics device was lost. +#[cfg(feature = "wgpu")] +fn ends_before_teardown(frames: u64, device_lost: bool) -> bool { + frames >= gpu::STARTUP_FRAMES && (device_lost || cfg!(all(target_os = "macos", feature = "accessibility"))) +} + +/// Without wgpu there is no device-lost report, and the window is torn down as usual. +#[cfg(not(feature = "wgpu"))] +fn ends_before_teardown(_frames: u64, _device_lost: bool) -> bool { + false +} + +#[cfg(all(test, feature = "wgpu"))] +mod tests { + use vectorcraft_ui_egui::graphics::GraphicsLoss; + + use super::*; + + /// A device lost while the app runs ends the process before eframe releases the window's + /// surface, on every platform; before the window has started, the start-up restart takes over. + #[test] + fn a_lost_graphics_device_ends_the_process_before_teardown() { + let always = cfg!(all(target_os = "macos", feature = "accessibility")); + let (loss, ctx) = (GraphicsLoss::default(), egui::Context::default()); + assert_eq!(ends_before_teardown(gpu::STARTUP_FRAMES, loss.happened()), always, "no loss: the usual teardown"); + let (l, c) = (loss.clone(), ctx.clone()); + std::thread::spawn(move || l.report(&c, "Unknown: Device is lost")).join().unwrap(); + assert!(loss.take().is_some(), "a frame handles the report"); + assert!(ends_before_teardown(gpu::STARTUP_FRAMES, loss.happened()), "after a loss the window is not torn down"); + assert!(!ends_before_teardown(gpu::STARTUP_FRAMES - 1, loss.happened()), "during start-up the adapter restart runs"); } } diff --git a/crates/ui-egui/src/graphics.rs b/crates/ui-egui/src/graphics.rs index 0ff54d12d3..27cf2c623c 100644 --- a/crates/ui-egui/src/graphics.rs +++ b/crates/ui-egui/src/graphics.rs @@ -10,6 +10,10 @@ //! - The web host then starts again with new graphics and a new egui context, handing it the same //! app. The app notices the new context and makes everything it uploaded to the old one again: //! its fonts and theme, the canvas, and every texture cache ([`TexCache`]). +//! - The desktop host can't give the window a new device. When the window closes after a loss +//! ([`GraphicsLoss::happened`]), the process ends once the app has saved what it keeps on +//! quitting, before the window's graphics are torn down: releasing a swapchain that still holds +//! a frame the lost device couldn't present panics in the graphics driver layer (#6374). use std::cell::{Cell, Ref, RefCell, RefMut}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -20,7 +24,16 @@ use crate::VectorcraftApp; /// Raised by the host when the window's graphics device is lost (from any thread), read on the UI /// thread. Cheap to clone; the clones share the report. #[derive(Clone, Default)] -pub struct GraphicsLoss(Arc>>); +pub struct GraphicsLoss(Arc>); + +/// What a [`GraphicsLoss`] holds. +#[derive(Default)] +struct Loss { + /// The loss not handled yet, for [`GraphicsLoss::take`]. + why: Option, + /// A loss was reported at some point, handled or not. + happened: bool, +} impl GraphicsLoss { /// The graphics device was lost (`why`, for the log): the next frame of `ctx` handles it. A @@ -28,13 +41,23 @@ impl GraphicsLoss { pub fn report(&self, ctx: &egui::Context, why: impl Into) { let why = why.into(); log::error!("vectorcraft: the graphics device was lost: {why}"); - self.0.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(why); + { + let mut loss = self.0.lock().unwrap_or_else(|e| e.into_inner()); + loss.why.get_or_insert(why); + loss.happened = true; + } ctx.request_repaint(); } /// The loss reported since the last call, if any. pub fn take(&self) -> Option { - self.0.lock().unwrap_or_else(|e| e.into_inner()).take() + self.0.lock().unwrap_or_else(|e| e.into_inner()).why.take() + } + + /// Whether the device was lost at any point, a loss [`Self::take`] already handled included. + /// A window can't be given a new device, so once true this stays true. + pub fn happened(&self) -> bool { + self.0.lock().unwrap_or_else(|e| e.into_inner()).happened } } @@ -190,6 +213,16 @@ mod tests { assert_eq!(loss.take(), None, "handled once"); } + #[test] + fn a_handled_loss_is_still_known_when_the_window_closes() { + let (loss, ctx) = (GraphicsLoss::default(), crate::testing::ui_context()); + assert!(!loss.happened(), "nothing lost yet"); + let (l, c) = (loss.clone(), ctx.clone()); + std::thread::spawn(move || l.report(&c, "Unknown: Device is lost")).join().unwrap(); + assert!(loss.take().is_some(), "the next frame handles it"); + assert!(loss.happened(), "the device stays lost after the frame handled the report"); + } + #[test] fn a_tex_cache_empties_when_the_ui_moves_to_a_new_context() { thread_local! { From ab4e56934be4afed5f89b44b64945d0e389bb8b5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 07:48:08 -0800 Subject: [PATCH 30/37] Linux: the log says why a pen's window stays on Wayland, and names the pens XWayland lists Part of #5622. On a Wayland session winit 0.30 receives no input from a pen, so the app opens its window through XWayland when a pen is attached (#4967). When it did not, the log said nothing, and a report could not tell a pen that was not found from a session with no X display. - On a Wayland session the log now says why the window opens on Wayland: no pen in /proc/bus/input/devices, the device list could not be read, VECTORCRAFT_NATIVE_WAYLAND is set, or there is no X display (DISPLAY is unset, as in the Flatpak, which has --socket=fallback-x11). The pen-found line names the pen, and the missing-libraries warning no longer says Linux Display Server is X11 when a pen chose XWayland. - Under X11 the tablet reader logs the pens the X server lists (for example XWayland's "xwayland-tablet stylus:16"), again when that list changes, and the first event from each pen. - docs/development.md lists the new log lines, the Flatpak override that gives it an X display, and that GDK_BACKEND=x11 does not move the window to XWayland. --- apps/vectorcraft/src/main.rs | 29 ++++++- apps/vectorcraft/src/tablet.rs | 71 ++++++++++++++++- apps/vectorcraft/src/xwayland.rs | 130 ++++++++++++++++++++++++++----- docs/development.md | 2 +- 4 files changed, 204 insertions(+), 28 deletions(-) diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 6ab6778597..943c4c6302 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -396,15 +396,36 @@ fn read_command_line( /// Whether the window opens through XWayland, for Linux Display Server `pref` (`main`). #[cfg(target_os = "linux")] fn opens_through_xwayland(pref: Option<&str>) -> bool { - if !xwayland::wanted(pref, |name| std::env::var_os(name), xwayland::pen_attached) { + use xwayland::Choice; + let choice = xwayland::choose(pref, |name| std::env::var_os(name), xwayland::pen_attached); + // On native Wayland winit 0.30 receives no pen input, so the log says why the window stays there. + match &choice { + Choice::NotWayland | Choice::Chosen | Choice::Pen(_) => {} + Choice::NoXDisplay { x11: true } => { + log::warn!("Linux Display Server is X11, but there is no X display (DISPLAY is unset): opening the window on Wayland") + } + Choice::NoXDisplay { x11: false } => log::info!( + "opening the window on Wayland, where a pen does not reach it: there is no X display (DISPLAY is unset) to open it through XWayland" + ), + Choice::NativeWayland => log::info!("VECTORCRAFT_NATIVE_WAYLAND is set: opening the window on Wayland, where a pen does not reach it"), + Choice::NoPen => log::info!("no pen in /proc/bus/input/devices: opening the window on Wayland"), + Choice::NoDeviceList(e) => log::warn!("can't look for a pen ({e}): opening the window on Wayland, where a pen does not reach it"), + } + if !choice.xwayland() { return false; } if !xwayland::x11_libraries_found() { - log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland"); + if let Choice::Pen(name) = &choice { + log::warn!( + "pen found ({name}), but the X11 libraries aren't all installed: opening the window on Wayland, where the pen does not reach it" + ); + } else { + log::warn!("Linux Display Server is X11, but the X11 libraries aren't all installed: opening the window on Wayland"); + } return false; } - if pref != Some("x11") { - log::info!("pen found: opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); + if let Choice::Pen(name) = &choice { + log::info!("pen found ({name}): opening the window through XWayland, where the pen works (VECTORCRAFT_NATIVE_WAYLAND=1 keeps Wayland)"); } else { log::info!("opening the window through XWayland (Preferences › Performance › Linux Display Server)"); } diff --git a/apps/vectorcraft/src/tablet.rs b/apps/vectorcraft/src/tablet.rs index 4dd8f7d9ec..2c6a8b68c1 100644 --- a/apps/vectorcraft/src/tablet.rs +++ b/apps/vectorcraft/src/tablet.rs @@ -41,7 +41,7 @@ //! the rotation's range is 0°, and an axis a pen lacks reads nothing. #![cfg_attr(not(target_os = "linux"), allow(dead_code))] -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use craft::behavior::PointerSample; use craft::ui::runtime::pen::PenSource; @@ -189,6 +189,8 @@ enum Update { struct Pens { devices: HashMap, last: HashMap; 5]>, + /// The pens an event has come from, for the log. + heard: HashSet, } impl Pens { @@ -197,10 +199,37 @@ impl Pens { /// same id starts without them. fn set_devices(&mut self, devices: impl IntoIterator) { let devices: HashMap = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect(); - self.last.retain(|id, _| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d))); + let unchanged = |id: &u16| devices.get(id).is_some_and(|d| self.devices.get(id) == Some(d)); + self.last.retain(|id, _| unchanged(id)); + self.heard.retain(|id| unchanged(id)); self.devices = devices; } + /// The names of the pens listed, by device id, for the log. + fn pen_names(&self) -> Vec<&str> { + let mut pens: Vec<&Device> = self.devices.values().filter(|d| d.is_pen()).collect(); + pens.sort_by_key(|d| d.id); + pens.into_iter().map(|d| d.name.as_str()).collect() + } + + /// The pens listed, as the log line says it: under XWayland on a Wayland session this tells + /// whether XWayland lists the pen at all (#5622). + fn summary(&self) -> String { + let names = self.pen_names(); + if names.is_empty() { + "the X server lists no pen (a pointer device with an \"Abs Pressure\" valuator): a pen draws at full pressure".to_string() + } else { + format!("pens listed: {}", names.join(", ")) + } + } + + /// The name of pen `id` when this is the first event from it since it was listed, for the log: + /// it tells whether the pen's events reach the app at all. + fn first_event(&mut self, id: u16) -> Option<&str> { + let device = self.devices.get(&id).filter(|d| d.is_pen())?; + self.heard.insert(id).then_some(device.name.as_str()) + } + /// A raw motion or button event of device `id`, with the valuators that changed. fn handle(&mut self, id: u16, valuators: impl IntoIterator) -> Update { let Some(device) = self.devices.get(&id) else { return Update::Keep }; @@ -231,6 +260,9 @@ impl Pens { /// A raw event as the X server sends it: its valuator mask and the values of the valuators /// set in it. A pen's sample or another pointer's `None` goes into `pen`. fn raw_event(&mut self, pen: &PenSource, id: u16, mask: &[u32], values: &[f64]) { + if let Some(name) = self.first_event(id) { + log::info!("tablet: events arrive from the pen {name:?}"); + } if let Update::Set(sample) = self.handle(id, valuators(mask, values)) { pen.set(sample); } @@ -304,6 +336,7 @@ mod x11 { .map_err(|e| format!("XISelectEvents failed: {e}"))?; let mut pens = Pens::default(); pens.set_devices(query_devices(&conn)); + log::info!("tablet: {}", pens.summary()); std::thread::Builder::new() .name("vectorcraft-tablet-x11".into()) .spawn(move || run(&conn, &mut pens, &pen)) @@ -321,7 +354,14 @@ mod x11 { let values: Vec = e.axisvalues.iter().map(|v| fp3232(v.integral, v.frac)).collect(); pens.raw_event(pen, e.deviceid, &e.valuator_mask, &values); } - Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => pens.set_devices(query_devices(conn)), + Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => { + let before = pens.summary(); + pens.set_devices(query_devices(conn)); + let after = pens.summary(); + if after != before { + log::info!("tablet: {after}"); + } + } _ => {} } } @@ -623,6 +663,31 @@ mod tests { assert!(s.pressure < 0.001, "{}", s.pressure); } + /// #5622: the log names the pens the X server lists (XWayland's included) and the first event + /// from each, once, again after the pen is listed anew, and never for a mouse. + #[test] + fn the_log_names_the_pens_listed_and_the_first_event_from_each() { + let stylus = Device::new(11, "xwayland-tablet stylus:16", Some("xwayland-tablet stylus"), pen_valuators()); + let eraser = Device::new(12, "xwayland-tablet eraser:16", Some("xwayland-tablet eraser"), pen_valuators()); + let mut pens = Pens::default(); + assert!(pens.summary().contains("lists no pen"), "{}", pens.summary()); + pens.set_devices([eraser.clone(), mouse(4), stylus.clone()]); + assert_eq!(pens.summary(), "pens listed: xwayland-tablet stylus:16, xwayland-tablet eraser:16"); + assert_eq!(pens.first_event(11), Some("xwayland-tablet stylus:16")); + assert_eq!(pens.first_event(11), None, "once"); + assert_eq!(pens.first_event(4), None, "a mouse"); + assert_eq!(pens.first_event(99), None, "a device not listed"); + // Listed again unchanged: still heard. Another device under the same id: heard anew. + pens.set_devices([eraser.clone(), mouse(4), stylus]); + assert_eq!(pens.first_event(11), None); + pens.set_devices([eraser, mouse(4), pen(11)]); + assert_eq!(pens.first_event(11), Some("Wacom Intuos Pro M Pen stylus")); + // The events go into the feed as before. + let source = PenSource::default(); + pens.raw_event(&source, 12, &[0b100], &[65535.0]); + assert_eq!(source.current().map(|s| (s.eraser, s.pressure)), Some((true, 1.0))); + } + #[test] fn fixed_point_values() { assert_eq!(fp3232(3, 1 << 31), 3.5); diff --git a/apps/vectorcraft/src/xwayland.rs b/apps/vectorcraft/src/xwayland.rs index 38b210c05e..1471f44199 100644 --- a/apps/vectorcraft/src/xwayland.rs +++ b/apps/vectorcraft/src/xwayland.rs @@ -22,18 +22,61 @@ use std::path::{Path, PathBuf}; const X11_LIBS: &[&str] = &["libX11.so.6", "libX11-xcb.so.1", "libxcb.so.1", "libXcursor.so.1", "libXi.so.6", "libxkbcommon.so.0", "libxkbcommon-x11.so.0"]; -/// Whether the saved `linuxDisplayServer` and the environment ask for XWayland: `x11` chosen, or -/// any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen and -/// `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`); a Wayland session (winit picks Wayland whenever -/// `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set); and an X display to open. `pen` runs only after -/// the other checks. -pub fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool) -> bool { +/// What the pen check found: the name of the first pen, `None` when there is none, or why the +/// device list could not be read. +pub type PenProbe = Result, String>; + +/// Where the window opens, and why, as [`choose`] decides it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Choice { + /// Not a Wayland session: the window opens where winit opens it. + NotWayland, + /// XWayland, because Linux Display Server is X11 (XWayland). + Chosen, + /// XWayland, because the pen of this name is attached. + Pen(String), + /// Wayland: the session has no X display (`DISPLAY` is unset, as in the Flatpak on a Wayland + /// session), so XWayland can't be used. `x11` is whether X11 (XWayland) was chosen. + NoXDisplay { x11: bool }, + /// Wayland: `VECTORCRAFT_NATIVE_WAYLAND` keeps the window there. + NativeWayland, + /// Wayland: no pen is attached. + NoPen, + /// Wayland: the input devices could not be listed, for this reason. + NoDeviceList(String), +} + +impl Choice { + /// Whether the window opens through XWayland. + pub fn xwayland(&self) -> bool { + matches!(self, Self::Chosen | Self::Pen(_)) + } +} + +/// Where the saved `linuxDisplayServer` and the environment open the window: XWayland for `x11` +/// chosen, or for any other choice (`automatic`, `x11WithPen`, none saved) with `pen` finding a pen +/// and `VECTORCRAFT_NATIVE_WAYLAND` unset (or `0`), on a Wayland session (winit picks Wayland +/// whenever `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is set) with an X display to open. `pen` runs +/// only after the other checks. +pub fn choose(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> PenProbe) -> Choice { let set = |name: &str| var(name).is_some_and(|v| !v.is_empty()); - let session = (set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET")) && set("DISPLAY"); - let native_wayland = var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0"); - match pref { - Some("x11") => session, - _ => session && !native_wayland && pen(), + if !set("WAYLAND_DISPLAY") && !set("WAYLAND_SOCKET") { + return Choice::NotWayland; + } + let x11 = pref == Some("x11"); + if !set("DISPLAY") { + return Choice::NoXDisplay { x11 }; + } + if x11 { + return Choice::Chosen; + } + if var("VECTORCRAFT_NATIVE_WAYLAND").is_some_and(|v| !v.is_empty() && v != "0") { + return Choice::NativeWayland; + } + match pen() { + Ok(Some(name)) => Choice::Pen(name), + Ok(None) => Choice::NoPen, + Err(e) => Choice::NoDeviceList(e), } } @@ -44,20 +87,28 @@ const BTN_TOOL_PEN: u32 = 0x140; const ABS_X: u32 = 0x00; const ABS_Y: u32 = 0x01; -/// Is a pen attached? Reads `/proc/bus/input/devices`; a file that can't be read has no pen. -pub fn pen_attached() -> bool { - std::fs::read_to_string("/proc/bus/input/devices").is_ok_and(|devices| has_pen(&devices)) +/// The pen attached, from `/proc/bus/input/devices`, or why that file could not be read. +pub fn pen_attached() -> PenProbe { + std::fs::read_to_string("/proc/bus/input/devices").map(|devices| find_pen(&devices)).map_err(|e| format!("/proc/bus/input/devices: {e}")) } -/// Is a pen among the input devices `/proc/bus/input/devices` lists? A pen is a device whose +/// Is a pen among the input devices `/proc/bus/input/devices` lists? +#[cfg(test)] +fn has_pen(devices: &str) -> bool { + find_pen(devices).is_some() +} + +/// The name of the first pen among the input devices `/proc/bus/input/devices` lists (its +/// `N: Name=` line without the quotes, empty when it has none). A pen is a device whose /// `B: KEY=` bitmap has `BTN_TOOL_PEN` and whose `B: ABS=` bitmap has `ABS_X` and `ABS_Y`, as /// libinput asks of a tablet tool. A virtual keyboard made with uinput can claim every key code, /// `BTN_TOOL_PEN` included, but has no absolute axes. -fn has_pen(devices: &str) -> bool { - devices.split("\n\n").any(|device| { - let bitmap = |name: &str| device.lines().find_map(|l| l.strip_prefix(name)); - bitmap("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) - && bitmap("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y)) +fn find_pen(devices: &str) -> Option { + devices.split("\n\n").find_map(|device| { + let field = |name: &str| device.lines().find_map(|l| l.strip_prefix(name)); + let pen = field("B: KEY=").is_some_and(|keys| bit_set(keys, BTN_TOOL_PEN)) + && field("B: ABS=").is_some_and(|axes| bit_set(axes, ABS_X) && bit_set(axes, ABS_Y)); + pen.then(|| field("N: Name=").map_or_else(String::new, |n| n.trim().trim_matches('"').to_string())) }) } @@ -147,6 +198,11 @@ mod tests { panic!("the pen check ran") } + /// [`choose`] as a yes or no, with a pen check that finds a pen or none. + fn wanted(pref: Option<&str>, var: impl Fn(&str) -> Option, pen: impl FnOnce() -> bool) -> bool { + choose(pref, var, || Ok(pen().then(|| "Pen".to_string()))).xwayland() + } + #[test] fn xwayland_only_when_chosen_on_wayland_with_an_x_display() { let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); @@ -183,6 +239,40 @@ mod tests { assert!(wanted(Some("x11"), &native, no_probe)); } + /// #5622: the choice names why the window stays on Wayland, where the pen does not reach it, + /// so that the log tells a missing X display (the Flatpak on a Wayland session) from a pen + /// that is not listed or a device list that can't be read. + #[test] + fn the_choice_says_why_the_window_stays_on_wayland() { + let wayland = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")]); + let no_x = env(&[("WAYLAND_DISPLAY", "wayland-0")]); + let native = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0"), ("VECTORCRAFT_NATIVE_WAYLAND", "1")]); + let pen = || Ok(Some("ELAN9008:00 04F3:2C82 Stylus".to_string())); + let never = || -> PenProbe { panic!("the pen check ran") }; + assert_eq!(choose(None, env(&[("DISPLAY", ":0")]), never), Choice::NotWayland); + assert_eq!(choose(None, &no_x, never), Choice::NoXDisplay { x11: false }); + assert_eq!(choose(Some("x11"), &no_x, never), Choice::NoXDisplay { x11: true }); + assert_eq!(choose(Some("x11"), &wayland, never), Choice::Chosen); + assert_eq!(choose(Some("automatic"), &native, never), Choice::NativeWayland); + assert_eq!(choose(Some("automatic"), &wayland, pen), Choice::Pen("ELAN9008:00 04F3:2C82 Stylus".to_string())); + assert_eq!(choose(Some("x11WithPen"), &wayland, || Ok(None)), Choice::NoPen); + let unreadable = choose(None, &wayland, || Err("/proc/bus/input/devices: Permission denied".to_string())); + assert_eq!(unreadable, Choice::NoDeviceList("/proc/bus/input/devices: Permission denied".to_string())); + for stays in [Choice::NotWayland, Choice::NoXDisplay { x11: true }, Choice::NativeWayland, Choice::NoPen, unreadable] { + assert!(!stays.xwayland(), "{stays:?}"); + } + assert!(Choice::Chosen.xwayland() && Choice::Pen(String::new()).xwayland()); + } + + /// The pen check names the pen it found, for the log. + #[test] + fn the_pen_check_names_the_pen() { + assert_eq!(find_pen(WITH_PEN).as_deref(), Some("Wacom Intuos Pro M Pen")); + let without = WITH_PEN.split("\n\n").take(2).collect::>().join("\n\n"); + assert_eq!(find_pen(&without), None); + assert_eq!(find_pen("B: KEY=1c03 0 0 0 0 0\nB: ABS=3\n").as_deref(), Some(""), "a pen without a name line"); + } + /// `/proc/bus/input/devices` of a laptop with a Wacom Intuos Pro attached (64-bit longs: the /// pen's `KEY=1c03 0 0 0 0 0` has bit 0x140, `BTN_TOOL_PEN`), from PhotoCraft's tests. const WITH_PEN: &str = "I: Bus=0011 Vendor=0001 Product=0001 Version=ab83\n\ diff --git a/docs/development.md b/docs/development.md index 5a1b6efd95..ce215da81f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -134,7 +134,7 @@ The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On - **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s for each format it tries, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. Every arboard read on Linux and the BSDs, including the UI thread's (a paste, and a Copy or Cut checking what the clipboard held), runs on a worker thread with a handle of its own and waits 2 s at most: an owner that never sends its data costs one read that wait, and later reads fail at once until it answers. A paste's bitmap read waits up to 10 s on the paste's background thread, so the UI thread does not wait for it. When one of a paste's reads gets no answer in its 2 s, or a paste follows a read that has not been answered yet, such as the paste's own check whether the clipboard still holds what VectorCraft copied, the paste waits on that thread for that read's answer, up to 10 s after the read was sent, and pastes what it holds. When the answer is what VectorCraft copied, holds nothing to paste, or does not come, the paste takes the internal clipboard. On X11, quitting within 25 s of a read that got no answer waits for that read to end, so the app's own handle is the last one and hands what it copied to the clipboard manager when one runs. That includes a read of the Paste menu check's handle: quitting waits up to 27 s for the background thread to drop it before the app drops its own, and quits after that wait even when the handle has not been dropped. The app takes its windows off screen before these waits (`apps/vectorcraft/src/quit_windows.rs`). An X11 main window, an XWayland one included, is hidden. winit cannot hide a native Wayland window, so on Linux the app attaches no buffer to the main window's surface, which unmaps it while the window and its connection stay open for the Wayland clipboard. On Linux the X11 windows of floating panels and documents are unmapped through a second X11 connection. On native Wayland, floating panels and documents are normally drawn inside the main window; on the BSDs a native Wayland main window stays on screen until the waits end. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. - **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. -- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found: opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. +- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found (): opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). When the window stays on Wayland on such a session, the log says why (#5622): `no pen in /proc/bus/input/devices`, `can't look for a pen` with the reason, `VECTORCRAFT_NATIVE_WAYLAND is set`, `there is no X display (DISPLAY is unset)`, or that the X11 libraries aren't all installed. The Flatpak gets no X display on a Wayland session (`--socket=fallback-x11`); `flatpak override --user --socket=x11 ai.storyteller.vectorcraft` gives it one. `GDK_BACKEND=x11` does not move the window to XWayland: winit does not read it. Under X11 the log lists the pens the X server lists (`tablet: pens listed: …`, for example `xwayland-tablet stylus:16` under XWayland, or `the X server lists no pen`) and the first event from each pen (`tablet: events arrive from the pen …`). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. - **Pen pressure under X11 and XWayland (#764):** winit 0.30 hands a pen to an X11 window as a mouse, without its pressure. When the window is on X11, XWayland included, the desktop app opens a second X connection (x11rb's `RustConnection`) and reads XInput2 raw events for every device (`apps/vectorcraft/src/tablet.rs`, from PhotoCraft's `crates/tablet`). A device with an `Abs Pressure` valuator is a pen, unless its XInput type is `TOUCHPAD` or `TOUCHSCREEN`. While a pen is the pointer that moved last, its pressure, scaled from the valuator's range to 0..1, reaches the tools that use pressure: the Paintbrush's pressure-sensitive brushes and the Liquify tools' Use Pressure Pen. The reader also reads `Abs Tilt X` and `Abs Tilt Y` (from a pen that has both) in degrees, scaled to ±60° when the valuator's range does not fit in ±90, and `Abs Rotary Z` (an Art Pen's barrel rotation) as a turn with the middle of the range at 0°; the Paintbrush records them for brushes with Tilt, Bearing and Rotation variation. A pen device whose name or XInput type contains `eraser` (in any case) is the pen's eraser end: while the pointer is over the window, the canvas selects the Eraser tool when the eraser end moves, and it selects the tool used before when the tip moves again (`crates/ui-egui/src/stylus.rs`). The X server needs XInput 2.1 or later; otherwise the log has a `tablet pressure:` warning with the reason, and the pen draws at full pressure. - **Pen tilt and rotation on macOS (#764):** with each tablet event's pressure (#852), `apps/vectorcraft/src/mac_tablet.rs` reads its `tilt`, −1..1 on each axis, scaled to ±60° with each axis keeping AppKit's sign (x positive to the right, y positive towards the bottom and the user), and its `rotation`, negated to run clockwise. Until a pen reports a tilt or a rotation other than 0 after it comes near the tablet, that value reads as none, since a pen without one reports 0. The Paintbrush records them as it does under X11. From 7310a8eb4f63ee0fc478c882cfecffd3204100c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 07:49:50 -0800 Subject: [PATCH 31/37] Dimension: Alt whole-path measure takes the outside of the stroke with Use Preview Bounds off too With Alt held, the Dimension tool's box over a path and the dimension of the whole path it places now reach the outside of the path's strokes whether Use Preview Bounds is on or off. Before, they did so only with Use Preview Bounds on, and with it off they went through the outermost points of the path. Every dimension of a whole path the tool places now records `"preview": true` in its extent source. Dimensions saved without it keep measuring between the outermost points, and `dimension.create` still defaults `preview` to false. --- crates/doc/src/dimension.rs | 14 +++--- crates/tools/src/dimension.rs | 80 +++++++++++++++++------------------ docs/dimensions.md | 16 ++++--- docs/target-app-parity.md | 2 +- 4 files changed, 58 insertions(+), 54 deletions(-) diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 537a1d6e60..8a5c4e24fb 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -394,9 +394,11 @@ pub enum DimensionSource { /// it is vertical. Versions without this source do not open the file. Extent { node: NodeId, - /// Placed with Use Preview Bounds on: the points are moved out to the outside of the - /// strokes the path paints ([`preview_extents`]), the width or height that W and H show. - /// Versions without it measure between the outermost points themselves. + /// The points are moved out to the outside of the strokes the path paints + /// ([`preview_extents`]), the width or height that W and H show with Use Preview Bounds on. + /// The Dimension tool sets it on every dimension of a whole path it places. Without it, + /// as in files saved before the tool set it and in versions without it, the dimension + /// measures between the outermost points themselves. #[serde(default, skip_serializing_if = "std::ops::Not::not")] preview: bool, }, @@ -431,9 +433,9 @@ impl DimensionSource { } /// Whether a path it measures differs between `before` and `after`, or is in only one of them. /// A node without a path, or missing from both, counts as changed. For a dimension of a whole - /// path placed with Use Preview Bounds on, so does a change to the strokes the path paints - /// ([`stroked_by`]): their appearance, the node they come from, or which arrowheads they draw - /// on it, and the path being made into a guide or released from one. + /// path measured to the outside of its strokes (`preview`), so does a change to the strokes the + /// path paints ([`stroked_by`]): their appearance, the node they come from, or which arrowheads + /// they draw on it, and the path being made into a guide or released from one. pub fn art_changed(&self, before: &Document, after: &Document) -> bool { let strokes = matches!(self, Self::Extent { preview: true, .. }); self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) { diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 7f2a652e1f..e2337b5be0 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -42,35 +42,37 @@ impl Kind { } /// What the pointer is over. `Extent` is a path hovered with Alt held: its overall width or height, -/// with `preview` (Use Preview Bounds on) to the outside of its strokes. +/// to the outside of its strokes. #[derive(Clone, Debug, PartialEq)] enum Target { Segment(SegmentRef), Corner { first: SegmentRef, second: SegmentRef, at: Point }, Radial { source: DimensionSource, center: Point, radius: f64 }, - Extent { node: NodeId, preview: bool }, + Extent { node: NodeId }, } -/// A path, whether its points are moved out to its strokes, and the document its outermost points -/// ([`whole_ends`]) were read from ([`whole_box_source`]). -type WholeBoxKey = (NodeId, bool, (u64, u64, usize)); +/// A path and the document its outermost points ([`whole_ends`]) were read from +/// ([`whole_box_source`]). +type WholeBoxKey = (NodeId, (u64, u64, usize)); /// The key of a path's outermost points ([`WholeBoxKey`]), with the points. type WholeBox = (WholeBoxKey, Option<[(Point, Point); 2]>); /// The document a path's box is read from, with what identifies it: while an interaction is in /// progress, the document as it began; otherwise the document `cx` shows, at its revision. -fn whole_box_source<'a>(cx: &ToolContext<'a>, node: NodeId, preview: bool) -> (&'a vectorcraft_doc::Document, WholeBoxKey) { +fn whole_box_source<'a>(cx: &ToolContext<'a>, node: NodeId) -> (&'a vectorcraft_doc::Document, WholeBoxKey) { match cx.interaction_doc { - Some(began) => (began, (node, preview, (cx.revision.0, 0, std::ptr::from_ref(began).addr()))), - None => (cx.doc, (node, preview, (cx.revision.0, cx.revision.1, 0))), + Some(began) => (began, (node, (cx.revision.0, 0, std::ptr::from_ref(began).addr()))), + None => (cx.doc, (node, (cx.revision.0, cx.revision.1, 0))), } } -/// The outermost points a dimension of the whole path `node` measures: [`dimension::extents`], or -/// with `preview` [`dimension::preview_extents`], moved out to the outside of the path's strokes. -fn whole_ends(doc: &vectorcraft_doc::Document, node: NodeId, preview: bool) -> Option<[(Point, Point); 2]> { - if preview { dimension::preview_extents(doc, node) } else { dimension::extents(doc, node) } +/// The outermost points a dimension the tool places on the whole path `node` measures +/// ([`dimension::preview_extents`]): moved out to the outside of the path's strokes, whether Use +/// Preview Bounds is on or off. The dimension records `"preview": true`, so it measures to there +/// after later edits too. +fn whole_ends(doc: &vectorcraft_doc::Document, node: NodeId) -> Option<[(Point, Point); 2]> { + dimension::preview_extents(doc, node) } #[derive(Default)] @@ -1045,23 +1047,23 @@ impl DimensionTool { /// document changes. While an interaction is in progress they are read from the document as /// the interaction began, which each preview starts again from (as the levels in /// [`Self::preview`] are), so the previews themselves do not make the tool read the path again. - fn whole_box(&mut self, cx: &ToolContext, node: NodeId, preview: bool) -> Option<[(Point, Point); 2]> { - let (from, key) = whole_box_source(cx, node, preview); + fn whole_box(&mut self, cx: &ToolContext, node: NodeId) -> Option<[(Point, Point); 2]> { + let (from, key) = whole_box_source(cx, node); if let Some((kept, ends)) = self.whole_box && kept == key { return ends; } - let ends = whole_ends(from, node, preview); + let ends = whole_ends(from, node); self.whole_box = Some((key, ends)); ends } /// What the pointer at `p` is over. A Linear path hovered with `alt` held, before any point - /// is picked, is the whole path: with Use Preview Bounds on, to the outside of its strokes. + /// is picked, is the whole path, to the outside of its strokes. fn target(&self, cx: &ToolContext, p: Point, alt: bool) -> Option { let edge = pick(cx, p)?; match self.kind { - Kind::Linear if alt && self.points.is_empty() => Some(Target::Extent { node: edge.node, preview: cx.preview_bounds }), + Kind::Linear if alt && self.points.is_empty() => Some(Target::Extent { node: edge.node }), Kind::Linear => Some(Target::Segment(edge)), Kind::Angular => { let (anchor, at) = anchor_near(cx, &edge, p)?; @@ -1113,8 +1115,8 @@ impl DimensionTool { let mode = if p.distance(*center) >= *radius { DimensionMode::Radius } else { DimensionMode::Diameter }; self.recipe(mode, *center, p, Point::ZERO, Some(source.clone())) } - Target::Extent { node, preview } => { - let source = DimensionSource::Extent { node: *node, preview: *preview }; + Target::Extent { node } => { + let source = DimensionSource::Extent { node: *node, preview: true }; let mut d = self.recipe(DimensionMode::Linear, Point::ZERO, Point::new(1.0, 0.0), Point::ZERO, Some(source)); d.orientation = Orientation::Horizontal; d @@ -1139,7 +1141,7 @@ impl DimensionTool { } self.level_guide = None; let whole = match self.pending.as_ref().and_then(|d| d.source.as_ref()) { - Some(DimensionSource::Extent { node, preview }) => Some(self.whole_box(cx, *node, *preview)), + Some(DimensionSource::Extent { node, .. }) => Some(self.whole_box(cx, *node)), _ => None, }; let Some(d) = &mut self.pending else { return vec![] }; @@ -1408,8 +1410,8 @@ impl Tool for DimensionTool { } self.hover = self.target(cx, ev.pos, ev.mods.alt); let whole = match self.hover { - Some(Target::Extent { node, preview }) => { - self.whole_box(cx, node, preview); + Some(Target::Extent { node }) => { + self.whole_box(cx, node); true } _ => false, @@ -1562,15 +1564,14 @@ impl Tool for DimensionTool { out.push(Overlay::Line { a: *center, b: *center + toward / toward.hypot() * *radius, color, dashed: true }); } } - Some(Target::Extent { node, preview }) => { - // The box through the path's outermost points (with Use Preview Bounds on, out - // to its strokes): a Smart Guide, or with Smart Guides off a line in the - // tool's own color. Read again when the path changed since the pointer last - // moved. - let (from, at) = whole_box_source(cx, *node, *preview); + Some(Target::Extent { node }) => { + // The box through the path's outermost points, out to its strokes: a Smart + // Guide, or with Smart Guides off a line in the tool's own color. Read again + // when the path changed since the pointer last moved. + let (from, at) = whole_box_source(cx, *node); let b = match self.whole_box { Some((key, ends)) if key == at => ends, - _ => whole_ends(from, *node, *preview), + _ => whole_ends(from, *node), } .map(extent_box); if let Some(b) = b { @@ -2890,7 +2891,7 @@ mod tests { }; let mut t = DimensionTool::default(); t.pointer(&c, &held(PointerKind::Move, 150.0, 100.0)); - assert_eq!(t.hover, Some(Target::Extent { node: id, preview: false })); + assert_eq!(t.hover, Some(Target::Extent { node: id })); assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color))); // With Smart Guides off the box is not a Smart Guide, and at a high zoom the size stays by // the pointer. @@ -2907,7 +2908,7 @@ mod tests { t.pointer(&c, &held(PointerKind::Up, 150.0, 100.0)); assert!(t.pending.is_some() && t.points.is_empty()); let above = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0))); - assert_eq!(above["source"], json!({"kind":"extent","node":id})); + assert_eq!(above["source"], json!({"kind":"extent","node":id,"preview":true})); assert_eq!(above["orientation"], json!("horizontal")); // Past a corner, the side the pointer is farther out on decides. let corner = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 280.0, 70.0))); @@ -2954,29 +2955,28 @@ mod tests { assert!(o.iter().any(near), "{o:?}"); } - /// With Use Preview Bounds on, the box Alt shows over a stroked path reaches the outside of its - /// stroke, and the dimension of the whole path it places measures to there, as W and H do; it - /// keeps doing so after the art changes (`"preview": true`). With the preference off, the box - /// and the dimension go through the outermost points. + /// With Use Preview Bounds on or off, the box Alt shows over a stroked path reaches the outside + /// of its stroke, and the dimension of the whole path it places measures to there; it keeps + /// doing so after the art changes (`"preview": true`). #[test] - fn with_preview_bounds_an_alt_placed_dimension_measures_the_outside_of_the_stroke() { + fn an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off() { let (d, id) = doc_with_rect(); let (s, p) = (Selection::default(), paint()); let held = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y).with_mods(Mods { alt: true, ..Mods::default() }); let near = |a: f64, b: f64| (a - b).abs() < 1e-9; - for (preview, (left, right)) in [(true, (99.5, 200.5)), (false, (100.0, 200.0))] { + let (left, right) = (99.5, 200.5); + for preview in [true, false] { let c = ToolContext { preview_bounds: preview, ..cx(&d, &s, &p) }; let mut t = DimensionTool::default(); t.pointer(&c, &held(PointerKind::Move, 150.0, 100.0)); - assert_eq!(t.hover, Some(Target::Extent { node: id, preview })); + assert_eq!(t.hover, Some(Target::Extent { node: id })); let xs: Vec = t.overlays(&c).iter().filter_map(|o| if let Overlay::Line { a, .. } = o { Some(a.x) } else { None }).collect(); assert!(xs.iter().any(|x| near(*x, left)) && xs.iter().any(|x| near(*x, right)), "preview {preview}: {xs:?}"); t.pointer(&c, &held(PointerKind::Down, 150.0, 100.0)); t.pointer(&c, &held(PointerKind::Up, 150.0, 100.0)); let acts = t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0)); let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; - let source = if preview { json!({"kind":"extent","node":id,"preview":true}) } else { json!({"kind":"extent","node":id}) }; - assert_eq!(params["source"], source); + assert_eq!(params["source"], json!({"kind":"extent","node":id,"preview":true}), "preview {preview}"); let (a, b) = (params["a"][0].as_f64().unwrap_or(f64::NAN), params["b"][0].as_f64().unwrap_or(f64::NAN)); assert!(near(a, left) && near(b, right), "preview {preview}: {a} to {b}"); } diff --git a/docs/dimensions.md b/docs/dimensions.md index ab5003a2b9..27972418af 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -105,12 +105,14 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers that starts no segment is left out. They are read again whenever the path changes, so a turned path shows its new overall width or height rather than that of its bounding box before the turn. The line keeps its distance from the whole path when the path changes or the dimension - changes orientation. With Use Preview Bounds on, the box and the dimension reach the outside of - the path's strokes, the width or height that W and H show: each outermost point moves out to the - edge of the box the strokes paint (a member of a compound path takes the compound path's - strokes, with an arrowhead only where the compound path draws one on that member), and a dimension placed that way measures to there again when the path or its strokes - change. Geometry effects are not included. Alt has this effect only before the first point is - clicked. + changes orientation. With Use Preview Bounds on or off, the box and the dimension reach the + outside of the path's strokes, the width or height that W and H show with Use Preview Bounds + on: each outermost point moves out to the edge of the box the strokes paint (a member of a + compound path takes the compound path's strokes, with an arrowhead only where the compound path + draws one on that member), and a dimension placed that way measures to there again when the + path or its strokes change. Geometry effects are not included. A dimension of a whole path saved + without `"preview":true` keeps measuring between the outermost points. Alt has this effect only + before the first point is clicked. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two straight lines that meet (or would, extended), then click to place. - **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its @@ -205,7 +207,7 @@ another document. `vertical`), offset and style; returns the group id and label. `{"kind":"extent","node":}` measures a whole path, linear only: between its leftmost and rightmost points when horizontal or aligned, and its topmost and bottommost points when vertical. With `"preview":true` (what - the tool records with Use Preview Bounds on; `false` when omitted, and any value other than + the tool records for an Alt-placed dimension; `false` when omitted, and any value other than `true` or `false` is an error) those points move out to the outside of the path's strokes. A version without the extent source does not open a file that holds one, and a version without `preview` measures such a dimension between the points themselves. `offset` is the distance of diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9469046bc4..51ba964c82 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -757,7 +757,7 @@ since 2026-10-01. **Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it. **Drawing tools, selected Dimension extension-line style (#7078):** Properties › Dimension exposes the selected editable dimension's existing extension-line color and weight. Both extension lines share that style, independently of the main dimension line and label. Apply to All keeps its full-style behavior for editable dimensions, leaving a protected dimension unchanged; Set as Default keeps the whole style for a new dimension created without explicit options, without changing existing dimensions. The dimension remains editable. Four cases in `crates/ui-egui/tests/dimension_extension_properties.rs` verify actual Properties input, both canvas extension lines, independent main-line/label styling, full-style Apply to All, locked and unselected controls, defaults/new dimensions, Undo/Redo, and native save/reopen with further editing. Existing document-color conversion is unchanged. The measured geometry and existing snapping behavior are unchanged; no whole-Dimension completion or score/hour change is claimed. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. -**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows a box through its outermost points (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on, the box and the dimension reach the outside of the path's strokes, which is the size W and H show when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `with_preview_bounds_an_alt_placed_dimension_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. +**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows a box through its outermost points (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on or off, the box and the dimension reach the outside of the path's strokes, which is the size W and H show with Use Preview Bounds on when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included; a dimension saved without it keeps measuring between the outermost points. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. From aa3415aa5e6d8a4f0b09a2511a80f191d739d34c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 08:09:18 -0800 Subject: [PATCH 32/37] Dimension: the Alt hover box is described as reaching the outside of the stroke The parity doc, docs/dimensions.md and two comments said the box shown while hovering a path with Alt held goes through the path's outermost points. It follows the box the strokes paint, which reaches 0.5 pt past those points for a centered 1 pt stroke. --- crates/tools/src/dimension.rs | 5 +++-- docs/dimensions.md | 4 ++-- docs/target-app-parity.md | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index e2337b5be0..b63dc44d9a 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -177,7 +177,8 @@ fn orientation_at(a: Point, b: Point, p: Point) -> Orientation { .map_or(Orientation::Aligned, |(_, orientation)| orientation) } -/// The box through a path's outermost points ([`whole_ends`]): left, top, right and bottom. +/// The box through a path's outermost points moved out to its strokes ([`whole_ends`]): left, top, +/// right and bottom. fn extent_box([(left, right), (top, bottom)]: [(Point, Point); 2]) -> Rect { Rect::new(left.x, top.y, right.x, bottom.y) } @@ -2875,7 +2876,7 @@ mod tests { } } - /// With Alt held, hovering a path shows the box through its outermost points as a Smart Guide, + /// With Alt held, hovering a path shows the box its strokes paint as a Smart Guide, /// and a click starts placing a dimension of the whole path: above or below it, its width; /// beside it, its height. A drag places it on release. Without Alt the same click picks a point. #[test] diff --git a/docs/dimensions.md b/docs/dimensions.md index 27972418af..a7359497aa 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -93,8 +93,8 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions by holding Alt - (Option on macOS) over its path. With Alt held, hovering a path shows a box through the path's - outermost points, as a Smart Guide when Smart Guides are on and in the tool's own color when + (Option on macOS) over its path. With Alt held, hovering a path shows the box the path's strokes + paint (described below), as a Smart Guide when Smart Guides are on and in the tool's own color when they are off, with its width and height beside the pointer when Measurement Labels are on. Clicking the path, then moving and clicking, places a dimension of the whole path; dragging out from the path places it on release. The rest is VectorCraft's own rule. With diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 51ba964c82..fa9187df61 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -757,7 +757,7 @@ since 2026-10-01. **Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it. **Drawing tools, selected Dimension extension-line style (#7078):** Properties › Dimension exposes the selected editable dimension's existing extension-line color and weight. Both extension lines share that style, independently of the main dimension line and label. Apply to All keeps its full-style behavior for editable dimensions, leaving a protected dimension unchanged; Set as Default keeps the whole style for a new dimension created without explicit options, without changing existing dimensions. The dimension remains editable. Four cases in `crates/ui-egui/tests/dimension_extension_properties.rs` verify actual Properties input, both canvas extension lines, independent main-line/label styling, full-style Apply to All, locked and unselected controls, defaults/new dimensions, Undo/Redo, and native save/reopen with further editing. Existing document-color conversion is unchanged. The measured geometry and existing snapping behavior are unchanged; no whole-Dimension completion or score/hour change is claimed. **Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it. -**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows a box through its outermost points (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on or off, the box and the dimension reach the outside of the path's strokes, which is the size W and H show with Use Preview Bounds on when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included; a dimension saved without it keeps measuring between the outermost points. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. +**Drawing tools, Dimension tool overall width and height of a path:** The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes plotting an object's horizontal and vertical dimensions with Alt (Option on macOS) held over its path. By VectorCraft's own rule, hovering a path with Alt held shows the box its strokes paint, which reaches 0.5 pt past its outermost points for a centered 1 pt stroke (a Smart Guide when Smart Guides are on); a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, and the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. With Use Preview Bounds on or off, the box and the dimension reach the outside of the path's strokes, which is the size W and H show with Use Preview Bounds on when the path is not rotated and has no geometry effect (geometry effects such as Offset Path are not included), and the source records `"preview":true` so the dimension measures to there after later edits, a new stroke weight included; a dimension saved without it keeps measuring between the outermost points. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `an_alt_placed_dimension_measures_the_outside_of_the_stroke_with_preview_bounds_on_or_off`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height`, `a_dimension_of_a_whole_path_with_preview_bounds_measures_the_outside_of_the_stroke`, `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` and `a_dimension_of_a_whole_path_survives_a_native_file` cover it. **Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it. **Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. From 3d628608c6a488ec490fe759f888402cd84eb9d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 08:09:21 -0800 Subject: [PATCH 33/37] Docs: the Flatpak override clears fallback-x11 before it allows X11 --- docs/development.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development.md b/docs/development.md index ce215da81f..d176088bcb 100644 --- a/docs/development.md +++ b/docs/development.md @@ -134,7 +134,7 @@ The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On - **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s for each format it tries, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. Every arboard read on Linux and the BSDs, including the UI thread's (a paste, and a Copy or Cut checking what the clipboard held), runs on a worker thread with a handle of its own and waits 2 s at most: an owner that never sends its data costs one read that wait, and later reads fail at once until it answers. A paste's bitmap read waits up to 10 s on the paste's background thread, so the UI thread does not wait for it. When one of a paste's reads gets no answer in its 2 s, or a paste follows a read that has not been answered yet, such as the paste's own check whether the clipboard still holds what VectorCraft copied, the paste waits on that thread for that read's answer, up to 10 s after the read was sent, and pastes what it holds. When the answer is what VectorCraft copied, holds nothing to paste, or does not come, the paste takes the internal clipboard. On X11, quitting within 25 s of a read that got no answer waits for that read to end, so the app's own handle is the last one and hands what it copied to the clipboard manager when one runs. That includes a read of the Paste menu check's handle: quitting waits up to 27 s for the background thread to drop it before the app drops its own, and quits after that wait even when the handle has not been dropped. The app takes its windows off screen before these waits (`apps/vectorcraft/src/quit_windows.rs`). An X11 main window, an XWayland one included, is hidden. winit cannot hide a native Wayland window, so on Linux the app attaches no buffer to the main window's surface, which unmaps it while the window and its connection stay open for the Wayland clipboard. On Linux the X11 windows of floating panels and documents are unmapped through a second X11 connection. On native Wayland, floating panels and documents are normally drawn inside the main window; on the BSDs a native Wayland main window stays on screen until the waits end. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. - **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.37 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. -- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found (): opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). When the window stays on Wayland on such a session, the log says why (#5622): `no pen in /proc/bus/input/devices`, `can't look for a pen` with the reason, `VECTORCRAFT_NATIVE_WAYLAND is set`, `there is no X display (DISPLAY is unset)`, or that the X11 libraries aren't all installed. The Flatpak gets no X display on a Wayland session (`--socket=fallback-x11`); `flatpak override --user --socket=x11 ai.storyteller.vectorcraft` gives it one. `GDK_BACKEND=x11` does not move the window to XWayland: winit does not read it. Under X11 the log lists the pens the X server lists (`tablet: pens listed: …`, for example `xwayland-tablet stylus:16` under XWayland, or `the X server lists no pen`) and the first event from each pen (`tablet: events arrive from the pen …`). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. +- **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, the app runs under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer: Preferences › Performance › Linux Display Server's Automatic (the default) and X11 (XWayland) When a Pen Is Attached (`x11WithPen`) open the window through XWayland when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and log `pen found (): opening the window through XWayland`, as PhotoCraft does (#4967; `VECTORCRAFT_NATIVE_WAYLAND=1` keeps the window on Wayland). When the window stays on Wayland on such a session, the log says why (#5622): `no pen in /proc/bus/input/devices`, `can't look for a pen` with the reason, `VECTORCRAFT_NATIVE_WAYLAND is set`, `there is no X display (DISPLAY is unset)`, or that the X11 libraries aren't all installed. The Flatpak gets no X display on a Wayland session (`--socket=fallback-x11`); `flatpak override --user --nosocket=fallback-x11 --socket=x11 ai.storyteller.vectorcraft` gives it one and keeps its Wayland socket. `--socket=x11` alone is not enough: while `fallback-x11` is set, Flatpak gives the app no X display whenever Wayland is available. `GDK_BACKEND=x11` does not move the window to XWayland: winit does not read it. Under X11 the log lists the pens the X server lists (`tablet: pens listed: …`, for example `xwayland-tablet stylus:16` under XWayland, or `the X server lists no pen`) and the first event from each pen (`tablet: events arrive from the pen …`). For a pen attached after the app started, either run the app under XWayland (Preferences › Performance › Linux Display Server › X11 (XWayland); `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse. Under XWayland the app also reads the pen's pressure (next item); with KWin's emulation on native Wayland the pen has no pressure. Other compositors that don't emulate a pointer for tablets behave the same way. - **Pen pressure under X11 and XWayland (#764):** winit 0.30 hands a pen to an X11 window as a mouse, without its pressure. When the window is on X11, XWayland included, the desktop app opens a second X connection (x11rb's `RustConnection`) and reads XInput2 raw events for every device (`apps/vectorcraft/src/tablet.rs`, from PhotoCraft's `crates/tablet`). A device with an `Abs Pressure` valuator is a pen, unless its XInput type is `TOUCHPAD` or `TOUCHSCREEN`. While a pen is the pointer that moved last, its pressure, scaled from the valuator's range to 0..1, reaches the tools that use pressure: the Paintbrush's pressure-sensitive brushes and the Liquify tools' Use Pressure Pen. The reader also reads `Abs Tilt X` and `Abs Tilt Y` (from a pen that has both) in degrees, scaled to ±60° when the valuator's range does not fit in ±90, and `Abs Rotary Z` (an Art Pen's barrel rotation) as a turn with the middle of the range at 0°; the Paintbrush records them for brushes with Tilt, Bearing and Rotation variation. A pen device whose name or XInput type contains `eraser` (in any case) is the pen's eraser end: while the pointer is over the window, the canvas selects the Eraser tool when the eraser end moves, and it selects the tool used before when the tip moves again (`crates/ui-egui/src/stylus.rs`). The X server needs XInput 2.1 or later; otherwise the log has a `tablet pressure:` warning with the reason, and the pen draws at full pressure. - **Pen tilt and rotation on macOS (#764):** with each tablet event's pressure (#852), `apps/vectorcraft/src/mac_tablet.rs` reads its `tilt`, −1..1 on each axis, scaled to ±60° with each axis keeping AppKit's sign (x positive to the right, y positive towards the bottom and the user), and its `rotation`, negated to run clockwise. Until a pen reports a tilt or a rotation other than 0 after it comes near the tablet, that value reads as none, since a pen without one reports 0. The Paintbrush records them as it does under X11. From 798a029bfcb4f445b42f6c545d220b7d554131eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 11:44:20 -0800 Subject: [PATCH 34/37] Smooth Bridge: a group the bridged circles leave empty goes When outlines replace circles that sit in different groups, the circles that go left their groups behind with nothing in them. Each group or compound path left empty now goes in the same undo step, and so does each group above it left empty in turn; layers and sublayers stay. --- .../engine/src/cmd/addons/pathtools/bridge.rs | 25 ++++- .../src/cmd/addons/pathtools/bridge/tests.rs | 97 +++++++++++++++++++ docs/mcp.md | 4 +- 3 files changed, 123 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 4d4eb9cdf8..6742183bb8 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -34,7 +34,7 @@ pub(super) fn specs() -> Vec { "Smooth Bridge", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", + "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them, and a group or compound path the other circles leave empty goes; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", has_selection, bridge )] @@ -117,7 +117,8 @@ fn bridge(s: &mut Session, p: &Value) -> Result { } beside.finish(d)?; } else { - // Each shape's topmost circle becomes its outline (a plain path now) and the others go. + // Each shape's topmost circle becomes its outline (a plain path now) and the others go, + // with each group they leave empty. let mut gone = vec![]; for (members, outline) in shapes { let Some((&top, rest)) = members.split_last() else { continue }; @@ -128,7 +129,9 @@ fn bridge(s: &mut Session, p: &Value) -> Result { made.push(top); gone.extend_from_slice(rest); } + let parents: Vec = gone.iter().filter_map(|id| d.parent_of(*id)).collect(); remove_each(d, &gone)?; + remove_emptied(d, parents)?; } sel.set(made.iter().chain(&alone).copied()); Ok(made) @@ -140,6 +143,24 @@ fn bridge(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// Remove each of `parents` that is left with nothing in it, and then each group above it left with +/// nothing in it in turn. Layers stay. +fn remove_emptied(d: &mut vectorcraft_doc::Document, parents: Vec) -> Result<()> { + for parent in parents { + let mut at = Some(parent); + while let Some(id) = at { + match d.node(id) { + Some(n) if !n.is_layer() && n.children().is_some_and(|c| c.is_empty()) => { + at = d.parent_of(id); + d.remove(id)?; + } + _ => break, + } + } + } + Ok(()) +} + /// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order). fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec { at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect() diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs index 745f216b68..726277b8b7 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -329,6 +329,103 @@ fn an_id_given_twice_is_one_circle() { assert_eq!(top_level(&s), [b]); } +/// The objects directly inside `id`. +fn inside(s: &Session, id: NodeId) -> Vec { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|n| n.id).collect() +} + +fn make(s: &mut Session, command: &str, ids: &[NodeId]) -> NodeId { + select(s, ids); + NodeId(s.execute(command, &json!({})).unwrap()["id"].as_u64().unwrap()) +} + +#[test] +fn a_group_the_bridged_circles_leave_empty_goes_in_the_same_undo_step() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let ga = make(&mut s, "object.group", &[a]); + let gb = make(&mut s, "object.group", &[b]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(r["id"], json!(b.0)); + assert_eq!(top_level(&s), [gb], "the lower circle's group, left empty, goes"); + assert_eq!(inside(&s, gb), [b], "the outline stays in the upper circle's group"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(top_level(&s), [ga, gb]); + assert_eq!((inside(&s, ga), inside(&s, gb)), (vec![a], vec![b])); + + // Kept circles leave their groups as they are. + s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap(); + assert_eq!(top_level(&s), [ga, gb]); + assert_eq!(inside(&s, ga), [a]); +} + +#[test] +fn groups_above_an_emptied_group_go_in_turn_and_a_group_with_other_objects_stays() { + let mut s = session(); + // a in a group that is all of another group; c in a group with a square; b on the layer. + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + let c = circle(&mut s, 200.0, 100.0, 20.0); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 300, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let inner = make(&mut s, "object.group", &[a]); + let outer = make(&mut s, "object.group", &[inner]); + let gc = make(&mut s, "object.group", &[square, c]); + let layer = s.doc().unwrap().doc.layers[0].id; + let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + assert_eq!(ids(&r["ids"]), [c], "one shape, in the topmost circle's place"); + assert_eq!(top_level(&s), [gc], "both groups around a go, b goes from the layer"); + assert_eq!(inside(&s, gc), [c, square], "the group with the square stays"); + let d = &s.doc().unwrap().doc; + assert!(d.node(inner).is_none() && d.node(outer).is_none()); + assert!(d.node(layer).is_some(), "the layer stays"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(inside(&s, outer), [inner]); + assert_eq!(inside(&s, inner), [a]); +} + +#[test] +fn a_compound_path_the_bridged_circles_leave_empty_goes() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let compound = make(&mut s, "object.compoundPath.make", &[a]); + assert_eq!(inside(&s, compound), [a]); + s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(top_level(&s), [b]); + assert!(s.doc().unwrap().doc.node(compound).is_none()); +} + +#[test] +fn layers_and_sublayers_the_bridged_circles_leave_empty_stay() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let upper = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": upper.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let c = circle(&mut s, 220.0, 100.0, 20.0); + // a below in the first layer, b and c in the sublayer: c's shape takes a's and b's places. + s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0], "reach": 30})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.layers.iter().any(|l| l.id != upper && l.children().is_some_and(|c| c.is_empty())), "the emptied layer stays"); + assert_eq!(inside(&s, sub), [c]); + // The sublayer left with nothing in it stays too. + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let upper = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let sub = NodeId(s.execute("layer.newSublayer", &json!({"parent": upper.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let b = circle(&mut s, 160.0, 100.0, 20.0); + s.execute("layer.setCurrent", &json!({"id": upper.0})).unwrap(); + let c = circle(&mut s, 220.0, 100.0, 20.0); + s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0], "reach": 30})).unwrap(); + assert_eq!(inside(&s, sub), Vec::::new(), "the emptied sublayer stays"); + assert_eq!(inside(&s, upper), [sub, c]); +} + #[test] fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index e0e702d1cc..47247d1b8c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -16869,7 +16869,9 @@ Commands: larger radius or gap only when the largest (1,000% or 1,000 pt) would bridge the circles. The outline replaces the two circles, painted as the upper one (a plain path), unless `keepOriginals` is true: then it goes directly above the upper circle, painted as it, and the circles stay. The outline is selected. Two circles are bridged however far apart - their outlines are; `reach` does not apply to them. + their outlines are; `reach` does not apply to them. When outlines replace circles (with any number of circles), a group + or compound path that the circles leave with nothing in it is removed, and so is each group above it left empty in + turn; layers stay. With three or more circles, every two whose outlines are at most `reach` apart (0 to 10,000 pt, 10 by default; overlapping ones included) are bridged the same way, and the bridges that connect are united into one shape each, which can have holes where bridges enclose space; holes smaller than 1% of the smallest circle's area are filled. A From 1d880065f3168180a251a4a9102238f8d02d113c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 12:17:05 -0800 Subject: [PATCH 35/37] Smooth Bridge: test a selected group of grouped circles A selected group that holds two groups of one circle each keeps the group with the outline, and the lower circle's group is removed. --- .../src/cmd/addons/pathtools/bridge/tests.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs index 088b707af3..3630bd6650 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -398,6 +398,21 @@ fn a_compound_path_the_bridged_circles_leave_empty_goes() { assert!(s.doc().unwrap().doc.node(compound).is_none()); } +#[test] +fn a_selected_group_of_grouped_circles_keeps_only_the_outlines_group() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + let ga = make(&mut s, "object.group", &[a]); + let gb = make(&mut s, "object.group", &[b]); + let outer = make(&mut s, "object.group", &[ga, gb]); + select(&mut s, &[outer]); + s.execute(BRIDGE, &json!({})).unwrap(); + assert_eq!(top_level(&s), [outer]); + assert_eq!(inside(&s, outer), [gb], "the lower circle's group goes, the outline's stays"); + assert_eq!(inside(&s, gb), [b]); +} + #[test] fn layers_and_sublayers_the_bridged_circles_leave_empty_stay() { let mut s = session(); From 77ed30177516bc6c2ef7f1de6a564a0692ae50d8 Mon Sep 17 00:00:00 2001 From: BFlat Date: Tue, 1 Dec 2026 03:42:59 +0700 Subject: [PATCH 36/37] SVG import: refuse an SVG the memory can't hold instead of running out (#10303) * SVG import: refuse an SVG the memory can't hold instead of running out The element limit now follows the installed memory, or the process's cgroup limit where that is lower: about 8 KB an element, up to the 999,999 elements usvg reads. Past it the SVG is refused with an error naming the memory, before usvg makes its tree. Fixes #10165 * Tests: the shared element limit test follows the machine's limit --- Cargo.lock | 1 + crates/svg/Cargo.toml | 2 + crates/svg/src/import.rs | 13 +++++-- crates/svg/src/import/budget.rs | 54 ++++++++++++++++++++++++--- crates/svg/src/import/files.rs | 8 ++-- crates/svg/src/lib.rs | 6 ++- crates/svg/tests/it/import_details.rs | 21 +++++++++-- xtask/src/layers.rs | 2 + 8 files changed, 89 insertions(+), 18 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 170ad40f3d..5aff7bd0a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9049,6 +9049,7 @@ dependencies = [ "vectorcraft-effects", "vectorcraft-geom 0.25.1", "vectorcraft-pathops 0.25.1", + "vectorcraft-render", "vectorcraft-testkit", "vectorcraft-text", ] diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 310b9c8e6f..08fcbbd3de 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -21,6 +21,8 @@ vectorcraft-effects = { workspace = true } vectorcraft-brush = { workspace = true } vectorcraft-text = { workspace = true } vectorcraft-pathops = { workspace = true } +# Installed memory (cgroup limits included), which sizes the element limit. +vectorcraft-render = { workspace = true } kurbo = { workspace = true } # Image elements still go through usvg's image href resolution (src/import/files.rs, src/import/budget.rs). usvg = { workspace = true } diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 5e7afdd55a..20261eef95 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -28,6 +28,11 @@ pub(crate) use fx::BLEND; /// expansion bombs (#3564). pub const MAX_NODES: usize = if cfg!(target_arch = "wasm32") { 500_000 } else { 2_000_000 }; +/// Most elements an SVG may expand to on this machine, its memory considered (#10165). +pub fn max_elements() -> usize { + budget::max_elements() as usize +} + mod convert; mod importer; mod layers; @@ -112,7 +117,7 @@ pub(crate) fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) } let xml = parse(svg)?; // Before the style cascade of `depth::height`, as `import` measures it. - budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; + budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?; if depth::height(&xml, depth::MAX_ELEMENT_DEPTH).is_none() { return Err(too_deep()); } @@ -142,7 +147,7 @@ pub(crate) fn import_finding( let xml = parse(svg)?; // Before the style cascade of `depth::height` and the prepass, which keeps the declarations of // each element it reads; measured again below on the text usvg reads when that differs. - let spent = budget::check(&xml, budget::Cost::LIMITS, depth::MAX_ELEMENT_DEPTH)?; + let spent = budget::check(&xml, budget::Cost::limits(), depth::MAX_ELEMENT_DEPTH)?; let Some(height) = depth::height(&xml, depth::MAX_ELEMENT_DEPTH) else { return Err(too_deep()); }; @@ -165,8 +170,8 @@ pub(crate) fn import_finding( // Before usvg copies what ``s show and the style values of each copy: the text usvg reads. let spent = match &src { Cow::Borrowed(_) if !rewritten => spent, - Cow::Borrowed(_) => budget::check(&xml, budget::Cost::LIMITS, usize::MAX)?, - Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::LIMITS, usize::MAX)?, + Cow::Borrowed(_) => budget::check(&xml, budget::Cost::limits(), usize::MAX)?, + Cow::Owned(prepared) => budget::check(&parse(prepared)?, budget::Cost::limits(), usize::MAX)?, }; let files = found.files; files.spent_by_svg(spent); diff --git a/crates/svg/src/import/budget.rs b/crates/svg/src/import/budget.rs index 2520a8932a..b7b45f03da 100644 --- a/crates/svg/src/import/budget.rs +++ b/crates/svg/src/import/budget.rs @@ -6,8 +6,9 @@ //! sheets and the `style` attribute give the element, so a long style on an element that ``s //! copy, again and again in a chain, or that a style sheet rule gives to many elements, takes more //! memory than the file holds many times over. usvg stops past 1,000,000 elements, but only after -//! it has made them and copied their styles. An SVG past [`MAX_SVG_ELEMENTS`] elements or -//! [`MAX_COPIED_STYLES`] bytes of copied styles is refused here instead. +//! it has made them and copied their styles. An SVG past [`max_elements`] elements (fewer than +//! [`MAX_SVG_ELEMENTS`] when the machine's memory has room for fewer) or [`MAX_COPIED_STYLES`] +//! bytes of copied styles is refused here instead. //! //! The copies are counted, never made: each element's count is worked out once and added up, so a //! `` of an element costs one addition, however many elements its copy holds. References @@ -43,6 +44,32 @@ use crate::{MAX_ELEMENT_DEPTH, SvgError}; /// which usvg stops (its count includes a root of its own). pub(crate) const MAX_SVG_ELEMENTS: usize = if MAX_NODES < 999_999 { MAX_NODES } else { 999_999 }; +/// Memory an element takes, about, from reading the SVG to drawing what is made of it (bytes): a +/// 400,000-path SVG converted to PNG peaked at about 4.4 KB a path (#10165), with room to spare. +const ELEMENT_BYTES: u64 = 8 << 10; + +/// Most elements usvg may make of an SVG on this machine: [`MAX_SVG_ELEMENTS`], fewer when the +/// installed memory (or the process's cgroup limit) has room for fewer, so a large SVG is refused +/// with an error instead of running out of memory. +pub(crate) fn max_elements() -> u64 { + static LIMIT: std::sync::OnceLock = std::sync::OnceLock::new(); + *LIMIT.get_or_init(|| elements_for(vectorcraft_render::installed_memory())) +} + +/// [`max_elements`] with `memory` bytes installed (`None` or 0: not known). +fn elements_for(memory: Option) -> u64 { + memory.filter(|&m| m > 0).map_or(MAX_SVG_ELEMENTS as u64, |m| (m / ELEMENT_BYTES).min(MAX_SVG_ELEMENTS as u64)) +} + +/// The error for an SVG past [`max_elements`]: naming the memory when that is what limits it. +fn too_many_elements() -> SvgError { + let most = max_elements(); + match vectorcraft_render::installed_memory() { + Some(memory) if most < MAX_SVG_ELEMENTS as u64 => SvgError::TooLargeForMemory(most as usize, memory >> 20), + _ => SvgError::TooLarge(MAX_SVG_ELEMENTS), + } +} + /// Most bytes of style values usvg may copy into the elements of an SVG and the SVG images it /// shows, all together: VectorCraft's own limit. pub(crate) const MAX_COPIED_STYLES: u64 = 64 << 20; @@ -209,7 +236,9 @@ pub(crate) struct Cost { impl Cost { /// The most an SVG and the SVG images it shows may cost together. - pub(crate) const LIMITS: Cost = Cost { elements: MAX_SVG_ELEMENTS as u64, bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS }; + pub(crate) fn limits() -> Cost { + Cost { elements: max_elements(), bytes: MAX_COPIED_STYLES, tests: MAX_SELECTOR_TESTS } + } pub(crate) fn add(self, other: Cost) -> Cost { Cost { @@ -408,7 +437,7 @@ pub(super) fn check(xml: &roxmltree::Document, left: Cost, depth: usize) -> Resu pub(super) fn check_spending(xml: &roxmltree::Document, left: Cost, depth: usize) -> (Result, u64) { let (result, tests) = measure_spending(xml, left, depth); let result = result.map_err(|past| match past { - Past::Elements => SvgError::TooLarge(MAX_SVG_ELEMENTS), + Past::Elements => too_many_elements(), Past::Bytes => SvgError::StylesTooLarge((MAX_COPIED_STYLES >> 20) as usize), Past::Tests => SvgError::StylesTooComplex, Past::Depth => SvgError::TooDeep(MAX_ELEMENT_DEPTH), @@ -562,6 +591,19 @@ mod tests { assert_eq!(MAX_SVG_ELEMENTS, if cfg!(target_arch = "wasm32") { 500_000 } else { 999_999 }); } + #[test] + fn less_memory_reads_fewer_elements_up_to_the_element_limit() { + let most = MAX_SVG_ELEMENTS as u64; + assert_eq!(elements_for(None), most, "unknown memory"); + assert_eq!(elements_for(Some(0)), most, "unknown memory"); + assert_eq!(elements_for(Some(1 << 40)), most, "plenty of memory"); + // A 1 GiB container can't hold the 400,000 paths that took 1.77 GB (#10165). + let small = elements_for(Some(1 << 30)); + assert!(small < 400_000, "{small}"); + assert!(elements_for(Some(512 << 20)) < small); + assert!(max_elements() <= most); + } + #[test] fn style_sheet_rules_count_where_they_match() { let groups = "".repeat(4); @@ -614,7 +656,7 @@ mod tests { let xml = roxmltree::Document::parse(&deep).unwrap(); assert_eq!(measure(&xml, NO_LIMITS, MAX_ELEMENT_DEPTH).err(), Some(Past::Depth)); assert!(super::super::depth::height(&xml, MAX_ELEMENT_DEPTH).is_none()); - assert!(matches!(check(&xml, Cost::LIMITS, MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); + assert!(matches!(check(&xml, Cost::limits(), MAX_ELEMENT_DEPTH), Err(SvgError::TooDeep(_)))); for text in [chain(5, ""), svg("")] { let xml = roxmltree::Document::parse(&text).unwrap(); let height = super::super::depth::height(&xml, usize::MAX).unwrap_or(0); @@ -674,7 +716,7 @@ mod tests { fn a_selector_that_never_matches_stops_at_the_test_limit() { let never = nested(60, &format!(".missing{} {{fill:red}}", " g".repeat(20))); let xml = roxmltree::Document::parse(&never).unwrap(); - assert_eq!(measure(&xml, Cost::LIMITS, usize::MAX).err(), Some(Past::Tests)); + assert_eq!(measure(&xml, Cost::limits(), usize::MAX).err(), Some(Past::Tests)); let before = super::super::css::selector_tests(); let err = super::super::import(&never, &crate::ImportOptions::default(), MAX_NODES).err(); assert!(matches!(err, Some(SvgError::StylesTooComplex)), "{err:?}"); diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index 631bed3d0c..525e900c87 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -478,7 +478,7 @@ impl Files { // reads it ([`Files::svg_tree`]), which then refuses one past the limits, within what the // linked SVG files measured before it left: past it, its links aren't read, and the // selector tests it made still count. - let (result, tests) = budget::check_spending(&xml, budget::Cost::LIMITS.less(reading.measured), left); + let (result, tests) = budget::check_spending(&xml, budget::Cost::limits().less(reading.measured), left); match result { Ok(cost) => reading.measured = reading.measured.add(cost), Err(e) => { @@ -593,13 +593,13 @@ impl Files { } /// What usvg makes of the SVG holding the images ([`budget::check`]): its images make at most - /// what is left of [`budget::Cost::LIMITS`]. + /// what is left of [`budget::Cost::limits()`]. pub(in crate::import) fn spent_by_svg(&self, spent: budget::Cost) { self.set_spent(spent); } fn spent(&self) -> budget::Cost { - self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::LIMITS) + self.spent.lock().map(|s| *s).unwrap_or(budget::Cost::limits()) } fn set_spent(&self, spent: budget::Cost) { @@ -807,7 +807,7 @@ impl Files { // with theirs while usvg reads it, and only when it decodes. Too deep, it is left out; // past the other limits, the whole SVG is refused. let spent = self.spent(); - let cost = match budget::check(&xml, budget::Cost::LIMITS.less(spent), left) { + let cost = match budget::check(&xml, budget::Cost::limits().less(spent), left) { Ok(cost) => cost, Err(SvgError::TooDeep(_)) => return leave_out(&self.too_deep, true), Err(e) => { diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index ad3e91588f..0bcd5999b7 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -363,6 +363,10 @@ pub enum SvgError { /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} objects")] TooLarge(usize), + /// The SVG expands to more objects (the first number) than this machine's memory, or the + /// process's memory limit (the second number, in MB), has room to read (#10165). + #[error("the SVG expands to more than {0} objects, more than the {1} MB of memory available has room for")] + TooLargeForMemory(usize, u64), /// The SVG expands to more nested SVG images than the reader takes (a guard against /// nested-image expansion bombs, #3564). #[error("the SVG expands to more than {0} nested SVG images")] @@ -536,7 +540,7 @@ pub fn svg_filters(svg: &str, room: usize, taken: impl Fn(&str) -> bool) -> Resu pub use glyph::glyph_art; pub use import::{ MAX_DATA_URL_BYTES, MAX_ELEMENT_DEPTH, MAX_FOREIGN, MAX_FOREIGN_VALUE, MAX_NESTED_SVG_IMAGES, MAX_NESTED_SVG_READS, MAX_NESTED_SVG_TEXT, - MAX_NODES, + MAX_NODES, max_elements, }; /// Import an SVG document reading the files it links to as `opts` says, also returning warnings. diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 25c5152de9..a4046e3fe7 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -892,11 +892,22 @@ fn styles_that_expand_past_the_limit_are_refused() { assert_eq!(art(&d).len(), 5000); } +/// `err` refuses an SVG past the element limit: the most usvg reads, or fewer on a machine whose +/// memory has room for fewer (#10165). +fn past_the_element_limit(err: &SvgError) -> bool { + let most = vectorcraft_svg::MAX_NODES.min(999_999); + match *err { + SvgError::TooLarge(n) => n == most, + SvgError::TooLargeForMemory(n, _) => n < most && n == vectorcraft_svg::max_elements(), + _ => false, + } +} + /// A chain of ``s that makes more elements than usvg reads is refused before usvg makes them. #[test] fn a_use_chain_past_the_elements_usvg_reads_is_refused() { let err = import_with(&use_chain(20, ""), &ImportOptions::default()).unwrap_err(); - assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); + assert!(past_the_element_limit(&err), "{err:?}"); } /// An SVG image whose styles expand past the limit refuses the SVG showing it, and the SVG images @@ -927,9 +938,13 @@ fn svg_images_share_the_element_limit() { assert_ne!(chain, unshown); let image = image_of("image/svg+xml", &unshown); let rect = r#""#; - assert!(import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()).is_ok()); + // One image fits, unless this machine's memory has room for fewer elements than it makes. + match import_with(&svg(&format!("{rect}{image}")), &ImportOptions::default()) { + Ok(_) => {} + Err(err) => assert!(vectorcraft_svg::max_elements() < 700_000 && past_the_element_limit(&err), "{err:?}"), + } let err = import_with(&svg(&format!("{rect}{}", image.repeat(2))), &ImportOptions::default()).unwrap_err(); - assert!(matches!(err, SvgError::TooLarge(n) if n == vectorcraft_svg::MAX_NODES.min(999_999)), "{err:?}"); + assert!(past_the_element_limit(&err), "{err:?}"); } /// A `:not()` rule, which only the import's own style cascade reads, counts toward the style limit diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index f2fb1f1ce0..869074b03f 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -80,6 +80,8 @@ pub const INTRA_LAYER_ORDER: &[&[&str]] = &[ &["pathops", "trace"], &["text", "effects"], &["render", "eps"], + // SVG import sizes its element limit from the installed memory the renderer reads (#10165). + &["render", "svg"], &["metafile", "eps"], // Non-native art in Illustrator editing data is a PDF, drawn by the PDF importer. &["pdf", "eps"], From cf2d168d49e50f92ff03fd9b89e51de247c67219 Mon Sep 17 00:00:00 2001 From: BFlat Date: Tue, 1 Dec 2026 05:05:57 +0700 Subject: [PATCH 37/37] PDF import: inline images with the same dictionary keep their own pixels (#10313) An inline image has no object of its own, and the interpreter keys an image by its dictionary alone, so every inline image of one size and encoding got the key of the first one and was imported with its pixels: Type 3 glyphs drawn as inline stencil images came in as the wrong letters. An inline raster image is now keyed by its samples too, and a stencil image by its decoded pixels. Fixes #9247 --- crates/pdf/src/import/device.rs | 10 +++++++- crates/pdf/src/tests/import_fidelity.rs | 33 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 70aacd89cf..cd40578cec 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -246,8 +246,13 @@ impl<'a> Device<'a> for Builder<'_> { // replaces DeviceCMYK, so it is cached apart from the same image drawn where one does. let intent = !white && self.intent_cmyk.is_some() && self.scan.cmyk_defaults.get(&r.stream().dict().obj_id()) == Some(&false); // Inside an alpha mask the same image is read again, white (its own cache key). - let key = craft::pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 }; let st = r.stream(); + // An inline image (no object of its own) is keyed by its samples too: the + // interpreter keys an image by its dictionary, the same for inline images of one + // size and encoding (#9247). + let inline = if st.dict().obj_id().is_none() { crate::import_scan::hash128(&*st.raw_data()) } else { 0 }; + let key = + craft::pdf::interpret::CacheKey::cache_key(&r) ^ inline ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 }; let (w, h) = (r.width(), r.height()); // CMYK images keep their samples (read once per image). let known = !white && self.cmyk_keys.contains(&key); @@ -370,6 +375,9 @@ impl<'a> Device<'a> for Builder<'_> { None, ); let Some((px, w, h, sf)) = decoded else { return }; + // Keyed by its pixels too, as an inline raster image is by its samples: a stencil + // doesn't show its stream, and inline ones of one size share a dictionary (#9247). + let key = key ^ crate::import_scan::hash128(&px); let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64); match colorize { // Its own key: its pixels are the gray ones, whatever color paints it. diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 0be8dce82f..5fdafeb5fc 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -507,6 +507,39 @@ fn a_form_drawn_many_times_reads_its_font_resources_once() { assert_eq!(walk.fonts.len(), 1); } +/// Inline images with the same dictionary but other samples come in with their own pixels: the +/// stencil glyphs of a Type 3 font (#9247) and raster images on the page. +#[test] +fn inline_images_with_the_same_dictionary_keep_their_own_pixels() { + let n = first_extra(1); + let glyph = |hex: &str| { + stream("", &format!("1000 0 0 0 1000 1000 d1 q 1000 0 0 1000 0 0 cm BI /IM true /W 8 /H 8 /BPC 1 /D [1 0] /F /AHx ID\n{hex}>\nEI Q")) + }; + let objects = [ + format!( + "<< /Type /Font /Subtype /Type3 /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << /a {} 0 R /b {} 0 R >> /Encoding << /Type /Encoding /Differences [97 /a /b] >> /FirstChar 97 /LastChar 98 /Widths [1000 1000] /Resources << >> >>", + n + 1, + n + 2 + ), + glyph("1818181818181818"), + glyph("000000FFFF000000"), + ]; + let raster = |hex: &str| format!("q 10 0 0 10 0 0 cm BI /W 2 /H 1 /CS /RGB /BPC 8 /F /AHx ID\n{hex}>\nEI Q "); + let content = format!("BT /T3 24 Tf 10 30 Td (ab) Tj ET {}{}", raster("FF000000FF00"), raster("0000FFFFFFFF")); + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + let d = open(&one_page(&content, &format!("/Font << /T3 {n} 0 R >>"), &extra)); + let blobs: Vec>> = all(&d) + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Image(im) => Some(d.images[&im.key].bytes.clone()), + _ => None, + }) + .collect(); + assert_eq!(blobs.len(), 4, "two glyphs and two raster images"); + let distinct: std::collections::HashSet<&Arc>> = blobs.iter().collect(); + assert_eq!(distinct.len(), blobs.len(), "each image has its own pixels"); +} + /// A Type 3 font that every page lists in a font dictionary of its own, and a form lists in its /// resources, has its glyph procedures read once for the document. Each page still maps the font's /// glyphs, and the font whose glyphs set their own color (`d0`) is told from the one whose glyphs