From 1cc90036fb200fa4886875a0279298b991570b16 Mon Sep 17 00:00:00 2001 From: merik <93556297+xmerik@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:02:16 +0000 Subject: [PATCH 01/55] File: a command for each export format, so each can have a key (#10176) (#10177) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Export STEP…, STL…, 3MF…, OBJ… and URDF… were UI actions around the shared file.export, so Keyboard Shortcuts had no row for them. file.export_step, _stl, _3mf, _obj and _urdf now do what those items do when started from a key, command search or the menu (a save picker; Save As Mesh for STL and 3MF), and take a path when called with JSON. The File menu shows their keys. Each has a contract and a reply type (schema/file.rs). Co-authored-by: Claude Opus 5.5 --- .../pending/export-format-commands.json | 51 +++++++ crates/engine/src/cmd/file.rs | 124 ++++++++++++++-- crates/engine/src/schema/file.rs | 135 ++++++++++++++++++ crates/engine/src/schema/file_tests.rs | 38 +++++ crates/engine/src/schema/mod.rs | 1 + crates/engine/src/tests.rs | 11 +- crates/ui-egui/src/control_job.rs | 3 +- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/shortcut_box.rs | 4 + crates/ui-egui/src/toolbar.rs | 78 ++++++++-- 10 files changed, 424 insertions(+), 23 deletions(-) create mode 100644 assets/locales/pending/export-format-commands.json create mode 100644 crates/engine/src/schema/file.rs create mode 100644 crates/engine/src/schema/file_tests.rs diff --git a/assets/locales/pending/export-format-commands.json b/assets/locales/pending/export-format-commands.json new file mode 100644 index 000000000..463ef0815 --- /dev/null +++ b/assets/locales/pending/export-format-commands.json @@ -0,0 +1,51 @@ +{ + "en": { + "cmd.file.export_step": "Export STEP", + "cmd.file.export_stl": "Export STL", + "cmd.file.export_3mf": "Export 3MF", + "cmd.file.export_obj": "Export OBJ", + "cmd.file.export_urdf": "Export URDF" + }, + "de": { + "cmd.file.export_step": "Als STEP exportieren", + "cmd.file.export_stl": "Als STL exportieren", + "cmd.file.export_3mf": "Als 3MF exportieren", + "cmd.file.export_obj": "Als OBJ exportieren", + "cmd.file.export_urdf": "Als URDF exportieren" + }, + "ar": { + "cmd.file.export_step": "تصدير STEP", + "cmd.file.export_stl": "تصدير STL", + "cmd.file.export_3mf": "تصدير 3MF", + "cmd.file.export_obj": "تصدير OBJ", + "cmd.file.export_urdf": "تصدير URDF" + }, + "he": { + "cmd.file.export_step": "ייצוא STEP", + "cmd.file.export_stl": "ייצוא STL", + "cmd.file.export_3mf": "ייצוא 3MF", + "cmd.file.export_obj": "ייצוא OBJ", + "cmd.file.export_urdf": "ייצוא URDF" + }, + "ja": { + "cmd.file.export_step": "STEP をエクスポート", + "cmd.file.export_stl": "STL をエクスポート", + "cmd.file.export_3mf": "3MF をエクスポート", + "cmd.file.export_obj": "OBJ をエクスポート", + "cmd.file.export_urdf": "URDF をエクスポート" + }, + "vi": { + "cmd.file.export_step": "Xuất tệp STEP", + "cmd.file.export_stl": "Xuất tệp STL", + "cmd.file.export_3mf": "Xuất tệp 3MF", + "cmd.file.export_obj": "Xuất tệp OBJ", + "cmd.file.export_urdf": "Xuất tệp URDF" + }, + "zh": { + "cmd.file.export_step": "导出 STEP", + "cmd.file.export_stl": "导出 STL", + "cmd.file.export_3mf": "导出 3MF", + "cmd.file.export_obj": "导出 OBJ", + "cmd.file.export_urdf": "导出 URDF" + } +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 95100ebd4..9b2df48fd 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -61,6 +61,39 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("export") .noundo() .params("path; format?: stl|stla|obj|step|3mf|3mf-tagged|urdf|json (default from extension; 3mf-tagged: 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis tools; docs/formats/3mf-face-tags.md; obj: the colours of the bodies go in a material library (`.mtl`) written next to the mesh file; urdf: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md); bodies?: [names] (JSON and URDF export the complete design); urdf only: mesh_prefix? (before each mesh file name, e.g. package://robot/meshes/), effort? (default 1000), velocity? (default 10); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts)"), + // One command per format, so each File › Export item can have a key of its own; started + // from a key or command search, the app opens the save picker (the mesh dialog for STL and + // 3MF). Each takes `file.export`'s parameters for its format, without `format`. + CommandSpec::new("file.export_step", "Export STEP", crate::checked!("file.export_step", export_step)) + .icon("export") + .noundo() + .contract(&EXPORT_STEP_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body; a design with components then exports as a STEP assembly) → {path, bytes, format}: STEP, whatever the path's extension"), + CommandSpec::new("file.export_stl", "Export STL", crate::checked!("file.export_stl", export_stl)) + .icon("mesh_export") + .noundo() + .contract(&EXPORT_STL_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard) → {path, bytes, format}: binary STL, whatever the path's extension"), + CommandSpec::new("file.export_3mf", "Export 3MF", crate::checked!("file.export_3mf", export_3mf)) + .icon("mesh_export") + .noundo() + .contract(&EXPORT_3MF_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard); objects?: body|component (as file.export) → {path, bytes, format}: 3MF, whatever the path's extension"), + CommandSpec::new("file.export_obj", "Export OBJ", crate::checked!("file.export_obj", export_obj_cmd)) + .icon("export") + .noundo() + .contract(&EXPORT_OBJ_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; bodies?: [names] (default: every body); quality?: standard|fine|finest (default standard) → {path, bytes, format, files}: OBJ, with the colours of the bodies in a material library (`.mtl`) next to it"), + CommandSpec::new("file.export_urdf", "Export URDF", crate::checked!("file.export_urdf", export_urdf_cmd)) + .icon("export") + .noundo() + .contract(&EXPORT_URDF_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("path; mesh_prefix?; effort? (default 1000); velocity? (default 10) → {path, format, files, links, joints, warnings}: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md"), CommandSpec::new("file.save_mesh", "Save As Mesh", save_mesh) .at("INSERT", "FILES") .icon("mesh_export") @@ -89,6 +122,12 @@ fn new_doc(s: &mut Session, p: &Value) -> Result { Ok(json!({"name": name})) } +const EXPORT_STEP_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_STL_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_3MF_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_OBJ_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); +const EXPORT_URDF_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + fn path_arg<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> { str_(p, "path").filter(|x| !x.trim().is_empty() && x.len() < 4096).ok_or_else(|| bad(cmd, "`path` is required")) } @@ -700,6 +739,7 @@ fn component_parts(s: &Session) -> Vec<(String, Vec)> { fn export_to( s: &Session, + cmd: &str, path: &str, format: Format, bodies: &[String], @@ -714,7 +754,7 @@ fn export_to( // A design with components exports as a STEP assembly; otherwise bodies as placed. let bytes = if format == Format::Design { if !bodies.is_empty() { - return Err(bad("file.export", "design JSON exports the complete document; omit bodies")); + return Err(bad(cmd, "design JSON exports the complete document; omit bodies")); } solidcraft_io::write_design(&s.design()) } else if format == Format::Step && bodies.is_empty() && !s.doc.occurrences.is_empty() { @@ -753,11 +793,44 @@ fn export(s: &mut Session, p: &Value) -> Result { let path = path_arg(p, cmd)?; let format = Format::from_name(str_(p, "format").unwrap_or(path))?; if format == Format::Urdf { - return export_urdf(s, path, p); + if !string_list(cmd, p, "bodies")?.is_empty() { + return Err(bad(cmd, "urdf exports the whole assembly; omit bodies")); + } + return export_urdf(s, cmd, path, p); } let quality = mesh_quality(p, cmd)?; let parts = mesh_parts(s, p, cmd, format)?; - export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) + export_to(s, cmd, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) +} + +fn export_step(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_step"; + let path = path_arg(p, cmd)?; + export_to(s, cmd, path, Format::Step, &string_list(cmd, p, "bodies")?, &[], solidcraft_io::MeshQuality::default()) +} + +fn export_stl(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_stl"; + let path = path_arg(p, cmd)?; + export_to(s, cmd, path, Format::StlBinary, &string_list(cmd, p, "bodies")?, &[], mesh_quality(p, cmd)?) +} + +fn export_3mf(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_3mf"; + let path = path_arg(p, cmd)?; + let parts = mesh_parts(s, p, cmd, Format::ThreeMf)?; + export_to(s, cmd, path, Format::ThreeMf, &string_list(cmd, p, "bodies")?, &parts, mesh_quality(p, cmd)?) +} + +fn export_obj_cmd(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_obj"; + let path = path_arg(p, cmd)?; + export_to(s, cmd, path, Format::Obj, &string_list(cmd, p, "bodies")?, &[], mesh_quality(p, cmd)?) +} + +fn export_urdf_cmd(s: &mut Session, p: &Value) -> Result { + let cmd = "file.export_urdf"; + export_urdf(s, cmd, path_arg(p, cmd)?, p) } /// The OBJ export: the mesh file and the material library beside it, with the colours of the @@ -788,11 +861,7 @@ fn export_obj(s: &Session, path: &str, bodies: &[String], quality: solidcraft_io /// The assembly as a URDF and its meshes next to it (docs/urdf.md). Every path is checked before /// anything is written; the meshes go first and the `.urdf` last. -fn export_urdf(s: &Session, path: &str, p: &Value) -> Result { - let cmd = "file.export"; - if !string_list(cmd, p, "bodies")?.is_empty() { - return Err(bad(cmd, "urdf exports the whole assembly; omit bodies")); - } +fn export_urdf(s: &Session, cmd: &str, path: &str, p: &Value) -> Result { let positive = |k: &str| match p.get(k) { None | Some(Value::Null) => Ok(None), Some(_) => num(p, k).filter(|x| *x > 0.0).map(Some).ok_or_else(|| bad(cmd, format!("`{k}` must be a positive number"))), @@ -887,7 +956,7 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result { }, ); } - export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) + export_to(s, cmd, path, format, &string_list(cmd, p, "bodies")?, &parts, quality) } /// The browser build can't start a program. @@ -1050,6 +1119,43 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Each format's own export command (one key each in Keyboard Shortcuts) writes that format + /// whatever the path's extension, as `file.export` does with `format`, and says so. + #[test] + fn each_format_has_an_export_command_of_its_own() { + let dir = std::env::temp_dir().join(format!("solidcraft-export-per-format-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let at = |n: &str| dir.join(n).to_string_lossy().to_string(); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 20, "width": 10, "height": 5, "body_name": "Block"})).unwrap(); + for (cmd, format, signature) in [ + ("file.export_step", "Step", &b"ISO-10303-21;"[..]), + ("file.export_3mf", "ThreeMf", &b"PK"[..]), + ("file.export_obj", "Obj", &b""[..]), + ("file.export_stl", "StlBinary", &b""[..]), + ] { + // A name with another format's extension: the command, not the name, picks the format. + let path = at(&format!("{format}.txt")); + let r = s.execute(cmd, &json!({"path": path})).unwrap(); + assert_eq!((r["path"].as_str(), r["format"].as_str()), (Some(path.as_str()), Some(format)), "{cmd}: {r}"); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(r["bytes"].as_u64(), Some(bytes.len() as u64), "{cmd}"); + assert!(bytes.starts_with(signature), "{cmd}"); + } + // The triangles `file.export` writes (the 80-byte header holds the file's name): a box is + // 12 triangles, 84 + 50 bytes each. + s.execute("file.export", &json!({"path": at("box.stl")})).unwrap(); + assert_eq!(std::fs::read(at("StlBinary.txt")).unwrap()[80..], std::fs::read(at("box.stl")).unwrap()[80..]); + assert_eq!(std::fs::metadata(at("box.stl")).unwrap().len(), 84 + 50 * 12); + let obj = std::fs::read_to_string(at("Obj.txt")).unwrap(); + assert_eq!(obj.lines().filter(|l| l.starts_with("f ")).count(), 12, "{obj}"); + let r = s.execute("file.export_urdf", &json!({"path": at("robot.urdf")})).unwrap(); + assert_eq!(r["format"], "Urdf"); + assert!(std::fs::read_to_string(at("robot.urdf")).unwrap().contains(", +} + +/// Export bodies as a mesh file: binary STL for `file.export_stl`, OBJ for `file.export_obj` +/// (the colours of the bodies go in a material library, `.mtl`, written next to it). The file +/// has that format whatever the path's extension. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ExportMeshParams { + /// The file to write. + pub path: String, + /// The bodies to export, by name. Default: every body. + #[serde(default)] + pub bodies: Option, + /// How closely the mesh follows curved faces. Default: standard. + #[serde(default)] + pub quality: Option, +} + +/// Export bodies as a 3MF file, whatever the path's extension. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct Export3mfParams { + /// The file to write. + pub path: String, + /// The bodies to export, by name. Default: every body. + #[serde(default)] + pub bodies: Option, + /// How closely the mesh follows curved faces. Default: standard. + #[serde(default)] + pub quality: Option, + /// What each object in the file holds. Default: body. + #[serde(default)] + pub objects: Option, +} + +/// Export the whole assembly as a robot description (URDF), with an STL mesh for each link +/// written next to it (docs/urdf.md). +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct ExportUrdfParams { + /// The `.urdf` file to write; the meshes go in its folder. + pub path: String, + /// Put before each mesh file name in the URDF, such as `package://robot/meshes/`. Default: none. + #[serde(default)] + pub mesh_prefix: Option, + /// Each joint's effort limit, a positive number. Default: 1000. + #[serde(default)] + pub effort: Option, + /// Each joint's velocity limit, a positive number. Default: 10. + #[serde(default)] + pub velocity: Option, +} + +/// What `file.export_step`, `file.export_stl`, `file.export_3mf` and `file.export_obj` return. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ExportResult { + /// The file written. + pub path: String, + /// Its size in bytes. + pub bytes: usize, + /// The format written: Step, StlBinary, ThreeMf or Obj. + pub format: String, + /// OBJ only: every file written, the material library first and the mesh file last. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub files: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `file.export_urdf` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct UrdfExportResult { + /// The `.urdf` file written. + pub path: String, + /// Always Urdf. + pub format: String, + /// Every file written, the meshes first and the `.urdf` last. + pub files: Vec, + /// How many links the robot has. + pub links: usize, + /// How many joints the robot has. + pub joints: usize, + /// What the export could not carry over as it is in the design. + pub warnings: Vec, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "file_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/file_tests.rs b/crates/engine/src/schema/file_tests.rs new file mode 100644 index 000000000..f040637bf --- /dev/null +++ b/crates/engine/src/schema/file_tests.rs @@ -0,0 +1,38 @@ +use serde_json::json; + +use super::{Export3mfParams, ExportMeshParams, ExportStepParams, ExportUrdfParams}; +use crate::Session; +use crate::schema::tests::assert_keys; +use crate::schema::{ParamCheck, input_schema_for}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["bodies", "path"]); + assert_keys(input_schema_for::(), &["bodies", "path", "quality"]); + assert_keys(input_schema_for::(), &["bodies", "objects", "path", "quality"]); + assert_keys(input_schema_for::(), &["effort", "mesh_prefix", "path", "velocity"]); +} + +#[test] +fn bad_calls_say_what_is_wrong_and_write_nothing() { + let dir = std::env::temp_dir().join(format!("solidcraft-export-schemas-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}")); + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}")); + for cmd in ["file.export_step", "file.export_stl", "file.export_3mf", "file.export_obj", "file.export_urdf"] { + let e = s.execute(cmd, &json!({})).unwrap_err().to_string(); + assert!(e.contains(cmd) && e.contains("path"), "{cmd}: {e}"); + } + let at = dir.join("a.stl").to_string_lossy().to_string(); + let e = s.execute("file.export_stl", &json!({"path": at, "quality": "rough"})).unwrap_err().to_string(); + assert!(e.contains("quality"), "{e}"); + s.param_check = ParamCheck::Strict; + let e = s.execute("file.export_stl", &json!({"path": at, "objects": "component"})).unwrap_err().to_string(); + assert!(e.contains("objects"), "objects is for 3MF only: {e}"); + s.param_check = ParamCheck::Off; + let e = s.execute("file.export_urdf", &json!({"path": at, "effort": -1})).unwrap_err().to_string(); + assert!(e.contains("effort"), "{e}"); + assert_eq!(std::fs::read_dir(&dir).map(|d| d.count()).unwrap_or(0), 0, "nothing written"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 4896d91e1..eeb03e524 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -58,6 +58,7 @@ pub mod component; pub mod construct; pub mod edit; pub mod features; +pub mod file; pub mod inspect; pub mod joints; pub mod mass_properties; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e689a8ff8..e2dfd5e39 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -889,8 +889,15 @@ fn hostile_params_never_panic() { while let Some(&id) = ids.get(next.fetch_add(1, std::sync::atomic::Ordering::Relaxed)) { for v in hostile_values() { for k in keys { - if k == "path" && (id.starts_with("parameters.") || id == "timeline.export_script") { - continue; // parameter and script files: covered by their own tests (no stray files) + if k == "path" + && (id.starts_with("parameters.") + || id == "timeline.export_script" + || matches!( + id, + "file.export_3mf" | "file.export_obj" | "file.export_step" | "file.export_stl" | "file.export_urdf" + )) + { + continue; // parameter, script and export files: covered by their own tests (no stray files) } let mut s = Session::default(); // A model with a sketch, a body and an active sketch, so most commands get far. diff --git a/crates/ui-egui/src/control_job.rs b/crates/ui-egui/src/control_job.rs index 5b8f7bf71..03b30c327 100644 --- a/crates/ui-egui/src/control_job.rs +++ b/crates/ui-egui/src/control_job.rs @@ -67,7 +67,8 @@ const AHEAD_AREAS: &[&str] = &[ const NAMES_A_FILE: &[&str] = &["path", "paths", "file", "files", "dir", "folder", "url", "out"]; /// Commands that change nothing in the design and write a file: they run on a copy. -const ANSWERED_ON_A_COPY: &[&str] = &["file.export", "file.save_mesh"]; +const ANSWERED_ON_A_COPY: &[&str] = + &["file.export", "file.export_3mf", "file.export_obj", "file.export_step", "file.export_stl", "file.export_urdf", "file.save_mesh"]; /// Commands that only read the design, which can take long on a large one (a measure of every /// body, an inspection that measures them, #4604; a clearance or interference check of every pair diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8dfdf51c0..e38f7ea7a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1746,7 +1746,7 @@ impl SolveApp { dim_view::cancel(); self.tool = None; self.home.open = false; - if dialogs_sheet::start_export(self, id) { + if dialogs_sheet::start_export(self, id) || toolbar::start_export(self, id) { return; } if id == "component.finish_edit" { diff --git a/crates/ui-egui/src/shortcut_box.rs b/crates/ui-egui/src/shortcut_box.rs index 91afb68c5..d2276f014 100644 --- a/crates/ui-egui/src/shortcut_box.rs +++ b/crates/ui-egui/src/shortcut_box.rs @@ -173,6 +173,10 @@ fn keywords(id: &str) -> &'static str { match id { "file.save_mesh" => "export stl 3mf mesh 3d print printing slicer", "file.export" => "export stl 3mf obj step urdf mesh 3d print", + "file.export_step" => "stp cad", + "file.export_stl" | "file.export_3mf" => "mesh 3d print printing", + "file.export_obj" => "mesh", + "file.export_urdf" => "robot ros simulation", _ => "", } } diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 07ba04b0e..2a565528e 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -703,32 +703,36 @@ fn file_menu(app: &mut SolveApp, ctx: &egui::Context) { close = true; } ui.separator(); - if item_if(ui, "Export STL…", "", "mesh_export", shown) { - FileAction::ExportMesh("stl").run(app); + // Each format's item runs its own command, so it shows that command's key. + let key = |id: &str| crate::keymap::effective(app, id).unwrap_or_default(); + let (stl_key, mf_key, step_key, obj_key, urdf_key) = + (key("file.export_stl"), key("file.export_3mf"), key("file.export_step"), key("file.export_obj"), key("file.export_urdf")); + if item_if(ui, "Export STL…", &stl_key, "mesh_export", shown) { + FileAction::Command("file.export_stl").run(app); close = true; } - if item_if(ui, "Export 3MF…", "", "mesh_export", shown) { - FileAction::ExportMesh("3mf").run(app); + if item_if(ui, "Export 3MF…", &mf_key, "mesh_export", shown) { + FileAction::Command("file.export_3mf").run(app); close = true; } if item_if(ui, "Send to Slicer", "", "mesh_export", shown && crate::dialogs_save_mesh::available(app)) { app.start("file.send_to_slicer"); close = true; } - if item_if(ui, "Export STEP…", "", "export", shown) { - FileAction::Export("step").run(app); + if item_if(ui, "Export STEP…", &step_key, "export", shown) { + FileAction::Command("file.export_step").run(app); close = true; } if item_if(ui, app.tr_label("Export Current View as DXF…"), "", "export", shown) { FileAction::Command("file.export_view_dxf").run(app); close = true; } - if item_if(ui, "Export OBJ…", "", "export", shown) { - FileAction::Export("obj").run(app); + if item_if(ui, "Export OBJ…", &obj_key, "export", shown) { + FileAction::Command("file.export_obj").run(app); close = true; } - if item_if(ui, "Export URDF…", "", "export", shown) { - FileAction::Export("urdf").run(app); + if item_if(ui, "Export URDF…", &urdf_key, "export", shown) { + FileAction::Command("file.export_urdf").run(app); close = true; } if item(ui, "Export Design as JSON…", "", "export") { @@ -838,6 +842,30 @@ pub(crate) fn export(app: &mut SolveApp, ext: &str) { export_as(app, ext, None); } +/// Each format's own export command, started from its key, command search or the File menu, +/// does what that File › Export item does: STEP, OBJ and URDF ask where to save, STL and 3MF +/// open the mesh dialog with the format chosen. `false`: `id` is no such command. +pub(crate) fn start_export(app: &mut SolveApp, id: &str) -> bool { + let (extension, mesh) = match id { + "file.export_step" => ("step", false), + "file.export_obj" => ("obj", false), + "file.export_urdf" => ("urdf", false), + "file.export_stl" => ("stl", true), + "file.export_3mf" => ("3mf", true), + _ => return false, + }; + // As the File menu's items: not while a file is being picked or loaded, or behind a bug report. + if !FileAction::Export(extension).enabled(app) { + return true; + } + if mesh { + crate::dialogs_save_mesh::start_with_format(app, extension); + } else { + export(app, extension); + } + true +} + /// Export to a file with extension `ext`, in `format` when the extension alone doesn't name it. fn export_as(app: &mut SolveApp, ext: &str, format: Option<&str>) { let name = format!("{}.{ext}", app.session.doc.name); @@ -3466,6 +3494,36 @@ mod header_report_tests { assert!(FileAction::Export("step").enabled(&h.app)); } + /// File › Export STEP…, STL…, 3MF…, OBJ… and URDF… each run a command of their own, so each + /// can be given a key in Keyboard Shortcuts: the key asks where to save the file as the menu + /// item does (STL and 3MF open Save As Mesh). + #[test] + fn each_export_format_has_a_key_that_starts_it() { + let mut h = crate::scenario::Harness::new(); + let offered = std::rc::Rc::new(std::cell::RefCell::new(Vec::<(String, Vec)>::new())); + let (seen, dir) = (offered.clone(), h.dir.clone()); + h.app.services.pick_save = Some(Box::new(move |name, extensions| { + seen.borrow_mut().push((name.to_string(), extensions.iter().map(|e| e.to_string()).collect())); + Box::pin(std::future::ready(Some(dir.join(name).to_string_lossy().into_owned()))) + })); + h.app.run("solid.box", json!({"length":2,"width":3,"height":4})).unwrap(); + h.app.session.doc_mut().name = "Bracket".into(); + for (id, key) in [("file.export_step", "Alt+Shift+F7"), ("file.export_stl", "Alt+Shift+F8")] { + crate::keymap::bind(&mut h.app, id, key, false).unwrap(); + assert_eq!(crate::keymap::effective(&h.app, id).as_deref(), Some(key), "the File menu shows it"); + } + crate::keymap::press(&mut h.app, "Alt+Shift+F7", false); + h.frames(3); + h.settle(); + assert_eq!(offered.borrow().last().cloned(), Some(("Bracket.step".to_string(), vec!["step".to_string()]))); + let step = std::fs::read(h.dir.join("Bracket.step")).unwrap(); + assert!(step.starts_with(b"ISO-10303-21;"), "a STEP file is written"); + + crate::keymap::press(&mut h.app, "Alt+Shift+F8", false); + assert_eq!(h.app.dialog.as_ref().and_then(|d| d.command()), Some("file.save_mesh"), "STL opens Save As Mesh"); + crate::dialogs::cancel(&mut h.app); + } + /// New designs are saved as `.sc`. A design opened from a `.solidcraft` file is saved back to /// that file by Save (no rename behind the user's back); Save As offers `.sc` and leaves it. #[test] From c454c05f88de270a41e379031f86ec91a8d5c365 Mon Sep 17 00:00:00 2001 From: Nathan Dane Date: Sun, 1 Nov 2026 18:02:24 +0000 Subject: [PATCH 02/55] Preferences redesign 1/11: design reference in docs (#9873) (#9889) * claim: #9873 * Add the Preferences design reference: pages, figures, measurements, tokens * Fix the selection look in the design reference to match the app --- attribution/pending/preferences-v2.md | 124 +++++++++++++++ docs/design/preferences/README.md | 143 +++++++++++++++++ docs/design/preferences/figures/README.md | 111 +++++++++++++ .../design/preferences/figures/aa-2x.dark.svg | 1 + .../preferences/figures/aa-2x.light.svg | 1 + .../design/preferences/figures/aa-4x.dark.svg | 1 + .../preferences/figures/aa-4x.light.svg | 1 + .../design/preferences/figures/aa-8x.dark.svg | 1 + .../preferences/figures/aa-8x.light.svg | 1 + .../preferences/figures/aa-off.dark.svg | 1 + .../preferences/figures/aa-off.light.svg | 1 + .../figures/agent-pointer-speed.dark.svg | 1 + .../figures/agent-pointer-speed.light.svg | 1 + .../design/preferences/figures/ao-on.dark.svg | 1 + .../preferences/figures/ao-on.light.svg | 1 + .../figures/assembly-move.dark.svg | 1 + .../figures/assembly-move.light.svg | 1 + .../preferences/figures/browser-card.dark.svg | 1 + .../figures/browser-card.light.svg | 1 + .../figures/browser-column.dark.svg | 1 + .../figures/browser-column.light.svg | 1 + .../figures/colour-vision-axes.dark.svg | 1 + .../figures/colour-vision-axes.light.svg | 1 + .../figures/colour-vision-bends.dark.svg | 1 + .../figures/colour-vision-bends.light.svg | 1 + .../figures/colour-vision-draft.dark.svg | 1 + .../figures/colour-vision-draft.light.svg | 1 + .../figures/colour-vision-failed.dark.svg | 1 + .../figures/colour-vision-failed.light.svg | 1 + .../figures/colour-vision-fixed.dark.svg | 1 + .../figures/colour-vision-fixed.light.svg | 1 + .../figures/colour-vision-projected.dark.svg | 1 + .../figures/colour-vision-projected.light.svg | 1 + .../figures/direct-interaction.dark.svg | 1 + .../figures/direct-interaction.light.svg | 1 + .../preferences/figures/frame-rate.dark.svg | 1 + .../preferences/figures/frame-rate.light.svg | 1 + .../figures/history-bottom.dark.svg | 1 + .../figures/history-bottom.light.svg | 1 + .../figures/history-in-browser.dark.svg | 1 + .../figures/history-in-browser.light.svg | 1 + .../preferences/figures/history-left.dark.svg | 1 + .../figures/history-left.light.svg | 1 + .../figures/history-under-browser.dark.svg | 1 + .../figures/history-under-browser.light.svg | 1 + .../figures/layout-schematic.dark.svg | 1 + .../figures/layout-schematic.light.svg | 1 + .../figures/measure-axis-distances.dark.svg | 1 + .../figures/measure-axis-distances.light.svg | 1 + .../figures/mouse-mapping.dark.svg | 1 + .../figures/mouse-mapping.light.svg | 1 + .../figures/navigator-axes.dark.svg | 1 + .../figures/navigator-axes.light.svg | 1 + .../figures/navigator-cube.dark.svg | 1 + .../figures/navigator-cube.light.svg | 1 + .../preferences/figures/orbit-centre.dark.svg | 1 + .../figures/orbit-centre.light.svg | 1 + .../preferences/figures/orbit-cursor.dark.svg | 1 + .../figures/orbit-cursor.light.svg | 1 + .../preferences/figures/orbit-origin.dark.svg | 1 + .../figures/orbit-origin.light.svg | 1 + .../figures/orientation-y-up.dark.svg | 1 + .../figures/orientation-y-up.light.svg | 1 + .../figures/orientation-z-up.dark.svg | 1 + .../figures/orientation-z-up.light.svg | 1 + .../figures/quick-measure.dark.svg | 1 + .../figures/quick-measure.light.svg | 1 + .../figures/select-bodies.dark.svg | 1 + .../figures/select-bodies.light.svg | 1 + .../figures/select-faces-edges.dark.svg | 1 + .../figures/select-faces-edges.light.svg | 1 + .../figures/sketch-conflict.dark.svg | 1 + .../figures/sketch-conflict.light.svg | 1 + .../figures/sketch-exit-keep.dark.svg | 1 + .../figures/sketch-exit-keep.light.svg | 1 + .../figures/sketch-exit-previous.dark.svg | 1 + .../figures/sketch-exit-previous.light.svg | 1 + .../sketch-exit-unless-turned.dark.svg | 1 + .../sketch-exit-unless-turned.light.svg | 1 + .../figures/sketch-guides.dark.svg | 1 + .../figures/sketch-guides.light.svg | 1 + .../figures/sketch-hide-glyphs.dark.svg | 1 + .../figures/sketch-hide-glyphs.light.svg | 1 + .../figures/sketch-state-icons.dark.svg | 1 + .../figures/sketch-state-icons.light.svg | 1 + .../figures/style-shaded-edges.dark.svg | 1 + .../figures/style-shaded-edges.light.svg | 1 + .../preferences/figures/tess-coarse.dark.svg | 1 + .../preferences/figures/tess-coarse.light.svg | 1 + .../preferences/figures/tess-fine.dark.svg | 1 + .../preferences/figures/tess-fine.light.svg | 1 + .../preferences/figures/tess-normal.dark.svg | 1 + .../preferences/figures/tess-normal.light.svg | 1 + .../preferences/figures/tess-ultra.dark.svg | 1 + .../preferences/figures/tess-ultra.light.svg | 1 + .../preferences/figures/theme-dark.dark.svg | 1 + .../preferences/figures/theme-dark.light.svg | 1 + .../figures/theme-gruvbox.dark.svg | 1 + .../figures/theme-gruvbox.light.svg | 1 + .../figures/theme-imported.dark.svg | 1 + .../figures/theme-imported.light.svg | 1 + .../preferences/figures/theme-light.dark.svg | 1 + .../preferences/figures/theme-light.light.svg | 1 + .../figures/theme-system-dark-half.dark.svg | 1 + .../figures/theme-system-dark-half.light.svg | 1 + .../figures/theme-system-light-half.dark.svg | 1 + .../figures/theme-system-light-half.light.svg | 1 + .../preferences/figures/tool-cursor.dark.svg | 1 + .../preferences/figures/tool-cursor.light.svg | 1 + .../preferences/figures/tool-extrude.dark.svg | 1 + .../figures/tool-extrude.light.svg | 1 + .../preferences/figures/tool-hole.dark.svg | 1 + .../preferences/figures/tool-hole.light.svg | 1 + .../figures/tool-placement.dark.svg | 1 + .../figures/tool-placement.light.svg | 1 + .../figures/vertex-markers.dark.svg | 1 + .../figures/vertex-markers.light.svg | 1 + .../preferences/figures/view-angles.dark.svg | 1 + .../preferences/figures/view-angles.light.svg | 1 + .../preferences/figures/view-grid.dark.svg | 1 + .../preferences/figures/view-grid.light.svg | 1 + .../figures/view-perspective.dark.svg | 1 + .../figures/view-perspective.light.svg | 1 + .../preferences/figures/view-shadow.dark.svg | 1 + .../preferences/figures/view-shadow.light.svg | 1 + docs/design/preferences/measurements.md | 84 ++++++++++ docs/design/preferences/pages/appearance.md | 67 ++++++++ docs/design/preferences/pages/assistant.md | 61 +++++++ docs/design/preferences/pages/design.md | 50 ++++++ docs/design/preferences/pages/general.md | 73 +++++++++ docs/design/preferences/pages/graphics.md | 77 +++++++++ docs/design/preferences/pages/layout.md | 80 ++++++++++ docs/design/preferences/pages/mouse3d.md | 52 ++++++ docs/design/preferences/pages/navigation.md | 55 +++++++ docs/design/preferences/pages/plugins.md | 32 ++++ docs/design/preferences/pages/shortcuts.md | 39 +++++ docs/design/preferences/pages/sketch.md | 65 ++++++++ docs/design/preferences/pages/tools.md | 41 +++++ docs/design/preferences/tokens.md | 150 ++++++++++++++++++ 139 files changed, 1426 insertions(+) create mode 100644 attribution/pending/preferences-v2.md create mode 100644 docs/design/preferences/README.md create mode 100644 docs/design/preferences/figures/README.md create mode 100644 docs/design/preferences/figures/aa-2x.dark.svg create mode 100644 docs/design/preferences/figures/aa-2x.light.svg create mode 100644 docs/design/preferences/figures/aa-4x.dark.svg create mode 100644 docs/design/preferences/figures/aa-4x.light.svg create mode 100644 docs/design/preferences/figures/aa-8x.dark.svg create mode 100644 docs/design/preferences/figures/aa-8x.light.svg create mode 100644 docs/design/preferences/figures/aa-off.dark.svg create mode 100644 docs/design/preferences/figures/aa-off.light.svg create mode 100644 docs/design/preferences/figures/agent-pointer-speed.dark.svg create mode 100644 docs/design/preferences/figures/agent-pointer-speed.light.svg create mode 100644 docs/design/preferences/figures/ao-on.dark.svg create mode 100644 docs/design/preferences/figures/ao-on.light.svg create mode 100644 docs/design/preferences/figures/assembly-move.dark.svg create mode 100644 docs/design/preferences/figures/assembly-move.light.svg create mode 100644 docs/design/preferences/figures/browser-card.dark.svg create mode 100644 docs/design/preferences/figures/browser-card.light.svg create mode 100644 docs/design/preferences/figures/browser-column.dark.svg create mode 100644 docs/design/preferences/figures/browser-column.light.svg create mode 100644 docs/design/preferences/figures/colour-vision-axes.dark.svg create mode 100644 docs/design/preferences/figures/colour-vision-axes.light.svg create mode 100644 docs/design/preferences/figures/colour-vision-bends.dark.svg create mode 100644 docs/design/preferences/figures/colour-vision-bends.light.svg create mode 100644 docs/design/preferences/figures/colour-vision-draft.dark.svg create mode 100644 docs/design/preferences/figures/colour-vision-draft.light.svg create mode 100644 docs/design/preferences/figures/colour-vision-failed.dark.svg create mode 100644 docs/design/preferences/figures/colour-vision-failed.light.svg create mode 100644 docs/design/preferences/figures/colour-vision-fixed.dark.svg create mode 100644 docs/design/preferences/figures/colour-vision-fixed.light.svg create mode 100644 docs/design/preferences/figures/colour-vision-projected.dark.svg create mode 100644 docs/design/preferences/figures/colour-vision-projected.light.svg create mode 100644 docs/design/preferences/figures/direct-interaction.dark.svg create mode 100644 docs/design/preferences/figures/direct-interaction.light.svg create mode 100644 docs/design/preferences/figures/frame-rate.dark.svg create mode 100644 docs/design/preferences/figures/frame-rate.light.svg create mode 100644 docs/design/preferences/figures/history-bottom.dark.svg create mode 100644 docs/design/preferences/figures/history-bottom.light.svg create mode 100644 docs/design/preferences/figures/history-in-browser.dark.svg create mode 100644 docs/design/preferences/figures/history-in-browser.light.svg create mode 100644 docs/design/preferences/figures/history-left.dark.svg create mode 100644 docs/design/preferences/figures/history-left.light.svg create mode 100644 docs/design/preferences/figures/history-under-browser.dark.svg create mode 100644 docs/design/preferences/figures/history-under-browser.light.svg create mode 100644 docs/design/preferences/figures/layout-schematic.dark.svg create mode 100644 docs/design/preferences/figures/layout-schematic.light.svg create mode 100644 docs/design/preferences/figures/measure-axis-distances.dark.svg create mode 100644 docs/design/preferences/figures/measure-axis-distances.light.svg create mode 100644 docs/design/preferences/figures/mouse-mapping.dark.svg create mode 100644 docs/design/preferences/figures/mouse-mapping.light.svg create mode 100644 docs/design/preferences/figures/navigator-axes.dark.svg create mode 100644 docs/design/preferences/figures/navigator-axes.light.svg create mode 100644 docs/design/preferences/figures/navigator-cube.dark.svg create mode 100644 docs/design/preferences/figures/navigator-cube.light.svg create mode 100644 docs/design/preferences/figures/orbit-centre.dark.svg create mode 100644 docs/design/preferences/figures/orbit-centre.light.svg create mode 100644 docs/design/preferences/figures/orbit-cursor.dark.svg create mode 100644 docs/design/preferences/figures/orbit-cursor.light.svg create mode 100644 docs/design/preferences/figures/orbit-origin.dark.svg create mode 100644 docs/design/preferences/figures/orbit-origin.light.svg create mode 100644 docs/design/preferences/figures/orientation-y-up.dark.svg create mode 100644 docs/design/preferences/figures/orientation-y-up.light.svg create mode 100644 docs/design/preferences/figures/orientation-z-up.dark.svg create mode 100644 docs/design/preferences/figures/orientation-z-up.light.svg create mode 100644 docs/design/preferences/figures/quick-measure.dark.svg create mode 100644 docs/design/preferences/figures/quick-measure.light.svg create mode 100644 docs/design/preferences/figures/select-bodies.dark.svg create mode 100644 docs/design/preferences/figures/select-bodies.light.svg create mode 100644 docs/design/preferences/figures/select-faces-edges.dark.svg create mode 100644 docs/design/preferences/figures/select-faces-edges.light.svg create mode 100644 docs/design/preferences/figures/sketch-conflict.dark.svg create mode 100644 docs/design/preferences/figures/sketch-conflict.light.svg create mode 100644 docs/design/preferences/figures/sketch-exit-keep.dark.svg create mode 100644 docs/design/preferences/figures/sketch-exit-keep.light.svg create mode 100644 docs/design/preferences/figures/sketch-exit-previous.dark.svg create mode 100644 docs/design/preferences/figures/sketch-exit-previous.light.svg create mode 100644 docs/design/preferences/figures/sketch-exit-unless-turned.dark.svg create mode 100644 docs/design/preferences/figures/sketch-exit-unless-turned.light.svg create mode 100644 docs/design/preferences/figures/sketch-guides.dark.svg create mode 100644 docs/design/preferences/figures/sketch-guides.light.svg create mode 100644 docs/design/preferences/figures/sketch-hide-glyphs.dark.svg create mode 100644 docs/design/preferences/figures/sketch-hide-glyphs.light.svg create mode 100644 docs/design/preferences/figures/sketch-state-icons.dark.svg create mode 100644 docs/design/preferences/figures/sketch-state-icons.light.svg create mode 100644 docs/design/preferences/figures/style-shaded-edges.dark.svg create mode 100644 docs/design/preferences/figures/style-shaded-edges.light.svg create mode 100644 docs/design/preferences/figures/tess-coarse.dark.svg create mode 100644 docs/design/preferences/figures/tess-coarse.light.svg create mode 100644 docs/design/preferences/figures/tess-fine.dark.svg create mode 100644 docs/design/preferences/figures/tess-fine.light.svg create mode 100644 docs/design/preferences/figures/tess-normal.dark.svg create mode 100644 docs/design/preferences/figures/tess-normal.light.svg create mode 100644 docs/design/preferences/figures/tess-ultra.dark.svg create mode 100644 docs/design/preferences/figures/tess-ultra.light.svg create mode 100644 docs/design/preferences/figures/theme-dark.dark.svg create mode 100644 docs/design/preferences/figures/theme-dark.light.svg create mode 100644 docs/design/preferences/figures/theme-gruvbox.dark.svg create mode 100644 docs/design/preferences/figures/theme-gruvbox.light.svg create mode 100644 docs/design/preferences/figures/theme-imported.dark.svg create mode 100644 docs/design/preferences/figures/theme-imported.light.svg create mode 100644 docs/design/preferences/figures/theme-light.dark.svg create mode 100644 docs/design/preferences/figures/theme-light.light.svg create mode 100644 docs/design/preferences/figures/theme-system-dark-half.dark.svg create mode 100644 docs/design/preferences/figures/theme-system-dark-half.light.svg create mode 100644 docs/design/preferences/figures/theme-system-light-half.dark.svg create mode 100644 docs/design/preferences/figures/theme-system-light-half.light.svg create mode 100644 docs/design/preferences/figures/tool-cursor.dark.svg create mode 100644 docs/design/preferences/figures/tool-cursor.light.svg create mode 100644 docs/design/preferences/figures/tool-extrude.dark.svg create mode 100644 docs/design/preferences/figures/tool-extrude.light.svg create mode 100644 docs/design/preferences/figures/tool-hole.dark.svg create mode 100644 docs/design/preferences/figures/tool-hole.light.svg create mode 100644 docs/design/preferences/figures/tool-placement.dark.svg create mode 100644 docs/design/preferences/figures/tool-placement.light.svg create mode 100644 docs/design/preferences/figures/vertex-markers.dark.svg create mode 100644 docs/design/preferences/figures/vertex-markers.light.svg create mode 100644 docs/design/preferences/figures/view-angles.dark.svg create mode 100644 docs/design/preferences/figures/view-angles.light.svg create mode 100644 docs/design/preferences/figures/view-grid.dark.svg create mode 100644 docs/design/preferences/figures/view-grid.light.svg create mode 100644 docs/design/preferences/figures/view-perspective.dark.svg create mode 100644 docs/design/preferences/figures/view-perspective.light.svg create mode 100644 docs/design/preferences/figures/view-shadow.dark.svg create mode 100644 docs/design/preferences/figures/view-shadow.light.svg create mode 100644 docs/design/preferences/measurements.md create mode 100644 docs/design/preferences/pages/appearance.md create mode 100644 docs/design/preferences/pages/assistant.md create mode 100644 docs/design/preferences/pages/design.md create mode 100644 docs/design/preferences/pages/general.md create mode 100644 docs/design/preferences/pages/graphics.md create mode 100644 docs/design/preferences/pages/layout.md create mode 100644 docs/design/preferences/pages/mouse3d.md create mode 100644 docs/design/preferences/pages/navigation.md create mode 100644 docs/design/preferences/pages/plugins.md create mode 100644 docs/design/preferences/pages/shortcuts.md create mode 100644 docs/design/preferences/pages/sketch.md create mode 100644 docs/design/preferences/pages/tools.md create mode 100644 docs/design/preferences/tokens.md diff --git a/attribution/pending/preferences-v2.md b/attribution/pending/preferences-v2.md new file mode 100644 index 000000000..2ffbd29f9 --- /dev/null +++ b/attribution/pending/preferences-v2.md @@ -0,0 +1,124 @@ +| File | Author | Source | Licence | +|---|---|---|---| +| docs/design/preferences/figures/aa-2x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-2x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-4x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-4x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-8x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-8x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-off.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-off.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/agent-pointer-speed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/agent-pointer-speed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/ao-on.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/ao-on.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/assembly-move.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/assembly-move.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-card.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-card.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-column.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-column.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-bends.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-bends.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-draft.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-draft.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-failed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-failed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-fixed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-fixed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-projected.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-projected.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/direct-interaction.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/direct-interaction.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/frame-rate.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/frame-rate.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-bottom.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-bottom.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-in-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-in-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-left.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-left.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-under-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-under-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/layout-schematic.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/layout-schematic.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/measure-axis-distances.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/measure-axis-distances.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/mouse-mapping.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/mouse-mapping.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-cube.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-cube.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-centre.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-centre.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-origin.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-origin.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-y-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-y-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-z-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-z-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/quick-measure.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/quick-measure.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-bodies.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-bodies.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-faces-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-faces-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-conflict.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-conflict.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-keep.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-keep.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-previous.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-previous.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-unless-turned.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-unless-turned.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-guides.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-guides.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-hide-glyphs.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-hide-glyphs.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-state-icons.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-state-icons.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/style-shaded-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/style-shaded-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-coarse.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-coarse.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-fine.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-fine.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-normal.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-normal.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-ultra.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-ultra.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-dark.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-dark.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-gruvbox.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-gruvbox.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-imported.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-imported.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-light.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-light.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-dark-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-dark-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-light-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-light-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-extrude.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-extrude.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-hole.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-hole.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-placement.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-placement.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/vertex-markers.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/vertex-markers.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-angles.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-angles.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-grid.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-grid.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-perspective.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-perspective.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-shadow.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-shadow.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | diff --git a/docs/design/preferences/README.md b/docs/design/preferences/README.md new file mode 100644 index 000000000..9c1d7ca9a --- /dev/null +++ b/docs/design/preferences/README.md @@ -0,0 +1,143 @@ +# Preferences redesign: design reference + +This folder holds everything the Preferences design boards know, so that nobody needs the +design canvas to build a page. It belongs to tracker #9863 and was extracted from the 13 +`Prefs2_*` boards (canvas version 202) plus four reference boards. Once merged it is +authoritative: if a board and this folder disagree, fix this folder in a docs-only pull request. + +Nothing in the redesign changes a default. It regroups settings, restyles their controls and adds +the settings-profile switcher. + +## Files + +| File | What it holds | +|---|---| +| `pages/.md` | One spec per page: sections in order, each control with its verbatim label, control type, the setting it edits, default, hover text, figure, and the mismatches with the code. | +| `figures/*.light.svg`, `figures/*.dark.svg` | Every illustration on the boards as a standalone SVG, verbatim geometry. `figures/README.md` states the house style. | +| `measurements.md` | Dialog frame, spacing, control sizes, radii, type sizes, as measured from the boards. | +| `tokens.md` | Every board colour mapped to a `theme::Tokens` field, or flagged "no token". | +| `boards/` | Not included: the boards are rendered from the canvas, which is private. The figures and the measurements replace them. | + +Pages: [General](pages/general.md), [Appearance](pages/appearance.md), [Layout](pages/layout.md), +[Graphics](pages/graphics.md), [Design](pages/design.md), [Sketch](pages/sketch.md), +[Tools](pages/tools.md), [Navigation](pages/navigation.md), [3D mouse](pages/mouse3d.md), +[Shortcuts](pages/shortcuts.md), [Assistant](pages/assistant.md), [Plugins](pages/plugins.md). + +## Page structure: 9 pages become 12, in four headings + +`General` sits on top, ungrouped. Every heading holds at least two pages. The page list also shows +a profile switcher card at its foot on every page. + +| Heading | Pages | +|---|---| +| (none) | General | +| Look | Appearance, Layout, Graphics | +| Work | Design, Sketch, Tools | +| Input | Navigation, 3D mouse, Shortcuts | +| Extend | Assistant, Plugins | + +Today's pages (`PAGES` in `crates/ui-egui/src/prefs.rs`): General, Interface, Design, Navigation, +Keyboard Shortcuts, Sketch, Graphics, AI, Plugins. The old board's map (`Prefs2_Map`) showed "Sketch +& selection" under Input and Graphics under "Display"; the later boards and tracker supersede it. + +### Where settings move + +| Setting group | From | To | +|---|---|---| +| Layout, toolbar, status bar, notices, menus, History and browser placement, dialog placement, toolbar tabs, navigation bar | Interface | Layout | +| Theme, theme options, viewport background, logo, scale and text, colour vision | Interface | Appearance | +| 3D mouse (all of it, including the navigation bridge) | Navigation | 3D mouse | +| Direct interaction, "Tool at the cursor" | Navigation | Tools | +| Hole, Extrude, Placement, Assembly Move (joint handles, near and far steps, ghost) | Design | Tools | +| "Axis distances in Measure" | Graphics | Tools | +| Sketch and selection | Sketch | Sketch | +| Largest file, network locations, slicer reuse, print-face highlight | General / Design | General > Files | +| Renderer, window system, graphics card | Graphics | Graphics ("This computer") | +| Ambient occlusion | Graphics > Edges and shading | Graphics > Current view (a fourth tile) | +| Origin plane names, hide-origin | Interface / Design | Design > Origin | +| Profiles | General | General > Profiles, plus the profile card in every page list | + +## Settings profiles + +`crates/ui-egui/src/settings_profiles.rs` holds the Interface, Navigation and Sketch preferences, +language, shortcuts, toolbar and S-box favourites, and the imported theme in use. It excludes the 3D +mouse, Graphics and the Assistant. Pages a profile stores (General for language, Appearance, Layout, +Sketch, Navigation, Shortcuts) carry an **In profile** tag beside the page title, with the hover text +"Saved in settings profiles". The profile card at the foot of the page list shows the active profile +name, with a dot and the hover text "Changed since saved" when it was edited. + +## Five ways to show a setting + +| Way | Use | +|---|---| +| Picture cards | Options that look different. | +| Segmented | Two to four short options. | +| Checkbox | Explanation on hover (the (i) icon). | +| Stepper plus live sample | Numbers with their result. | +| List or table | Per-item data. | + +The checkbox, segmented, dropdown, slider, stepper and badge are existing `ui_kit` controls. New: +the page-list group headings and profile card, the "In profile" tag, the picture card, toggle tile, +preset card, hover-help icon and carousel (step 2 of #9863), the theme carousel and options panel, +the layout preview, the navigation-bar editor and the colour vision sample row. + +## Design rules the boards follow + +1. **Few words.** No explanatory paragraphs. Help moves to an (i) icon with a hover tooltip (the + `title` text on the board, quoted verbatim in the page files). Visible text is labels, values and + short badges ("Restart needed", "Desktop only", "Not on this GPU"). +2. **One illustration style**: see `figures/README.md`. +3. **Generous spacing**: 38 px between sections (`measurements.md`). +4. Colours are the existing theme tokens, never literals; where a board colour has no token, + `tokens.md` says so. +5. Section titles are plain text on the board and upper-cased by the style + (`text-transform: uppercase`, 11 px, weight 600, tracking 0.07 em). Write them in sentence case + in catalogs. + +## Reading a page file + +Each control row is `Label | control | edits | default | hover | figure | notes`: + +* **Label** and **hover** are verbatim from the board. Board spelling is UK English (Centre, + Colour); the catalogs hold US text in `en.json` and the UK spelling in `en-GB.json`. +* **Edits** is the `Prefs` field (in `crates/ui-egui/src/prefs.rs`, the `preference_settings!` + table) or the app/session field or command that the control changes, as of main at the time of + writing. `app.ui.*` and `app.session.*` fields are session values that Preferences edits through + its `Snapshot`. +* **Default** is the default of the field in `Prefs::default()`. +* **Notes** flag every mismatch: a control with no setting behind it, a setting with no control on + the board, a label that differs from the current catalog, and anything uncertain. + +## Controls with no board + +Settings present in the code with no control on any board (not to be added by this redesign): +`parameters_apply_live` (Parameters apply live) and `personal_sheet_rules`. Settings that exist +only for other features and sit on no Preferences page (`render_*`, `save_mesh_*`, `view_dxf_*`, +`send_slicer`, `custom_slicers`, `easyprint_consent`, `update` and similar memos) are also not on +the boards. + +## Placeholder content (not to be built as drawn) + +The boards show sample content. Build the real data, not these examples: + +| Page | Placeholder | +|---|---| +| General | Profile names (Laptop, Large monitor, Presentation), the network host chips (`\\files.studio`, `\\nas01`), "3 saved", "2 saved" crash reports, the update time. | +| Appearance | The "Studio glass" imported theme and its options; the sample "Extrude 112.5 mm" distance row. | +| Layout | The navigation-bar slot icons and names (Faces and edges, Spin, Projection, Ground shadow, Ambient occlusion) stand in for the app's own slots and icons; "10 of 16 slots". | +| Navigation | The mapping rows and the mouse figure show the Fusion-style mapping only as an example of the shape. | +| 3D mouse | The device ("SpaceMouse Compact"), the live bars, and the button jobs (Open Preferences, View · Fit, View · Top, Hold Shift, Not assigned). | +| Shortcuts | The whole command list, groups and key assignments. | +| Assistant | Agent names and states (Claude Code, Codex CLI, Local model), "Signed in", "Key in environment". | +| Plugins | The three plugin cards (Gear generator, Bracket tools, Thread library), their versions, permissions and descriptions. | + +## Known gaps + +* The boards were checked in a browser in the light theme after the last edits; the dark half is + generated from the same layout. +* Theme options follow the text of `Theme_Options.dc.html`; the Appearance board was not compared + against its rendering. +* The graphics presets are the three in the code (Performance, Quality, Custom). An earlier board + showed a fourth, "Balanced", which does not exist. +* Screenshots of the boards (`boards/*.png`) are not included. The canvas is private and the + extracted figures, measurements and token map are the substitute. diff --git a/docs/design/preferences/figures/README.md b/docs/design/preferences/figures/README.md new file mode 100644 index 000000000..b1c9f6df5 --- /dev/null +++ b/docs/design/preferences/figures/README.md @@ -0,0 +1,111 @@ +# Preferences figures + +Every illustration on the Preferences boards, as a standalone SVG with the board's own geometry. +`.light.svg` is the figure as drawn in the light dialog and `.dark.svg` as drawn in the +dark dialog. Open any file in a browser to see it. They were extracted verbatim from the boards: only +the wrapper styles were removed (width 100 %, aspect ratio, corner radius), the `xmlns` was added and +`width` and `height` were set to the `viewBox` size. + +The figures are original artwork made for SolidCraft; the Orientation pair is copied from the app. +Their ATTRIBUTION row is in `attribution/pending/preferences-v2.md`. + +Not here: the 24x24 line icons on the boards (page-list icons, section icons, the (i) help icon, the +chevrons and checks). They are stand-ins for the app's own icon set, drawn with +`stroke="currentColor"`; use the app's icons. Also not SVG on the boards, and so not here: the +navigation-bar preview strip and slot chips, the theme-options controls, the live-input bars and the +shortcut key caps. Those are HTML on the boards; `pages/*.md` and `measurements.md` give their sizes. + +## House style + +* **Canvas** 120x64 for card figures. Exceptions: theme thumbnails 124x76, Orientation 120x80, + Layout schematic and the History and Browser mini-schematics 226x148, mouse figure 96x120, sketch + exit panels 30x30 nested inside a 120x64 canvas, colour vision samples 84x44, agent pointer 230x84, + style icon 64x64. +* **Ground**: a full-canvas rectangle (light `#F7F8FA`, dark `#1C1F26`) under every card figure. +* **Cubes** are isometric (30 degree axes) in three fixed tones: top face lightest, left face mid, + right face darkest. Light: `#FFFFFF`, `#E4E9F0`, `#C9D2DE`. Dark: `#6B7790`, `#515B72`, `#394256`. + Outline 0.9, round joins, `#6F7C8F` light and `#A3AEC2` dark. +* **Accent blue** (`#236EAD` light, `#8CBEF5` dark) marks what the setting acts on. +* **Amber** (`#8A5300` light, `#E8C24A` dark) marks a reference point: the pivot, the origin, the + pointer. +* **Red, green, blue** appear only for the X, Y and Z axes (values in `tokens.md`). +* **Green, amber, red** mean ok, warning, error. **Grey** is context. +* **Line weights**: 0.9 for outlines and dashed reference lines, 1.2 to 1.6 for emphasis, 2 for the + thing being shown (an orbit arc), 2.4 for the colour vision samples. Dashes `3 3` for reference + geometry. Text inside figures is IBM Plex Mono at 6.5 to 7 px, for tiny captions only (the `16` + under the tessellation figures, `before`, `sketch`, `after`). +* **Corners**: the card rounds the figure (5 px on the board); the figure itself is square. +* The Anti-aliasing figures are pixel tiles: 6x6 squares of the accent at 0.25, 0.5, 0.75 and 1.0 + opacity along an edge, so they are long (8 to 9 KB) but regular. + +## Painters + +Step 2 of #9863 paints these in `crates/ui-egui/src/ui_kit/preferences_figures.rs`, one function +per figure, with `Tokens` colours instead of the literals in these files. `tokens.md` lists which +token each literal maps to. + +## Index + +| File name | Canvas | Board | Shows | +|---|---|---|---| +| `theme-light` | 124x76 | Prefs2_Appearance | Theme carousel card, built-in Light theme | +| `theme-dark` | 124x76 | Prefs2_Appearance | Theme carousel card, built-in Dark theme | +| `theme-system-light-half` | 124x76 | Prefs2_Appearance | Theme card "System": light half (clipped to one triangle of the card) | +| `theme-system-dark-half` | 124x76 | Prefs2_Appearance | Theme card "System": dark half (the other triangle) | +| `theme-gruvbox` | 124x76 | Prefs2_Appearance | Theme carousel card, Gruvbox (has options) | +| `theme-imported` | 124x76 | Prefs2_Appearance | Theme carousel card, imported file "Studio glass" (sample) | +| `colour-vision-fixed` | 84x44 | Prefs2_Appearance | Colour vision sample cell "Fixed" | +| `colour-vision-projected` | 84x44 | Prefs2_Appearance | Colour vision sample cell "Projected" | +| `colour-vision-axes` | 84x44 | Prefs2_Appearance | Colour vision sample cell "Axes" | +| `colour-vision-bends` | 84x44 | Prefs2_Appearance | Colour vision sample cell "Bends" | +| `colour-vision-draft` | 84x44 | Prefs2_Appearance | Colour vision sample cell "Draft" | +| `colour-vision-failed` | 84x44 | Prefs2_Appearance | Colour vision sample cell "Failed" | +| `agent-pointer-speed` | 230x84 | Prefs2_Assistant | Assistant > Agent pointer: the pointer path preview | +| `orientation-z-up` | 120x80 | Prefs2_Design | Design > Orientation card "Z up" (copied from the app) | +| `orientation-y-up` | 120x80 | Prefs2_Design | Design > Orientation card "Y up" (copied from the app) | +| `tess-coarse` | 120x64 | Prefs2_Graphics | Curved surfaces card "Coarse" | +| `tess-normal` | 120x64 | Prefs2_Graphics | Curved surfaces card "Normal" | +| `tess-fine` | 120x64 | Prefs2_Graphics | Curved surfaces card "Fine" | +| `tess-ultra` | 120x64 | Prefs2_Graphics | Curved surfaces card "Ultra" | +| `aa-off` | 120x64 | Prefs2_Graphics | Anti-aliasing card "Off" | +| `aa-2x` | 120x64 | Prefs2_Graphics | Anti-aliasing card "2x" | +| `aa-4x` | 120x64 | Prefs2_Graphics | Anti-aliasing card "4x" | +| `aa-8x` | 120x64 | Prefs2_Graphics | Anti-aliasing card "8x" (badge "not on this GPU") | +| `view-grid` | 120x64 | Prefs2_Graphics | Current view tile "Grid" | +| `view-shadow` | 120x64 | Prefs2_Graphics | Current view tile "Ground shadow" | +| `view-perspective` | 120x64 | Prefs2_Graphics | Current view tile "Perspective" | +| `ao-on` | 120x64 | Prefs2_Graphics | Current view tile "Ambient occlusion" | +| `style-shaded-edges` | 64x64 | Prefs2_Graphics | Visual style dropdown icon, 64x64 | +| `view-angles` | 120x64 | Prefs2_Graphics | In the view tile "View angles" | +| `vertex-markers` | 120x64 | Prefs2_Graphics | In the view tile "Vertex markers" | +| `quick-measure` | 120x64 | Prefs2_Graphics | In the view tile "Quick measurement" | +| `frame-rate` | 120x64 | Prefs2_Graphics | In the view tile "Frame rate" | +| `layout-schematic` | 226x148 | Prefs2_Layout | Layout > Panels: schematic of the window (226x148, shown 262 px wide) | +| `history-bottom` | 226x148 | Prefs2_Layout | History card "Bottom" | +| `history-left` | 226x148 | Prefs2_Layout | History card "Left" | +| `history-under-browser` | 226x148 | Prefs2_Layout | History card "Under browser" | +| `history-in-browser` | 226x148 | Prefs2_Layout | History card "In browser" | +| `browser-column` | 226x148 | Prefs2_Layout | Browser card "Column" | +| `browser-card` | 226x148 | Prefs2_Layout | Browser card "Card" | +| `mouse-mapping` | 96x120 | Prefs2_Navigation | Navigation > Mouse: the mouse button figure | +| `orbit-origin` | 120x64 | Prefs2_Navigation | Orbit around card "Origin" | +| `orbit-centre` | 120x64 | Prefs2_Navigation | Orbit around card "View centre" | +| `orbit-cursor` | 120x64 | Prefs2_Navigation | Orbit around card "Under the cursor" | +| `navigator-axes` | 120x64 | Prefs2_Navigation | View navigator card "Axes, signed" | +| `navigator-cube` | 120x64 | Prefs2_Navigation | View navigator card "Cube, compact" | +| `sketch-guides` | 120x64 | Prefs2_Sketch | Sketch > Snapping and guides figure | +| `sketch-exit-previous` | 120x64 | Prefs2_Sketch | "When a sketch ends" card "Return to the view before" (before / sketch / after trio) | +| `sketch-exit-keep` | 120x64 | Prefs2_Sketch | "When a sketch ends" card "Keep" (default) | +| `sketch-exit-unless-turned` | 120x64 | Prefs2_Sketch | "When a sketch ends" card "Unless turned" | +| `sketch-state-icons` | 120x64 | Prefs2_Sketch | Marks in the sketch tile "State icons" | +| `sketch-conflict` | 120x64 | Prefs2_Sketch | Marks in the sketch tile "Conflict colour" | +| `sketch-hide-glyphs` | 120x64 | Prefs2_Sketch | Marks in the sketch tile "Hide glyphs zoomed out" | +| `select-faces-edges` | 120x64 | Prefs2_Sketch | Click selects card "Faces and edges" | +| `select-bodies` | 120x64 | Prefs2_Sketch | Click selects card "Whole bodies" | +| `tool-hole` | 120x64 | Prefs2_Tools | Tools > Create: Hole figure | +| `tool-extrude` | 120x64 | Prefs2_Tools | Tools > Create: Extrude figure | +| `tool-placement` | 120x64 | Prefs2_Tools | Tools > Create: Rest, Boss, Snap Fit figure | +| `assembly-move` | 120x64 | Prefs2_Tools | Tools > Assembly Move figure | +| `measure-axis-distances` | 120x64 | Prefs2_Tools | Measure and pointer tile "Axis distances in Measure" | +| `tool-cursor` | 120x64 | Prefs2_Tools | Measure and pointer tile "Tool at the cursor" | +| `direct-interaction` | 120x64 | Prefs2_Tools | Measure and pointer tile "Direct interaction" | diff --git a/docs/design/preferences/figures/aa-2x.dark.svg b/docs/design/preferences/figures/aa-2x.dark.svg new file mode 100644 index 000000000..3d9ae052b --- /dev/null +++ b/docs/design/preferences/figures/aa-2x.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/aa-2x.light.svg b/docs/design/preferences/figures/aa-2x.light.svg new file mode 100644 index 000000000..f708b54fd --- /dev/null +++ b/docs/design/preferences/figures/aa-2x.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/aa-4x.dark.svg b/docs/design/preferences/figures/aa-4x.dark.svg new file mode 100644 index 000000000..16cbd1c40 --- /dev/null +++ b/docs/design/preferences/figures/aa-4x.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/aa-4x.light.svg b/docs/design/preferences/figures/aa-4x.light.svg new file mode 100644 index 000000000..e580a6c7c --- /dev/null +++ b/docs/design/preferences/figures/aa-4x.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/aa-8x.dark.svg b/docs/design/preferences/figures/aa-8x.dark.svg new file mode 100644 index 000000000..f4b8ade33 --- /dev/null +++ b/docs/design/preferences/figures/aa-8x.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/aa-8x.light.svg b/docs/design/preferences/figures/aa-8x.light.svg new file mode 100644 index 000000000..283212273 --- /dev/null +++ b/docs/design/preferences/figures/aa-8x.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/aa-off.dark.svg b/docs/design/preferences/figures/aa-off.dark.svg new file mode 100644 index 000000000..6284764ae --- /dev/null +++ b/docs/design/preferences/figures/aa-off.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/aa-off.light.svg b/docs/design/preferences/figures/aa-off.light.svg new file mode 100644 index 000000000..b4c19064b --- /dev/null +++ b/docs/design/preferences/figures/aa-off.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/agent-pointer-speed.dark.svg b/docs/design/preferences/figures/agent-pointer-speed.dark.svg new file mode 100644 index 000000000..6a5fffb0f --- /dev/null +++ b/docs/design/preferences/figures/agent-pointer-speed.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/agent-pointer-speed.light.svg b/docs/design/preferences/figures/agent-pointer-speed.light.svg new file mode 100644 index 000000000..7bd858e73 --- /dev/null +++ b/docs/design/preferences/figures/agent-pointer-speed.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/ao-on.dark.svg b/docs/design/preferences/figures/ao-on.dark.svg new file mode 100644 index 000000000..5ea6a7102 --- /dev/null +++ b/docs/design/preferences/figures/ao-on.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/ao-on.light.svg b/docs/design/preferences/figures/ao-on.light.svg new file mode 100644 index 000000000..25f2273d7 --- /dev/null +++ b/docs/design/preferences/figures/ao-on.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/assembly-move.dark.svg b/docs/design/preferences/figures/assembly-move.dark.svg new file mode 100644 index 000000000..f7f4ade20 --- /dev/null +++ b/docs/design/preferences/figures/assembly-move.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/assembly-move.light.svg b/docs/design/preferences/figures/assembly-move.light.svg new file mode 100644 index 000000000..c312144d7 --- /dev/null +++ b/docs/design/preferences/figures/assembly-move.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/browser-card.dark.svg b/docs/design/preferences/figures/browser-card.dark.svg new file mode 100644 index 000000000..5fac84d2d --- /dev/null +++ b/docs/design/preferences/figures/browser-card.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/browser-card.light.svg b/docs/design/preferences/figures/browser-card.light.svg new file mode 100644 index 000000000..aee268f3d --- /dev/null +++ b/docs/design/preferences/figures/browser-card.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/browser-column.dark.svg b/docs/design/preferences/figures/browser-column.dark.svg new file mode 100644 index 000000000..6db6ca46a --- /dev/null +++ b/docs/design/preferences/figures/browser-column.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/browser-column.light.svg b/docs/design/preferences/figures/browser-column.light.svg new file mode 100644 index 000000000..1f961e5c1 --- /dev/null +++ b/docs/design/preferences/figures/browser-column.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-axes.dark.svg b/docs/design/preferences/figures/colour-vision-axes.dark.svg new file mode 100644 index 000000000..b94318251 --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-axes.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-axes.light.svg b/docs/design/preferences/figures/colour-vision-axes.light.svg new file mode 100644 index 000000000..54d95c6af --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-axes.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-bends.dark.svg b/docs/design/preferences/figures/colour-vision-bends.dark.svg new file mode 100644 index 000000000..375837511 --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-bends.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-bends.light.svg b/docs/design/preferences/figures/colour-vision-bends.light.svg new file mode 100644 index 000000000..3e30db333 --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-bends.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-draft.dark.svg b/docs/design/preferences/figures/colour-vision-draft.dark.svg new file mode 100644 index 000000000..48d780e87 --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-draft.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-draft.light.svg b/docs/design/preferences/figures/colour-vision-draft.light.svg new file mode 100644 index 000000000..760c19ebc --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-draft.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-failed.dark.svg b/docs/design/preferences/figures/colour-vision-failed.dark.svg new file mode 100644 index 000000000..5a9f70158 --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-failed.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-failed.light.svg b/docs/design/preferences/figures/colour-vision-failed.light.svg new file mode 100644 index 000000000..f80d7d5c1 --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-failed.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-fixed.dark.svg b/docs/design/preferences/figures/colour-vision-fixed.dark.svg new file mode 100644 index 000000000..8709221d0 --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-fixed.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-fixed.light.svg b/docs/design/preferences/figures/colour-vision-fixed.light.svg new file mode 100644 index 000000000..be88680aa --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-fixed.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-projected.dark.svg b/docs/design/preferences/figures/colour-vision-projected.dark.svg new file mode 100644 index 000000000..cfb4f3d86 --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-projected.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/colour-vision-projected.light.svg b/docs/design/preferences/figures/colour-vision-projected.light.svg new file mode 100644 index 000000000..581157464 --- /dev/null +++ b/docs/design/preferences/figures/colour-vision-projected.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/direct-interaction.dark.svg b/docs/design/preferences/figures/direct-interaction.dark.svg new file mode 100644 index 000000000..d115acdf1 --- /dev/null +++ b/docs/design/preferences/figures/direct-interaction.dark.svg @@ -0,0 +1 @@ ++18 mm diff --git a/docs/design/preferences/figures/direct-interaction.light.svg b/docs/design/preferences/figures/direct-interaction.light.svg new file mode 100644 index 000000000..5c462a3ef --- /dev/null +++ b/docs/design/preferences/figures/direct-interaction.light.svg @@ -0,0 +1 @@ ++18 mm diff --git a/docs/design/preferences/figures/frame-rate.dark.svg b/docs/design/preferences/figures/frame-rate.dark.svg new file mode 100644 index 000000000..523c65507 --- /dev/null +++ b/docs/design/preferences/figures/frame-rate.dark.svg @@ -0,0 +1 @@ +60 fps diff --git a/docs/design/preferences/figures/frame-rate.light.svg b/docs/design/preferences/figures/frame-rate.light.svg new file mode 100644 index 000000000..ae2221a30 --- /dev/null +++ b/docs/design/preferences/figures/frame-rate.light.svg @@ -0,0 +1 @@ +60 fps diff --git a/docs/design/preferences/figures/history-bottom.dark.svg b/docs/design/preferences/figures/history-bottom.dark.svg new file mode 100644 index 000000000..6db6ca46a --- /dev/null +++ b/docs/design/preferences/figures/history-bottom.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/history-bottom.light.svg b/docs/design/preferences/figures/history-bottom.light.svg new file mode 100644 index 000000000..1f961e5c1 --- /dev/null +++ b/docs/design/preferences/figures/history-bottom.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/history-in-browser.dark.svg b/docs/design/preferences/figures/history-in-browser.dark.svg new file mode 100644 index 000000000..dd565ceff --- /dev/null +++ b/docs/design/preferences/figures/history-in-browser.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/history-in-browser.light.svg b/docs/design/preferences/figures/history-in-browser.light.svg new file mode 100644 index 000000000..ea8dbd3f3 --- /dev/null +++ b/docs/design/preferences/figures/history-in-browser.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/history-left.dark.svg b/docs/design/preferences/figures/history-left.dark.svg new file mode 100644 index 000000000..c5897b32f --- /dev/null +++ b/docs/design/preferences/figures/history-left.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/history-left.light.svg b/docs/design/preferences/figures/history-left.light.svg new file mode 100644 index 000000000..034844b02 --- /dev/null +++ b/docs/design/preferences/figures/history-left.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/history-under-browser.dark.svg b/docs/design/preferences/figures/history-under-browser.dark.svg new file mode 100644 index 000000000..6310f89af --- /dev/null +++ b/docs/design/preferences/figures/history-under-browser.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/history-under-browser.light.svg b/docs/design/preferences/figures/history-under-browser.light.svg new file mode 100644 index 000000000..21aef785c --- /dev/null +++ b/docs/design/preferences/figures/history-under-browser.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/layout-schematic.dark.svg b/docs/design/preferences/figures/layout-schematic.dark.svg new file mode 100644 index 000000000..6db6ca46a --- /dev/null +++ b/docs/design/preferences/figures/layout-schematic.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/layout-schematic.light.svg b/docs/design/preferences/figures/layout-schematic.light.svg new file mode 100644 index 000000000..1f961e5c1 --- /dev/null +++ b/docs/design/preferences/figures/layout-schematic.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/measure-axis-distances.dark.svg b/docs/design/preferences/figures/measure-axis-distances.dark.svg new file mode 100644 index 000000000..73c521e45 --- /dev/null +++ b/docs/design/preferences/figures/measure-axis-distances.dark.svg @@ -0,0 +1 @@ +X 46Y 28 diff --git a/docs/design/preferences/figures/measure-axis-distances.light.svg b/docs/design/preferences/figures/measure-axis-distances.light.svg new file mode 100644 index 000000000..63b3c4beb --- /dev/null +++ b/docs/design/preferences/figures/measure-axis-distances.light.svg @@ -0,0 +1 @@ +X 46Y 28 diff --git a/docs/design/preferences/figures/mouse-mapping.dark.svg b/docs/design/preferences/figures/mouse-mapping.dark.svg new file mode 100644 index 000000000..5f5a9821f --- /dev/null +++ b/docs/design/preferences/figures/mouse-mapping.dark.svg @@ -0,0 +1 @@ +LRM diff --git a/docs/design/preferences/figures/mouse-mapping.light.svg b/docs/design/preferences/figures/mouse-mapping.light.svg new file mode 100644 index 000000000..62fdb36fc --- /dev/null +++ b/docs/design/preferences/figures/mouse-mapping.light.svg @@ -0,0 +1 @@ +LRM diff --git a/docs/design/preferences/figures/navigator-axes.dark.svg b/docs/design/preferences/figures/navigator-axes.dark.svg new file mode 100644 index 000000000..fab9d67f4 --- /dev/null +++ b/docs/design/preferences/figures/navigator-axes.dark.svg @@ -0,0 +1 @@ +ZXY diff --git a/docs/design/preferences/figures/navigator-axes.light.svg b/docs/design/preferences/figures/navigator-axes.light.svg new file mode 100644 index 000000000..244319672 --- /dev/null +++ b/docs/design/preferences/figures/navigator-axes.light.svg @@ -0,0 +1 @@ +ZXY diff --git a/docs/design/preferences/figures/navigator-cube.dark.svg b/docs/design/preferences/figures/navigator-cube.dark.svg new file mode 100644 index 000000000..a938c720c --- /dev/null +++ b/docs/design/preferences/figures/navigator-cube.dark.svg @@ -0,0 +1 @@ +TOPFRONTRIGHT diff --git a/docs/design/preferences/figures/navigator-cube.light.svg b/docs/design/preferences/figures/navigator-cube.light.svg new file mode 100644 index 000000000..8534ad855 --- /dev/null +++ b/docs/design/preferences/figures/navigator-cube.light.svg @@ -0,0 +1 @@ +TOPFRONTRIGHT diff --git a/docs/design/preferences/figures/orbit-centre.dark.svg b/docs/design/preferences/figures/orbit-centre.dark.svg new file mode 100644 index 000000000..df6348b51 --- /dev/null +++ b/docs/design/preferences/figures/orbit-centre.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/orbit-centre.light.svg b/docs/design/preferences/figures/orbit-centre.light.svg new file mode 100644 index 000000000..0d48e00b7 --- /dev/null +++ b/docs/design/preferences/figures/orbit-centre.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/orbit-cursor.dark.svg b/docs/design/preferences/figures/orbit-cursor.dark.svg new file mode 100644 index 000000000..daac367e1 --- /dev/null +++ b/docs/design/preferences/figures/orbit-cursor.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/orbit-cursor.light.svg b/docs/design/preferences/figures/orbit-cursor.light.svg new file mode 100644 index 000000000..37fdae91e --- /dev/null +++ b/docs/design/preferences/figures/orbit-cursor.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/orbit-origin.dark.svg b/docs/design/preferences/figures/orbit-origin.dark.svg new file mode 100644 index 000000000..f04d72f6b --- /dev/null +++ b/docs/design/preferences/figures/orbit-origin.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/orbit-origin.light.svg b/docs/design/preferences/figures/orbit-origin.light.svg new file mode 100644 index 000000000..90805ff70 --- /dev/null +++ b/docs/design/preferences/figures/orbit-origin.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/orientation-y-up.dark.svg b/docs/design/preferences/figures/orientation-y-up.dark.svg new file mode 100644 index 000000000..abe7cc7e7 --- /dev/null +++ b/docs/design/preferences/figures/orientation-y-up.dark.svg @@ -0,0 +1 @@ +YXZ diff --git a/docs/design/preferences/figures/orientation-y-up.light.svg b/docs/design/preferences/figures/orientation-y-up.light.svg new file mode 100644 index 000000000..a4e380e5b --- /dev/null +++ b/docs/design/preferences/figures/orientation-y-up.light.svg @@ -0,0 +1 @@ +YXZ diff --git a/docs/design/preferences/figures/orientation-z-up.dark.svg b/docs/design/preferences/figures/orientation-z-up.dark.svg new file mode 100644 index 000000000..e9b6eb2d8 --- /dev/null +++ b/docs/design/preferences/figures/orientation-z-up.dark.svg @@ -0,0 +1 @@ +ZXY diff --git a/docs/design/preferences/figures/orientation-z-up.light.svg b/docs/design/preferences/figures/orientation-z-up.light.svg new file mode 100644 index 000000000..e0f31f052 --- /dev/null +++ b/docs/design/preferences/figures/orientation-z-up.light.svg @@ -0,0 +1 @@ +ZXY diff --git a/docs/design/preferences/figures/quick-measure.dark.svg b/docs/design/preferences/figures/quick-measure.dark.svg new file mode 100644 index 000000000..673d3e927 --- /dev/null +++ b/docs/design/preferences/figures/quick-measure.dark.svg @@ -0,0 +1 @@ +12.5 mm diff --git a/docs/design/preferences/figures/quick-measure.light.svg b/docs/design/preferences/figures/quick-measure.light.svg new file mode 100644 index 000000000..201173b75 --- /dev/null +++ b/docs/design/preferences/figures/quick-measure.light.svg @@ -0,0 +1 @@ +12.5 mm diff --git a/docs/design/preferences/figures/select-bodies.dark.svg b/docs/design/preferences/figures/select-bodies.dark.svg new file mode 100644 index 000000000..e12178fe4 --- /dev/null +++ b/docs/design/preferences/figures/select-bodies.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/select-bodies.light.svg b/docs/design/preferences/figures/select-bodies.light.svg new file mode 100644 index 000000000..07571f7e6 --- /dev/null +++ b/docs/design/preferences/figures/select-bodies.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/select-faces-edges.dark.svg b/docs/design/preferences/figures/select-faces-edges.dark.svg new file mode 100644 index 000000000..346c3a947 --- /dev/null +++ b/docs/design/preferences/figures/select-faces-edges.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/select-faces-edges.light.svg b/docs/design/preferences/figures/select-faces-edges.light.svg new file mode 100644 index 000000000..6b4313e33 --- /dev/null +++ b/docs/design/preferences/figures/select-faces-edges.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/sketch-conflict.dark.svg b/docs/design/preferences/figures/sketch-conflict.dark.svg new file mode 100644 index 000000000..e375a4128 --- /dev/null +++ b/docs/design/preferences/figures/sketch-conflict.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/sketch-conflict.light.svg b/docs/design/preferences/figures/sketch-conflict.light.svg new file mode 100644 index 000000000..f3374d070 --- /dev/null +++ b/docs/design/preferences/figures/sketch-conflict.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/sketch-exit-keep.dark.svg b/docs/design/preferences/figures/sketch-exit-keep.dark.svg new file mode 100644 index 000000000..fac796296 --- /dev/null +++ b/docs/design/preferences/figures/sketch-exit-keep.dark.svg @@ -0,0 +1 @@ +beforesketchafter diff --git a/docs/design/preferences/figures/sketch-exit-keep.light.svg b/docs/design/preferences/figures/sketch-exit-keep.light.svg new file mode 100644 index 000000000..6ea61c4b9 --- /dev/null +++ b/docs/design/preferences/figures/sketch-exit-keep.light.svg @@ -0,0 +1 @@ +beforesketchafter diff --git a/docs/design/preferences/figures/sketch-exit-previous.dark.svg b/docs/design/preferences/figures/sketch-exit-previous.dark.svg new file mode 100644 index 000000000..d5efaa931 --- /dev/null +++ b/docs/design/preferences/figures/sketch-exit-previous.dark.svg @@ -0,0 +1 @@ +beforesketchafter diff --git a/docs/design/preferences/figures/sketch-exit-previous.light.svg b/docs/design/preferences/figures/sketch-exit-previous.light.svg new file mode 100644 index 000000000..bedaf7369 --- /dev/null +++ b/docs/design/preferences/figures/sketch-exit-previous.light.svg @@ -0,0 +1 @@ +beforesketchafter diff --git a/docs/design/preferences/figures/sketch-exit-unless-turned.dark.svg b/docs/design/preferences/figures/sketch-exit-unless-turned.dark.svg new file mode 100644 index 000000000..1745840f3 --- /dev/null +++ b/docs/design/preferences/figures/sketch-exit-unless-turned.dark.svg @@ -0,0 +1 @@ +beforesketchafter diff --git a/docs/design/preferences/figures/sketch-exit-unless-turned.light.svg b/docs/design/preferences/figures/sketch-exit-unless-turned.light.svg new file mode 100644 index 000000000..f88c1c29e --- /dev/null +++ b/docs/design/preferences/figures/sketch-exit-unless-turned.light.svg @@ -0,0 +1 @@ +beforesketchafter diff --git a/docs/design/preferences/figures/sketch-guides.dark.svg b/docs/design/preferences/figures/sketch-guides.dark.svg new file mode 100644 index 000000000..133b55b09 --- /dev/null +++ b/docs/design/preferences/figures/sketch-guides.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/sketch-guides.light.svg b/docs/design/preferences/figures/sketch-guides.light.svg new file mode 100644 index 000000000..3c2ca3e40 --- /dev/null +++ b/docs/design/preferences/figures/sketch-guides.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/sketch-hide-glyphs.dark.svg b/docs/design/preferences/figures/sketch-hide-glyphs.dark.svg new file mode 100644 index 000000000..ef53c5de2 --- /dev/null +++ b/docs/design/preferences/figures/sketch-hide-glyphs.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/sketch-hide-glyphs.light.svg b/docs/design/preferences/figures/sketch-hide-glyphs.light.svg new file mode 100644 index 000000000..5fcf5a466 --- /dev/null +++ b/docs/design/preferences/figures/sketch-hide-glyphs.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/sketch-state-icons.dark.svg b/docs/design/preferences/figures/sketch-state-icons.dark.svg new file mode 100644 index 000000000..413becb91 --- /dev/null +++ b/docs/design/preferences/figures/sketch-state-icons.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/sketch-state-icons.light.svg b/docs/design/preferences/figures/sketch-state-icons.light.svg new file mode 100644 index 000000000..0a19c0e7d --- /dev/null +++ b/docs/design/preferences/figures/sketch-state-icons.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/style-shaded-edges.dark.svg b/docs/design/preferences/figures/style-shaded-edges.dark.svg new file mode 100644 index 000000000..eccd078ff --- /dev/null +++ b/docs/design/preferences/figures/style-shaded-edges.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/style-shaded-edges.light.svg b/docs/design/preferences/figures/style-shaded-edges.light.svg new file mode 100644 index 000000000..2ac8b0f23 --- /dev/null +++ b/docs/design/preferences/figures/style-shaded-edges.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/tess-coarse.dark.svg b/docs/design/preferences/figures/tess-coarse.dark.svg new file mode 100644 index 000000000..16dcd0ece --- /dev/null +++ b/docs/design/preferences/figures/tess-coarse.dark.svg @@ -0,0 +1 @@ +8 diff --git a/docs/design/preferences/figures/tess-coarse.light.svg b/docs/design/preferences/figures/tess-coarse.light.svg new file mode 100644 index 000000000..103e4a416 --- /dev/null +++ b/docs/design/preferences/figures/tess-coarse.light.svg @@ -0,0 +1 @@ +8 diff --git a/docs/design/preferences/figures/tess-fine.dark.svg b/docs/design/preferences/figures/tess-fine.dark.svg new file mode 100644 index 000000000..751f64647 --- /dev/null +++ b/docs/design/preferences/figures/tess-fine.dark.svg @@ -0,0 +1 @@ +32 diff --git a/docs/design/preferences/figures/tess-fine.light.svg b/docs/design/preferences/figures/tess-fine.light.svg new file mode 100644 index 000000000..0ae3b0c69 --- /dev/null +++ b/docs/design/preferences/figures/tess-fine.light.svg @@ -0,0 +1 @@ +32 diff --git a/docs/design/preferences/figures/tess-normal.dark.svg b/docs/design/preferences/figures/tess-normal.dark.svg new file mode 100644 index 000000000..ba0ea01be --- /dev/null +++ b/docs/design/preferences/figures/tess-normal.dark.svg @@ -0,0 +1 @@ +16 diff --git a/docs/design/preferences/figures/tess-normal.light.svg b/docs/design/preferences/figures/tess-normal.light.svg new file mode 100644 index 000000000..7d5056d20 --- /dev/null +++ b/docs/design/preferences/figures/tess-normal.light.svg @@ -0,0 +1 @@ +16 diff --git a/docs/design/preferences/figures/tess-ultra.dark.svg b/docs/design/preferences/figures/tess-ultra.dark.svg new file mode 100644 index 000000000..c85046582 --- /dev/null +++ b/docs/design/preferences/figures/tess-ultra.dark.svg @@ -0,0 +1 @@ +64 diff --git a/docs/design/preferences/figures/tess-ultra.light.svg b/docs/design/preferences/figures/tess-ultra.light.svg new file mode 100644 index 000000000..b6617b441 --- /dev/null +++ b/docs/design/preferences/figures/tess-ultra.light.svg @@ -0,0 +1 @@ +64 diff --git a/docs/design/preferences/figures/theme-dark.dark.svg b/docs/design/preferences/figures/theme-dark.dark.svg new file mode 100644 index 000000000..0bdb03838 --- /dev/null +++ b/docs/design/preferences/figures/theme-dark.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/theme-dark.light.svg b/docs/design/preferences/figures/theme-dark.light.svg new file mode 100644 index 000000000..4f642bd9b --- /dev/null +++ b/docs/design/preferences/figures/theme-dark.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/theme-gruvbox.dark.svg b/docs/design/preferences/figures/theme-gruvbox.dark.svg new file mode 100644 index 000000000..fc53f3b65 --- /dev/null +++ b/docs/design/preferences/figures/theme-gruvbox.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/theme-gruvbox.light.svg b/docs/design/preferences/figures/theme-gruvbox.light.svg new file mode 100644 index 000000000..b36608b02 --- /dev/null +++ b/docs/design/preferences/figures/theme-gruvbox.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/theme-imported.dark.svg b/docs/design/preferences/figures/theme-imported.dark.svg new file mode 100644 index 000000000..79970acb4 --- /dev/null +++ b/docs/design/preferences/figures/theme-imported.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/theme-imported.light.svg b/docs/design/preferences/figures/theme-imported.light.svg new file mode 100644 index 000000000..99aed0346 --- /dev/null +++ b/docs/design/preferences/figures/theme-imported.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/theme-light.dark.svg b/docs/design/preferences/figures/theme-light.dark.svg new file mode 100644 index 000000000..dcca583c0 --- /dev/null +++ b/docs/design/preferences/figures/theme-light.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/theme-light.light.svg b/docs/design/preferences/figures/theme-light.light.svg new file mode 100644 index 000000000..cfc1a09e5 --- /dev/null +++ b/docs/design/preferences/figures/theme-light.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/theme-system-dark-half.dark.svg b/docs/design/preferences/figures/theme-system-dark-half.dark.svg new file mode 100644 index 000000000..a73c6084e --- /dev/null +++ b/docs/design/preferences/figures/theme-system-dark-half.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/theme-system-dark-half.light.svg b/docs/design/preferences/figures/theme-system-dark-half.light.svg new file mode 100644 index 000000000..b873f621b --- /dev/null +++ b/docs/design/preferences/figures/theme-system-dark-half.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/theme-system-light-half.dark.svg b/docs/design/preferences/figures/theme-system-light-half.dark.svg new file mode 100644 index 000000000..d7105169d --- /dev/null +++ b/docs/design/preferences/figures/theme-system-light-half.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/theme-system-light-half.light.svg b/docs/design/preferences/figures/theme-system-light-half.light.svg new file mode 100644 index 000000000..d0d4d0993 --- /dev/null +++ b/docs/design/preferences/figures/theme-system-light-half.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/tool-cursor.dark.svg b/docs/design/preferences/figures/tool-cursor.dark.svg new file mode 100644 index 000000000..6b3217352 --- /dev/null +++ b/docs/design/preferences/figures/tool-cursor.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/tool-cursor.light.svg b/docs/design/preferences/figures/tool-cursor.light.svg new file mode 100644 index 000000000..808fcb673 --- /dev/null +++ b/docs/design/preferences/figures/tool-cursor.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/tool-extrude.dark.svg b/docs/design/preferences/figures/tool-extrude.dark.svg new file mode 100644 index 000000000..821be2332 --- /dev/null +++ b/docs/design/preferences/figures/tool-extrude.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/tool-extrude.light.svg b/docs/design/preferences/figures/tool-extrude.light.svg new file mode 100644 index 000000000..9c0181abd --- /dev/null +++ b/docs/design/preferences/figures/tool-extrude.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/tool-hole.dark.svg b/docs/design/preferences/figures/tool-hole.dark.svg new file mode 100644 index 000000000..d5493792d --- /dev/null +++ b/docs/design/preferences/figures/tool-hole.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/tool-hole.light.svg b/docs/design/preferences/figures/tool-hole.light.svg new file mode 100644 index 000000000..b83c2b675 --- /dev/null +++ b/docs/design/preferences/figures/tool-hole.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/tool-placement.dark.svg b/docs/design/preferences/figures/tool-placement.dark.svg new file mode 100644 index 000000000..04ac7d5d8 --- /dev/null +++ b/docs/design/preferences/figures/tool-placement.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/tool-placement.light.svg b/docs/design/preferences/figures/tool-placement.light.svg new file mode 100644 index 000000000..d1cb343e3 --- /dev/null +++ b/docs/design/preferences/figures/tool-placement.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/vertex-markers.dark.svg b/docs/design/preferences/figures/vertex-markers.dark.svg new file mode 100644 index 000000000..d90492c7f --- /dev/null +++ b/docs/design/preferences/figures/vertex-markers.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/vertex-markers.light.svg b/docs/design/preferences/figures/vertex-markers.light.svg new file mode 100644 index 000000000..351c59963 --- /dev/null +++ b/docs/design/preferences/figures/vertex-markers.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/view-angles.dark.svg b/docs/design/preferences/figures/view-angles.dark.svg new file mode 100644 index 000000000..c23f1fa0a --- /dev/null +++ b/docs/design/preferences/figures/view-angles.dark.svg @@ -0,0 +1 @@ +ZXY45°35°0° diff --git a/docs/design/preferences/figures/view-angles.light.svg b/docs/design/preferences/figures/view-angles.light.svg new file mode 100644 index 000000000..f7d796d1b --- /dev/null +++ b/docs/design/preferences/figures/view-angles.light.svg @@ -0,0 +1 @@ +ZXY45°35°0° diff --git a/docs/design/preferences/figures/view-grid.dark.svg b/docs/design/preferences/figures/view-grid.dark.svg new file mode 100644 index 000000000..edcd12a19 --- /dev/null +++ b/docs/design/preferences/figures/view-grid.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/view-grid.light.svg b/docs/design/preferences/figures/view-grid.light.svg new file mode 100644 index 000000000..ee2d9ec40 --- /dev/null +++ b/docs/design/preferences/figures/view-grid.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/view-perspective.dark.svg b/docs/design/preferences/figures/view-perspective.dark.svg new file mode 100644 index 000000000..32b95bbca --- /dev/null +++ b/docs/design/preferences/figures/view-perspective.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/view-perspective.light.svg b/docs/design/preferences/figures/view-perspective.light.svg new file mode 100644 index 000000000..fab7018f2 --- /dev/null +++ b/docs/design/preferences/figures/view-perspective.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/view-shadow.dark.svg b/docs/design/preferences/figures/view-shadow.dark.svg new file mode 100644 index 000000000..7991eb7be --- /dev/null +++ b/docs/design/preferences/figures/view-shadow.dark.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/figures/view-shadow.light.svg b/docs/design/preferences/figures/view-shadow.light.svg new file mode 100644 index 000000000..3b9af9a8a --- /dev/null +++ b/docs/design/preferences/figures/view-shadow.light.svg @@ -0,0 +1 @@ + diff --git a/docs/design/preferences/measurements.md b/docs/design/preferences/measurements.md new file mode 100644 index 000000000..9320c0efb --- /dev/null +++ b/docs/design/preferences/measurements.md @@ -0,0 +1,84 @@ +# Preferences measurements + +Measured from the rendered boards (light dialog; the dark dialog has the same layout). Sizes are in +CSS pixels, which is the board's unit and equals the app's logical points at 100 % interface scale. +Borders are 1 px (2 px on a selected card or tile); a measured 40.9 means 40 plus a 1 px border. +Where the app already has a token for a dimension, the token is named; otherwise map the value to +the nearest `space_*` / `font_*` token or add one. + +Fonts are IBM Plex Sans (text) and IBM Plex Mono (key caps, figure captions), as in the app. + +## Dialog frame + +| Part | Size | +|---|---| +| Dialog | 880 px wide; height follows the content except Shortcuts (fixed 992 px board with a scrolling list). Outer radius 10, border 1 `dialog_border`, shadow `0 4 16 rgba(20,30,45,.10)` light, `rgba(0,0,0,.30)` dark. | +| Title bar | 40 px, padding 0 8 0 12, gap 8, 1 px bottom rule. Icon 19 px (`form_icon_size`), title "Preferences" 14 px / 600, search field 230x26 radius 6 with a 14 px search icon, placeholder "Search preferences" and the key cap "Ctrl F" (10.5 px mono, radius 4, 17.7 high), close button 26x26 radius 6 (`form_close_size`). | +| Page list | 188 px wide (190 with its 1 px right rule), fill `dialog_footer`, padding 6 8 10, 2 px between items. | +| Page list item | 171 x 32, padding 0 10, gap 9, radius 6, 12.5 px; icon 16 px. Selected: weight 600, fill `selected_bg`, accent text. | +| Page list heading | "Look", "Work", "Input", "Extend": 11 px / 600, tracking 0.07 em, upper-cased, `form_dim`. "General" has none. | +| Profile card | foot of the list: label "Profile" (10.5 px / 600, tracking 0.06 em, upper-cased), then the profile name with a 7x7 amber dot (`#B84A00`, radius 4, hover "Changed since saved") when edited, and a 14 px chevron. | +| Content column | 690 wide (the dialog 880 minus the 188 list minus the border), padding 18 22 10: sections are 646 px wide (the issue's 648 ignores the borders). | +| Footer | 48 px, padding 0 12, gap 8, 1 px top rule, fill `dialog_footer`. "Restore page defaults" at the left (144x28), "Cancel" (60x28) and "OK" (72x28, weight 600, accent fill, `on_accent` ink) at the right. | + +## Page head + +* Title: 20 px / 600, one line, with the "In profile" tag at the far right on pages that a profile holds. +* Subtitle: 12.5 px `form_dim`, one line (e.g. "Where the parts of the window sit."). Together the head is 46 px tall. +* "In profile" tag: a pill with a 12 px profile icon and the text "In profile", hover "Saved in settings profiles". + +## Sections + +* **38 px between sections** (flex gap of the content column). +* Section head: a 30 px row, gap 6, a 14 px disclosure chevron (sections fold), then the title (11 px / 600, tracking 0.07 em, upper-cased, `form_dim`), a 1 px `dialog_rule` line fills the rest of the row (left margin 4). The sub-heads inside a section ("When a sketch ends", "Click selects", "History", "Browser") are the same style at 11 px / 600 with 0.06 em tracking, no icon. +* A checkbox row is 16.6 px high (a 15 px checkbox and 12.5 px text, gap 8); label-and-control rows are 28 px high; the label column is about 64 px wide for "Visual style"-length labels (the app uses `form_label_width` 70). + +## Controls (all heights are the app's `control_height` 28 unless noted) + +| Control | Size and style | +|---|---| +| Checkbox | The native 15x15 checkbox with `accent-color` set to the accent; label 12.5 px, gap 8. In the app use the existing `ui_kit` checkbox. A dimmed (disabled) row uses ink `#8A94A3` (no token, see `tokens.md`). | +| Text and number field | height 28, radius 6, 1 px `control_border`, text 12 px. Widths seen: number 56 to 72, "Port" 80, "Profile name" 220. Unit suffix beside it in 12 px `form_dim`. | +| Dropdown | height 28, radius 6, 12.5 px; widths 180, 200, 220, 240 or 280 as the options need; chevron at the right. Visual style dropdown is 240x30 with an 18 px style icon. | +| Segmented | The existing `ui_kit` segmented control, as the app draws it (the board's accent-filled segment was wrong). A row of segments on a `control_fill` ground, 1 px `control_border` around, radius `control_radius` (6) on the group only, a 1 px `control_border` divider between segments, button padding 0 12, 12.5 px. Height is the control row (about 28). The selected segment fills its whole cell, top to bottom, with `selected_bg` (no gap under it, no inset), its text in `selected_ink` at weight 600; the others have `form_ink` text at weight 400; a hovered unselected segment fills with `hover`. A disabled segment uses `form_dim`. An accent-filled segment with `on_accent` text exists only for a primary choice in a dialog footer, never on a Preferences page. | +| Button | 28 high, radius 6, 1 px `control_border`, 12.5 px; primary: accent fill, weight 600. Small button (Apply, Reset, Test, Show in folder, Remove): 24 high, 12 px. | +| Chip (scale presets) | 22 high, radius 11, 11.5 px, padding 0 8: "75%", "100%", "110%", "125%", "150%", "200%". Selected: 1 px `form_primary` border, `selected_bg` fill, `selected_ink` text, weight 600. | +| Key cap | 17.7 high, radius 4, 1 px `control_border`, IBM Plex Mono 10.5 px, padding 0 5. | +| Badge | 18 high, radius 9, 11 px, padding 0 8: warning `pref_note` on `pref_note_fill` ("Restart needed", "Not on this GPU", "Desktop only"); success badge for "Connected", "Calibrated", "Up to date", "Signed in", "Default". | +| (i) help icon | A 13 px (11 px in dense rows) line icon, `form_dim`; its `title` is the hover text. It sits right after the label. | +| Value readout | e.g. "1.00x", "110 %", "34 degrees": a 44 px column. | + +## Cards and tiles + +| Piece | Size and style | +|---|---| +| Picture card | A radio button. Radius 9, 1 px `dialog_border`, fill `control_fill`, padding 6 6 7, gap 5, a centred column: the figure at the full inside width (a 130 px card shows a 118 px figure; the figure has radius 5 and keeps its canvas aspect ratio), then the label (12.5 px, weight 400) and an optional sub-label (11 px `form_dim`). Selected: 2 px `form_primary` border (padding drops to 5 5 6 so the card does not grow), `selected_bg` fill, `selected_ink` label at weight 600. "Has options" badge: a 16 px accent disc with a 10 px icon at right 5, top 5, hover "Has options". | +| Card widths (by grid) | Curved surfaces 130 (4 across, 117 high); Anti-aliasing 130; History and Browser 116 (101 high; the figure is 100); Orbit around 196 x 133.5 (3 across); View navigator 190 x 149; Orientation 150 x 146 (2 across); Selecting 150 x 109; "When a sketch ends" 196 x 152.5 (3 across); Theme 88 x 100.8. Grid gap 10. | +| Toggle tile | A checkbox button. Radius 9, same padding and gap as the picture card, the figure on top, the label beneath (12.5 px; selected: `selected_ink`, weight 600), and a 15 px square (radius 4) at the top-right corner, right 6 top 6: accent fill with an 11 px white tick when on. Selected: 2 px `form_primary` border and `selected_bg`. Widths 155.6 (Current view and In the view, 4 across, 112 high) and 208.8 x 140 (Marks in the sketch, Measure and pointer, 3 across). | +| Preset card | A radio button 204 wide x 69.5 high, radius 10, padding 14, 1 px `dialog_border`. Inside, gap 12: a 38x38 icon box (radius 10, fill `pref_well`, `form_dim` icon 21 px), then the name (15 px / 600) over one word (11.5 px `form_dim`). Selected: 2 px `form_primary` border, `selected_bg`; the icon box turns `form_primary` with an `on_accent` icon, the name turns `selected_ink`, and an 18 px `form_primary` disc with a 12 px white tick sits at the right. Three across: Performance "Fastest", Quality "Sharpest", Custom "Your own mix". | +| Theme card | A picture card 88 wide (thumbnail 124x76 shown 76 wide), the name, then one line (11 px) for the source: "Built in", "Follows the OS", "Imported file". The "has options" disc applies. | +| Import card | A button 88 wide, padding 6, gap 5, dashed 1 px `control_border`, transparent fill, centred: a plus icon in the accent, "Import..." (ink) and "theme file" (11 px). | +| Carousel | A row, gap 8: a previous button, the cards, a next button. The arrows are 26 x 64, radius 8, 1 px `dialog_border`, `control_fill`, 16 px chevron; opacity 0.35 when there is nothing further in that direction. | +| Theme options panel | Under the carousel: radius 10, 1 px `dialog_border`, fill `pref_well`, padding 8 16 10. Head 34 high: theme name (13 px / 600), "6 options" (11.5 px `form_dim`), then a ghost "Reset" button (24 high). Below, two columns (gap 2 / 32): each option is a row of at least 30 px, a 92 px label column and the control. Slider: 92 px wide, 4 px track (radius 2, `dialog_rule`), accent fill, a 16 px thumb (white, 2 px accent border); the value is IBM Plex Mono 12 px, min width 40 ("72 %"). Contrast, Corners and Density are segmented controls. An unavailable option stays in place with ink and thumb border `#8A94A3` and a text reason beside it ("Software graphics", "System: Reduce transparency"). | +| Layout schematic | 226x148 viewBox, 262 px wide (`figures/layout-schematic.*`). | +| Colour vision sample | 84 x 44 cell with the label beneath ("Fixed", "Projected", "Axes", "Bends", "Draft", "Failed"); above them four 13 px status icons with names ("Selected", "Warning", "Error", "Done"). | +| Profile row (General) | A 17 px profile icon, the name (weight 600 for the active profile), "Edited" and "Active" badges, then 15 px icon buttons Export, Rename and Delete (each with its hover title), and a 24 px "Apply" button (48.5 wide) on rows that are not active. | + +## Type scale in use + +| Size / weight | Where | +|---|---| +| 20 / 600 | Page title. | +| 14 / 600 | Dialog title. | +| 12.5 / 400 and 600 | Labels, values, buttons, subtitles (600 for the selected page and primary button). | +| 12 / 400 | Fields, small buttons, units. | +| 11.5 / 400 | Chips. | +| 11 / 600, tracking 0.07 em, upper-case | Section titles; also 11 / 400 for card sub-labels and badges. | +| 10.5 / 600, tracking 0.06 em | Profile card label, nav-bar editor sub-labels. | +| 10.5 mono / 400 | Key caps and keyboard hints. | +| 6.5 to 7 mono | Figure captions. | + +## Radii in use + +4 (key cap, tile corner box, status dot), 5 (figure), 6 (field, button, segmented group, page list item, search), 8 (carousel arrow), +9 (picture card, tile, badge disc), 10 (preset card, theme options panel, dialog), 11 (chip). diff --git a/docs/design/preferences/pages/appearance.md b/docs/design/preferences/pages/appearance.md new file mode 100644 index 000000000..a6f95545c --- /dev/null +++ b/docs/design/preferences/pages/appearance.md @@ -0,0 +1,67 @@ +# Appearance + +Board: `Prefs2_Appearance` (1920x1595). Heading: Look. Subtitle "Colours, text and accessibility." +Tag: In profile (hover "Saved in settings profiles"). Reference boards: `Theme_Options` for the theme options, +`Settings_Interface` for Scale and text and Colour vision. Source today: Interface page +(`prefs/interface.rs`). + +## Theme (6 themes) + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Theme cards: Light (Built in), Dark (Built in), System (Follows the OS), Gruvbox (Built in), Studio glass (Imported file) | Carousel of picture cards (88 wide) with previous and next arrows ("Previous themes", "Next themes") | `Prefs.theme` (id string); "System" follows the OS (`app.window_theme`) | `"dark"` | "Has options" on the disc of cards that have theme options | `theme-light`, `theme-dark`, `theme-system-light-half` + `theme-system-dark-half`, `theme-gruvbox`, `theme-imported` | The count "6 themes" is the number of cards. Gruvbox and Studio glass carry the "has options" disc. Build the cards from the theme list in `theme_files` (built-ins in `assets/styles/ui/themes`, imported in `Prefs.custom_themes`); only the first five are drawn on the board, the carousel scrolls to the rest. | +| Import... / theme file | Dashed card at the end of the carousel | theme import (`Prefs.custom_themes`) | n/a | none | none | "Import..." with the sub-label "theme file". | + +### Theme options panel ("Studio glass", "6 options", Reset) + +Follows `Theme_Options.dc.html`. Shown under the carousel for a theme that has options. "Reset" +restores the theme's own option values (`Prefs.theme_options[]`). Two columns. + +| Label | Control | Edits | Default | Hover | Notes | +|---|---|---|---|---|---| +| Opacity | Slider with "72 %" readout | `Prefs.theme_options[theme]["opacity"]` (standard option id `opacity`; the only provider registered on main, `theme_options::PROVIDERS`) | the theme's | "Opacity" (the label) | aria-label "Panel opacity". | +| Blur | Slider (dimmed, thumb grey) with the reason "Software graphics" | `theme_options[theme]["blur"]` (standard id `blur`; no provider on main yet, so it is not offered until one registers) | the theme's | "Blur" | aria-label "Blur behind panels". Unavailable on this computer: it stays in place, disabled, with the reason as text. On `Theme_Options` the value reads "18 px" with the hover "Relative GPU cost", and the stops are "Off" (hover "No GPU work"), "8 px", "18 px", "40 px"; 0 is off and the cost meter flatlines. | +| Tab colours | Switch + "Fade" and "240 ms" (a duration stepper, aria "Fade duration") | `theme_options[theme]["tab_colours"]` and `["tab_fade_ms"]` (standard ids) | the theme's | "Tab colours" | The theme defines the tab colours: 3 surfaces per tab (panel, view top, view bottom; hovers on `Theme_Options`). | +| Contrast | Segmented: Standard / High | a theme-declared option (custom id, `OptionDef` in the theme file) | the theme's | "Contrast" | aria-label "Contrast". Not a standard behaviour on main: it appears only where the theme file declares it. | +| Corners | Segmented: Square / Soft / Round | a theme-declared option | the theme's | "Corners" | As Contrast. | +| Density | Switch (aria "Compact density") | a theme-declared option | the theme's | "Density" | As Contrast. | +| More . 3 | Disclosure | Style, Edge glow, Shadows (`Theme_Options`), theme-declared options | the theme's | none | The page board does not draw the extra three; `Theme_Options` lists them. | + +Disabled options keep their place with a reason badge: "Software graphics" for Blur; "System: Reduce +transparency" for Opacity on `Theme_Options`. The adaptation is one ordered list: the standard options +first, then the theme's own. + +## Viewport and logo + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Background | Segmented: Theme's gradient / Colour, plus a hex field "#FFFFFF" | `Prefs.viewport_background` (`None` = the theme's gradient; `Some([r,g,b])` = Colour) | `None` | none | none | The hex field is active only for Colour. | +| 3D view colours | Segmented: Theme's own / Light / Dark | `Prefs.viewport_theme` (`ViewportTheme`) | Theme | none | none | | +| Logo | Segmented: Theme's colours / Accent | `Prefs.logo_accent` | `false` | none | none | | +| Follow a theme file | Checkbox + "Choose..." button + badge "Desktop only" | `Prefs.theme_follow` (path; empty = off) | empty | "Reloads when another tool rewrites the file." | none | "Desktop only" is a badge: the control is hidden or disabled on the web build. | + +## Scale and text + +Source: `Settings_Interface.dc.html` (section "Scale and text"). + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Interface scale | Slider with "110 %" readout and six chips 75%, 100%, 110%, 125%, 150%, 200% | `Prefs.ui_scale` (accepted 0.5 to 2.5) | `1.0` | none | none | aria-label "Interface scale". Chip row selects a preset; the selected chip is accent. | +| Live preview | A framed sample: "Distance" field ("OK"), a command row "Extrude 112.5 mm" with a 16 px icon | none (sample) | n/a | none | none | The preview rescales as the slider moves. Placeholder content. | +| Font | Dropdown "IBM Plex Sans (built in)" (aria "Interface font"), "Choose font file..." button, "Reset" | `Prefs.ui_font` (path; empty = built-in) | empty | none | none | | +| The quick brown fox . O12.50 mm . 45.0 deg . 0123456789 | Sample line | none | n/a | none | none | Placeholder sample text. | + +## Colour vision + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Mode | Segmented: Off / Protan / Deutan / Tritan | `Prefs.color_vision` (`ColorVision`) | Off | "Changes the colours that carry a meaning: sketch states, axes, bends, analyses and icons." | none | The sample row previews the chosen mode (the preference previews before applying; `Tokens::get_in`). | +| Status chips: Selected, Warning, Error, Done | Four 13 px icons with names | none (sample) | n/a | none | none | | +| Sample row: Fixed, Projected, Axes, Bends, Draft, Failed | Six 84x44 cells | none (sample) | n/a | none | `colour-vision-fixed`, `-projected`, `-axes`, `-bends`, `-draft`, `-failed` | Drawn with the mode's colours as the app does today. | + +## Mismatches + +* The dark board's accent `#8CBEF5` has no token (see `tokens.md`). +* Only `opacity` has a provider on main (`theme_options.rs`); blur, tab colours and the fade are standard ids + without one yet, so the board shows them ahead of the code. +* Only 5 of the 6 theme cards are drawn on the board. diff --git a/docs/design/preferences/pages/assistant.md b/docs/design/preferences/pages/assistant.md new file mode 100644 index 000000000..5aab775a1 --- /dev/null +++ b/docs/design/preferences/pages/assistant.md @@ -0,0 +1,61 @@ +# Assistant + +Board: `Prefs2_Assistant` (1920x1339). Heading: Extend. Subtitle "AI agents in SolidCraft." No "In +profile" tag. Source today: the AI page (`crates/ui-egui/src/agent_chat/settings.rs`, page +`PAGE_AI`). The whole page dims when "Show AI features" is off (the hover says so). + +## Availability + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Show AI features | Checkbox | `Prefs.ai_features` | `true` | "Off hides the Assistant everywhere and starts nothing. Everything below dims." | none | | +| Assistant button in the application bar | Checkbox | `Prefs.ai_toolbar_button` | `true` | none | none | | + +## Permissions + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Ask first: "Asks for every change" / Make edits: "Edits freely, asks for the rest" / Do everything: "Never asks" | Three radio cards (204 x 65, name and one line) | `Prefs.ai_permissions` (`agent_chat::agents::Mode`) | Make edits (`Mode::Edits`) | "Use with care" on Do everything | none | | + +## Agents (3) + +One card per agent, with an "Add agent..." and a "Refresh" button at the end. + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Agent card (Claude Code "Default" "Signed in"; Codex CLI "Not signed in"; Local model "Key in environment") | Card with name, badges, buttons "Test" (40 x 24) and for custom agents "Remove" | `Prefs.agents` (`agent_chat::agents::AgentConfig`), `Prefs.agent_default` | none configured | none | none | Names and states are samples; build from `agents.rs`. | +| Permissions | Dropdown (220 wide, "Same as above") | `Prefs.agent_permissions[agent]` (`Mode`) | same as above | none | none | Per agent. | +| Request timeout | Number field (64 wide, aria "Seconds") with "seconds" | the agent's timeout in `AgentConfig` | per agent | none | none | | +| Add agent... | Button (109 x 28) | opens the add-agent form | n/a | none | none | | +| Refresh | Button (65 x 28) | refreshes agent states | n/a | none | none | | + +## Panel + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Dock the chat: Left / Right / Own window | Segmented | `Prefs.agent_chat_side` (`"left"`, `"right"`) and `Prefs.agent_chat_popped` (Own window) | Right | none | none | Two fields behind one control. | +| Changes per message | Dropdown ("Unlimited") | `Prefs.agent_chat_turn_limit` (aria "Limit") | `DEFAULT_TURN_LIMIT` | none | none | The board shows "Unlimited" as the sample; the default is the code's `DEFAULT_TURN_LIMIT`. | + +## Connecting + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Let AI agents connect | Checkbox | `Prefs.agent_control` | `true` | "A local channel (MCP). Nothing leaves this computer." | none | | +| Add SolidCraft to AI apps | Checkbox | `Prefs.connect_ai_apps` | `true` | "Off takes the entries out again." | none | | +| Run slow commands in the background | Checkbox | `Prefs.agent_off_thread` | `false` | none | none | | +| Connect the last agent at start | Checkbox | `Prefs.agent_connect_at_start` | `false` | none | none | | +| Open the chat at start | Checkbox | `Prefs.agent_chat_open_at_start` | `false` | none | none | | + +## Agent pointer + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Show the agent's pointer | Checkbox | `app.ui.agent_cursor.show` (`agent_cursor::Settings`) | per session | none | none | Session value; in the Snapshot. | +| Speed | Slider, "1.00x" readout, with the path preview (230x84) at the right | `app.ui.agent_cursor.speed` (`Speed`) | 1.0 | none | `agent-pointer-speed` | aria-label "Pointer speed". | +| Follow the camera | Checkbox | `app.ui.agent_cursor.follow_camera` | per session | "Look At sketches move the view with the pointer." | none | | + +## Mismatches + +* `agent_chat_width`, `agent_chat_minimized`, `agent_chat_window`, `agent_last`, `agent_models` and + `agent_always_allow` have no control on the board. +* Agent names and states are sample content. diff --git a/docs/design/preferences/pages/design.md b/docs/design/preferences/pages/design.md new file mode 100644 index 000000000..7f5e09b51 --- /dev/null +++ b/docs/design/preferences/pages/design.md @@ -0,0 +1,50 @@ +# Design + +Board: `Prefs2_Design` (1920x1196). Heading: Work. Subtitle "What new designs start with." No "In +profile" tag. Source today: Design page (`prefs/design.rs`). + +## Units and precision + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Units of new designs | Segmented: mm / cm / m / in / ft | `Prefs.default_units` | `"mm"` | none | none | | +| Length decimals | Stepper (56 wide, aria "Length decimals") with the live sample "12.50 mm" | `Prefs.length_decimals` | `2` | none | none | | +| Angle decimals | Stepper (aria "Angle decimals") with the live sample "45.0 deg" | `Prefs.angle_decimals` | `1` | none | none | | +| Parameter list rows | Stepper (aria "Rows") | `Prefs.parameter_list_rows` (5 to 200, `PARAMETER_LIST_ROWS`) | `50` | "The most parameters Down arrow lists in an empty expression box." | none | | +| Step values with arrows and wheel | Checkbox | `Prefs.step_values` | `false` | "Up/Down and the wheel over a value field change its number." | none | | +| Show values beside their handles | Checkbox | `Prefs.value_boxes_in_view` | `true` | "Extrude's Distance, Fillet's Radius... as a box in the view." | none | | + +## Orientation + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Z up (default), Y up | Two picture cards (150 x 146) | `Prefs.up_axis` (`"z"`, `"y"`) | `"z"` | none | `orientation-z-up`, `orientation-y-up` | The figures are copied from the app (`Settings_Pages`); the existing orientation figure in `ui_kit` stays as it is. | +| Offer to stand up Y-up files | Checkbox | `Prefs.offer_stand_up` | `true` | "After a STEP or IGES file opens with Z up, offer a quarter turn about X." | none | | + +## Imported files + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Files from unknown programs | Dropdown (200 wide, "Ask" as drawn) | `Prefs.stand_up_unknown` (`StandUpUnknown`: Ask, Note, Off) | Note (the board sample shows Ask) | "How the offer is made when the file names no known program." | none | aria-label "Ask". | + +## Origin + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Origin plane names | Segmented: "XY . XZ . YZ" / "Top . Front . Right" | `Prefs.origin_plane_names` (`OriginPlaneNames`: Xyz, TopFrontRight) | Xyz | none | none | Moves from Interface. | +| Hide the Origin folder in new designs | Checkbox | `Prefs.hide_origin` | `false` | none | none | | + +## Linked designs + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Update changed links when a tab comes back | Checkbox | `Prefs.update_changed_links` | `true` | none | none | | +| Double-click a component to activate it | Checkbox | `Prefs.double_click_components` | `true` | "Or to edit a linked one in place." | none | | +| Insert Design lists open designs first | Checkbox | `Prefs.insert_lists_open_designs` | `true` | none | none | | + +## Mismatches + +* Hole, Extrude, Placement and Assembly Move controls (today on Design) move to Tools; network + locations moves to General > Files; "Show moved parts' old place as a ghost" + (`Prefs.drive_joints_ghost`) moves to Tools. +* `parameters_apply_live` has no control on this board either. diff --git a/docs/design/preferences/pages/general.md b/docs/design/preferences/pages/general.md new file mode 100644 index 000000000..64b824365 --- /dev/null +++ b/docs/design/preferences/pages/general.md @@ -0,0 +1,73 @@ +# General + +Board: `Prefs2_General` (1920x1436). Heading: none (top of the page list). Subtitle "Profiles, +language, files and updates." Tag: **In profile**, as drawn (a profile holds the language; the other sections are +not in a profile). Not shown on the board: everything in the +"Controls with no board" list of the README. + +Page title and tag: "General", "In profile" (hover "Saved in settings profiles"). + +## Profiles (3 saved) + +Source: today's General > Profiles section (`crates/ui-egui/src/settings_profiles.rs`, #6237). Section +title "Profiles", with the count "3 saved" at the right of the title. + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Profile rows (Laptop, Large monitor, Presentation) | List | `app.settings_profiles` (saved list) | none saved | Icon buttons: "Export", "Rename", "Delete" | none (17 px profile icon) | The active row shows badges "Edited" (when changed since saved) and "Active", and no Apply. Other rows show "Apply". Names are sample. | +| Apply | Small button per row | settings profile apply | n/a | none | none | Applying replaces what a profile holds (see README). | +| Profile name | Text field (220 wide) | the name for "Save as new" | empty | none | none | aria-label "Profile name". | +| Save as new | Button | settings profile save | n/a | none | none | | +| Import... | Button | settings profile import | n/a | none | none | | +| Held / This computer chips | Two chip rows | none (information) | n/a | none | none | "Held": Appearance, Layout, Navigation, Sketch, Shortcuts, Language. "This computer": 3D mouse, Graphics, Assistant. Matches `settings_profiles::PAGES` plus language, shortcuts, toolbar, S-box favourites and the imported theme; mismatch: the board lists page names, the code lists the Interface, Navigation and Sketch pages (`settings_profiles::PAGES`), so after the page split map Appearance and Layout to the old Interface fields. | + +## Language + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Interface language | Dropdown, 280 wide ("English (United Kingdom)") | `Prefs.language` | `"en"` | none | none | The dropdown lists `i18n::LOCALES`. Page: 0 (General). | + +## Start and save + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Reopen the designs that were open last time | Checkbox | `Prefs.reopen_designs` | `true` | none | none | Today's label is longer ("Reopen the designs that were open when SolidCraft was last closed"). | +| Autosave every | Number field (64 wide) with "minutes", an (i) and a "-30 min ... now" strip | `app.autosave_minutes` (not a `Prefs` field; `set_autosave`) | session value | "0 turns it off" | none | The strip under the field ("30 min ... now") is today's `settings_autosave_timeline`. aria-label "Minutes". | + +## Files + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Largest file to open: STEP and import | Number field, "MB" (72 wide) | `Prefs.max_step_file_mb` | `DEFAULT_STEP_MB` | none | none | Moves here from Design/General. | +| Largest file to open: Design | Number field, "MB" | `Prefs.max_design_file_mb` | `DEFAULT_DESIGN_MB` | none | none | | +| Allow network locations in designs | Checkbox | `Prefs.network_locations` | `false` | "For organisations that keep designs on file servers. Off: only servers you allow." | none | Moves from Design (`PAGE_DESIGN`). | +| `\\files.studio`, `\\nas01` | Chip list with a remove icon (11 px) | `Prefs.network_hosts` | empty | none | none | Shown only when network locations is on. Names are sample. | +| Open files in a slicer that is already running | Checkbox | `Prefs.slicer_single_instance` | `true` | "For slicers that load a file into a running window." | none | | +| Print face highlight | Slider, "60 %" readout (44 px column) | `Prefs.print_face_highlight` (0.0 to 1.0) | `0.2` (20 %) | none | none | aria-label "Print face highlight". The sample shows 60 %. Moves from Design. | + +## Updates + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Up to date . today 09:12 | Success badge (11 px icon) | `Prefs.update` memo (read only) | n/a | none | none | Sample time. | +| Check now | Button | the update check command | n/a | none | none | | +| Check at start and once a day | Checkbox | `Prefs.check_updates` | `true` | none | none | | + +## Crash reports + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| 2 saved | Text count | crash report store | n/a | none | none | Sample count. | +| Open crash reports... | Button | opens the crash reports | n/a | none | none | Programmatic calls must not open a dialog. | + +## Footer + +"Restore page defaults" (`reset_preferences` for this page), "Cancel", "OK". The page-list profile +card ("Profile", "Laptop", dot with hover "Changed since saved") is the same on every page. + +## Mismatches + +* No control on the board for `parameters_apply_live` or `personal_sheet_rules`. +* Print face highlight and Largest file come from Design; network locations comes from Design. +* "Profiles" section details (what the Held chips mean) are specified in `settings_profiles.rs`; the + board is the only authority for the layout. diff --git a/docs/design/preferences/pages/graphics.md b/docs/design/preferences/pages/graphics.md new file mode 100644 index 000000000..62b355ade --- /dev/null +++ b/docs/design/preferences/pages/graphics.md @@ -0,0 +1,77 @@ +# Graphics + +Board: `Prefs2_Graphics` (1920x1821). Heading: Look. Subtitle "Trade speed for smoothness." No +"In profile" tag: the Graphics page stays on this computer (see README). Source today: Graphics page +(`prefs/graphics.rs`). + +## Preset + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Performance "Fastest", Quality "Sharpest", Custom "Your own mix" | Three preset cards (204 x 69.5) | command `view.graphics_preset` with `{"preset":"performance"}` or `"quality"`; the selection is derived from the settings by `graphics_preset(&prefs)`, Custom when neither matches | derived | Today's tooltip `ui.graphics_preset_help`: "Quality: ambient occlusion, Fine display quality and adaptive 2x supersampling. Performance: no ambient occlusion, Normal display quality and supersampling off. Manual changes show Custom. MSAA stays unchanged." The board shows no hover; keep the existing text on the card group. | preset icons (not figures; the app's icons) | The board shows no meters. Custom cannot be chosen to set values: choosing it changes nothing. Only these three exist ("Balanced" in an earlier board does not). | + +## Curved surfaces + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Coarse "fastest", Normal "default", Fine "smoother", Ultra "slowest" | Four picture cards (130 wide, 117 high) | `Prefs.display_quality` (string ids; `"normal"` is the default and `"ultra"` is accepted, see `prefs/graphics.rs` for the full list) | `"normal"` | none | `tess-coarse`, `tess-normal`, `tess-fine`, `tess-ultra` | The figure shows a polygon on a circle with 8, 16, 32 and 64 segments (the corner caption of each figure). The caption number in `tess-normal` ("16") is part of the figure. | + +## Edges and shading + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Anti-aliasing + badge "Restart needed" | Four picture cards: Off, 2x, 4x, 8x ("not on this GPU") | `Prefs.msaa` (1, 2, 4, 8) | `4` | tooltip on the cards: `settings.msaa_applies_on_restart` (the restart note) | `aa-off`, `aa-2x`, `aa-4x`, `aa-8x` | A level the adapter lacks (`app.msaa_supported`) is disabled with the badge "not on this GPU". Changing it applies on restart. | +| Supersampling | Segmented: Off / 1.5x / 2x | `Prefs.supersampling` (1.0, 1.5, 2.0) | `1.0` (Off) | `settings.supersampling_note` | none | | +| Only while the view is still | Checkbox | `Prefs.supersampling_adaptive` | `true` | none | none | Disabled while Supersampling is Off (`supersampling > 1.0`). | + +## Current view (with the badge "Also in the view bar") + +Four toggle tiles (155.6 wide). These are the view toggles that also sit in the view bar. + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Grid | Toggle tile | `app.ui.show_grid` (session; in the Snapshot) | per session | none | `view-grid` | | +| Ground shadow | Toggle tile | `app.ui.ground_shadow` | per session | none | `view-shadow` | | +| Perspective | Toggle tile | `app.ui.perspective` | per session | none | `view-perspective` | | +| Ambient occlusion | Toggle tile (moves here from Edges and shading) | `Prefs.ambient_occlusion` | `false` | none | `ao-on` | | +| Visual style | Dropdown (240 x 30) with the style icon: "Shaded with edges" | `app.ui.visual_style` (0..3: shaded with edges, shaded, wireframe, hidden edges) | 0 | none | `style-shaded-edges` (icon shape; use the app's `style_shaded_edges`, `style_shaded`, `style_wireframe`, `style_hidden_edges`) | aria-label "Visual style". | +| Field of view | Slider with "34 degrees" readout (44 px column) | `Prefs.perspective_fov` in radians (accepted 15 to 90 degrees) | `0.6` rad (34.4 degrees) | none | none | aria-label "Field of view". | + +## In the view + +Four toggle tiles, then a chip row. + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| View angles | Toggle tile | `Prefs.show_view_angles` | `false` | none | `view-angles` | | +| Vertex markers | Toggle tile | `Prefs.vertex_markers` | `false` | none | `vertex-markers` | | +| Quick measurement | Toggle tile | `Prefs.quick_measure` (today on the Interface page) | `false` | none | `quick-measure` | Moves here. | +| Frame rate | Toggle tile | `Prefs.show_frame_rate` | `false` | none | `frame-rate` | | +| Status chips: Analysis, Section, Live details, Fold items | Four small chips (the row is labelled "Status chips") | `Prefs.viewport_analysis_status`, `Prefs.viewport_section_status`, `Prefs.viewport_status_details`, `Prefs.viewport_status_summary` | all `true` | none | none | Mapping by catalog label: "Live details" is `viewport_status_details` ("Live viewport details") and "Fold items" is `viewport_status_summary` ("Fold viewport status items"). These four move here from Interface. `Prefs.frame_rate_details` (frame rate details) has no control on the board. | + +## Surfaces and edges + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Cosmetic thread markings | Checkbox | `Prefs.cosmetic_threads` | `false` | none | none | | +| Halo under sketch curves | Checkbox | `Prefs.sketch_halo` | `false` | none | none | | +| Reference geometry through bodies | Checkbox | `Prefs.reference_geometry_through_bodies` | `false` | none | none | | +| Grid follows the view | Checkbox | `Prefs.grid_follows_view` (no page id in the table today) | `false` | "Side views show the grid on the facing plane." | none | | +| Single surface analysis | Checkbox | `Prefs.single_surface_analysis` | `true` | "Shading and Continuity share one analysis." | none | | + +## This computer + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Apple M2 / Metal . GPU renderer | Read-only device card (the first line is the adapter name, the second the backend) | none (from the renderer) | n/a | none | none | Sample values. | +| Graphics card + badge "Restart needed" | Dropdown (240 wide, "Automatic") | `Prefs.graphics_adapter` (empty = automatic) | empty | none | none | aria-label "Graphics card". | +| Window system | Dropdown (240 wide, "Automatic") with "Linux" badge | `Prefs.window_system` (`"auto"`) | `"auto"` | none | none | The "Linux" badge says the choice is for Linux only; hide the row elsewhere. aria-label "Window system". | +| Use previous Render preview geometry budget | Checkbox | `Prefs.render_previous_geometry_budget` | `false` | "Restores the earlier fixed budget." | none | | + +## Mismatches + +* "Axis distances in Measure" (`Prefs.measure_axis_distances`) leaves this page for Tools. +* The board has no control for `frame_rate_details`. +* Renderer and window system rows come from the old page's "Renderer" block. +* The tracker's "Edges and shading" note says Ambient occlusion moves to Current view; the code still + lists it under Graphics with `PAGE_GRAPHICS`. diff --git a/docs/design/preferences/pages/layout.md b/docs/design/preferences/pages/layout.md new file mode 100644 index 000000000..b36849891 --- /dev/null +++ b/docs/design/preferences/pages/layout.md @@ -0,0 +1,80 @@ +# Layout + +Board: `Prefs2_Layout` (1920x1750). Heading: Look. Subtitle "Where the parts of the window sit." +Tag: In profile. Reference for the navigation-bar editor's interaction states: `Navbar_Settings`. +Source today: Interface page (`prefs/interface.rs`, `prefs/navbar.rs`). + +## Window + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Workspace | Segmented: Floating / Compact | `Prefs.layout` (`shell::LayoutMode`: `Floating`, and `Docked` serialised as `compact`) | Floating | none | `layout-schematic` | Today's labels are Floating and Docked; the board says Compact (the serialised name is `compact`). | +| Toolbar | Segmented: Labels / Icons only | `Prefs.ribbon_labels` | `true` (Labels) | none | none | | +| Menus | Segmented: List / Large icons | `Prefs.ribbon_icon_grid` | `false` (List) | none | none | | +| Notices | Segmented: Bottom right / Bottom centre | `Prefs.toast_place` (`ToastPlace`; Corner = Bottom right) | Corner (Bottom right) | none | none | | +| Status bar | Checkbox | `Prefs.status_bar` | `false` | "What is being edited, the sketch state and units." | none | | +| Layout preview | Schematic (262 wide) of the window, showing the choices above | none | n/a | none | `layout-schematic` | Reflects the Workspace choice and the History, Browser and Dialog choices below. | + +## Panels + +### History + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| History: Bottom / Left / Under browser / In browser | Four picture cards (116 wide) | `Prefs.timeline_left`, `Prefs.timeline_under_browser`, `Prefs.history_in_browser` (three booleans; Bottom is all off) | Bottom | none | `history-bottom`, `history-left`, `history-under-browser`, `history-in-browser` | One choice maps to the three booleans; keep them mutually consistent as today's page does. | + +### Browser + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Browser: Column / Card | Two picture cards | `Prefs.browser_float` (Card = floating) | Column (`false`) | none | `browser-column`, `browser-card` | | +| Shown | Segmented: Shown / On hover | `Prefs.browser_show` (`browser::BrowserShow`) | Shown | none | none | | +| Sketches in History | Segmented: In order / Under feature | `Prefs.history_sketches` (`HistorySketches`) | In order | none | none | | +| Bodies folders | Segmented: Always / Several / Never | `Prefs.browser_bodies_folders` (`BodiesFolders`) | Several | none | none | | +| Play History button | Checkbox | `Prefs.history_play_button` | `true` | none | none | | +| Origin and bodies on top | Checkbox | `Prefs.timeline_origin_bodies` | `false` | "Vertical history only." | none | | +| Eye beside the fold arrow | Checkbox | `Prefs.browser_eye_left` | `false` | none | none | | + +## Dialogs + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Open | Segmented: At the view's edge / In the left column | `Prefs.dialog_place` (`dialog_column::DialogPlace`: Edge, LeftColumn) | Edge | none | none | | +| OK and Cancel | Segmented: Bottom / Top | `Prefs.dialog_buttons` (`ui_kit::DialogButtons`) | Bottom | none | none | | +| Also in the view's corner | Checkbox | `Prefs.view_confirm_corner` | `false` | "While a dialog or sketch is open." | none | | + +## Toolbar tabs + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Model, Surface, Mesh, Form, Sheet Metal, Render | Six tab chips, each with a show/hide toggle | `Prefs.hidden_toolbar_tabs` (list of hidden tab ids) | none hidden | none | none | | +| Keep the Sketch tab shown | Checkbox | `Prefs.sketch_tab_always` | `false` | none | none | | +| Highlight active commands | Checkbox | `Prefs.persistent_ribbon_pressed` | `true` | none | none | | +| Show search results in the ribbon | Checkbox | `Prefs.ribbon_reveal` | `false` | none | none | Verify the field: `ribbon_reveal` is the only ribbon search field in the table. | +| Pinned commands out of menus | Checkbox | `Prefs.ribbon_menus_skip_pinned` | `false` | none | none | | + +## Navigation bar + +Source: `Prefs.navigation_bar` (`navigation_bar::NavigationBar`) and `app.ui.show_navigation_bar`. +The interaction states (drag onto the bar, drop targets, reorder) stay as in `Navbar_Settings`. + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Preview as | Tabs: Design / Render | which workspace's bar is edited | Design | none | none | The Render tab edits the Render workspace's slots. | +| Preview strip | The bar drawn as it will look, with the slots in order | `navigation_bar.slots` (plus `slot_options`) | orbit, pan, zoom, separator, fit, look_at, home, separator, visual_style, display | none | none | Slot icons on the board are stand-ins; use the app's icons. | +| Show navigation bar | Checkbox | `app.ui.show_navigation_bar` (session; in the Snapshot) | per session | none | none | | +| Reset to default | Button | resets `navigation_bar` | n/a | none | none | | +| 10 of 16 slots | Count text | none | n/a | none | none | Sample numbers; the count is slots on the bar of all available slots. | +| Available | Row of slot chips, e.g. Faces and edges, Spin, Projection, Ground shadow, Ambient occlusion | none (drag source) | n/a | "Drag onto the bar" on each chip and on the label | none | Slot names and icons are sample content. | +| Position | Segmented: Left / Centre / Right | `navigation_bar.position` (`Position`) | Centre | none | none | | +| Edge | Segmented: Bottom / Top | `navigation_bar.edge` (`Edge`) | Bottom | none | none | | +| Size | Segmented: Compact / Regular | `navigation_bar.size` (`Size`) | Regular | none | none | | +| Buttons | Segmented: Icons / Icons + labels | `navigation_bar.labels` (`Labels`) | Icons (`Labels::Icons`) | none | none | | +| When idle | Segmented: Always / Fade / Hover | `navigation_bar.idle` (`Idle`: Always, Fade, Hide) | Fade | none | none | The third option reads "Hover" on the board and `Hide` in the code. | + +## Mismatches + +* "Compact" on the board is `LayoutMode::Docked` (serialised `compact`) in the code. +* The History choice is three booleans in the code, one card group on the board. +* The status chips ("Analysis", "Section", "Live details", "Fold items") are not on this page; they + are on Graphics under "In the view". diff --git a/docs/design/preferences/pages/mouse3d.md b/docs/design/preferences/pages/mouse3d.md new file mode 100644 index 000000000..354c5cd52 --- /dev/null +++ b/docs/design/preferences/pages/mouse3d.md @@ -0,0 +1,52 @@ +# 3D mouse + +Board: `Prefs2_3DMouse` (1920x1625). Heading: Input. Subtitle "SpaceMouse and SpaceNavigator." No "In +profile" tag (the 3D mouse stays on this computer). Source today: the 3D mouse block of the Navigation +page (`prefs/navigation.rs`) and `crates/ui-egui/src/space_mouse.rs`. + +## Device + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| SpaceMouse Compact + badges "Connected", "Calibrated" | Device card | none (device state) | n/a | none | none | Sample device name and states; build from the detected device. | +| Calibrate... | Button (82 x 28) | `Prefs.space_mouse_calibrations[device]` | none | none | none | Starts the calibration command; programmatic calls must not open dialogs. | +| Forget calibration | Button (120 x 28) | clears `space_mouse_calibrations[device]` | n/a | none | none | | +| Navigate with the 3D mouse | Checkbox | `Prefs.space_mouse_enabled` | `true` | none | none | | +| Show it in the 3D view | Checkbox | `Prefs.space_mouse_in_view` | `false` | "A picture that moves as the device does." | none | | +| Overall speed | Slider, "1.10x" readout | `Prefs.space_mouse_speed` | `1.0` | none | none | aria-label "Overall speed". The board sample reads 1.10x. | +| Picture position | Dropdown (240 wide, "Lower left of the viewport") | `Prefs.space_mouse_ghost_position` (`SpaceMouseGhost`) | lower left | none | none | | + +## Orbit + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Turn around: Model / View centre | Segmented | `Prefs.space_mouse_model_pivot` (Model = `true`) | View centre (`false`) | "Model: the model in the middle of the view." | none | | +| Turn the view while a sketch is edited | Checkbox | `Prefs.space_mouse_sketch_orbit` | `false` | none | none | | + +## Axes + +A table with the columns "Axis", "Live input", "Speed" and a "Reset axes" button under it. + +| Row | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Push X, Push Y, Push Z, Tilt X, Tilt Y, Tilt Z | Per row: a live bar with a dead-zone mark, an "Invert" checkbox, a speed readout ("1.00x"; Tilt Z shows 0.80x as a sample) | `Prefs.space_mouse_reverse[6]`, `Prefs.space_mouse_axis_speed[6]`, `Prefs.space_mouse_axis_source[6]` (`space_mouse::SAME_AXES`) | no inversion, 1.0, same axes | none | none | The live bars read the device; the dead zone is the device's calibration. `space_mouse_axis_source` (which physical axis feeds which row) has no control on the board. | +| Reset axes | Button | resets the three arrays | n/a | none | none | | + +## Buttons + +| Row | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Button 1: Open Preferences; Button 2: View . Fit; Button 3: View . Top; Button 4: Hold Shift; Button 5: Not assigned | One dropdown per device button (240 wide) | `Prefs.space_mouse_buttons[device][button]` (`space_mouse::ButtonJob`) | per device | none | none | Sample jobs. The list length follows the device. `ButtonJob::Settings` ("Open Preferences") must open this page, not Navigation. | + +## Advanced + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Driver + badge "Linux" | Dropdown (200 wide, "Automatic") | `Prefs.space_mouse_driver` (`SpaceMouseDriver`: Automatic, Spacenavd, Direct) | Automatic | none | none | Linux only; hide elsewhere. | +| Navigate with a device app on this computer | Checkbox | `Prefs.nav_bridge_enabled` | `false` | "Connects to its navigation bridge. Off unless asked for." | none | | +| Port | Number field (80 wide) | `Prefs.nav_bridge_port` | `8765` | none | none | aria-label "Port". Enabled with the previous checkbox. | + +## Mismatches + +* `space_mouse_offer_never` and `space_mouse_offered` (the "offer to use the 3D mouse" memory) have no control. +* The live bars and the dead zone are new drawing, not a setting. diff --git a/docs/design/preferences/pages/navigation.md b/docs/design/preferences/pages/navigation.md new file mode 100644 index 000000000..1b431d881 --- /dev/null +++ b/docs/design/preferences/pages/navigation.md @@ -0,0 +1,55 @@ +# Navigation + +Board: `Prefs2_Navigation` (1920x1584). Heading: Input. Subtitle "Mouse and trackpad. The 3D mouse has +its own page." Tag: In profile. Source today: Navigation page (`prefs/navigation.rs`). + +## Mouse + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Mouse mapping | Dropdown (220 wide, "Fusion style") | `Prefs.nav` (preset id) with `Prefs.mouse_gestures` | `"fusion"` | none | `mouse-mapping` | The mouse figure (96x120) sits at the left of the list. Presets set `right_drag_orbits` and friends (`prefs.rs` preset block). | +| Middle drag: Pan; Shift + Middle drag: Orbit; Right drag: Orbit; Wheel: Zoom; Left click: Select; Right click: Menu | Key-cap table (gesture, then action) | the mapping's gestures (`Prefs.mouse_gestures`) | the mapping | none | `mouse-mapping` | Rows follow the chosen mapping; the board shows the Fusion style as the example. | +| Right drag orbits | Checkbox | `Prefs.right_drag_orbits` | `true` | "Shown where the mapping orbits on a right drag." | none | | +| Radial context menu | Checkbox | `Prefs.radial_context_menu` | `false` | "Hold or flick the right button for a ring of tools." | none | | +| Middle double-click | Dropdown (220 wide, "Home view") | `Prefs.middle_double_click` | `"home"` | none | none | | + +## Orbit around + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Origin / View centre / Under the cursor | Three picture cards (196 x 133.5) | `Prefs.orbit_around` (`OrbitAround`: Origin, ViewCentre, Cursor); `Prefs.orbit_cursor` is the older boolean for the cursor choice | ViewCentre | none | `orbit-origin`, `orbit-centre`, `orbit-cursor` | | + +## Orbit style + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Orbit: Turntable / Free | Segmented | `Prefs.free_orbit` (Free = `true`) | Turntable (`false`) | "Free turns through both poles, with roll and no Shift axis snap." | none | | +| Turn about the world's up axis | Checkbox | `Prefs.free_orbit_upright` | `false` | "With Free." | none | Dimmed unless Free is chosen. | + +## Wheel and trackpad + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Zoom to the cursor | Checkbox | `Prefs.zoom_to_cursor` | `true` | none (today: "The wheel zooms toward the point under the cursor (off: toward the view's center)") | none | | +| Smooth wheel zoom | Checkbox | `Prefs.smooth_wheel_zoom` | `true` | none | none | | +| Reverse zoom direction | Checkbox | `Prefs.zoom_reverse` | `false` | none | none | | +| Two-finger scroll pans | Checkbox | `Prefs.trackpad_pan` | `true` | "Off: it zooms like the wheel. Pinch always zooms." | none | | +| Reverse horizontal pan | Checkbox | `Prefs.pan_reverse_x` | `false` | none | none | | +| Reverse vertical pan | Checkbox | `Prefs.pan_reverse_y` | `false` | none | none | | +| Reverse trackpad orbit | Checkbox | `Prefs.orbit_reverse` | `false` | none | none | | +| Stop zoom at the model | Checkbox | `Prefs.zoom_stop_at_model` | `false` | none | none | | +| Wheel zoom speed | Slider, "1.00x" readout (44 px) | `Prefs.wheel_zoom_speed` (0.25 to 4.0) | `1.0` | none | none | aria-label "Wheel zoom speed". | +| Two-finger zoom while holding | Dropdown (180 wide, "Ctrl / Cmd") | `Prefs.trackpad_zoom_modifier` (`TrackpadZoomModifier`: Cmd, Alt, Ctrl, Off) | Off | none | none | | + +## View + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| View navigator: Axes (signed) / Cube (compact) | Two picture cards (190 x 149) | `Prefs.navigator_style` (`NavigatorStyle`: Axes, Cube) | Axes | none | `navigator-axes`, `navigator-cube` | The cards have no ground rectangle. The Axes figure draws a disc with signed axis labels; the Cube figure draws the view cube with TOP, FRONT, RIGHT faces. Paint from the `Tokens` in the app's navigator (`cube_face`, `cube_border`, `cube_text`, `axis_x`..`axis_z`). | +| Animate view changes | Checkbox | `Prefs.look_at_anim` | `true` | "Axis view, Look At, Home and Fit." | none | | +| Animation speed | Slider, "1.00x" readout | `Prefs.look_at_speed` (0.25 to 4.0; slider 0.5 to 3.0) | `1.0` | none | none | Disabled while Animate view changes is off. | + +## Mismatches + +* "Direct interaction" and "tool at cursor" move to Tools; all 3D mouse settings move to 3D mouse. +* The mouse mapping table is as drawn for Fusion only; rows must follow the chosen preset. diff --git a/docs/design/preferences/pages/plugins.md b/docs/design/preferences/pages/plugins.md new file mode 100644 index 000000000..2deb01244 --- /dev/null +++ b/docs/design/preferences/pages/plugins.md @@ -0,0 +1,32 @@ +# Plugins + +Board: `Prefs2_Plugins` (1920x876). Heading: Extend. Subtitle "Sandboxed add-ons." No "In profile" +tag. Source today: Plugins page (`crates/ui-egui/src/plugins.rs`, `Prefs.disabled_plugins`, page +`PAGE_PLUGINS`). + +## Toolbar of the page + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Search plugins | Search field, full width | filters the cards only | empty | none | none | | + +## Installed (3) + +One card per installed plugin, 61.7 px high. + +| Part | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Name, version, permission badge, description | Text and a badge ("No permissions", "Reads files") | none (from the plugin manifest) | n/a | none | none | Sample content: Gear generator 1.2.0 "Adds a parametric gear feature.", Bracket tools 0.4.1 "Batch-place mounting brackets." (Reads files), Thread library 2.0.0 "Standard thread profiles.". Build from the installed plugins. | +| Show in folder | Small button (114.6 x 24) | opens the plugin's folder | n/a | none | none | | +| Enabled | Checkbox (16 px) | `Prefs.disabled_plugins` (a plugin is enabled when its id is not in the set) | enabled | none | none | | + +## Footer row + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Show plugins folder | Button (152 x 28) | opens the plugins folder | n/a | none | none | The page has no "Restore page defaults" button on the board; the footer shows "Cancel" and "OK" only. | + +## Mismatches + +* Plugin cards are sample content (see README). +* The board footer omits "Restore page defaults" because nothing on this page has a default. diff --git a/docs/design/preferences/pages/shortcuts.md b/docs/design/preferences/pages/shortcuts.md new file mode 100644 index 000000000..a34834dc2 --- /dev/null +++ b/docs/design/preferences/pages/shortcuts.md @@ -0,0 +1,39 @@ +# Shortcuts + +Board: `Prefs2_Shortcuts` (1920x992). Heading: Input. Subtitle "Keys for each command." Tag: In +profile. Source today: Keyboard Shortcuts page (`crates/ui-egui/src/keymap.rs`, customised keys in +`app.keymap.custom`). This page is the only fixed-height dialog: the command list scrolls +(content area 646 wide; list about 580 high on the board). + +## Toolbar of the page + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Filter commands or keys | Search field, full width | filters the list only | empty | none | none | | +| Done | Primary button (52 x 28) | leaves "Press a key..." capture mode | n/a | none | none | | +| Export | Button (79 x 28) | exports `app.keymap.custom` | n/a | none | none | Programmatic calls must not open dialogs. | +| Import | Button (81 x 28) | imports a keymap | n/a | none | none | | + +## List + +A list grouped by menu group with a group heading (11 px, upper-cased: File, Edit, View, Sketch, +Features). Each row: the command name at the left and its key caps at the right (IBM Plex Mono +10.5 px key caps), then two icon buttons (reset to default, clear). + +| Row state | Drawing | Notes | +|---|---|---| +| Assigned | Command name and key caps ("Ctrl" "N") | | +| Not assigned | The text "Not assigned" in `form_dim` | | +| Capturing | The text "Press a key..." in the accent | Exactly one row at a time. | + +The groups and commands on the board (New design Ctrl N, Open Ctrl O, Save Ctrl S, Save as Ctrl +Shift S; Undo Ctrl Z, Redo Ctrl Shift Z, Cut Ctrl X, Copy Ctrl C, Paste Ctrl V, Delete Del; Fit F, +Home view Home, Look at Not assigned; Line Press a key..., Rectangle, Circle, Trim Not assigned; +Extrude, Fillet, Hole, Shell Not assigned) are **sample content**: build the list from the command +registry and the keymap (`keymap.rs`). + +## Mismatches + +* The per-row "reset" and "clear" affordances are two icon buttons on the board; check `keymap.rs` for + what today's keymap edit offers before building them. +* The board's footer is the shared "Restore page defaults / Cancel / OK". diff --git a/docs/design/preferences/pages/sketch.md b/docs/design/preferences/pages/sketch.md new file mode 100644 index 000000000..7fb4cfebc --- /dev/null +++ b/docs/design/preferences/pages/sketch.md @@ -0,0 +1,65 @@ +# Sketch + +Board: `Prefs2_Sketch` (1920x1570). Heading: Work. Subtitle "Drawing, snapping and selecting." +Tag: In profile. Source today: "Sketch" page (`prefs/sketch.rs`) plus the selection controls. + +## Snapping and guides + +A 120x64 figure at the left (`sketch-guides`), the checkboxes at the right. + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Centre and midpoint guides | Checkbox | `Prefs.sketch_tracking_guides` | `true` | "Temporary horizontal and vertical guides from hovered centres and edge midpoints." | `sketch-guides` | | +| Guides from sketch points too | Checkbox | `Prefs.sketch_tracking_points` | `true` | none | none | Disabled while the first is off (`sketch_tracking_guides`). | +| Snap to where two guides cross | Checkbox | `Prefs.sketch_recent_snap` | `false` | none | none | Catalog label today: "Auto snap to recent centers and midpoints". | +| Line up with other sketch points | Checkbox | `Prefs.sketch_align_points` | `false` | "Drawing lines align with points on both axes at once." | none | | +| Hold to stop snapping | Dropdown (200 wide, "Alt / Option") | `Prefs.suppress_sketch_snap` (`ModifierCombo`) | Ctrl + Alt (`ModifierCombo::CTRL_ALT`) | none | none | The board sample shows "Alt / Option" and the key caps "Ctrl / Cmd"; the default in the code is Ctrl+Alt. | + +## Drawing + +Two columns of checkboxes. + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Press and drag draws one line | Checkbox | `Prefs.line_drag_draws_one` | `false` | none | none | | +| Centre-point arc follows the cursor | Checkbox | `Prefs.center_arc_follows_cursor` | `true` | none | none | | +| Extended construction line tools | Checkbox | `Prefs.sketch_construction_lines` | `true` | none | none | | +| Dimension new shapes fully | Checkbox | `Prefs.sketch_auto_dimensions` | `false` | "Typed values plus every dimension that fixes the shape." | none | | +| Place from the sketch origin | Checkbox (dimmed on the board while the one above is off) | `Prefs.sketch_auto_locate` | `false` | "With full dimensions." | none | Dimmed unless "Dimension new shapes fully" is on. | +| Shortcut again switches mode | Checkbox | `Prefs.shortcut_cycles_modes` | `false` | "Off: it starts the tool again." | none | | +| Project face edges into new sketches | Checkbox | `app.session.auto_project` (session; in the Snapshot) | per session | none | none | Not a `Prefs` field. | +| Ask for Project options first | Checkbox | `Prefs.project_options_dialog` | `true` | none | none | | + +## Opening and closing + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Turn to face a sketch when it opens | Checkbox | `Prefs.sketch_open_look_at` | `true` | none | none | | +| When a sketch ends: Return to the view before / Keep (default) / Unless turned (return if not rotated) | Three picture cards (196 x 152.5), a before / sketch / after trio each | `Prefs.sketch_exit_view` (`SketchExitView`: Previous, Keep, UnlessRotated) | Keep | none | `sketch-exit-previous`, `sketch-exit-keep`, `sketch-exit-unless-turned` | Card labels: "Return to the view before" / "Keep" with sub-label "default" / "Unless turned" with sub-label "return if not rotated". The 30x30 panels are nested SVGs inside the figure. | + +## Marks in the sketch + +Three toggle tiles (208.8 x 140). + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| State icons | Toggle tile | `Prefs.sketch_state_icons` | `true` | none | `sketch-state-icons` | | +| Conflict colour | Toggle tile | `Prefs.sketch_conflict_colour` | `true` | none | `sketch-conflict` | | +| Hide glyphs zoomed out | Toggle tile | `Prefs.hide_constraint_glyphs_zoomed_out` | `true` | none | `sketch-hide-glyphs` | | + +## Selecting + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Click selects: Faces and edges / Whole bodies | Two picture cards (150 x 109) | `app.ui.pick_bodies` (session; in the Snapshot) | per session | none | `select-faces-edges`, `select-bodies` | Not a `Prefs` field. | +| Click, Shift Click, Ctrl / Cmd Click | A key-cap table: "Click" Select one item; "Shift Click" Add the item, or take it out again; "Ctrl / Cmd Click" Add the item, or take it out again | none (information) | n/a | none | none | The Shift and Ctrl/Cmd rows read the same on the board; the next checkbox changes the Shift row. The key caps are sample content in the sense that they describe the current behaviour, not settings. | +| Shift adds only; Ctrl / Cmd toggles | Checkbox | `Prefs.selection_shift_add_only` | `false` | none | none | | +| Prefer movable points where they overlap | Checkbox | `Prefs.prefer_free_sketch_points` | `true` | none | none | | +| Select Other reaches hidden geometry | Checkbox | `Prefs.select_other_hidden` | `true` | none | none | | +| Alt / Option also frees manipulator arrows | Checkbox | `Prefs.manipulator_free_alt` | `true` | none | none | | + +## Mismatches + +* "Hold to stop snapping" default differs between the board sample and the code (see above). +* "Project face edges into new sketches" and "Click selects" are session values, not `Prefs`. +* `Prefs.sketch_variants` and the hole preset library have no control here (not on any board). diff --git a/docs/design/preferences/pages/tools.md b/docs/design/preferences/pages/tools.md new file mode 100644 index 000000000..2dbaefd85 --- /dev/null +++ b/docs/design/preferences/pages/tools.md @@ -0,0 +1,41 @@ +# Tools + +Board: `Prefs2_Tools` (1920x1033). Heading: Work. Subtitle "How modelling tools behave." No "In +profile" tag. Sources today: Design (Hole, Extrude, Placement, Assembly Move), Navigation (Direct +interaction, tool at cursor), Graphics (axis distances in Measure). + +## Create + +Each group is a 120x64 figure at the left of its checkboxes, with a group name under it. + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Hole: Snap to centres | Checkbox | `Prefs.hole_snaps` | `false` | "The middle of a face and the centres of its round edges." | `tool-hole` | Today's label "Snap to face and edge centres". | +| Hole: Move by click or drag | Checkbox | `Prefs.hole_moves` | `false` | "Picking the face again moves the hole instead of removing it." | `tool-hole` | Today's label "Move holes by clicking or dragging". | +| Extrude: Extrude to a picked target | Checkbox | `Prefs.extrude_auto_to_object` | `false` | "A face, vertex or parallel plane switches the extent to To Object." | `tool-extrude` | | +| Extrude: Choose the operation automatically | Checkbox | `Prefs.auto_operation` | `true` | "Join, New Body or Cut, from what the material touches." | `tool-extrude` | | +| Rest, Boss, Snap Fit: Placement handles | Checkbox | `Prefs.placement_handles` | `false` | "A marker to drag the feature across the model and a ring to turn it." | `tool-placement` | | + +## Assembly Move + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Use joint motion handles for Move | Checkbox | `Prefs.assembly_move_handles` | `true` | "Off: the previous Move panel." | `assembly-move` | | +| Show moved parts' old place as a ghost | Checkbox | `Prefs.drive_joints_ghost` | `true` | none | `assembly-move` | | +| Near-axis step | Number field (64 wide, aria "Degrees") with "deg" | `Prefs.joint_rotation_coarse` (0.001 to 180) or `joint_rotation_fine`: see note | `10` (coarse) / `0.1` (fine) | "Pull outside the dashed guide for the fine step." | `assembly-move` | The board's hover says pulling outside the dashed guide uses the fine step, so the "Near-axis" field edits the step used near the axis and the "Far-axis step" the other. In `joint_handles.rs` the coarse step applies unless `d.fine` is set. Assumed mapping: Near-axis = `joint_rotation_coarse`, Far-axis = `joint_rotation_fine`; confirm with the design reviewer before building. | +| Far-axis step | Number field with "deg" | `Prefs.joint_rotation_fine` (assumed) | `0.1` | none | `assembly-move` | | + +## Measure and pointer + +Three toggle tiles (208.8 x 140). + +| Label | Control | Edits | Default | Hover | Figure | Notes | +|---|---|---|---|---|---|---| +| Axis distances in Measure | Toggle tile (the figure shows "X 46", "Y 28") | `Prefs.measure_axis_distances` | `true` | none | `measure-axis-distances` | Moves from Graphics. | +| Tool at the cursor | Toggle tile | `app.ui.tool_cursor` (session; in the Snapshot) | per session | none | `tool-cursor` | Moves from Navigation. | +| Direct interaction | Toggle tile (the figure shows "+18 mm") | `Prefs.direct_interaction` | `false` | none (today: "Work on the model directly in the viewport. Press a flat face or a profile and pull: up extrudes, down into a body cuts, and sideways movement sets the step size") | `direct-interaction` | Moves from Navigation. The board has no hover on the tile; keep the existing help text as the tooltip. | + +## Mismatches + +* The Near-axis and Far-axis mapping above is an assumption (see the row). +* The Hole, Extrude and Placement groups reuse one 120x64 figure per group, not one per checkbox. diff --git a/docs/design/preferences/tokens.md b/docs/design/preferences/tokens.md new file mode 100644 index 000000000..92a056d67 --- /dev/null +++ b/docs/design/preferences/tokens.md @@ -0,0 +1,150 @@ +# Preferences colours and theme tokens + +Every colour used on the Preferences boards, taken in light and dark pairs (the dark dialog is the +same layout as the light one, so the n-th colour of one is the n-th of the other). Token values are +from `assets/styles/ui/palettes.rs` (`Tokens::light()` and `Tokens::dark()`); field names are in +`crates/ui-egui/src/theme.rs` (`Tokens`). + +The tracker says the board colours are the existing token values. That holds for the dialog chrome +(first table). The figure palette and a few badge and accent colours have **no token**; the second +table says what to add. This step adds none: step 2 (#9874) adds the ones it paints with, with both +theme values, and notes them in its pull request. Names are proposals; take a shorter existing name +if one fits. + +## Dialog chrome and controls (exact matches) + +| Role | Light | Dark | Token | +|---|---|---|---| +| Text, labels, values | `#1B2430` | `#DEE2E8` | `form_ink` | +| Secondary text, icon strokes, section titles, (i) icon | `#4A5868` | `#B4BBC8` | `form_dim` | +| Dialog border | `#D5DBE3` | `#3F4552` | `dialog_border` | +| Rules between header, list, footer and rows | `#E6EAF0` | `#353B47` | `dialog_rule` | +| Footer fill, page-list fill | `#F4F6F9` | `#2F343E` | `dialog_footer` | +| Control borders: field, segmented, button, checkbox, card border | `#C3CBD6` | `#4A5262` | `control_border` | +| Control fill: field, dropdown, button, checkbox box, card face | `#FFFFFF` | `#1C1F26` | `control_fill` | +| Selected segment, row, page, card and tile fill | `#E8F1FA` | `#2A466E` | `selected_bg` | + +## Selection (segments, cards, tiles, chips, pages) + +The app's own selection look is the reference, not the board's accent fills: a selected item has +fill `selected_bg`, text `selected_ink` at weight 600, and (cards, tiles, chips) a border in +`form_primary` (2 px on cards and tiles, 1 px on chips). `Tokens::light()` values: `selected_bg` +#E8F1FA, `selected_ink` #1A507F, `form_primary` #236EAD; dark: #2A466E, #9CC7F5, #3A88EE. The board's +`#236EAD` / `#8CBEF5` on selected text and borders is replaced by these. + +## Needing a token, or a mix + +| Role | Light | Dark | Token | +|---|---|---|---| +| Dialog surface (97 % opaque) | `rgba(255,255,255,0.97)` | `rgba(39,43,52,0.97)` | dark: `dialog_bg` at 0.97. Light: `dialog_body` (#FFFFFF) at 0.97; `dialog_bg` is #FAFBFC, so the board uses the lighter `dialog_body` | +| Accent drawn inside figures (and the figures' accent marks only). Light is `form_primary`; dark `#8CBEF5` is lighter than dark `form_primary` (#3A88EE) | `#236EAD` | `#8CBEF5` | light `form_primary`; dark: **no token: add `pref_accent`** = light `#236EAD` / dark `#8CBEF5` (nearest: `selected_ink` #9CC7F5) | +| Ink on an accent fill (primary button "OK", checked checkbox tick) | `#FFFFFF` | `#0F1620` | light `on_accent`; dark: **no token: add `pref_on_accent`** = light `#FFFFFF` / dark `#0F1620` (dark `on_accent` is white) | +| Tint behind a figure in a card or tile and behind the theme options panel (not the segmented control, which has no well) | `#EEF1F5` | `#2F343E` | dark `dialog_footer`; light: **no token: add `pref_well`** = light `#EEF1F5` / dark `#2F343E` | +| Figure ground (the rectangle under every card figure) | `#F7F8FA` | `#1C1F26` | dark `control_fill`; light: **no token: add `figure_ground`** = light `#F7F8FA` / dark `#1C1F26` | +| Figure outlines (cube edges, geometry strokes) | `#6F7C8F` | `#A3AEC2` | **no token: add `figure_line`** = `#6F7C8F` / `#A3AEC2` | +| Figure cube, left face | `#E4E9F0` | `#515B72` | **no token: add `figure_face_left`** = `#E4E9F0` / `#515B72` | +| Figure cube, right face | `#C9D2DE` | `#394256` | **no token: add `figure_face_right`** = `#C9D2DE` / `#394256` | +| Figure cube, top face and figure paper | `#FFFFFF` | `#6B7790` | **no token: add `figure_face_top`** = `#FFFFFF` / `#6B7790` | +| Warning badge text and stroke ("Restart needed", "not on this GPU") | `#B84A00` | `#F0A27A` | **no token: add `pref_note`** = `#B84A00` / `#F0A27A` (nearest: `surface_ink` #A45000) | +| Warning badge fill | `#FBEBDD` | `#4A3326` | **no token: add `pref_note_fill`** = `#FBEBDD` / `#4A3326` | +| Success badge fill ("Connected", "Up to date", "Signed in") | `#E5F2E6` | `#1F3A31` | light `form_success_fill`; dark: **no token: add `pref_ok_fill`** dark `#1F3A31` (dark `form_success_fill` is #2C4A33) | +| Success badge text and icon | `#276B2C` | `#7FD1AE` | light `form_success`; dark: **no token**, dark `form_success` is #27584E; add `#7FD1AE` | +| Amber reference point (pivot, origin, pointer) in figures | `#8A5300` | `#E8C24A` | **no token: add `figure_reference`** = `#8A5300` / `#E8C24A` | +| Axis Z (blue) in figures | `#2F6FD0` | `#6CA8F7` | **no token: add `figure_axis_z`**; the app `axis_z` is #3C64E6 light and dark | +| Axis X (red) in figures | `#D64545` | `#F27A7A` | **no token: add `figure_axis_x`**; app `axis_x` is #DC3C3C / #C82828 | +| Axis Y (green) in figures | `#2E9E5B` | `#62D48E` | **no token: add `figure_axis_y`**; app `axis_y` is #3CAA3C / #78D250 | + +## Board backdrop (not part of the dialog) + +The canvas behind each dialog: `#F7F8FA` / `#2E3440` fill (dark = `viewport_top`), with a 24 px grid +in `#E3E7ED` / `#3A414D` (dark = `grid` #3B414C), and a shadow `rgba(20,30,45,0.10)` light / +`rgba(0,0,0,0.30)` dark on the dialog (`Tokens::shell_shadow` derives the app's own). Not built in +the app. + +## Theme thumbnails and Gruvbox / imported samples + +The theme thumbnails (`theme-*.svg`) paint each theme's own palette, so they use literal colours by +design and are never themed by the dialog's theme: Light (`#F4F6F9` ground, `#FFFFFF` bars, +`#236EAD` accent), Dark (`#2A2F3A`, `#323845`, `#8CBEF5`, bars `#6C7689`), Gruvbox (`#282828`, +`#3C3836`, `#EBDBB2`, `#83A598`), and the imported sample (`#2B2F52`, `#3B4170`, `#B6A6FF`, +`#9CA3DE`). In the app, paint a theme card from the theme's own `Tokens` (built-ins and imported +files are available from `theme_files`), not from literals. + +## Colour vision samples + +`colour-vision-*.svg` use the colour-blind-safe set the app already applies per mode (Okabe-Ito +values): `#E69F00` (orange), `#56B4E9` (sky), `#0072B2` (blue), `#D55E00` (vermilion), `#CC79A7` +(purple) and `#A1342C` / `#FF9C98` for failed. Map them to the sketch and analysis tokens in +`Tokens` (`sketch_fixed`, `sketch_projected`, `axis_x`..`axis_z`, `bend_up`, `bend_down`, +`sketch_conflict`) so that each colour vision mode changes them. The board draws them with literals +for the Off mode. + +## Remaining pairs + +All other colours in the boards, with the nearest tokens. Light and dark are listed in the board's +own pairing. + +| Light | Dark | Uses | Nearest tokens (light / dark) | +|---|---|---|---| +| `#F7F8FA` | `#2E3440` | 13 boards | `file_background` (#F7F9FB), `toolbar` (#F6F7F9) / `viewport_bottom`, `viewport_top` | +| `#E3E7ED` | `#3A414D` | 13 boards | `file_border` (#E0E5EC), `dialog_rule` (#E6EAF0) / `grid` (#3B414C), `nav_hover` (#3A4150) | +| `#FFFFFF` | `#2F343E` | 3 boards | `control_fill`, `dialog_body` / `dialog_footer`, `nav_field` | +| `#FFFFFF` | `#FFFFFF` | 2 boards | `control_fill`, `dialog_body` / `file_image_tint`, `file_rail_ink` | +| `#1B2430` | `#1B2430` | 1 board | `form_ink`, `nav_tip` / `nav_tip_ink`, `file_background` (#1F232B) | +| `#236EAD` | `#236EAD` | 1 board | `file_rail`, `form_primary` / `sheet_fill` (#2A7FA8), `chip` (#3B65A8) | +| `#C3CBD6` | `#C3CBD6` | 1 board | `control_border`, `grid` (#C4CAD4) / `hover_edge_halo` (#CBCBCB), `icon` (#D0D6E2) | +| `#FFFFFF` | `#DEE2E8` | 1 board | `control_fill`, `dialog_body` / `dialog_label`, `form_ink` | +| `#FFFFFF` | `#272B34` | 1 board | `control_fill`, `dialog_body` / `dialog_bg`, `dialog_body` | +| `#FFFFFF` | `#1B2430` | 1 board | `control_fill`, `dialog_body` / `nav_tip_ink`, `file_background` (#1F232B) | +| `#F4F6F9` | `#F4F6F9` | 1 board | `dialog_footer`, `toolbar` (#F6F7F9) / `nav_tip` (#EEF1F5), `cube_face` (#ECEFF4) | +| `#EEF1F5` | `#EEF1F5` | 1 board | `nav_viewport`, `cube_face` (#ECEFF4) / `nav_tip`, `cube_face` (#ECEFF4) | +| `#EEF1F5` | `#3A4150` | 1 board | `nav_viewport`, `cube_face` (#ECEFF4) / `nav_hover`, `grid` (#3B414C) | +| `#276B2C` | `#8FDB9A` | 1 board | `form_success`, `bend_up` (#1E8C32) / `timeline_marker` (#AAB2C0), `body` (#989CA2) | +| `#D9DFE7` | `#D9DFE7` | 1 board | `nav_press` (#DCE2EA), `dialog_border` (#D5DBE3) / `dialog_label` (#DEE2E8), `form_ink` (#DEE2E8) | +| `#9AA7B6` | `#9AA7B6` | 1 board | `grid_major` (#AAB2BE), `nav_dim` (#8895A7) / `text_dim` (#949BA8), `timeline_marker` (#AAB2C0) | +| `#7B8798` | `#7B8798` | 1 board | `app_bar_separator` (#8891A0), `nav_dim` (#8895A7) / `nav_dim` (#7C879A), `app_bar_separator` (#8891A0) | +| `#A8B3C1` | `#A8B3C1` | 1 board | `grid_major` (#AAB2BE), `body` (#B0BAC6) / `timeline_marker` (#AAB2C0), `file_dim` (#B4BBC8) | +| `#C9D1DB` | `#C9D1DB` | 1 board | `viewport_bottom` (#CBD2DD), `border` (#D0D4DC) / `icon` (#D0D6E2), `origin_point` (#D6D7DA) | +| `#3A4150` | `#3A4150` | 1 board | `dialog_label` (#3A4656), `file_dim` (#3A4656) / `nav_hover`, `grid` (#3B414C) | +| `#252A34` | `#252A34` | 1 board | `cube_text` (#262A32), `text` (#262A32) / `nav_viewport` (#262B35), `cube_text` (#262A32) | +| `#2A2F3A` | `#2A2F3A` | 1 board | `body_edge` (#282C34), `cube_text` (#262A32) / `glyph_bg` (#2C323C), `nav_viewport` (#262B35) | +| `#323845` | `#323845` | 1 board | `app_bar_tab_active` (#353B47), `app_bar` (#343840) / `timeline_item` (#343A46), `app_bar_tab_active` (#353B47) | +| `#6C7689` | `#6C7689` | 1 board | `text_dim` (#6E7480), `cube_border` (#555E6E) / `nav_dim` (#7C879A), `form_accent` (#7B63A6) | +| `#8CBEF5` | `#8CBEF5` | 1 board | `sel_edge_rim` (#7FBFFF), `agent_busy` (#6CB4F0) / `sel_edge_rim` (#7FBFFF), `file_primary_ink` (#9CC7F5) | +| `#99A5BA` | `#99A5BA` | 1 board | `grid_major` (#AAB2BE), `nav_dim` (#8895A7) / `text_dim` (#949BA8), `timeline_marker` (#AAB2C0) | +| `#7E8AA0` | `#7E8AA0` | 1 board | `app_bar_separator` (#8891A0), `nav_dim` (#8895A7) / `nav_dim` (#7C879A), `app_bar_separator` (#8891A0) | +| `#566176` | `#566176` | 1 board | `cube_border` (#555E6E), `form_dim` (#4A5868) / `cube_border` (#555E6E), `control_border` (#4A5262) | +| `#3F485A` | `#3F485A` | 1 board | `dialog_label` (#3A4656), `file_dim` (#3A4656) / `border` (#3F4552), `dialog_border` (#3F4552) | +| `#454D5E` | `#454D5E` | 1 board | `icon` (#464E5C), `timeline_marker` (#464C58) / `nav_press` (#464E60), `grid_major` (#494F5A) | +| `#32302F` | `#32302F` | 1 board | `body_edge` (#282C34), `cube_text` (#262A32) / `dialog_bg` (#272B34), `dialog_body` (#272B34) | +| `#1D2021` | `#1D2021` | 1 board | `form_ink` (#1B2430), `nav_tip` (#1B2430) / `app_bar` (#1C1F26), `control_fill` (#1C1F26) | +| `#282828` | `#282828` | 1 board | `cube_text` (#262A32), `text` (#262A32) / `timeline` (#21252D), `cube_text` (#262A32) | +| `#3C3836` | `#3C3836` | 1 board | `app_bar` (#343840), `app_bar_tab_active` (#353B47) / `dialog_footer` (#2F343E), `nav_field` (#2F343E) | +| `#7C6F64` | `#7C6F64` | 1 board | `text_dim` (#6E7480), `cube_border` (#555E6E) / `cube_border` (#555E6E), `control_border` (#4A5262) | +| `#83A598` | `#83A598` | 1 board | `app_bar_separator` (#8891A0), `nav_dim` (#8895A7) / `app_bar_separator` (#8891A0), `body` (#989CA2) | +| `#EBDBB2` | `#EBDBB2` | 1 board | `file_recovery_well` (#F7E2B8), `file_recovery_border` (#F0D29A) / `timeline_item_error` (#E8C4AA), `hover_edge_halo` (#CBCBCB) | +| `#D5C4A1` | `#D5C4A1` | 1 board | `file_recovery_border` (#F0D29A), `hover_edge_halo` (#CBCBCB) / `timeline_item_error` (#E8C4AA), `file_recovery_ink` (#F5CC89) | +| `#A89984` | `#A89984` | 1 board | `app_bar_separator` (#8891A0), `nav_dim` (#8895A7) / `body` (#989CA2), `glyph_edge` (#C88278) | +| `#504945` | `#504945` | 1 board | `timeline_marker` (#464C58), `icon` (#464E5C) / `border` (#3F4552), `dialog_border` (#3F4552) | +| `#6A5AC8` | `#6A5AC8` | 1 board | `form_accent` (#7349CD), `form_fill` (#7349CD) / `form_fill` (#8A6FCC), `form_accent` (#7B63A6) | +| `#2E5A9E` | `#2E5A9E` | 1 board | `sel_profile` (#1A54A7), `file_rail` (#236EAD) / `file_rail_hover` (#2E6395), `chip` (#3B65A8) | +| `#2B2F52` | `#2B2F52` | 1 board | `app_bar_tab_active` (#353B47), `app_bar` (#343840) / `form_soft` (#372F4F), `timeline_item` (#343A46) | +| `#3B4170` | `#3B4170` | 1 board | `icon` (#464E5C), `dialog_label` (#3A4656) / `accent_soft` (#2A466E), `selected_bg` (#2A466E) | +| `#9CA3DE` | `#9CA3DE` | 1 board | `grid_major` (#AAB2BE), `body` (#B0BAC6) / `form_tab_ink` (#B39BEE), `timeline_marker` (#AAB2C0) | +| `#B6A6FF` | `#B6A6FF` | 1 board | `cube_hover` (#BEDCFC), `control_border` (#C3CBD6) / `form_tab_ink` (#B39BEE), `file_primary_ink` (#9CC7F5) | +| `#E7E1FF` | `#E7E1FF` | 1 board | `form_soft` (#EEE8FA), `hover` (#E2EAF6) / `app_bar_text` (#E6EAF2), `cube_face` (#ECEFF4) | +| `#9C8FE8` | `#9C8FE8` | 1 board | `preview_add` (#70A0E2), `body_selected` (#6EAAEB) / `form_tab_ink` (#B39BEE), `form_fill` (#8A6FCC) | +| `#6E8FE0` | `#6E8FE0` | 1 board | `preview_add` (#70A0E2), `body_selected` (#6EAAEB) / `preview_add` (#70A0E2), `body_selected` (#6EAAEB) | +| `#6E76B8` | `#6E76B8` | 1 board | `sel_face` (#4C7FCB), `sel_vertex` (#466EAA) / `form_accent` (#7B63A6), `form_fill` (#8A6FCC) | +| `#8A94A3` | `#8A94A3` | 1 board | `nav_dim` (#8895A7), `app_bar_separator` (#8891A0) / `app_bar_separator` (#8891A0), `text_dim` (#949BA8) | +| `#7C8899` | `#5A6475` | 1 board | `app_bar_separator` (#8891A0), `nav_dim` (#8895A7) / `cube_border` (#555E6E), `control_border` (#4A5262) | +| `#E69F00` | `#E69F00` | 1 board | `joint_manipulator` (#EB9D00), `mesh_fill` (#E0B200) / `joint_manipulator` (#EB9D00), `mesh_fill` (#C6A800) | +| `#E69F00` | `#F0C060` | 1 board | `joint_manipulator` (#EB9D00), `mesh_fill` (#E0B200) / `preview_new` (#F0E169), `warning` (#ECAA46) | +| `#D55E00` | `#F0A27A` | 1 board | `bend_down` (#C85A14), `surface_accent` (#A45000) / `file_recovery_ink` (#F5CC89), `glyph_edge` (#C88278) | +| `#0072B2` | `#56B4E9` | 1 board | `file_rail` (#236EAD), `form_primary` (#236EAD) / `sheet_ink` (#4FB3D9), `body_selected` (#6EAAEB) | +| `#56B4E9` | `#8CBEF5` | 1 board | `agent_busy` (#6CB4F0), `body_selected` (#6EAAEB) / `sel_edge_rim` (#7FBFFF), `file_primary_ink` (#9CC7F5) | +| `#56B4E9` | `#56B4E9` | 1 board | `agent_busy` (#6CB4F0), `body_selected` (#6EAAEB) / `sheet_ink` (#4FB3D9), `body_selected` (#6EAAEB) | +| `#CC79A7` | `#CC79A7` | 1 board | `glyph_edge` (#BE6E64), `grid_major` (#AAB2BE) / `render_accent` (#E074AE), `render_ink` (#E074AE) | +| `#A1342C` | `#FF9C98` | 1 board | `form_error`, `surface_accent` (#A45000) / `agent_busy` (#E896BE), `timeline_item_error` (#E8C4AA) | +| `#2F7D5B` | `#7FD1AE` | 1 board | `box_crossing` (#28A050), `bend_up` (#1E8C32) / `timeline_marker` (#AAB2C0), `text_dim` (#949BA8) | +| `#C98A00` | `#E8C24A` | 1 board | `warning` (#DE961E), `joint_manipulator` (#EB9D00) / `warning` (#ECAA46), `mesh_ink` (#D4B726) | From 2014e60ae6934e9bc36399007c146c3f708be8a4 Mon Sep 17 00:00:00 2001 From: N3MI-DG <129717180+N3MI-DG@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:02:32 +0000 Subject: [PATCH 03/55] Sketch Offset: an Instances count stacks offsets one behind another (#9827) (#9828) * claim: #9827 * Sketch Offset: an Instances count stacks offsets one behind another (#9827) Offset made one offset at a time, so a set of evenly spaced outlines meant running it again on the curves it had just made, once per ring: a separate undo step and a separate driving dimension each time. `sketch.offset` now takes `instances`, a whole number or a unitless expression from 1 to 100 (1, today's behaviour, by default). The per-group work the command did inline becomes `offset_rung`, and `offset_ladder` runs it once per instance, each rung offsetting the one before it the same distance again, so instance n stands n distances from the curves picked. Every rung of a side is driven by that side's own dimension, so editing it moves the whole set and keeps the spacing even, and each side of a Two Sides or Symmetric offset grows its own ladder. A rung the shape has no room for refuses the whole command and names which instance it was. A later rung reads its side from the geometry, through the rung's own normal-distance annotation, rather than from the distance's sign: an output's stored ends need not run the way the chain through them is walked, and a reversed walk reads the same sign as the other side. A circle is the exception and keeps the sign, because it offsets concentrically with no chain to walk, and a step past a ring smaller than the distance lands beyond the centre, where the circle's "outside the current radius" side test reads as the outward side: an inward ladder turned round and grew again (1, 4, 1, 4 mm) instead of running out of room. Co-Authored-By: Claude Opus 5 * Sketch Offset: the Instances row in the offset window (#9827) The offset window gets an Instances row under Distance: a whole number with step arrows, 1 by default, so the count can be walked up a ring at a time and the preview follows each step. The count is not kept in the design, as Mirror's and Scale's values are not, so the window sends the number it evaluates to rather than the text. Co-Authored-By: Claude Opus 5 * UI kit: a count's step arrows are not text (#9827) The arrows stand inside the editor, which asks for the text cursor across its whole rect, so hovering one showed an I-beam and the arrows read as part of the number. They take the ordinary cursor back after it, and the pointer is read from the arrow's rect rather than from the hover the editor underneath competes for, which keeps the hover highlight in step with it. The pattern Quantity rows share this field and had the same thing. Co-Authored-By: Claude Opus 5 * Sketch Offset: Instances label in the complete catalogs and the other shipped languages Co-Authored-By: Claude Opus 5.5 * Sketch Offset Instances: translations for the complete catalogs Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5 Co-authored-by: bherbruck --- .../pending/sketch-offset-instances.json | 71 +++++++ .../pending/sketch-offset-instances.md | 2 + crates/engine/src/cmd/sketch_modify.rs | 200 ++++++++++++++---- crates/engine/src/cmd/sketch_modify_tests.rs | 137 ++++++++++++ crates/ui-egui/src/dialogs_sketch_tests.rs | 2 +- crates/ui-egui/src/sketch_modify_ui.rs | 32 ++- crates/ui-egui/src/ui_kit/fields.rs | 9 +- crates/ui-egui/src/ui_kit/fields_tests.rs | 33 +++ 8 files changed, 434 insertions(+), 52 deletions(-) create mode 100644 assets/locales/pending/sketch-offset-instances.json create mode 100644 attribution/pending/sketch-offset-instances.md diff --git a/assets/locales/pending/sketch-offset-instances.json b/assets/locales/pending/sketch-offset-instances.json new file mode 100644 index 000000000..717b57add --- /dev/null +++ b/assets/locales/pending/sketch-offset-instances.json @@ -0,0 +1,71 @@ +{ + "en": { + "ui.instances": "Instances" + }, + "ar": { + "ui.instances": "النسخ" + }, + "bs": { + "ui.instances": "Instance" + }, + "cs": { + "ui.instances": "Instance" + }, + "da": { + "ui.instances": "Forekomster" + }, + "de": { + "ui.instances": "Instanzen" + }, + "en-GB": { + "ui.instances": "Instances" + }, + "es": { + "ui.instances": "Instancias" + }, + "fi": { + "ui.instances": "Esiintymät" + }, + "fr": { + "ui.instances": "Instances" + }, + "he": { + "ui.instances": "מופעים" + }, + "hr": { + "ui.instances": "Instance" + }, + "it": { + "ui.instances": "Istanze" + }, + "ja": { + "ui.instances": "インスタンス" + }, + "ko": { + "ui.instances": "인스턴스" + }, + "nl": { + "ui.instances": "Instanties" + }, + "pl": { + "ui.instances": "Wystąpienia" + }, + "pt-BR": { + "ui.instances": "Instâncias" + }, + "sr": { + "ui.instances": "Инстанце" + }, + "uk": { + "ui.instances": "Екземпляри" + }, + "vi": { + "ui.instances": "Số bản" + }, + "zh": { + "ui.instances": "实例数" + }, + "zh-TW": { + "ui.instances": "實例數" + } +} diff --git a/attribution/pending/sketch-offset-instances.md b/attribution/pending/sketch-offset-instances.md new file mode 100644 index 000000000..4e1b0ab7e --- /dev/null +++ b/attribution/pending/sketch-offset-instances.md @@ -0,0 +1,2 @@ +| File | Author | Source | Licence | +| `assets/locales/pending/sketch-offset-instances.json` | SolidCraft contributors | Original offset instance-count label and translations | MIT OR Apache-2.0 | diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs index 970472329..c6109d9db 100644 --- a/crates/engine/src/cmd/sketch_modify.rs +++ b/crates/engine/src/cmd/sketch_modify.rs @@ -48,7 +48,8 @@ pub static COMMANDS: &[CommandSpec] = &[ .params(concat!( "curves: [ids], distance: number in mm or length expression (creates an editable dimension; positive = left of the chain, or toward `side`), side?: [x,y], chain?: bool (default true: the connected chain, including ends that only coincide). A corner is trimmed back to the crossing when the offset runs past it, and extended until the offset curves intersect when the corner falls short; ", "direction?: one_side|symmetric (default one_side) or symmetric?: bool (the same distance each way; no `side`, whose job it takes over), ", - "distance2?: positive length expression (Two Sides: an independent distance the other way, as for `solid.extrude`). Each side is its own offset association, listed in `sides`; flip?: bool reverses the primary side; `param`/`param2` name the driving dimensions", + "distance2?: positive length expression (Two Sides: an independent distance the other way, as for `solid.extrude`). Each side is its own offset association, listed in `sides`; flip?: bool reverses the primary side; `param`/`param2` name the driving dimensions; ", + "instances?: whole number or unitless expression, 1…100 (default 1): each instance after the first offsets the instance before it by the same distance again, so instance n stands n distances from the curves picked. Every instance of a side is driven by that side's own dimension, and each entry of `sides` names its `instance`; an instance the shape cannot take refuses the whole command", created_doc!() )), CommandSpec::new("sketch.offset.break", "Break Offset Association", break_offset).icon("sketch_break") @@ -112,6 +113,10 @@ pub static COMMANDS: &[CommandSpec] = &[ const TOL: f64 = 1e-7; const MAX_COPIES: usize = 500; +/// The most offsets `sketch.offset` stacks one behind the other in a single run. Each instance +/// is its own association, so this stays below the sketch's own caps on analytic offset groups +/// and free-form associations (both 128). +const MAX_INSTANCES: usize = 100; fn curve_arg(sk: &Sketch, p: &Value, cmd: &str) -> Result { let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a curve id"))?; @@ -2386,6 +2391,24 @@ fn offset_length(s: &Session, p: &Value, key: &str, positive: bool) -> Result<(f Ok((value, expression)) } +/// `instances`: how many offsets stand one behind the other, each at the same distance from the +/// one before it. A number or a unitless expression; one (the offset by itself) by default. +fn offset_instances(s: &Session, p: &Value, cmd: &str) -> Result { + let message = format!("`instances` must be a whole number from 1 to {MAX_INSTANCES}, or an expression for one"); + let count = match p.get("instances") { + None | Some(Value::Null) => return Ok(1), + Some(Value::Number(_)) => num(p, "instances").ok_or_else(|| bad(cmd, message.clone()))?, + Some(_) => { + let expression = expr(p, "instances").ok_or_else(|| bad(cmd, message.clone()))?.into_string(); + s.doc.eval(&expression, solidcraft_doc::expr::Kind::Unitless).map_err(|error| bad(cmd, format!("`instances`: {error}")))? + } + }; + if !count.is_finite() || count.fract() != 0.0 || !(1.0..=MAX_INSTANCES as f64).contains(&count) { + return Err(bad(cmd, message)); + } + Ok(count as usize) +} + #[derive(Clone, Copy)] struct OffsetOptions { side: Option, @@ -2520,6 +2543,125 @@ fn offset_group(sk: &mut Sketch, ids: &[String], eligible: &std::collections::Ha Ok(sides) } +/// One rung of an offset ladder: the offsets of `ids`, with the infinite flag carried over from +/// infinite sources (#1359) and a driving dimension on each side that is linked to its source. +/// `names` is the parameter each side is driven by, in side order, falling back to the first for +/// a side the rung before it had none for. The sources the rung consumed come back with it. +fn offset_rung( + sk: &mut Sketch, + cmd: &str, + ids: &[String], + eligible: &std::collections::HashSet, + options: OffsetOptions, + names: &[String], +) -> Result<(Vec, Vec)> { + let mut group = offset_group(sk, ids, eligible, options)?; + let output = group.first().and_then(|side| side.curves.first()).ok_or_else(|| bad(cmd, "offset produced no curves"))?; + let sources = sk + .offsets + .iter() + .find(|o| o.owns_output(output)) + .map(|o| o.sources.iter().map(|(id, _)| id.clone()).collect::>()) + .or_else(|| sk.freeform_offsets.iter().find(|o| o.output == *output).map(|o| vec![o.source.clone()])) + .or_else(|| group.iter().find_map(|side| side.unlinked_sources.clone())) + .ok_or_else(|| bad(cmd, "offset association is missing"))?; + // An offset of infinite lines is infinite lines too (#1359). + let infinite = sources.iter().all(|id| sk.curve_index(id).and_then(|c| sk.curves.get(c)).is_some_and(|c| c.infinite)); + if infinite { + for id in group.iter().flat_map(|side| side.curves.iter()) { + if let Some(cu) = sk.curve_index(id).and_then(|c| sk.curves.get_mut(c)) + && matches!(cu.kind, CurveKind::Line { .. }) + { + cu.infinite = true; + cu.construction = true; + } + } + } + for (index, side) in group.iter_mut().enumerate() { + // A trimmed offset is not linked to its source: it has no distance to drive. + if side.unlinked_sources.is_some() { + continue; + } + let name = names.get(index).or_else(|| names.first()).ok_or_else(|| bad(cmd, "offset has no driving dimension"))?; + let output = side.curves.first().ok_or_else(|| bad(cmd, "offset produced no curves"))?; + side.constraints.push(sk.add_constraint( + ConstraintKind::OffsetDistance { output: output.clone(), value: side.distance.abs(), reverse: side.distance < 0.0 }, + Some(name.clone()), + )?); + side.param = Some(name.clone()); + } + Ok((group, sources)) +} + +/// Where the next instance of an offset belongs: one more step the way the rung already went. +/// The rung's own normal-distance annotation knows that, since its ends are the middle of its +/// first source curve and the point one signed distance away on the rung itself; the same step +/// again lands one distance past the rung. The side is taken from the geometry this way rather +/// than from the sign again, because an output's stored ends need not run the way the chain +/// through them is walked, and a reversed walk reads the same sign as the other side. A trimmed +/// offset has no annotation and is ordinary geometry: `None` leaves the sign to speak for it. +fn offset_beyond(sk: &Sketch, rung: &[String]) -> Option { + // A circle offsets concentrically: there is no chain to walk and so no walk direction to + // mistake, and its own side is read as "outside the current radius". A step past a ring + // smaller than the distance lands beyond the centre, which reads as outside and would turn + // an inward ladder round into a growing one instead of letting it run out of room. Its + // signed distance already says which way, so leave the side to it. + let index = sk.curve_index(rung.first()?)?; + if matches!(sk.curves.get(index)?.kind, CurveKind::Circle { .. }) { + return None; + } + let (from, to) = sk.offset_dimension_points(rung.first()?)?; + (from.dist(to) > TOL).then(|| to + (to - from)) +} + +/// What one side of a rung leaves for the next: the curves to offset again, its own signed +/// distance, and the dimension its whole ladder is driven by. +fn offset_leaves(side: &Side, fallback: &str) -> (Vec, f64, String) { + (side.curves.clone(), side.distance, side.param.clone().unwrap_or_else(|| fallback.to_string())) +} + +/// Every offset of one connected source group: the first rung at the distances asked for, then +/// one more rung per extra instance, each offsetting the rung before it the same way and the +/// same distance again, so instance n stands n distances from the curves picked. Each side comes +/// back paired with the instance it belongs to, and the first rung's sources come with them, so +/// the caller can take those out of the selection it is still working through. +fn offset_ladder( + sk: &mut Sketch, + cmd: &str, + ids: &[String], + eligible: &std::collections::HashSet, + options: OffsetOptions, + instances: usize, + names: &[String], +) -> Result<(Vec<(usize, Side)>, Vec)> { + let primary = names.first().cloned().ok_or_else(|| bad(cmd, "offset has no driving dimension"))?; + let (first, sources) = offset_rung(sk, cmd, ids, eligible, options, names)?; + let mut rung: Vec<(Vec, f64, String)> = first.iter().map(|side| offset_leaves(side, &primary)).collect(); + let mut sides: Vec<(usize, Side)> = first.into_iter().map(|side| (1, side)).collect(); + for instance in 2..=instances { + let mut next = Vec::new(); + for (curves, distance, name) in &rung { + // One side at a time from here: the side this rung follows is the whole of its + // direction, so `side`, `symmetric` and `distance2` had their say in the first rung. + let beyond = offset_beyond(sk, curves); + let step = OffsetOptions { side: beyond, chain: false, distance: *distance, symmetric: false, distance2: None }; + // Which instance ran out of room is the whole of the answer, so the refusal names it + // in front of the reason, rather than wrapping one "invalid parameters" in another. + let (made, _) = offset_rung(sk, cmd, curves, eligible, step, std::slice::from_ref(name)).map_err(|error| { + let reason = match &error { + crate::EngineError::BadParams { msg, .. } => msg.clone(), + other => other.to_string(), + }; + bad(cmd, format!("instance {instance} of {instances}: {reason}")) + })?; + next.extend(made.iter().map(|side| offset_leaves(side, name))); + sides.extend(made.into_iter().map(|side| (instance, side))); + } + rung = next; + } + Ok((sides, sources)) +} + fn offset(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.offset"; let ids = string_list(cmd, p, "curves")?; @@ -2550,6 +2692,7 @@ fn offset(s: &mut Session, p: &Value) -> Result { if symmetric && side.is_some() { return Err(bad(cmd, "`symmetric` offsets both sides, so `side` has no side left to pick: drop one of them")); } + let instances = offset_instances(s, p, cmd)?; let ((sides, param, param2), info) = edit(s, p, cmd, true, |sk, doc| { sk.refresh_offsets()?; let rep = solve_current(sk, doc)?; @@ -2564,41 +2707,8 @@ fn offset(s: &mut Session, p: &Value) -> Result { let mut pending = ids.clone(); let mut sides = Vec::new(); while !pending.is_empty() { - let mut group = offset_group(sk, &pending, &eligible, OffsetOptions { side, chain: use_chain, distance: d0, symmetric, distance2 })?; - let output = group.first().and_then(|side| side.curves.first()).ok_or_else(|| bad(cmd, "offset produced no curves"))?; - let sources = sk - .offsets - .iter() - .find(|o| o.owns_output(output)) - .map(|o| o.sources.iter().map(|(id, _)| id.clone()).collect::>()) - .or_else(|| sk.freeform_offsets.iter().find(|o| o.output == *output).map(|o| vec![o.source.clone()])) - .or_else(|| group.iter().find_map(|side| side.unlinked_sources.clone())) - .ok_or_else(|| bad(cmd, "offset association is missing"))?; - // An offset of infinite lines is infinite lines too (#1359). - let infinite = sources.iter().all(|id| sk.curve_index(id).and_then(|c| sk.curves.get(c)).is_some_and(|c| c.infinite)); - if infinite { - for id in group.iter().flat_map(|side| side.curves.iter()) { - if let Some(cu) = sk.curve_index(id).and_then(|c| sk.curves.get_mut(c)) - && matches!(cu.kind, CurveKind::Line { .. }) - { - cu.infinite = true; - cu.construction = true; - } - } - } - for (index, side) in group.iter_mut().enumerate() { - // A trimmed offset is not linked to its source: it has no distance to drive. - if side.unlinked_sources.is_some() { - continue; - } - let name = if index == 1 { param2.as_ref().unwrap_or(¶m) } else { ¶m }; - let output = side.curves.first().ok_or_else(|| bad(cmd, "offset produced no curves"))?; - side.constraints.push(sk.add_constraint( - ConstraintKind::OffsetDistance { output: output.clone(), value: side.distance.abs(), reverse: side.distance < 0.0 }, - Some(name.clone()), - )?); - side.param = Some(name.clone()); - } + let options = OffsetOptions { side, chain: use_chain, distance: d0, symmetric, distance2 }; + let (group, sources) = offset_ladder(sk, cmd, &pending, &eligible, options, instances, &made)?; let before = pending.len(); pending.retain(|id| !sources.contains(id)); if pending.len() == before { @@ -2607,31 +2717,31 @@ fn offset(s: &mut Session, p: &Value) -> Result { sides.extend(group); } // Parameters made for distances that only trimmed (unlinked) offsets used drive nothing. - let used = |name: &String| sides.iter().any(|side: &Side| side.param.as_ref() == Some(name)); + let used = |name: &String| sides.iter().any(|(_, side): &(usize, Side)| side.param.as_ref() == Some(name)); let param = used(¶m).then_some(param); let param2 = param2.filter(|name| used(name)); doc.params.retain(|p| !made.contains(&p.name) || param.as_ref() == Some(&p.name) || param2.as_ref() == Some(&p.name)); Ok((sides, param, param2)) })?; - let curves: Vec<&String> = sides.iter().flat_map(|side| side.curves.iter()).collect(); - let constraints: Vec<&String> = sides.iter().flat_map(|side| side.constraints.iter()).collect(); + let curves: Vec<&String> = sides.iter().flat_map(|(_, side)| side.curves.iter()).collect(); + let constraints: Vec<&String> = sides.iter().flat_map(|(_, side)| side.constraints.iter()).collect(); let each: Vec = sides .iter() - .map(|side| { - let mut entry = json!({"distance": side.distance, "curves": side.curves, "param": side.param}); + .map(|(instance, side)| { + let mut entry = json!({"distance": side.distance, "curves": side.curves, "param": side.param, "instance": instance}); if let Some(association) = &side.association { entry["association"] = json!(association); } entry }) .collect(); - let mut response = json!({"curves":curves,"constraints":constraints,"sketch":info,"sides":each,"param":param}); + let mut response = json!({"curves":curves,"constraints":constraints,"sketch":info,"sides":each,"param":param,"instances":instances}); if let Some(param2) = param2 { response["param2"] = json!(param2); } - // One side keeps the single `association` it always returned. Two sides have one each, in - // `sides`, so there is no single association left to name. - if let [only] = sides.as_slice() + // One side keeps the single `association` it always returned. Two sides, or an instance + // behind another, have one each in `sides`, so there is no single association left to name. + if let [(_, only)] = sides.as_slice() && let Some(association) = &only.association { response["association"] = json!(association); diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 32f30349e..7d5b1b8da 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -2418,6 +2418,143 @@ fn offset_two_sides_of_one_curve_follows_the_sign_of_the_distance() { assert!(close(one.1.x - one.0.x, 40.0) && close(two.1.x - two.0.x, 40.0), "{one:?} {two:?}"); } +/// Each instance of an outward offset of a 40 by 30 rectangle, as a box one more step out. +fn offset_rings(sk: &solidcraft_sketch::Sketch, o: &Value, out: &[f64]) { + for (index, out) in out.iter().copied().enumerate() { + let curves = side_curves(o, index); + assert_eq!(curves.len(), 4, "{o}"); + assert!(box_is(sk, &curves, [-out, -out], [40.0 + out, 30.0 + out]), "instance {}: {:?}", index + 1, bounds(sk, &curves)); + } +} + +#[test] +fn offset_instances_stack_one_behind_another_at_the_same_distance() { + let mut s = new_sketch(); + let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let l = ids(&r["curves"]); + // Three instances outward by 5 from a 40 by 30 rectangle: rings 5, 10 and 15 out, each the + // offset of the one before it. + let o = run(&mut s, "sketch.offset", json!({"curves": [l[0]], "distance": 5, "side": [20, -10], "instances": 3})); + assert_eq!(o["instances"], 3, "{o}"); + let sides = o["sides"].as_array().unwrap().clone(); + assert_eq!(sides.len(), 3, "{o}"); + assert_eq!(sides.iter().map(|side| side["instance"].as_u64()).collect::>(), vec![Some(1), Some(2), Some(3)], "{o}"); + assert_eq!(ids(&o["curves"]).len(), 12, "{o}"); + offset_rings(&sketch(&s), &o, &[5.0, 10.0, 15.0]); + // One dimension drives the whole ladder, so every ring moves together when it changes. + let param = o["param"].as_str().unwrap().to_string(); + assert!(sides.iter().all(|side| side["param"].as_str() == Some(param.as_str())), "{o}"); + assert_eq!(sketch(&s).constraints.iter().filter(|c| matches!(c.kind, ConstraintKind::OffsetDistance { .. })).count(), 3); + run(&mut s, "parameters.change", json!({"name": param, "expression": "8 mm"})); + offset_rings(&sketch(&s), &o, &[8.0, 16.0, 24.0]); +} + +#[test] +fn offset_instances_go_the_way_the_first_one_went() { + let mut s = new_sketch(); + let r = run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let l = ids(&r["curves"]); + // Inward by 5: rings at (5,5)-(35,25) and (10,10)-(30,20). A later instance reads its side + // from the ring it follows, so it never doubles back over the one before it. + let o = run(&mut s, "sketch.offset", json!({"curves": [l[0]], "distance": 5, "side": [20, 15], "instances": 2})); + let sk = sketch(&s); + assert!(box_is(&sk, &side_curves(&o, 0), [5.0, 5.0], [35.0, 25.0]), "{:?}", bounds(&sk, &side_curves(&o, 0))); + assert!(box_is(&sk, &side_curves(&o, 1), [10.0, 10.0], [30.0, 20.0]), "{:?}", bounds(&sk, &side_curves(&o, 1))); +} + +#[test] +fn offset_instances_stop_where_the_shape_runs_out() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let before = s.doc.to_json(); + // Inward by 5 twice reaches a 20 by 10 ring; a third would have no height left, so the + // whole command is refused and names the instance that could not be made. + let error = s.execute("sketch.offset", &json!({"curves": ["l1"], "distance": 5, "side": [20, 15], "instances": 3})).unwrap_err().to_string(); + assert!(error.contains("instance 3 of 3"), "{error}"); + assert_eq!(s.doc.to_json(), before, "a refused instance leaves the design alone"); + // Two of them still work on the same shape. + let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 5, "side": [20, 15], "instances": 2})); + assert_eq!(o["sides"].as_array().map(Vec::len), Some(2), "{o}"); +} + +#[test] +fn offset_instances_count_must_be_a_whole_number_within_the_cap() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + for count in [json!(0), json!(-1), json!(1.5), json!(101), json!("two"), json!(true)] { + let params = json!({"curves": ["l1"], "distance": 1, "side": [20, -10], "instances": count.clone()}); + assert!(s.execute("sketch.offset", ¶ms).is_err(), "instances {count} must be refused"); + } + // No count, and a count of one, are the offset by itself. + for count in [json!(null), json!(1), json!("1")] { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 1, "side": [20, -10], "instances": count})); + assert_eq!(o["instances"], 1, "{o}"); + assert_eq!(o["sides"].as_array().map(Vec::len), Some(1), "{o}"); + assert_eq!(ids(&o["curves"]).len(), 4, "{o}"); + } +} + +#[test] +fn offset_instances_into_a_circle_run_out_at_the_centre() { + let mut s = new_sketch(); + let c = ids(&run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 10}))["curves"])[0].clone(); + let radii = |s: &Session, o: &Value| -> Vec { + let sk = sketch(s); + o["sides"] + .as_array() + .unwrap() + .iter() + .map(|side| match sk.curves.get(sk.curve_index(ids(&side["curves"])[0].as_str()).unwrap()).unwrap().kind { + CurveKind::Circle { r, .. } => r, + ref other => panic!("{other:?}"), + }) + .collect() + }; + // Inward by 3 from a 10 mm circle: rings at 7, 4 and 1 mm. + let o = run(&mut s, "sketch.offset", json!({"curves": [c.clone()], "distance": 3, "side": [0, 0], "instances": 3})); + let got = radii(&s, &o); + assert!(got.iter().zip([7.0, 4.0, 1.0]).all(|(a, b)| close(*a, b)), "{got:?}"); + let before = s.doc.to_json(); + // A fourth has nothing left to take. The ladder has to run out here: a step past a ring + // smaller than the distance lands beyond the centre, and reading that as the outward side + // turned the ladder round and grew it again (1, 4, 1, 4 ...) rather than refusing. + let error = s.execute("sketch.offset", &json!({"curves": [c.clone()], "distance": 3, "side": [0, 0], "instances": 4})).unwrap_err().to_string(); + assert!(error.contains("instance 4 of 4"), "{error}"); + assert!(error.contains("no size"), "{error}"); + assert_eq!(s.doc.to_json(), before, "a refused instance leaves the design alone"); + // Outward is unaffected: every ring is one distance larger than the last. + let out = run(&mut s, "sketch.offset", json!({"curves": [c], "distance": 3, "side": [40, 0], "instances": 3})); + let got = radii(&s, &out); + assert!(got.iter().zip([13.0, 16.0, 19.0]).all(|(a, b)| close(*a, b)), "{got:?}"); +} + +#[test] +fn offset_instances_follow_each_side_of_a_symmetric_offset() { + let mut s = new_sketch(); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})); + // Symmetric by 5, two instances: both ways get a second ring a further 5 out, so the four + // rings are 5 and 10 inside and 5 and 10 outside. + let o = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 5, "symmetric": true, "instances": 2})); + let sides = o["sides"].as_array().unwrap().clone(); + assert_eq!(sides.len(), 4, "{o}"); + assert_eq!(sides.iter().filter(|side| side["instance"] == 2).count(), 2, "{o}"); + let sk = sketch(&s); + let mut boxes: Vec<[f64; 4]> = sides + .iter() + .map(|side| { + let (lo, hi) = bounds(&sk, &ids(&side["curves"])); + [lo.x, lo.y, hi.x, hi.y] + }) + .collect(); + boxes.sort_by(|a, b| a[0].total_cmp(&b[0])); + let want = [[-10.0, -10.0, 50.0, 40.0], [-5.0, -5.0, 45.0, 35.0], [5.0, 5.0, 35.0, 25.0], [10.0, 10.0, 30.0, 20.0]]; + for (got, want) in boxes.iter().zip(&want) { + assert!(got.iter().zip(want).all(|(a, b)| close(*a, *b)), "{boxes:?}"); + } +} + #[test] fn offset_both_sides_of_a_rounded_boundary_keep_separate_associations() { let mut s = new_sketch(); diff --git a/crates/ui-egui/src/dialogs_sketch_tests.rs b/crates/ui-egui/src/dialogs_sketch_tests.rs index 545b94b2a..58c584756 100644 --- a/crates/ui-egui/src/dialogs_sketch_tests.rs +++ b/crates/ui-egui/src/dialogs_sketch_tests.rs @@ -80,7 +80,7 @@ macro_rules! form_case { } form_case!(scale, "sketch.scale", ["Factor"]); -form_case!(offset, "sketch.offset", ["Direction", "Distance"]); +form_case!(offset, "sketch.offset", ["Direction", "Distance", "Instances"]); form_case!(mirror, "sketch.mirror", []); form_case!(move_copy, "sketch.move", ["Position", "Angle"]); form_case!(rectangular_pattern, "sketch.pattern.rectangular", ["Quantity", "Spacing", "Alignment", "Quantity 2", "Spacing 2", "Alignment 2"]); diff --git a/crates/ui-egui/src/sketch_modify_ui.rs b/crates/ui-egui/src/sketch_modify_ui.rs index 3317e3272..716d3ed61 100644 --- a/crates/ui-egui/src/sketch_modify_ui.rs +++ b/crates/ui-egui/src/sketch_modify_ui.rs @@ -72,6 +72,9 @@ const CHAMFER_TYPE_ICONS: [&str; 3] = ["sketch_chamfer_equal", "sketch_chamfer_t /// The engine's own cap on the copies one sketch pattern may make. const MAX_COPIES: f64 = 500.0; +/// The engine's own cap on the offsets `sketch.offset` stacks one behind the other. +const MAX_OFFSET_INSTANCES: i64 = 100; + /// The offset directions, in the words and the order `solid.extrude` already uses for them. /// One Side offsets the way the distance points. Two Sides adds an independent distance the /// other way. Symmetric applies the one distance each way. @@ -102,8 +105,10 @@ pub enum Mod { /// `sketch.offset`: the curves to offset, the distance typed and whether the connected /// chain follows. A positive distance is left of the chain, as the command defines it; /// `flip` reverses whatever sign the field holds. `mode` indexes [`OFFSET_MODES`], and - /// `distance2` is the other side's distance that Two Sides asks for. - Offset { distance: String, distance2: String, mode: usize, chain: bool, flip: bool }, + /// `distance2` is the other side's distance that Two Sides asks for. `instances` is how many + /// offsets stand one behind the other, each the same distance again from the one before it: + /// one, the offset by itself, by default. + Offset { distance: String, distance2: String, instances: String, mode: usize, chain: bool, flip: bool }, /// `sketch.mirror`: the entities and the line they reflect in. The command has no number of /// its own, so the window's whole job is to show what is picked and let a pick be changed /// before anything is committed. @@ -227,6 +232,7 @@ pub fn start(app: &SolveApp, id: &str) -> Option<(Kind, Vec)> { "sketch.offset" => Mod::Offset { distance: crate::dialogs::length_default(&app.session, "2"), distance2: crate::dialogs::length_default(&app.session, "2"), + instances: "1".into(), mode: 0, chain: true, flip: false, @@ -526,12 +532,15 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Mod, doc: &Document) -> bool { let mut enter = false; match k { Mod::Scale { factor } => enter |= number(ui, "Factor", factor), - Mod::Offset { distance, distance2, mode, chain, flip } => { + Mod::Offset { distance, distance2, instances, mode, chain, flip } => { icons(ui, "Direction", &OFFSET_MODES, &OFFSET_MODE_ICONS, mode); enter |= number(ui, "Distance", distance); if *mode == TWO_SIDES { enter |= number(ui, "Distance 2", distance2); } + // Every instance after the first offsets the one before it by Distance again, so the + // arrows walk the offset outwards one ring at a time. + enter |= quantity(ui, doc, "Instances", instances, 1, MAX_OFFSET_INSTANCES); ui_kit::section(ui, "offset_options", "Options", true, |ui| { if *mode != SYMMETRIC { ui_kit::checkbox_grid(ui, &mut [("Flip", flip), ("Chain", chain)], 2); @@ -796,6 +805,15 @@ fn whole(app: &SolveApp, label: &str, text: &str) -> Result { Ok(v.round() as u64) } +/// Validate a typed offset instance count before sending it to the command. +fn offset_instances(app: &SolveApp, text: &str) -> Result { + let v = app.session.doc.eval(text.trim(), ValueKind::Unitless).map_err(|e| format!("Instances: {e}"))?; + if !v.is_finite() || !(1.0..=MAX_OFFSET_INSTANCES as f64).contains(&v) || (v - v.round()).abs() > 1e-9 { + return Err(format!("Instances must be a whole number from 1 to {MAX_OFFSET_INSTANCES}")); + } + Ok(v.round() as u64) +} + /// A typed length as the command wants it, in millimetres. A bare number means the design's /// units, as a typed sketch value does everywhere else. `value` above reads an empty row as /// zero, which a Move window wants and a pattern spacing does not. @@ -903,14 +921,18 @@ pub fn commands(app: &SolveApp, k: &Mod, inputs: &[SelInput], extra: &Map { + Mod::Offset { distance, distance2, instances, mode, chain, flip } => { let curves = curve_ids(inputs, 0); if curves.is_empty() { return Err("Select the curves to offset first".into()); } // Symmetric hides Flip, so a flip left over from another mode does not travel with it. signed_length(app, "Distance", distance, *flip && *mode != SYMMETRIC)?; - let mut params = json!({"curves": curves, "distance": distance.trim(), "flip": *flip && *mode != SYMMETRIC, "chain": chain}); + // The count is not kept in the design, so the command gets the number it evaluates to + // rather than the text, the way Scale and the pattern spacings send theirs. + let count = offset_instances(app, instances)?; + let mut params = + json!({"curves": curves, "distance": distance.trim(), "flip": *flip && *mode != SYMMETRIC, "chain": chain, "instances": count}); if let Value::Object(m) = &mut params { if *mode == SYMMETRIC { m.insert("symmetric".into(), json!(true)); diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs index 51e39ae34..af1071583 100644 --- a/crates/ui-egui/src/ui_kit/fields.rs +++ b/crates/ui-egui/src/ui_kit/fields.rs @@ -53,7 +53,14 @@ pub(crate) fn count_field(ui: &mut Ui, value: &mut String, limits: &Count<'_>) - let next = step_count(value, delta, limits); let arrow = ui.interact(half, ui.id().with(("sc_count_step", &row, name)), egui::Sense::click()); let enabled = ui.is_enabled() && next.is_some(); - if enabled && arrow.hovered() { + // The arrows stand inside the editor, which claims the text cursor across its whole + // rect: they are not text, so each one takes the ordinary cursor back after it. The + // pointer is read from the rect rather than from the hover the editor competes for. + let over = ui.rect_contains_pointer(half); + if over { + ui.ctx().set_cursor_icon(egui::CursorIcon::Default); + } + if enabled && over { painter.rect_filled(half.shrink(1.0), t.control_radius, t.selected_bg); } let ink = if enabled { t.form_ink } else { t.form_dim }; diff --git a/crates/ui-egui/src/ui_kit/fields_tests.rs b/crates/ui-egui/src/ui_kit/fields_tests.rs index c05710673..0a84b8a16 100644 --- a/crates/ui-egui/src/ui_kit/fields_tests.rs +++ b/crates/ui-egui/src/ui_kit/fields_tests.rs @@ -313,6 +313,39 @@ fn count_steps_stay_within_limits_and_keep_expressions() { assert_eq!(super::step_count("5", i64::MIN, &wide).as_deref(), Some("-9223372036854775803")); } +/// A count's step arrows stand inside the editor, which asks for the text cursor across its +/// whole rect, so the arrows showed an I-beam and read as part of the text. They are not text: +/// the pointer over one is the ordinary cursor, whether it can step or not, and the number +/// beside them is still typed. +#[test] +fn count_step_arrows_do_not_take_the_text_cursor() { + for value in ["5", "1"] { + let ctx = crate::fonts::test_context(); + let eval = |text: &str| text.trim().parse::().ok(); + let mut count = value.to_string(); + let mut draw = |ui: &mut Ui| { + count_row(ui, "Instances", &mut count, &Count { min: 1, max: 10, eval: &eval }); + }; + frame(&ctx, vec![], &mut draw); + let at = |name: &str| scenario::handle_at(&format!("dialog:Instances {name}")).unwrap_or_else(|| panic!("{name} has a handle")); + let (above, below) = (at("up"), at("down")); + let field = scenario::rect_of("dialog:widget:Instances").expect("the field has a rect"); + // The first frame registers the rects; the second reads the cursor they ask for. At 1 the + // down arrow is dimmed and the up arrow can still step: neither is text either way. + for (pos, which) in [(above, "up"), (below, "down")] { + frame_cursor(&ctx, pos, &mut draw); + assert_eq!(frame_cursor(&ctx, pos, &mut draw), egui::CursorIcon::Default, "{value}: the {which} arrow"); + } + let text = egui::pos2(field.left() + 2.0, field.center().y); + frame_cursor(&ctx, text, &mut draw); + assert_eq!(frame_cursor(&ctx, text, &mut draw), egui::CursorIcon::Text, "{value}: the number is still typed"); + // The enabled arrow still steps when it is clicked. + frame(&ctx, pointer(above, true), &mut draw); + frame(&ctx, pointer(above, false), &mut draw); + assert_eq!(count, if value == "1" { "2" } else { "6" }, "the up arrow steps"); + } +} + #[test] fn selection_field_has_three_distinct_looks_in_every_theme() { type Look = (Vec<(egui::Color32, egui::Color32)>, Option); From 3ccf04d4b29c408843f84fc6986a8b2444fc370a Mon Sep 17 00:00:00 2001 From: froglemonade2 <64703083+froglemonade2@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:02:39 +0000 Subject: [PATCH 04/55] Edit Extrude: close on the first Escape (#9084) (#9757) * claim: #9084 * Edit Extrude: close on the first Escape (#9084) An edit dialog whose value names a parameter (`T` in Edit Extrude) opened with that field focused and its completion list showing the longer names (`tan(`), unarmed. The list took the first Escape, so the dialog needed two. An unarmed list now leaves Escape to the window until the box is typed in, as it already leaves Enter and Tab; once typed in, Escape dismisses the list first as before. Its hint drops "Esc dismiss" in that state. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../completion-escape-closes-window.json | 9 +++++ crates/ui-egui/src/dialogs.rs | 30 ++++++++++++++++ crates/ui-egui/src/expression_complete.rs | 34 ++++++++++++++++++- 3 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 assets/locales/pending/completion-escape-closes-window.json diff --git a/assets/locales/pending/completion-escape-closes-window.json b/assets/locales/pending/completion-escape-closes-window.json new file mode 100644 index 000000000..1e49a4fd9 --- /dev/null +++ b/assets/locales/pending/completion-escape-closes-window.json @@ -0,0 +1,9 @@ +{ + "ar": { "↑ ↓ choose · Enter applies this value": "↑ ↓ اختيار · Enter يطبّق هذه القيمة" }, + "de": { "↑ ↓ choose · Enter applies this value": "↑ ↓ auswählen · Eingabe übernimmt diesen Wert" }, + "en": { "↑ ↓ choose · Enter applies this value": "↑ ↓ choose · Enter applies this value" }, + "he": { "↑ ↓ choose · Enter applies this value": "↑ ↓ בחירה · Enter מחיל את הערך הזה" }, + "ja": { "↑ ↓ choose · Enter applies this value": "↑ ↓ 選択 · Enter この値を適用" }, + "vi": { "↑ ↓ choose · Enter applies this value": "↑ ↓ để chọn · Enter để áp dụng giá trị này" }, + "zh": { "↑ ↓ choose · Enter applies this value": "↑ ↓ 选择 · Enter 应用此值" } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4a3ff51cc..b97a244ea 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -6845,6 +6845,36 @@ mod refused_ok_tests { } } + /// One Escape closes an edit dialog opened from its History row, also when its value names a parameter + /// and the field lists the longer names (`T` lists `tan(`, #9084). + #[test] + fn one_escape_closes_an_edit_dialog_whose_value_names_a_parameter() { + for name in ["Plate", "Corners", "Hole"] { + let mut h = Harness::new(); + for (command, params) in [ + ("parameters.add", json!({"name": "T", "expression": "3 mm"})), + ("parameters.add", json!({"name": "R", "expression": "5 mm"})), + ("sketch.create", json!({"plane": "XY"})), + ("sketch.rectangle.two_point", json!({"p0": [-40, -25], "p1": [40, 25]})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance": "T", "name": "Plate"})), + ("solid.fillet", json!({"edges": [[40, 25, 1.5], [-40, 25, 1.5]], "radius": "R", "name": "Corners"})), + ("solid.hole", json!({"position": [0, 0, 3], "diameter": 3.4, "name": "Hole"})), + ] { + h.app.run(command, params).unwrap(); + } + h.frames(2); + steps(&mut h, &[json!({"click": {"handle": format!("timeline:{name}")}, "double": true}), json!({"frames": 30})]); + assert!(h.app.dialog.as_ref().is_some_and(|d| d.editing.is_some()), "{name}: the edit dialog opened"); + if name != "Hole" { + assert!(h.ctx.memory(|m| m.focused()).is_some(), "{name}: its value field has the keyboard"); + assert!(crate::expression_complete::popup_state(&h.ctx).is_some(), "{name}: the field lists longer names"); + } + steps(&mut h, &[json!({"key": "Escape"}), json!({"frames": 2})]); + assert!(h.app.dialog.as_ref().is_none_or(|d| d.editing.is_none()), "{name}: one Escape closes the dialog"); + } + } + fn set_depth(h: &mut Harness, depth: &str) { steps(h, &[json!({"click": {"handle": "dialog:Depth"}}), json!({"key": "A", "cmd": true}), json!({"text": depth})]); } diff --git a/crates/ui-egui/src/expression_complete.rs b/crates/ui-egui/src/expression_complete.rs index 71c8f66ff..cafdf46ab 100644 --- a/crates/ui-egui/src/expression_complete.rs +++ b/crates/ui-egui/src/expression_complete.rs @@ -35,6 +35,11 @@ struct Popup { empty: bool, /// Down arrow in the empty box opened it: every named parameter, however many (#9246). every: bool, + /// The box was typed in since it took the focus. Until then an unarmed list only shows + /// what longer names there are, for a value the window filled in (`T` in Edit Extrude + /// lists `tan(`): Escape passes it by and closes the window as it would without the list, + /// as Enter and Tab do (#9084). + typed: bool, } fn popup_id() -> egui::Id { @@ -105,6 +110,7 @@ pub(crate) fn begin_frame(ctx: &egui::Context) { // Unarmed, the typed word is complete: Enter submits it and Tab moves on. Key::Enter | Key::Tab if !popup.armed => continue, Key::Enter | Key::Tab => popup.accept = true, + Key::Escape if !popup.armed && !popup.typed => continue, Key::Escape => { popup.dismissed = true; popup.accept = false; @@ -169,6 +175,7 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri // Dismissed suggestions stay closed until this box is typed in: another control rewriting // its text (a slider dragged while the box keeps the focus) or a moved caret is no reason. let dismissed = previous.as_ref().is_some_and(|p| p.dismissed) && !resp.changed(); + let typed = resp.changed() || previous.as_ref().is_some_and(|p| p.typed); // What the word follows, blanks aside. let before = text.chars().take(start).filter(|c| !c.is_whitespace()).last(); // A word that is already a complete name opens unarmed: Enter submits it as typed. A unit is @@ -191,7 +198,9 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri keyed: false, empty: false, every: false, + typed, }); + popup.typed = typed; popup.empty = text.is_empty(); popup.armed = popup.keyed || armed; // Never over a control being dragged: the drag dismisses them. @@ -251,10 +260,13 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri popup.armed.then_some(popup.selected), &options, // Unarmed, the typed word is complete and Enter submits it; an arrow key arms the list. + // Escape is the window's until the box is typed in. crate::i18n::tr_label(if popup.armed { "↑ ↓ choose · Enter / Tab complete · Esc dismiss" - } else { + } else if popup.typed { "↑ ↓ choose · Enter applies what you typed · Esc dismiss" + } else { + "↑ ↓ choose · Enter applies this value" }), ) && pick.is_none() && !released_after_press @@ -542,6 +554,26 @@ mod tests { } } + /// A list that opened by itself on a value the window filled in leaves Escape to the window + /// (#9084); once the box is typed in, Escape dismisses the list first. + #[test] + fn escape_passes_an_unarmed_list_until_the_box_is_typed_in() { + let mut e = Editor::new("width"); + assert_eq!(e.popup().map(|(_, armed)| armed), Some(false)); + e.key(Key::Escape); + assert!(e.leaked.contains(&Key::Escape)); + assert!(!e.ctx.memory(|m| m.has_focus(e.id))); + + let mut e = Editor::new("widt"); + e.frame(vec![egui::Event::Text("h".into())]); + assert_eq!(e.text, "width"); + assert_eq!(e.popup().map(|(_, armed)| armed), Some(false)); + e.key(Key::Escape); + assert!(e.leaked.is_empty()); + assert!(!showing(&e.ctx, e.id)); + assert!(e.ctx.memory(|m| m.has_focus(e.id))); + } + /// From the unarmed popup an arrow key picks a row (Down the first, Up the last); Enter or /// Tab then complete it as usual. #[test] From d135e1659c6e016e0542fe6ddb92402c24affee9 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:26:57 +0000 Subject: [PATCH 05/55] Regenerate generated files and fold pending files [skip ci] --- assets/locales/ar.json | 5 ++ assets/locales/de.json | 5 ++ assets/locales/en.json | 5 ++ assets/locales/he.json | 5 ++ assets/locales/ja.json | 5 ++ .../pending/export-format-commands.json | 51 ------------------- assets/locales/vi.json | 5 ++ assets/locales/zh.json | 5 ++ docs/features.md | 5 ++ 9 files changed, 40 insertions(+), 51 deletions(-) delete mode 100644 assets/locales/pending/export-format-commands.json diff --git a/assets/locales/ar.json b/assets/locales/ar.json index 2ed3d8964..206eaf441 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -936,6 +936,11 @@ "cmd.explode_show": "إظهار العرض المفكك", "cmd.expr_evaluate": "تقييم تعبير", "cmd.face_delete": "حذف وجه", + "cmd.file.export_3mf": "تصدير 3MF", + "cmd.file.export_obj": "تصدير OBJ", + "cmd.file.export_step": "تصدير STEP", + "cmd.file.export_stl": "تصدير STL", + "cmd.file.export_urdf": "تصدير URDF", "cmd.file_export": "تصدير", "cmd.file_insert_mesh": "إدراج شبكة", "cmd.file_insert_step": "إدراج STEP", diff --git a/assets/locales/de.json b/assets/locales/de.json index 536b7ae89..efa66c6a6 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -934,6 +934,11 @@ "cmd.explode_show": "Explosionsdarstellung anzeigen", "cmd.expr_evaluate": "Ausdruck auswerten", "cmd.face_delete": "Fläche löschen", + "cmd.file.export_3mf": "Als 3MF exportieren", + "cmd.file.export_obj": "Als OBJ exportieren", + "cmd.file.export_step": "Als STEP exportieren", + "cmd.file.export_stl": "Als STL exportieren", + "cmd.file.export_urdf": "Als URDF exportieren", "cmd.file_export": "Exportieren", "cmd.file_insert_mesh": "Netz einfügen", "cmd.file_insert_step": "STEP einfügen", diff --git a/assets/locales/en.json b/assets/locales/en.json index 9a76f0314..82501b8dc 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -936,6 +936,11 @@ "cmd.explode_show": "Show Exploded View", "cmd.expr_evaluate": "Evaluate Expression", "cmd.face_delete": "Delete Face", + "cmd.file.export_3mf": "Export 3MF", + "cmd.file.export_obj": "Export OBJ", + "cmd.file.export_step": "Export STEP", + "cmd.file.export_stl": "Export STL", + "cmd.file.export_urdf": "Export URDF", "cmd.file_export": "Export", "cmd.file_insert_mesh": "Insert Mesh", "cmd.file_insert_step": "Insert STEP", diff --git a/assets/locales/he.json b/assets/locales/he.json index f1b0ecf47..d51f424cf 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -936,6 +936,11 @@ "cmd.explode_show": "הצגת תצוגה מפוצצת", "cmd.expr_evaluate": "חישוב ביטוי", "cmd.face_delete": "מחיקת פאה", + "cmd.file.export_3mf": "ייצוא 3MF", + "cmd.file.export_obj": "ייצוא OBJ", + "cmd.file.export_step": "ייצוא STEP", + "cmd.file.export_stl": "ייצוא STL", + "cmd.file.export_urdf": "ייצוא URDF", "cmd.file_export": "ייצוא", "cmd.file_insert_mesh": "הוספת רשת משולשים", "cmd.file_insert_step": "הוספת STEP", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 23e380850..24f7dc7e2 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -936,6 +936,11 @@ "cmd.explode_show": "分解図を表示", "cmd.expr_evaluate": "式を評価", "cmd.face_delete": "面を削除", + "cmd.file.export_3mf": "3MF をエクスポート", + "cmd.file.export_obj": "OBJ をエクスポート", + "cmd.file.export_step": "STEP をエクスポート", + "cmd.file.export_stl": "STL をエクスポート", + "cmd.file.export_urdf": "URDF をエクスポート", "cmd.file_export": "エクスポート", "cmd.file_insert_mesh": "メッシュを挿入", "cmd.file_insert_step": "STEP を挿入", diff --git a/assets/locales/pending/export-format-commands.json b/assets/locales/pending/export-format-commands.json deleted file mode 100644 index 463ef0815..000000000 --- a/assets/locales/pending/export-format-commands.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "en": { - "cmd.file.export_step": "Export STEP", - "cmd.file.export_stl": "Export STL", - "cmd.file.export_3mf": "Export 3MF", - "cmd.file.export_obj": "Export OBJ", - "cmd.file.export_urdf": "Export URDF" - }, - "de": { - "cmd.file.export_step": "Als STEP exportieren", - "cmd.file.export_stl": "Als STL exportieren", - "cmd.file.export_3mf": "Als 3MF exportieren", - "cmd.file.export_obj": "Als OBJ exportieren", - "cmd.file.export_urdf": "Als URDF exportieren" - }, - "ar": { - "cmd.file.export_step": "تصدير STEP", - "cmd.file.export_stl": "تصدير STL", - "cmd.file.export_3mf": "تصدير 3MF", - "cmd.file.export_obj": "تصدير OBJ", - "cmd.file.export_urdf": "تصدير URDF" - }, - "he": { - "cmd.file.export_step": "ייצוא STEP", - "cmd.file.export_stl": "ייצוא STL", - "cmd.file.export_3mf": "ייצוא 3MF", - "cmd.file.export_obj": "ייצוא OBJ", - "cmd.file.export_urdf": "ייצוא URDF" - }, - "ja": { - "cmd.file.export_step": "STEP をエクスポート", - "cmd.file.export_stl": "STL をエクスポート", - "cmd.file.export_3mf": "3MF をエクスポート", - "cmd.file.export_obj": "OBJ をエクスポート", - "cmd.file.export_urdf": "URDF をエクスポート" - }, - "vi": { - "cmd.file.export_step": "Xuất tệp STEP", - "cmd.file.export_stl": "Xuất tệp STL", - "cmd.file.export_3mf": "Xuất tệp 3MF", - "cmd.file.export_obj": "Xuất tệp OBJ", - "cmd.file.export_urdf": "Xuất tệp URDF" - }, - "zh": { - "cmd.file.export_step": "导出 STEP", - "cmd.file.export_stl": "导出 STL", - "cmd.file.export_3mf": "导出 3MF", - "cmd.file.export_obj": "导出 OBJ", - "cmd.file.export_urdf": "导出 URDF" - } -} diff --git a/assets/locales/vi.json b/assets/locales/vi.json index f60921ed1..0fc975d6e 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -936,6 +936,11 @@ "cmd.explode_show": "Hiển thị chế độ xem phân rã", "cmd.expr_evaluate": "Tính giá trị biểu thức", "cmd.face_delete": "Xóa mặt", + "cmd.file.export_3mf": "Xuất tệp 3MF", + "cmd.file.export_obj": "Xuất tệp OBJ", + "cmd.file.export_step": "Xuất tệp STEP", + "cmd.file.export_stl": "Xuất tệp STL", + "cmd.file.export_urdf": "Xuất tệp URDF", "cmd.file_export": "Xuất tệp", "cmd.file_insert_mesh": "Chèn lưới đa giác (Mesh)", "cmd.file_insert_step": "Chèn tệp STEP", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index bf7da602f..05cd404b0 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -936,6 +936,11 @@ "cmd.explode_show": "显示爆炸图", "cmd.expr_evaluate": "计算表达式", "cmd.face_delete": "删除面", + "cmd.file.export_3mf": "导出 3MF", + "cmd.file.export_obj": "导出 OBJ", + "cmd.file.export_step": "导出 STEP", + "cmd.file.export_stl": "导出 STL", + "cmd.file.export_urdf": "导出 URDF", "cmd.file_export": "导出", "cmd.file_insert_mesh": "插入网格", "cmd.file_insert_step": "插入 STEP", diff --git a/docs/features.md b/docs/features.md index 84daea767..23a63024c 100644 --- a/docs/features.md +++ b/docs/features.md @@ -380,6 +380,11 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Command | Id | Toolbar | |---|---|---| | Export | `file.export` | – | +| Export 3MF | `file.export_3mf` | – | +| Export OBJ | `file.export_obj` | – | +| Export STEP | `file.export_step` | – | +| Export STL | `file.export_stl` | – | +| Export URDF | `file.export_urdf` | – | | Export Current View as DXF | `file.export_view_dxf` | – | | Insert Mesh | `file.insert_mesh` | SOLID › INSERT | | Insert STEP | `file.insert_step` | SOLID › INSERT | From 147d1cfaddcc6fe824399a58fea36a022278961e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:35:09 +0000 Subject: [PATCH 06/55] Regenerate generated files and fold pending files [skip ci] --- ATTRIBUTION.md | 123 +++++++++++++++++ assets/locales/ar.json | 2 + assets/locales/bs.json | 1 + assets/locales/cs.json | 1 + assets/locales/da.json | 1 + assets/locales/de.json | 2 + assets/locales/en-GB.json | 1 + assets/locales/en.json | 2 + assets/locales/es.json | 1 + assets/locales/fi.json | 1 + assets/locales/fr.json | 1 + assets/locales/he.json | 2 + assets/locales/hr.json | 1 + assets/locales/it.json | 1 + assets/locales/ja.json | 2 + assets/locales/ko.json | 1 + assets/locales/nl.json | 1 + .../completion-escape-closes-window.json | 9 -- .../pending/sketch-offset-instances.json | 71 ---------- assets/locales/pl.json | 1 + assets/locales/pt-BR.json | 1 + assets/locales/sr.json | 1 + assets/locales/uk.json | 1 + assets/locales/vi.json | 2 + assets/locales/zh-TW.json | 1 + assets/locales/zh.json | 2 + attribution/pending/preferences-v2.md | 124 ------------------ .../pending/sketch-offset-instances.md | 2 - 28 files changed, 153 insertions(+), 206 deletions(-) delete mode 100644 assets/locales/pending/completion-escape-closes-window.json delete mode 100644 assets/locales/pending/sketch-offset-instances.json delete mode 100644 attribution/pending/preferences-v2.md delete mode 100644 attribution/pending/sketch-offset-instances.md diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index a53a01105..8e3ae76cd 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -631,6 +631,129 @@ Original SolidCraft drawings, Open for owner review; no runtime assignments. | assets/icons/ui/design/svg/model/print_face.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/locales/fi.json | SolidCraft contributors | Original Finnish translation of SolidCraft's English catalog, AI-assisted (Claude Code) clean-room from the English and not yet reviewed line by line by a native speaker; no commercial CAD text used | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/plane_axis_point.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-2x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-2x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-4x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-4x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-8x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-8x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-off.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/aa-off.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/agent-pointer-speed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/agent-pointer-speed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/ao-on.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/ao-on.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/assembly-move.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/assembly-move.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-card.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-card.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-column.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/browser-column.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-bends.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-bends.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-draft.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-draft.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-failed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-failed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-fixed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-fixed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-projected.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/colour-vision-projected.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/direct-interaction.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/direct-interaction.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/frame-rate.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/frame-rate.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-bottom.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-bottom.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-in-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-in-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-left.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-left.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-under-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/history-under-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/layout-schematic.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/layout-schematic.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/measure-axis-distances.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/measure-axis-distances.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/mouse-mapping.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/mouse-mapping.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-cube.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/navigator-cube.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-centre.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-centre.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-origin.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orbit-origin.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-y-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-y-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-z-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/orientation-z-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/quick-measure.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/quick-measure.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-bodies.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-bodies.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-faces-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/select-faces-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-conflict.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-conflict.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-keep.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-keep.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-previous.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-previous.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-unless-turned.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-exit-unless-turned.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-guides.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-guides.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-hide-glyphs.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-hide-glyphs.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-state-icons.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/sketch-state-icons.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/style-shaded-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/style-shaded-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-coarse.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-coarse.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-fine.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-fine.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-normal.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-normal.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-ultra.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tess-ultra.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-dark.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-dark.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-gruvbox.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-gruvbox.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-imported.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-imported.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-light.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-light.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-dark-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-dark-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-light-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/theme-system-light-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-extrude.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-extrude.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-hole.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-hole.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-placement.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/tool-placement.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/vertex-markers.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/vertex-markers.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-angles.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-angles.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-grid.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-grid.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-perspective.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-perspective.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-shadow.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| docs/design/preferences/figures/view-shadow.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | +| `assets/locales/pending/sketch-offset-instances.json` | SolidCraft contributors | Original offset instance-count label and translations | MIT OR Apache-2.0 | ## Code adapted from sibling projects diff --git a/assets/locales/ar.json b/assets/locales/ar.json index 206eaf441..1ef623195 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -4731,6 +4731,7 @@ "ui.insert_design.saved_file": "في {name} تغييرات غير محفوظة، لذا أُدرج ملفه المحفوظ. احفظه، ثم استخدم تحديث الروابط لإدخال التغييرات.", "ui.insert_design.unsaved": "تغييرات غير محفوظة", "ui.inspect": "فحص", + "ui.instances": "النسخ", "ui.intersect": "تقاطع", "ui.isolate": "عزل", "ui.join": "ضم", @@ -5222,6 +5223,7 @@ "web.open_link": "فتح التصميم المرتبط؟", "web.open_link_confirm": "توجد تغييرات غير محفوظة. هل تريد فتح التصميم المرتبط في تبويب جديد؟", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ اختيار · Enter / Tab إكمال · Esc إغلاق", + "↑ ↓ choose · Enter applies this value": "↑ ↓ اختيار · Enter يطبّق هذه القيمة", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ اختيار · Enter يطبّق ما كتبته · Esc إغلاق", "⌘Enter continues on GitHub.": "⌘Enter يتابع في GitHub." } diff --git a/assets/locales/bs.json b/assets/locales/bs.json index b70570a6f..62f89da99 100644 --- a/assets/locales/bs.json +++ b/assets/locales/bs.json @@ -4709,6 +4709,7 @@ "ui.insert_design.saved_file": "{name} ima nesačuvane promjene, pa je umetnuta njegova sačuvana datoteka. Sačuvajte ga, a zatim pokrenite Ažuriraj veze da unesete promjene.", "ui.insert_design.unsaved": "Nesačuvane promjene", "ui.inspect": "Pregledaj", + "ui.instances": "Instance", "ui.intersect": "Presjek", "ui.isolate": "Izoluj", "ui.join": "Spoji", diff --git a/assets/locales/cs.json b/assets/locales/cs.json index ca136fc5d..007ea3d7b 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -4709,6 +4709,7 @@ "ui.insert_design.saved_file": "{name} obsahuje neuložené změny, proto byl vložen jeho uložený soubor. Uložte jej a pak použijte Aktualizovat odkazy, aby se změny převzaly.", "ui.insert_design.unsaved": "Neuložené změny", "ui.inspect": "Analýza", + "ui.instances": "Instance", "ui.intersect": "Průnik", "ui.isolate": "Izolovat", "ui.join": "Sjednotit", diff --git a/assets/locales/da.json b/assets/locales/da.json index fd113cefb..8c9551661 100644 --- a/assets/locales/da.json +++ b/assets/locales/da.json @@ -4709,6 +4709,7 @@ "ui.insert_design.saved_file": "{name} har ændringer, der ikke er gemt, så dens gemte fil blev indsat. Gem den, og kør derefter Opdatér forbindelser for at hente ændringerne.", "ui.insert_design.unsaved": "Ikke-gemte ændringer", "ui.inspect": "Inspicér", + "ui.instances": "Forekomster", "ui.intersect": "Fællesvolumen", "ui.isolate": "Isolér", "ui.join": "Foren", diff --git a/assets/locales/de.json b/assets/locales/de.json index efa66c6a6..fb7051139 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -4724,6 +4724,7 @@ "ui.insert_design.saved_file": "{name} hat ungespeicherte Änderungen, daher wurde die gespeicherte Datei eingefügt. Speichern Sie sie und wählen Sie dann Verknüpfungen aktualisieren, um die Änderungen zu übernehmen.", "ui.insert_design.unsaved": "Ungespeicherte Änderungen", "ui.inspect": "Prüfen", + "ui.instances": "Instanzen", "ui.intersect": "Schnitt", "ui.isolate": "Isolieren", "ui.join": "Verbinden", @@ -5214,6 +5215,7 @@ "web.open_link": "Verknüpftes Design öffnen?", "web.open_link_confirm": "Es gibt nicht gespeicherte Änderungen. Das verknüpfte Design in einem neuen Tab öffnen?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ auswählen · Eingabe / Tab vervollständigen · Esc schließen", + "↑ ↓ choose · Enter applies this value": "↑ ↓ auswählen · Eingabe übernimmt diesen Wert", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ wählen · Enter wendet das Getippte an · Esc schließt", "⌘Enter continues on GitHub.": "⌘Enter geht weiter zu GitHub." } diff --git a/assets/locales/en-GB.json b/assets/locales/en-GB.json index 6e55dc209..934271166 100644 --- a/assets/locales/en-GB.json +++ b/assets/locales/en-GB.json @@ -249,6 +249,7 @@ "ui.details_curvature_caption": "Faces are coloured by their local radius of curvature.", "ui.details_draft_caption": "Faces are coloured by their angle to the pull direction.", "ui.export_keymap_tip": "Keys, S box favourites and the toolbar, as a file", + "ui.instances": "Instances", "ui.layout_compact": "Compact", "ui.layout_floating": "Floating", "ui.material_review.claims": "Sources and licences are unverified claims. Missing values remain unknown.", diff --git a/assets/locales/en.json b/assets/locales/en.json index 82501b8dc..0972751b6 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -4731,6 +4731,7 @@ "ui.insert_design.saved_file": "{name} has unsaved changes, so its saved file was inserted. Save it, then Update Links to bring the changes in.", "ui.insert_design.unsaved": "Unsaved changes", "ui.inspect": "Inspect", + "ui.instances": "Instances", "ui.intersect": "Intersect", "ui.isolate": "Isolate", "ui.join": "Join", @@ -5222,6 +5223,7 @@ "web.open_link": "Open linked design?", "web.open_link_confirm": "There are unsaved changes. Open the linked design in a new tab?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ choose · Enter / Tab complete · Esc dismiss", + "↑ ↓ choose · Enter applies this value": "↑ ↓ choose · Enter applies this value", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ choose · Enter applies what you typed · Esc dismiss", "⌘Enter continues on GitHub.": "⌘Enter continues on GitHub." } diff --git a/assets/locales/es.json b/assets/locales/es.json index 9aa15125b..d010e5452 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -4357,6 +4357,7 @@ "ui.insert_design.saved_file": "{name} tiene cambios sin guardar, así que se insertó su archivo guardado. Guárdalo y luego Actualizar vínculos para traer los cambios.", "ui.insert_design.unsaved": "Cambios sin guardar", "ui.inspect": "Inspeccionar", + "ui.instances": "Instancias", "ui.intersect": "Intersecar", "ui.isolate": "Aislar", "ui.join": "Unir", diff --git a/assets/locales/fi.json b/assets/locales/fi.json index c5b1b7479..dac604c92 100644 --- a/assets/locales/fi.json +++ b/assets/locales/fi.json @@ -4321,6 +4321,7 @@ "ui.insert_design.saved_file": "Mallissa {name} on tallentamattomia muutoksia, joten sen tallennettu tiedosto lisättiin. Tallenna se ja tuo muutokset valitsemalla Päivitä linkit.", "ui.insert_design.unsaved": "Tallentamattomia muutoksia", "ui.inspect": "Tarkastele", + "ui.instances": "Esiintymät", "ui.intersect": "Leikkaus", "ui.isolate": "Eristä", "ui.join": "Yhdistä", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index d736e30bb..7d52aa1f3 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -4657,6 +4657,7 @@ "ui.insert_design.saved_file": "{name} contient des modifications non enregistrées ; c'est donc son fichier enregistré qui a été inséré. Enregistrez-le, puis utilisez Mettre à jour les liens pour intégrer les modifications.", "ui.insert_design.unsaved": "Modifications non enregistrées", "ui.inspect": "Inspecter", + "ui.instances": "Instances", "ui.intersect": "Intersection", "ui.isolate": "Isoler", "ui.join": "Joindre", diff --git a/assets/locales/he.json b/assets/locales/he.json index d51f424cf..4169dadef 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -4731,6 +4731,7 @@ "ui.insert_design.saved_file": "ב-{name} יש שינויים שלא נשמרו, ולכן נוסף הקובץ השמור שלו. שמרו אותו ואז בחרו עדכון קישורים כדי להכניס את השינויים.", "ui.insert_design.unsaved": "שינויים שלא נשמרו", "ui.inspect": "בדיקה", + "ui.instances": "מופעים", "ui.intersect": "חיתוך משותף", "ui.isolate": "בידוד", "ui.join": "איחוד", @@ -5222,6 +5223,7 @@ "web.open_link": "לפתוח את התכן המקושר?", "web.open_link_confirm": "יש שינויים שלא נשמרו. לפתוח את התכן המקושר בלשונית חדשה?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ בחירה · Enter / Tab השלמה · Esc סגירה", + "↑ ↓ choose · Enter applies this value": "↑ ↓ בחירה · Enter מחיל את הערך הזה", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ בחירה · Enter מחיל את מה שהוקלד · Esc סגירה", "⌘Enter continues on GitHub.": "⌘Enter ממשיך ב־GitHub." } diff --git a/assets/locales/hr.json b/assets/locales/hr.json index b16903bc9..9c30fb990 100644 --- a/assets/locales/hr.json +++ b/assets/locales/hr.json @@ -4709,6 +4709,7 @@ "ui.insert_design.saved_file": "{name} ima nespremljene promjene, pa je umetnuta njegova spremljena datoteka. Spremite ga, a zatim pokrenite Ažuriraj veze kako biste unijeli promjene.", "ui.insert_design.unsaved": "Nespremljene promjene", "ui.inspect": "Pregledaj", + "ui.instances": "Instance", "ui.intersect": "Presjek", "ui.isolate": "Izoliraj", "ui.join": "Spoji", diff --git a/assets/locales/it.json b/assets/locales/it.json index 222a68fe9..f4d0607ae 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -4709,6 +4709,7 @@ "ui.insert_design.saved_file": "{name} contiene modifiche non salvate, quindi è stato inserito il file salvato. Salvalo, poi usa Aggiorna collegamenti per includere le modifiche.", "ui.insert_design.unsaved": "Modifiche non salvate", "ui.inspect": "Esamina", + "ui.instances": "Istanze", "ui.intersect": "Interseca", "ui.isolate": "Isola", "ui.join": "Unisci", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 24f7dc7e2..5dadbc11a 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -4731,6 +4731,7 @@ "ui.insert_design.saved_file": "{name} に保存されていない変更があるため、保存済みのファイルを挿入しました。保存してから、リンクを更新で変更を取り込んでください。", "ui.insert_design.unsaved": "未保存の変更", "ui.inspect": "検査", + "ui.instances": "インスタンス", "ui.intersect": "交差", "ui.isolate": "分離表示", "ui.join": "結合", @@ -5222,6 +5223,7 @@ "web.open_link": "リンク先のデザインを開きますか?", "web.open_link_confirm": "保存していない変更があります。リンク先のデザインを新しいタブで開きますか?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 選択 · Enter / Tab 補完 · Esc 閉じる", + "↑ ↓ choose · Enter applies this value": "↑ ↓ 選択 · Enter この値を適用", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ 選択 · Enter 入力どおりに適用 · Esc 閉じる", "⌘Enter continues on GitHub.": "⌘EnterでGitHubに進みます。" } diff --git a/assets/locales/ko.json b/assets/locales/ko.json index c10e7f4e1..8a7c3d75a 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -3497,6 +3497,7 @@ "ui.insert_design.saved_file": "{name}에 저장되지 않은 변경 사항이 있어 저장된 파일을 삽입했습니다. 저장한 다음 링크 업데이트로 변경 사항을 가져오세요.", "ui.insert_design.unsaved": "저장되지 않은 변경 사항", "ui.inspect": "검사", + "ui.instances": "인스턴스", "ui.intersect": "교차", "ui.isolate": "분리 표시", "ui.join": "접합", diff --git a/assets/locales/nl.json b/assets/locales/nl.json index 8cd921643..af9b63a42 100644 --- a/assets/locales/nl.json +++ b/assets/locales/nl.json @@ -4709,6 +4709,7 @@ "ui.insert_design.saved_file": "{name} heeft niet-opgeslagen wijzigingen, dus is het opgeslagen bestand ingevoegd. Sla het op en gebruik daarna Koppelingen bijwerken om de wijzigingen over te nemen.", "ui.insert_design.unsaved": "Niet-opgeslagen wijzigingen", "ui.inspect": "Inspecteren", + "ui.instances": "Instanties", "ui.intersect": "Snijden", "ui.isolate": "Isoleren", "ui.join": "Samenvoegen", diff --git a/assets/locales/pending/completion-escape-closes-window.json b/assets/locales/pending/completion-escape-closes-window.json deleted file mode 100644 index 1e49a4fd9..000000000 --- a/assets/locales/pending/completion-escape-closes-window.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "ar": { "↑ ↓ choose · Enter applies this value": "↑ ↓ اختيار · Enter يطبّق هذه القيمة" }, - "de": { "↑ ↓ choose · Enter applies this value": "↑ ↓ auswählen · Eingabe übernimmt diesen Wert" }, - "en": { "↑ ↓ choose · Enter applies this value": "↑ ↓ choose · Enter applies this value" }, - "he": { "↑ ↓ choose · Enter applies this value": "↑ ↓ בחירה · Enter מחיל את הערך הזה" }, - "ja": { "↑ ↓ choose · Enter applies this value": "↑ ↓ 選択 · Enter この値を適用" }, - "vi": { "↑ ↓ choose · Enter applies this value": "↑ ↓ để chọn · Enter để áp dụng giá trị này" }, - "zh": { "↑ ↓ choose · Enter applies this value": "↑ ↓ 选择 · Enter 应用此值" } -} diff --git a/assets/locales/pending/sketch-offset-instances.json b/assets/locales/pending/sketch-offset-instances.json deleted file mode 100644 index 717b57add..000000000 --- a/assets/locales/pending/sketch-offset-instances.json +++ /dev/null @@ -1,71 +0,0 @@ -{ - "en": { - "ui.instances": "Instances" - }, - "ar": { - "ui.instances": "النسخ" - }, - "bs": { - "ui.instances": "Instance" - }, - "cs": { - "ui.instances": "Instance" - }, - "da": { - "ui.instances": "Forekomster" - }, - "de": { - "ui.instances": "Instanzen" - }, - "en-GB": { - "ui.instances": "Instances" - }, - "es": { - "ui.instances": "Instancias" - }, - "fi": { - "ui.instances": "Esiintymät" - }, - "fr": { - "ui.instances": "Instances" - }, - "he": { - "ui.instances": "מופעים" - }, - "hr": { - "ui.instances": "Instance" - }, - "it": { - "ui.instances": "Istanze" - }, - "ja": { - "ui.instances": "インスタンス" - }, - "ko": { - "ui.instances": "인스턴스" - }, - "nl": { - "ui.instances": "Instanties" - }, - "pl": { - "ui.instances": "Wystąpienia" - }, - "pt-BR": { - "ui.instances": "Instâncias" - }, - "sr": { - "ui.instances": "Инстанце" - }, - "uk": { - "ui.instances": "Екземпляри" - }, - "vi": { - "ui.instances": "Số bản" - }, - "zh": { - "ui.instances": "实例数" - }, - "zh-TW": { - "ui.instances": "實例數" - } -} diff --git a/assets/locales/pl.json b/assets/locales/pl.json index da725a804..17ba70f21 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -2998,6 +2998,7 @@ "ui.insert_design.saved_file": "{name} ma niezapisane zmiany, więc wstawiono jego zapisany plik. Zapisz go, a potem użyj Aktualizuj łącza, aby wprowadzić zmiany.", "ui.insert_design.unsaved": "Niezapisane zmiany", "ui.inspect": "Sprawdź", + "ui.instances": "Wystąpienia", "ui.intersect": "Przytnij", "ui.isolate": "Izoluj", "ui.join": "Połącz", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 4c63bb71a..4dbb4a957 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -2092,6 +2092,7 @@ "ui.infinite": "Infinita", "ui.insert": "Inserir", "ui.inspect": "Inspecionar", + "ui.instances": "Instâncias", "ui.intersect": "Interseção", "ui.isolate": "Isolar", "ui.join": "Unir", diff --git a/assets/locales/sr.json b/assets/locales/sr.json index b3b591cd4..7591e7348 100644 --- a/assets/locales/sr.json +++ b/assets/locales/sr.json @@ -4709,6 +4709,7 @@ "ui.insert_design.saved_file": "Дизајн {name} има несачуване промене, па је уметнута његова сачувана датотека. Сачувајте га, а затим покрените Ажурирај везе да бисте унели промене.", "ui.insert_design.unsaved": "Несачуване промене", "ui.inspect": "Прегледај", + "ui.instances": "Инстанце", "ui.intersect": "Пресек", "ui.isolate": "Изолуј", "ui.join": "Споји", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index f3262fa95..fded59b4d 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -4709,6 +4709,7 @@ "ui.insert_design.saved_file": "{name} має незбережені зміни, тому вставлено його збережений файл. Збережіть його, потім оновіть зв'язки, щоб перенести зміни.", "ui.insert_design.unsaved": "Незбережені зміни", "ui.inspect": "Перевірити", + "ui.instances": "Екземпляри", "ui.intersect": "Перетин", "ui.isolate": "Ізолювати", "ui.join": "З'єднати", diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 0fc975d6e..76ef51fd9 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -4731,6 +4731,7 @@ "ui.insert_design.saved_file": "{name} có thay đổi chưa lưu, nên tệp đã lưu của nó đã được chèn. Hãy lưu nó, rồi dùng Cập nhật liên kết để đưa các thay đổi vào.", "ui.insert_design.unsaved": "Thay đổi chưa lưu", "ui.inspect": "Kiểm tra", + "ui.instances": "Số bản", "ui.intersect": "Giao nhau", "ui.isolate": "Cô lập đối tượng", "ui.join": "Nối liền", @@ -5222,6 +5223,7 @@ "web.open_link": "Mở thiết kế liên kết?", "web.open_link_confirm": "Có những thay đổi chưa lưu. Mở thiết kế liên kết trong tab mới?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ chọn · Enter / Tab hoàn tất · Esc bỏ qua", + "↑ ↓ choose · Enter applies this value": "↑ ↓ để chọn · Enter để áp dụng giá trị này", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ để chọn · Enter để áp dụng nội dung đã nhập · Esc để đóng", "⌘Enter continues on GitHub.": "Nhấn ⌘Enter để tiếp tục trên GitHub." } diff --git a/assets/locales/zh-TW.json b/assets/locales/zh-TW.json index 9e00dd734..cb6d2585b 100644 --- a/assets/locales/zh-TW.json +++ b/assets/locales/zh-TW.json @@ -4711,6 +4711,7 @@ "ui.insert_design.saved_file": "{name} 有未儲存的變更,因此插入的是其已儲存的檔案。請儲存後執行「更新連結」以帶入變更。", "ui.insert_design.unsaved": "未儲存的變更", "ui.inspect": "檢查", + "ui.instances": "實例數", "ui.intersect": "相交", "ui.isolate": "隔離", "ui.join": "接合", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 05cd404b0..485a95b06 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -4731,6 +4731,7 @@ "ui.insert_design.saved_file": "{name} 有未保存的更改,因此插入的是其已保存的文件。请先保存,再使用“更新链接”导入这些更改。", "ui.insert_design.unsaved": "未保存的更改", "ui.inspect": "检查", + "ui.instances": "实例数", "ui.intersect": "相交", "ui.isolate": "隔离", "ui.join": "连接", @@ -5222,6 +5223,7 @@ "web.open_link": "打开链接的设计?", "web.open_link_confirm": "有未保存的更改。要在新标签页中打开链接的设计吗?", "↑ ↓ choose · Enter / Tab complete · Esc dismiss": "↑ ↓ 选择 · Enter / Tab 补全 · Esc 关闭", + "↑ ↓ choose · Enter applies this value": "↑ ↓ 选择 · Enter 应用此值", "↑ ↓ choose · Enter applies what you typed · Esc dismiss": "↑ ↓ 选择 · Enter 按原样应用 · Esc 关闭", "⌘Enter continues on GitHub.": "按⌘Enter在GitHub中继续。" } diff --git a/attribution/pending/preferences-v2.md b/attribution/pending/preferences-v2.md deleted file mode 100644 index 2ffbd29f9..000000000 --- a/attribution/pending/preferences-v2.md +++ /dev/null @@ -1,124 +0,0 @@ -| File | Author | Source | Licence | -|---|---|---|---| -| docs/design/preferences/figures/aa-2x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/aa-2x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/aa-4x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/aa-4x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/aa-8x.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/aa-8x.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/aa-off.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/aa-off.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/agent-pointer-speed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/agent-pointer-speed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/ao-on.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/ao-on.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/assembly-move.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/assembly-move.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/browser-card.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/browser-card.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/browser-column.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/browser-column.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-bends.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-bends.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-draft.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-draft.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-failed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-failed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-fixed.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-fixed.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-projected.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/colour-vision-projected.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/direct-interaction.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/direct-interaction.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/frame-rate.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/frame-rate.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/history-bottom.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/history-bottom.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/history-in-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/history-in-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/history-left.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/history-left.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/history-under-browser.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/history-under-browser.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/layout-schematic.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/layout-schematic.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/measure-axis-distances.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/measure-axis-distances.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/mouse-mapping.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/mouse-mapping.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/navigator-axes.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/navigator-axes.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/navigator-cube.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/navigator-cube.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/orbit-centre.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/orbit-centre.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/orbit-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/orbit-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/orbit-origin.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/orbit-origin.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/orientation-y-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/orientation-y-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/orientation-z-up.dark.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/orientation-z-up.light.svg | SolidCraft contributors | original SolidCraft artwork: the Orientation figure copied from the app and extracted from the Preferences redesign board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/quick-measure.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/quick-measure.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/select-bodies.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/select-bodies.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/select-faces-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/select-faces-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-conflict.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-conflict.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-exit-keep.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-exit-keep.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-exit-previous.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-exit-previous.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-exit-unless-turned.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-exit-unless-turned.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-guides.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-guides.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-hide-glyphs.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-hide-glyphs.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-state-icons.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/sketch-state-icons.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/style-shaded-edges.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/style-shaded-edges.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tess-coarse.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tess-coarse.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tess-fine.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tess-fine.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tess-normal.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tess-normal.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tess-ultra.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tess-ultra.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-dark.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-dark.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-gruvbox.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-gruvbox.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-imported.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-imported.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-light.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-light.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-system-dark-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-system-dark-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-system-light-half.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/theme-system-light-half.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tool-cursor.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tool-cursor.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tool-extrude.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tool-extrude.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tool-hole.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tool-hole.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tool-placement.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/tool-placement.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/vertex-markers.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/vertex-markers.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/view-angles.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/view-angles.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/view-grid.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/view-grid.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/view-perspective.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/view-perspective.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/view-shadow.dark.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | -| docs/design/preferences/figures/view-shadow.light.svg | SolidCraft contributors | original SolidCraft artwork drawn for the Preferences redesign (tracker #9863), extracted from the design board as a standalone SVG | MIT OR Apache-2.0 | diff --git a/attribution/pending/sketch-offset-instances.md b/attribution/pending/sketch-offset-instances.md deleted file mode 100644 index 4e1b0ab7e..000000000 --- a/attribution/pending/sketch-offset-instances.md +++ /dev/null @@ -1,2 +0,0 @@ -| File | Author | Source | Licence | -| `assets/locales/pending/sketch-offset-instances.json` | SolidCraft contributors | Original offset instance-count label and translations | MIT OR Apache-2.0 | From 38ae728538f52585473583a912479d812efa75b3 Mon Sep 17 00:00:00 2001 From: N3MI-DG <129717180+N3MI-DG@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:02:57 +0000 Subject: [PATCH 07/55] Preview: new surface is tinted whatever its size, and the tints can be turned off (#9111) (#9112) * claim: #9111 * Preview: new surface is tinted whatever its size, and the tints can be turned off (#9111) A preview decided which faces of a changed body were new surface by asking whether their triangle centroids lay on the old body, within a tolerance that follows the part's size. A round or chamfer small beside the part never leaves that tolerance, so it was drawn as if it had always been there, and sampling at a fixed step told alike faces apart by nothing but how many triangles they had. The kernel already records which faces an operation generated, so `build` takes that record alongside the geometric test. The test stays because a body carries the history of whatever last made it, which is not the previewed operation when a parameter change re-evaluates the design: the record only ever adds faces to the answer. The vote itself now asks about every centroid of a small face, spreads a large face's samples without a resonant step, and calls a face new above an eighth of its samples, which a blend tangent on both of its sides reaches with the one row of facets in five that is clearly off the old surface. Graphics gains two settings, both on as they come, so nothing changes out of the box: Tint new surface in a preview draws a changed body as itself when it is off, working out no face at all, and Show removed material in red leaves the see-through cut and the ghost of the shape a feature replaces fully transparent, drawing only their outlines. Co-Authored-By: Claude Opus 5 --------- Co-authored-by: Claude Opus 5 --- assets/locales/pending/preview-tints.json | 50 +++++ crates/ui-egui/src/dialogs.rs | 11 +- crates/ui-egui/src/dialogs_assembly_tests.rs | 6 + crates/ui-egui/src/extrude_preview.rs | 4 + crates/ui-egui/src/move_preview.rs | 8 +- crates/ui-egui/src/prefs.rs | 7 + crates/ui-egui/src/prefs/graphics.rs | 4 + crates/ui-egui/src/preview.rs | 185 ++++++++++++++++--- crates/ui-egui/src/preview_drag_tests.rs | 11 +- 9 files changed, 255 insertions(+), 31 deletions(-) create mode 100644 assets/locales/pending/preview-tints.json diff --git a/assets/locales/pending/preview-tints.json b/assets/locales/pending/preview-tints.json new file mode 100644 index 000000000..86db8893b --- /dev/null +++ b/assets/locales/pending/preview-tints.json @@ -0,0 +1,50 @@ +{ + "ar": { + "prefs.cut_preview_tint": "إظهار المادة المُزالة باللون الأحمر", + "prefs.cut_preview_tint_help": "تملأ المعاينة المادة التي تزيلها الميزة، والشكل الذي تستبدله، بطيف أحمر شبه شفاف. عند الإيقاف تكون هذه التعبئة شفافة تمامًا ولا تُرسم سوى مخططاتها.", + "prefs.preview_tint_new_faces": "تلوين السطح الجديد في المعاينة", + "prefs.preview_tint_new_faces_help": "يمكن لمعاينة ميزة تغيّر جسمًا أن ترسم السطح المضاف بلون المعاينة. عند الإيقاف يُرسم الجسم بلونه الأصلي." + }, + "de": { + "prefs.cut_preview_tint": "Entferntes Material rot anzeigen", + "prefs.cut_preview_tint_help": "Eine Vorschau füllt das Material, das ein Feature entfernt, sowie die ersetzte Form mit einem roten, durchscheinenden Geist. Wenn deaktiviert, sind diese Füllungen völlig transparent und es werden nur ihre Umrisse gezeichnet.", + "prefs.preview_tint_new_faces": "Neue Fläche in der Vorschau einfärben", + "prefs.preview_tint_new_faces_help": "Eine Vorschau eines Features, das einen Körper ändert, kann die hinzugefügte Fläche in der Vorschaufarbe zeichnen. Wenn deaktiviert, wird der Körper wie er ist gezeichnet." + }, + "en": { + "prefs.cut_preview_tint": "Show removed material in red", + "prefs.cut_preview_tint_help": "A preview fills the material a feature removes, and the shape it replaces, with a red see-through ghost. When off, those fills are fully transparent and only their outlines are drawn.", + "prefs.preview_tint_new_faces": "Tint new surface in a preview", + "prefs.preview_tint_new_faces_help": "A preview of a feature that changes a body can draw the surface it adds in the preview colour. When off, the body is drawn as itself." + }, + "he": { + "prefs.cut_preview_tint": "הצגת חומר שהוסר באדום", + "prefs.cut_preview_tint_help": "תצוגה מקדימה ממלאת את החומר שהפעולה מסירה, ואת הצורה שהיא מחליפה, ברוח אדומה שקופה. כשהאפשרות כבויה המילויים האלה שקופים לחלוטין ומצוירים רק קווי המתאר שלהם.", + "prefs.preview_tint_new_faces": "צביעת משטח חדש בתצוגה מקדימה", + "prefs.preview_tint_new_faces_help": "תצוגה מקדימה של פעולה שמשנה גוף יכולה לצבוע את המשטח שנוסף בצבע התצוגה המקדימה. כשהאפשרות כבויה הגוף מצויר בצבעו שלו." + }, + "ja": { + "prefs.cut_preview_tint": "除去される材料を赤で表示", + "prefs.cut_preview_tint_help": "プレビューでは、フィーチャーが除去する材料と置き換えられる形状を、赤い透過ゴーストで塗りつぶします。オフにすると、この塗りつぶしは完全に透明になり、輪郭のみが描画されます。", + "prefs.preview_tint_new_faces": "プレビューで新しい面に色を付ける", + "prefs.preview_tint_new_faces_help": "ボディを変更するフィーチャーのプレビューで、追加される面をプレビュー色で描画できます。オフにすると、ボディはそのままの色で描画されます。" + }, + "ko": { + "prefs.cut_preview_tint": "제거되는 재료를 빨간색으로 표시", + "prefs.cut_preview_tint_help": "미리 보기는 피처가 제거하는 재료와 대체되는 형상을 빨간색 반투명 고스트로 채웁니다. 끄면 이 채움이 완전히 투명해지고 윤곽선만 그려집니다.", + "prefs.preview_tint_new_faces": "미리 보기에서 새 면에 색 입히기", + "prefs.preview_tint_new_faces_help": "바디를 변경하는 피처의 미리 보기에서 추가되는 면을 미리 보기 색으로 그릴 수 있습니다. 끄면 바디가 원래 색으로 그려집니다." + }, + "vi": { + "prefs.cut_preview_tint": "Hiển thị vật liệu bị loại bỏ bằng màu đỏ", + "prefs.cut_preview_tint_help": "Bản xem trước tô vật liệu mà đặc trưng loại bỏ, và hình dạng mà nó thay thế, bằng một bóng mờ màu đỏ. Khi tắt, các phần tô này hoàn toàn trong suốt và chỉ vẽ đường viền của chúng.", + "prefs.preview_tint_new_faces": "Tô màu bề mặt mới trong bản xem trước", + "prefs.preview_tint_new_faces_help": "Bản xem trước của một đặc trưng làm thay đổi một khối có thể vẽ bề mặt được thêm vào bằng màu xem trước. Khi tắt, khối được vẽ bằng màu của chính nó." + }, + "zh": { + "prefs.cut_preview_tint": "以红色显示被移除的材料", + "prefs.cut_preview_tint_help": "预览会用红色半透明幻影填充特征所移除的材料以及被替换的形状。关闭时,这些填充完全透明,仅绘制其轮廓。", + "prefs.preview_tint_new_faces": "在预览中为新表面着色", + "prefs.preview_tint_new_faces_help": "更改实体的特征,其预览可以用预览颜色绘制新增的表面。关闭时,实体按自身颜色绘制。" + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b97a244ea..838c26b05 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -6774,7 +6774,16 @@ mod refused_ok_tests { let preview = crate::preview::compute( &app.session, &commands, - crate::preview::Colors { body: [1; 4], added: [2; 4], new_body: [3; 4], removed: [4; 4], edge: [5; 4], ghost: false }, + crate::preview::Colors { + body: [1; 4], + added: [2; 4], + new_body: [3; 4], + removed: [4; 4], + edge: [5; 4], + ghost: false, + tint_new: true, + cut_tint: true, + }, ) .expect("the angled plane previews"); diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index 07feadc53..3931c4b6d 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -167,6 +167,8 @@ fn joint_and_drive_preview_on_the_placed_model() { removed: [3, 3, 3, 100], edge: [0, 0, 0, 255], ghost: true, + tint_new: true, + cut_tint: true, }; let cmds = preview_commands(&app, &d).unwrap(); let b = world_preview(&app.session, &cmds, colors).unwrap().unwrap(); @@ -871,6 +873,8 @@ fn drive_says_where_a_loop_stopped_it() { removed: [3, 3, 3, 100], edge: [0, 0, 0, 255], ghost: true, + tint_new: true, + cut_tint: true, }; let rocker = app.session.doc.assembly.joints.iter().position(|j| j.name == "Rocker").unwrap(); let mut d = drive_joint(&app, app.session.doc.assembly.joints[rocker].id).unwrap(); @@ -931,6 +935,8 @@ fn drive_says_when_its_joint_is_joined_to_nothing_grounded() { removed: [3, 3, 3, 100], edge: [0, 0, 0, 255], ghost: true, + tint_new: true, + cut_tint: true, }; let b = world_preview(&app.session, &apply_commands(&app, &d).unwrap(), colors).unwrap().unwrap(); let why = b.stopped.as_ref().and_then(drive_stop).unwrap(); diff --git a/crates/ui-egui/src/extrude_preview.rs b/crates/ui-egui/src/extrude_preview.rs index 227daa4bb..e21182941 100644 --- a/crates/ui-egui/src/extrude_preview.rs +++ b/crates/ui-egui/src/extrude_preview.rs @@ -115,6 +115,10 @@ impl StraightPreview { let color = scene.color(color); let cut_edge = scene.color(cut_edge); let triangle = |scene: &mut GpuScene, points: [Vec3; 3], normal: Vec3| { + // Removed material the preference leaves fully transparent: only the cut's outline. + if operation == "cut" && !colors.cut_tint { + return; + } for point in points { if matches!(operation, "cut" | "intersect") { scene.xray_tri(point.to_f32(), normal.to_f32(), color); diff --git a/crates/ui-egui/src/move_preview.rs b/crates/ui-egui/src/move_preview.rs index f66ba782d..76a8ac2a6 100644 --- a/crates/ui-egui/src/move_preview.rs +++ b/crates/ui-egui/src/move_preview.rs @@ -95,7 +95,7 @@ impl MovePreview { let mut bounds = Aabb3::EMPTY; for mesh in &cache.meshes { draw(&mut scene, mesh, &m, colors, &mut bounds); - if !copy { + if !copy && colors.cut_tint { // Where the body was, as the scratch-design preview shows a body moved away. for t in &mesh.triangles { for k in t { @@ -119,9 +119,11 @@ impl MovePreview { } } -/// `mesh` moved by `m`, in the colour of geometry the feature adds, with its shaded edges. +/// `mesh` moved by `m`, in the colour of geometry the feature adds, or the body's own where +/// the preference leaves new surface untinted (a move makes none either way), with its shaded +/// edges. fn draw(scene: &mut GpuScene, mesh: &Mesh, m: &Mat, colors: Colors, bounds: &mut Aabb3) { - let added = scene.color(colors.added); + let added = scene.color(if colors.tint_new { colors.added } else { colors.body }); for t in &mesh.triangles { for k in t { let i = *k as usize; diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index b8efe27b9..d64c99ee9 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1102,6 +1102,13 @@ preference_settings! { /// A small dot at every vertex wherever edges are drawn (#7834). Off by default: the viewport /// draws edges only, as it always has. vertex_markers: bool = false => check("Vertex markers", "Show a small dot at every vertex wherever edges are drawn"); + /// A preview of a feature that changes a body draws the surface it adds in the preview + /// colour, working out face by face which surface that is. Off: the body is drawn as itself + /// and nothing is worked out (`preview::Colors::tint_new`). + preview_tint_new_faces: bool = true, PAGE_GRAPHICS => check_id("prefs.preview_tint_new_faces"); + /// A preview that removes material shows the removed shape as a red see-through ghost. Off: + /// the ghost is fully transparent and only its outline is drawn (`preview::Colors::cut_tint`). + cut_preview_tint: bool = true, PAGE_GRAPHICS => check_id("prefs.cut_preview_tint"); /// Restore the previous platform-specific fixed Render preview geometry budget. render_previous_geometry_budget: bool = false, PAGE_GRAPHICS => check_id("prefs.render_previous_geometry_budget"); /// How finely the viewport tessellates curved faces and edges: `coarse`, `normal`, `fine` or diff --git a/crates/ui-egui/src/prefs/graphics.rs b/crates/ui-egui/src/prefs/graphics.rs index d4d42d436..5b551dda1 100644 --- a/crates/ui-egui/src/prefs/graphics.rs +++ b/crates/ui-egui/src/prefs/graphics.rs @@ -181,6 +181,10 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { }); crate::prefs::view_angles_checkbox(app, left); setting::reference_geometry_through_bodies(app, left).on_hover_text(app.tr("settings.reference_geometry_through_bodies_help")); + let tint_new = setting::preview_tint_new_faces(app, left).on_hover_text(app.tr("prefs.preview_tint_new_faces_help")); + crate::scenario::publish_target("prefs:preview_tint_new_faces", tint_new.rect); + let cut_tint = setting::cut_preview_tint(app, left).on_hover_text(app.tr("prefs.cut_preview_tint_help")); + crate::scenario::publish_target("prefs:cut_preview_tint", cut_tint.rect); setting::sketch_halo(app, left); setting::vertex_markers(app, left); } diff --git a/crates/ui-egui/src/preview.rs b/crates/ui-egui/src/preview.rs index be5ffd407..7ff05ada1 100644 --- a/crates/ui-egui/src/preview.rs +++ b/crates/ui-egui/src/preview.rs @@ -1,9 +1,10 @@ //! Live operation previews. While a feature dialog is open, its commands are evaluated on a //! scratch copy of the session ([`solidcraft_engine::Session::preview`]), off the UI thread //! where threads exist, and the result is drawn in place of the bodies it changes: new surface -//! tinted, removed material as a translucent ghost. The last good preview stays up while the -//! next one computes; once the current inputs make the feature fail, nothing is previewed and -//! the error shows in the dialog (#3254). +//! tinted (unless Graphics' Tint new surface in a preview is off, when a changed body is drawn +//! as itself), removed material as a translucent ghost. The last good preview stays up while +//! the next one computes; once the current inputs make the feature fail, nothing is previewed +//! and the error shows in the dialog (#3254). //! Nothing here touches the document or the undo history. //! //! A feature that adds or removes a tool body (join, cut, intersect) shows only its tool. That @@ -19,6 +20,7 @@ use solidcraft_engine::Session; use solidcraft_engine::doc::ModelState; use solidcraft_engine::doc::progress::Progress; use solidcraft_engine::geom::{Aabb3, Mesh, Ring, Vec3}; +use solidcraft_engine::kernel::history::Change; use crate::SolveApp; use crate::gpu::{GpuScene, SceneSlot}; @@ -28,6 +30,8 @@ use crate::theme::Tokens; #[derive(Clone, Copy, Debug)] pub struct Colors { pub body: [u8; 4], + /// The tool a join, cut or intersect adds, a datum plane a preview creates, and, where the + /// preference asks for it (`tint_new`), the surface a feature adds to a body it changes. pub added: [u8; 4], /// A body the preview creates (New Body), so it doesn't look like a join. pub new_body: [u8; 4], @@ -35,12 +39,29 @@ pub struct Colors { pub edge: [u8; 4], /// Whether a moved component's old place is drawn as a ghost (Drive Joints' Show ghost). pub ghost: bool, + /// Whether the surface a feature adds to a body it changes is drawn in the added colour + /// (Graphics' Tint new surface in a preview). Off: that body is drawn as itself, and which + /// of its faces are new is never worked out. + pub tint_new: bool, + /// Whether removed material is filled in the cut colour (Graphics' Show removed material in + /// red): the see-through cut and the ghost of the shape a feature replaces. Off: those fills + /// are left out altogether, so they are fully transparent and only outlines are drawn. + pub cut_tint: bool, } impl Colors { pub fn from_tokens(t: &Tokens) -> Colors { let c = |c: egui::Color32| c.to_srgba_unmultiplied(); - Colors { body: c(t.body), added: c(t.preview_add), new_body: c(t.preview_new), removed: c(t.preview_cut), edge: c(t.body_edge), ghost: true } + Colors { + body: c(t.body), + added: c(t.preview_add), + new_body: c(t.preview_new), + removed: c(t.preview_cut), + edge: c(t.body_edge), + ghost: true, + tint_new: true, + cut_tint: true, + } } fn for_tool(t: &Tokens, tab: &str, active: bool) -> Colors { @@ -366,6 +387,8 @@ pub fn update(app: &mut SolveApp, ctx: &egui::Context) { if app.dialog.as_ref().is_some_and(|d| matches!(d.kind, crate::dialogs::Kind::Assembly(crate::dialogs_assembly::Asm::Drive { .. }))) { colors.ghost = app.preferences.drive_joints_ghost; } + colors.tint_new = app.preferences.preview_tint_new_faces; + colors.cut_tint = app.preferences.cut_preview_tint; let key = job_key(&cmds, app.session.revision, colors); let stream_key = stream_key(&cmds, app.session.revision, colors); let tool = as_new_body(&cmds).is_some(); @@ -577,6 +600,7 @@ fn build_tool(before: &ModelState, after: &ModelState, c: Colors, op: &str) -> B let i = *k as usize; if let (Some(p), Some(n)) = (m.positions.get(i), m.normals.get(i)) { match op { + "cut" if !c.cut_tint => {} "cut" => sc.xray_tri(p.to_f32(), n.to_f32(), removed), "intersect" => sc.xray_tri(p.to_f32(), n.to_f32(), intersect), _ => sc.tri(p.to_f32(), n.to_f32(), added), @@ -665,26 +689,43 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { if old.as_ref().is_some_and(|bm| same(bm, &am)) { continue; } - let nf = am.tri_face.iter().max().map_or(0, |m| *m as usize + 1); - let added: Vec = match &old { - Some(bm) => new_faces(&am, nf, bm), - None => vec![true; nf], - }; // Material removed from a body (a hole, a pocket): its new faces also show through the // body in the cut colour, so the cut is seen from any side. - let cut = old.as_ref().is_some_and(|bm| am.measure().volume < bm.measure().volume - 1e-6); + let cut = c.cut_tint && old.as_ref().is_some_and(|bm| am.measure().volume < bm.measure().volume - 1e-6); + // Which of the body's faces the feature made, asked only when something is drawn from + // the answer: the cut above, and the tint the preference offers. A changed body is + // otherwise drawn as itself, so a preview looks like the model and nothing has to be + // worked out face by face. + let new_face: Vec = match &old { + Some(bm) if cut || c.tint_new => { + let mut new = new_faces(&am, am.tri_face.iter().max().map_or(0, |m| *m as usize + 1), bm); + // The kernel recorded which faces the operation that made this body generated, + // i.e. has no face of an input under it. The two answers are taken together + // because each misses something on its own: geometry cannot see a round small + // beside the part, which lies within its tolerance of the faces it is tangent + // to all along both of its sides, while the record may be of a later operation + // than the one previewed (a parameter change re-evaluates the design, and a + // body keeps the history of whatever last made it), so the record only ever + // adds faces to the answer. + if let Some(history) = a.body.history() { + for (is_new, face) in new.iter_mut().zip(&history.faces) { + *is_new |= face.change == Change::Generated; + } + } + new + } + _ => Vec::new(), + }; + let kept = if old.is_some() { body_color } else { new_body }; for (t, f) in am.triangles.iter().zip(&am.tri_face) { - let new = added.get(*f as usize).copied().unwrap_or(true); - let col = match (new, old.is_some()) { - (false, _) => body_color, - (true, true) => added_color, - (true, false) => new_body, - }; + let new = new_face.get(*f as usize).copied().unwrap_or(false); + let col = if new && c.tint_new { added_color } else { kept }; + let through = cut && new; for k in t { let i = *k as usize; if let (Some(p), Some(n)) = (am.positions.get(i), am.normals.get(i)) { sc.tri(p.to_f32(), n.to_f32(), col); - if new && cut { + if through { sc.xray_tri(p.to_f32(), n.to_f32(), removed); } } @@ -708,11 +749,13 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { continue; } let m = b.mesh(); - for t in &m.triangles { - for k in t { - let i = *k as usize; - if let (Some(p), Some(n)) = (m.positions.get(i), m.normals.get(i)) { - sc.ghost_tri(p.to_f32(), n.to_f32(), removed); + if c.cut_tint { + for t in &m.triangles { + for k in t { + let i = *k as usize; + if let (Some(p), Some(n)) = (m.positions.get(i), m.normals.get(i)) { + sc.ghost_tri(p.to_f32(), n.to_f32(), removed); + } } } } @@ -755,6 +798,12 @@ pub fn build(before: &ModelState, after: &ModelState, c: Colors) -> Built { Built { scene: sc, sketches, replaced, error: None, bounds: Aabb3::EMPTY, applied: None, tapered: Vec::new(), stopped: None } } +/// Points of one face the vote in [`new_faces`] asks about: every centroid of a face with no +/// more than this many triangles, so its answer doesn't ride on where that face's rows of +/// facets happen to fall, and a spread sample of a larger one. The lookups per face stay +/// bounded, so a modeled thread's thousands of faces still cost little. +const FACE_SAMPLES: usize = 24; + /// Which of the `nf` faces of `m` are new surface, i.e. not on the old mesh? Each is decided by /// a vote of points on it (triangle centroids spread over the face). One pass over `m`'s /// triangles gathers the centroids, and the old mesh is indexed once, so the cost stays @@ -774,10 +823,23 @@ fn new_faces(m: &Mesh, nf: usize, old: &Mesh) -> Vec { if cents.is_empty() { return true; } - let step = cents.len().div_ceil(9); - let samples: Vec<&Vec3> = cents.iter().step_by(step.max(1)).collect(); + let samples: Vec<&Vec3> = if cents.len() <= FACE_SAMPLES { + cents.iter().collect() + } else { + // Spread by the golden ratio rather than at a fixed step: a face's triangles + // come in rows across its curve, and a step that divides the row length would + // ask about the same place in every row (a blend's tangent sides, say), so two + // alike faces could be told apart by nothing but how long they are. + let len = cents.len() as f64; + (0..FACE_SAMPLES).filter_map(|i| cents.get(((i as f64 * 0.618_033_988_75).fract() * len) as usize)).collect() + }; let off = samples.iter().filter(|p| !index.contains(***p)).count(); - off * 3 > samples.len() + // More than an eighth of the face off the old surface is new surface. A blend meets + // the faces it rounds tangentially, so the rows of facets along both of its sides + // lie within the tolerance of the old surface and only the band through its middle + // is clearly off: a small round on a large part never reaches the third the vote + // asked for before, and was drawn as if it had always been there. + off * 8 > samples.len() }) .collect() } @@ -933,7 +995,16 @@ mod tests { } fn colors() -> Colors { - Colors { body: [1, 1, 1, 255], added: [2, 2, 2, 255], new_body: [4, 4, 4, 255], removed: [3, 3, 3, 100], edge: [0, 0, 0, 255], ghost: true } + Colors { + body: [1, 1, 1, 255], + added: [2, 2, 2, 255], + new_body: [4, 4, 4, 255], + removed: [3, 3, 3, 100], + edge: [0, 0, 0, 255], + ghost: true, + tint_new: true, + cut_tint: true, + } } #[test] @@ -1205,6 +1276,32 @@ mod tests { assert_eq!(count(&b.scene, &b.scene.xray, 28, colors().removed), 0); } + /// Graphics' Show removed material in red, off: the cut and the ghost of the shape the + /// feature replaces are left out, and the body itself is still drawn. + #[test] + fn removed_material_can_be_left_fully_transparent() { + let mut s = solidcraft_engine::Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); + let cmds = [("solid.hole".to_string(), json!({"position": [20, 15, 20], "diameter": 5, "depth": 10}))]; + let p = s.preview(&cmds).unwrap(); + let plain = colors(); + let b = build(&p.before, &p.after, plain); + assert!(count(&b.scene, &b.scene.ghost, 28, plain.removed) > 0, "the replaced shape is ghosted while the tint is on"); + let quiet = Colors { cut_tint: false, ..plain }; + let b = build(&p.before, &p.after, quiet); + assert_eq!(count(&b.scene, &b.scene.xray, 28, quiet.removed), 0, "no see-through cut"); + assert_eq!(count(&b.scene, &b.scene.ghost, 28, quiet.removed), 0, "no ghost of the old shape"); + assert!(count(&b.scene, &b.scene.tris, 28, quiet.body) > 0, "the body is still drawn"); + // The tool of a cut is left out too, its outline alone showing where it goes. + let cmds = [("solid.box".to_string(), json!({"length": 10, "width": 10, "height": 30, "operation": "new"}))]; + let p = s.preview(&cmds).unwrap(); + let shown = build_tool(&p.before, &p.after, plain, "cut"); + assert!(count(&shown.scene, &shown.scene.xray, 28, plain.removed) > 0, "the tool is see-through red while the tint is on"); + let b = build_tool(&p.before, &p.after, quiet, "cut"); + assert_eq!(count(&b.scene, &b.scene.xray, 28, quiet.removed), 0, "no see-through tool"); + assert!(!b.scene.overlay.is_empty(), "the tool's outline still shows where the cut goes"); + } + fn plate() -> Session { let mut s = Session::default(); for (id, p) in [ @@ -1345,6 +1442,42 @@ mod tests { assert_eq!(s.undo.len(), undo); } + /// Graphics' Tint new surface in a preview, off: the changed body is drawn as itself, and + /// no face of it is worked out. + #[test] + fn the_tint_on_new_surface_can_be_turned_off() { + let s = plate(); + let cmds = [("solid.fillet".to_string(), json!({"edges": [[0, 0, 10]], "radius": 3}))]; + let plain = Colors { tint_new: false, ..colors() }; + let b = compute(&s, &cmds, plain).unwrap(); + assert_eq!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, plain.added), 0, "nothing is tinted"); + assert!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, plain.body) > 0, "the body is drawn as itself"); + } + + /// With the tint on, a round far smaller than the part is new surface too. Every facet of + /// this one lies within the preview's tolerance (half a millimetre here) of the faces it is + /// tangent to, so no point on it is off the old body and only the kernel's record of what + /// the fillet generated can tell. + #[test] + fn a_small_round_on_a_large_part_is_tinted_as_new() { + let mut s = Session::default(); + for (id, p) in [ + ("sketch.create", json!({"plane": "XY"})), + ("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [200, 150]})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"distance": 10})), + ] { + s.execute(id, &p).unwrap(); + } + // The plate's diagonal is 250 mm, so a point counts as on the old surface within half a + // millimetre: a 0.5 mm round never leaves it, bulging 0.15 mm at the most. + let tinted = Colors { tint_new: true, ..colors() }; + let b = compute(&s, &[("solid.fillet".into(), json!({"edges": [[100, 0, 10]], "radius": 0.5}))], tinted).unwrap(); + let added = count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, tinted.added); + assert!(added > 0, "the round is drawn as new surface, not as part of the old body"); + assert!(count(&b.scene, &b.scene.tris, crate::gpu::TRI_SIZE, tinted.body) > 0, "the rest of the plate is kept"); + } + /// A cut shows its tool see-through and replaces nothing. #[test] fn cut_preview_scene() { diff --git a/crates/ui-egui/src/preview_drag_tests.rs b/crates/ui-egui/src/preview_drag_tests.rs index 3167b3156..22e96f819 100644 --- a/crates/ui-egui/src/preview_drag_tests.rs +++ b/crates/ui-egui/src/preview_drag_tests.rs @@ -3,7 +3,16 @@ use super::*; use serde_json::json; fn colors() -> Colors { - Colors { body: [1, 1, 1, 255], added: [2, 2, 2, 255], new_body: [2, 2, 2, 255], removed: [3, 3, 3, 100], edge: [0, 0, 0, 255], ghost: true } + Colors { + body: [1, 1, 1, 255], + added: [2, 2, 2, 255], + new_body: [2, 2, 2, 255], + removed: [3, 3, 3, 100], + edge: [0, 0, 0, 255], + ghost: true, + tint_new: true, + cut_tint: true, + } } fn fixture() -> Session { From a0ed5a99235f5f08e9a1712aafb165d078f451b8 Mon Sep 17 00:00:00 2001 From: rbousigues88 Date: Sun, 1 Nov 2026 18:03:17 +0000 Subject: [PATCH 08/55] Measure: a fillet's torus or a sphere reports its radius (#7159) (#7160) * claim: #7159 * Measure: a fillet's torus or a sphere reports its radius (#7159) The face of a fillet round a circular edge is a torus and a ball's face a sphere, which Measure listed by area only. Their face item now carries radius, diameter and surface (and the ring radius of a torus); they stay out of Shape, so distances are unchanged. Fixes #7159. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- crates/engine/src/cmd/measure_sel.rs | 4 ++- crates/engine/src/cmd/measure_shape.rs | 21 ++++++++++++ crates/engine/src/measure_centre_tests.rs | 42 +++++++++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/measure_sel.rs b/crates/engine/src/cmd/measure_sel.rs index 00f3450b3..af38dd7ad 100644 --- a/crates/engine/src/cmd/measure_sel.rs +++ b/crates/engine/src/cmd/measure_sel.rs @@ -353,7 +353,8 @@ fn describe(s: &Session, sel: &Sel) -> Option { let planar = normals.first().copied().filter(|n0| normals.iter().all(|n| n.dot(*n0) > 1.0 - 1e-6)); let mut json = json!({"type": "face", "area_mm2": area, "planar": planar.is_some()}); let verts: Vec = tris.iter().flat_map(|t| t.iter().copied()).collect(); - let shape = match solidcraft_kernel::face_surface(&b.body, *index) { + let surface = solidcraft_kernel::face_surface(&b.body, *index); + let shape = match surface { Some(solidcraft_kernel::FaceSurface::Cylinder { origin, axis, radius }) => { super::measure_shape::cylinder(origin, axis, radius, &verts).unwrap_or(Shape::Other) } @@ -365,6 +366,7 @@ fn describe(s: &Session, sel: &Sel) -> Option { _ => Shape::Other, }; add_round(&mut json, &shape); + super::measure_shape::add_curved(&mut json, surface); let slot = if matches!(shape, Shape::Round { .. }) && !shape.full() { face_slot(b, &m, &shape, &verts) } else { None }; if let Some(sl) = &slot { json["slot"] = sl.json(); diff --git a/crates/engine/src/cmd/measure_shape.rs b/crates/engine/src/cmd/measure_shape.rs index 71fb6904a..cbe9b712e 100644 --- a/crates/engine/src/cmd/measure_shape.rs +++ b/crates/engine/src/cmd/measure_shape.rs @@ -68,6 +68,27 @@ pub(crate) fn add_round(v: &mut Value, shape: &Shape) { }); } +/// The radius of a toroidal or spherical face, added to its description: a fillet round a +/// circular edge is a torus whose tube radius is the fillet's (`major_radius` is the ring +/// through the middle of the rolling ball), a ball or a spherical corner patch a sphere. These +/// faces have no axis to measure from, so they stay out of [`Shape`]. +pub(crate) fn add_curved(v: &mut Value, surface: Option) { + use solidcraft_kernel::FaceSurface; + let (radius, kind) = match surface { + Some(FaceSurface::Torus { minor, major, .. }) if minor.is_finite() && minor > 0.0 => { + if major.is_finite() { + v["major_radius"] = json!(major.abs()); + } + (minor, "torus") + } + Some(FaceSurface::Sphere { radius, .. }) if radius.is_finite() && radius > 0.0 => (radius, "sphere"), + _ => return, + }; + v["diameter"] = json!(2.0 * radius); + v["radius"] = json!(radius); + v["surface"] = json!(kind); +} + /// Cylinder `axis` through `origin` of radius `radius` over the points of its face: the /// round shape, centred level with the middle of the face, with its extent and coverage. pub(crate) fn cylinder(origin: Vec3, axis: UnitVec3, radius: f64, pts: &[Vec3]) -> Option { diff --git a/crates/engine/src/measure_centre_tests.rs b/crates/engine/src/measure_centre_tests.rs index 36e0eda92..f0bff39b1 100644 --- a/crates/engine/src/measure_centre_tests.rs +++ b/crates/engine/src/measure_centre_tests.rs @@ -336,6 +336,48 @@ fn a_cylinders_top_circle_is_as_long_as_its_circumference() { assert!(close(&r["items"][0]["length_mm"], TAU * 5.0, 1e-9), "{r}"); } +/// The first face whose analytic surface satisfies `want`, as a pick. +fn face_of(s: &Session, want: impl Fn(solidcraft_kernel::FaceSurface) -> bool) -> Value { + let st = s.model.state(); + let b = st.bodies.first().unwrap(); + let m = b.mesh(); + let n = m.tri_face.iter().map(|f| *f as usize + 1).max().unwrap(); + let f = (0..n).find(|&f| solidcraft_kernel::face_surface(&b.body, f).is_some_and(&want)).expect("face"); + let p = m.triangles.iter().zip(&m.tri_face).find(|(_, tf)| **tf as usize == f).and_then(|(t, _)| m.tri(t)).unwrap()[0]; + json!({"type": "face", "body": b.name, "index": f, "point": p}) +} + +/// A fillet round the foot of a boss is a toroidal face: it measures its radius (the fillet's) +/// next to its area, and says it is a torus with its ring radius too. +#[test] +fn a_fillet_round_a_boss_reports_its_radius() { + use solidcraft_kernel::FaceSurface; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10})); + run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 12, "base": [20, 20, 10], "operation": "join"})); + run(&mut s, "solid.fillet", json!({"edges": [[25, 20, 10]], "radius": 3})); + let fillet = face_of(&s, |f| matches!(f, FaceSurface::Torus { minor, .. } if (minor - 3.0).abs() < 1e-6)); + let r = measure(&mut s, vec![fillet]); + assert!(close(&r["radius"], 3.0, 1e-6) && close(&r["diameter"], 6.0, 1e-6), "{r}"); + assert_eq!(r["items"][0]["surface"], "torus", "{r}"); + // The ring through the middle of the rolling ball: the boss's radius plus the fillet's. + assert!(close(&r["items"][0]["major_radius"], 8.0, 1e-6), "{r}"); + // The area is still there. + assert!(r["items"][0]["area_mm2"].as_f64().is_some_and(|a| a > 1.0), "{r}"); +} + +/// A ball's face reports its radius. +#[test] +fn a_sphere_face_reports_its_radius() { + use solidcraft_kernel::FaceSurface; + let mut s = Session::default(); + run(&mut s, "solid.sphere", json!({"radius": 7, "center": [0, 0, 0]})); + let ball = face_of(&s, |f| matches!(f, FaceSurface::Sphere { .. })); + let r = measure(&mut s, vec![ball]); + assert!(close(&r["radius"], 7.0, 1e-6) && close(&r["diameter"], 14.0, 1e-6), "{r}"); + assert_eq!(r["items"][0]["surface"], "sphere", "{r}"); +} + /// A plate with holes through STEP: the holes come back as cylinders, and measure the same. #[test] fn step_round_trip_of_a_plate_with_holes() { From 6f368a5b774cb35289b477d7443bb9db1e210a85 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:01:13 +0000 Subject: [PATCH 09/55] Regenerate generated files and fold pending files [skip ci] --- assets/locales/ar.json | 4 ++ assets/locales/de.json | 4 ++ assets/locales/en.json | 4 ++ assets/locales/he.json | 4 ++ assets/locales/ja.json | 4 ++ assets/locales/ko.json | 4 ++ assets/locales/pending/preview-tints.json | 50 ----------------------- assets/locales/vi.json | 4 ++ assets/locales/zh.json | 4 ++ 9 files changed, 32 insertions(+), 50 deletions(-) delete mode 100644 assets/locales/pending/preview-tints.json diff --git a/assets/locales/ar.json b/assets/locales/ar.json index 1ef623195..41a51c841 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -2156,6 +2156,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "الأسطح المنحنية", "prefs.curves": "الأسطح المنحنية", + "prefs.cut_preview_tint": "إظهار المادة المُزالة باللون الأحمر", + "prefs.cut_preview_tint_help": "تملأ المعاينة المادة التي تزيلها الميزة، والشكل الذي تستبدله، بطيف أحمر شبه شفاف. عند الإيقاف تكون هذه التعبئة شفافة تمامًا ولا تُرسم سوى مخططاتها.", "prefs.dark_parts_shading": "الحفاظ على شكل الأجزاء الداكنة", "prefs.dark_parts_shading_help": "تظليل العرض بإضاءة خطية مع إضاءة سماء ناعمة، لتحتفظ الأوجه الداكنة بتدرج بدل أن تصبح سوداء", "prefs.dead_zone_note": "الشريط المخطط هو المنطقة الميتة: تُتجاهل الحركة داخلها.", @@ -2275,6 +2277,8 @@ "prefs.placement": "الموضع", "prefs.prefer_free_sketch_points": "تفضيل نقاط الرسم القابلة للتحريك عند تداخل النقاط", "prefs.preview_choices": "معاينة اختياراتك", + "prefs.preview_tint_new_faces": "تلوين السطح الجديد في المعاينة", + "prefs.preview_tint_new_faces_help": "يمكن لمعاينة ميزة تغيّر جسمًا أن ترسم السطح المضاف بلون المعاينة. عند الإيقاف يُرسم الجسم بلونه الأصلي.", "prefs.print_face_highlight": "إبراز وجه الطباعة", "prefs.print_face_highlight_tip": "مدى قوة تلوين وجه الطباعة للجسم ورسم حدوده في العرض. القيمة 0 % لا تُظهر أي إبراز.", "prefs.profile_active": "ملف التعريف النشط", diff --git a/assets/locales/de.json b/assets/locales/de.json index fb7051139..3385d3f21 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -2154,6 +2154,8 @@ "prefs.ctrl_cmd": "Strg / Cmd", "prefs.curved_surfaces": "Gekrümmte Flächen", "prefs.curves": "Gekrümmte Flächen", + "prefs.cut_preview_tint": "Entferntes Material rot anzeigen", + "prefs.cut_preview_tint_help": "Eine Vorschau füllt das Material, das ein Feature entfernt, sowie die ersetzte Form mit einem roten, durchscheinenden Geist. Wenn deaktiviert, sind diese Füllungen völlig transparent und es werden nur ihre Umrisse gezeichnet.", "prefs.dark_parts_shading": "Form dunkler Teile erhalten", "prefs.dark_parts_shading_help": "Die Ansicht in linearem Licht mit sanftem Himmelslicht schattieren, damit dunkle Flächen einen Verlauf behalten statt schwarz zu werden", "prefs.dead_zone_note": "Der schraffierte Bereich kennzeichnet die Totzone. Bewegungen innerhalb dieses Bereichs werden ignoriert.", @@ -2271,6 +2273,8 @@ "prefs.placement": "Platzierung", "prefs.prefer_free_sketch_points": "Bei überlappenden Punkten bewegliche Skizzenpunkte bevorzugen", "prefs.preview_choices": "Vorschau Ihrer Einstellungen", + "prefs.preview_tint_new_faces": "Neue Fläche in der Vorschau einfärben", + "prefs.preview_tint_new_faces_help": "Eine Vorschau eines Features, das einen Körper ändert, kann die hinzugefügte Fläche in der Vorschaufarbe zeichnen. Wenn deaktiviert, wird der Körper wie er ist gezeichnet.", "prefs.print_face_highlight": "Hervorhebung der Auflagefläche", "prefs.print_face_highlight_tip": "Wie stark die Auflagefläche eines Körpers in der Ansicht eingefärbt und umrandet wird. 0 % zeigt keine Hervorhebung.", "prefs.profile_active": "Aktives Profil", diff --git a/assets/locales/en.json b/assets/locales/en.json index 0972751b6..e1745eebf 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -2156,6 +2156,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Curved surfaces", "prefs.curves": "Curved surfaces", + "prefs.cut_preview_tint": "Show removed material in red", + "prefs.cut_preview_tint_help": "A preview fills the material a feature removes, and the shape it replaces, with a red see-through ghost. When off, those fills are fully transparent and only their outlines are drawn.", "prefs.dark_parts_shading": "Keep the shape of dark parts", "prefs.dark_parts_shading_help": "Shade the view in linear light with a soft sky fill, so dark faces keep a gradient instead of turning black", "prefs.dead_zone_note": "The hatched band is the dead zone: motion inside it is ignored.", @@ -2275,6 +2277,8 @@ "prefs.placement": "Placement", "prefs.prefer_free_sketch_points": "Prefer movable sketch points when points overlap", "prefs.preview_choices": "Preview of your choices", + "prefs.preview_tint_new_faces": "Tint new surface in a preview", + "prefs.preview_tint_new_faces_help": "A preview of a feature that changes a body can draw the surface it adds in the preview colour. When off, the body is drawn as itself.", "prefs.print_face_highlight": "Print face highlight", "prefs.print_face_highlight_tip": "How strongly the print face of a body is tinted and outlined in the view. 0 % shows no highlight.", "prefs.profile_active": "Active profile", diff --git a/assets/locales/he.json b/assets/locales/he.json index 4169dadef..6fc55a7ff 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -2156,6 +2156,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "משטחים מעוקלים", "prefs.curves": "משטחים מעוקלים", + "prefs.cut_preview_tint": "הצגת חומר שהוסר באדום", + "prefs.cut_preview_tint_help": "תצוגה מקדימה ממלאת את החומר שהפעולה מסירה, ואת הצורה שהיא מחליפה, ברוח אדומה שקופה. כשהאפשרות כבויה המילויים האלה שקופים לחלוטין ומצוירים רק קווי המתאר שלהם.", "prefs.dark_parts_shading": "שמירה על צורת חלקים כהים", "prefs.dark_parts_shading_help": "הצללת התצוגה באור ליניארי עם תאורת שמיים רכה, כך שפאות כהות שומרות על מעבר גוונים במקום להפוך לשחורות", "prefs.dead_zone_note": "הפס המקווקו הוא האזור המת: תנועה בתוכו לא נלקחת בחשבון.", @@ -2275,6 +2277,8 @@ "prefs.placement": "מיקום", "prefs.prefer_free_sketch_points": "העדפת נקודות סקיצה ניתנות להזזה כשנקודות חופפות", "prefs.preview_choices": "תצוגה מקדימה של הבחירות שלך", + "prefs.preview_tint_new_faces": "צביעת משטח חדש בתצוגה מקדימה", + "prefs.preview_tint_new_faces_help": "תצוגה מקדימה של פעולה שמשנה גוף יכולה לצבוע את המשטח שנוסף בצבע התצוגה המקדימה. כשהאפשרות כבויה הגוף מצויר בצבעו שלו.", "prefs.print_face_highlight": "הדגשת פאת ההדפסה", "prefs.print_face_highlight_tip": "עד כמה חזק צובעים ומקיפים את פאת ההדפסה של גוף בתצוגה. ‏0 % אינו מציג הדגשה.", "prefs.profile_active": "פרופיל פעיל", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 5dadbc11a..90a4794bb 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -2156,6 +2156,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "曲面", "prefs.curves": "曲面", + "prefs.cut_preview_tint": "除去される材料を赤で表示", + "prefs.cut_preview_tint_help": "プレビューでは、フィーチャーが除去する材料と置き換えられる形状を、赤い透過ゴーストで塗りつぶします。オフにすると、この塗りつぶしは完全に透明になり、輪郭のみが描画されます。", "prefs.dark_parts_shading": "暗い部品の形状を保つ", "prefs.dark_parts_shading_help": "リニア光と柔らかいスカイライトでビューをシェーディングし、暗い面が黒くつぶれずにグラデーションを保つようにします", "prefs.dead_zone_note": "斜線の帯はデッドゾーンです。この範囲内の動きは無視されます。", @@ -2275,6 +2277,8 @@ "prefs.placement": "配置", "prefs.prefer_free_sketch_points": "スケッチ点が重なったときは移動可能な点を優先する", "prefs.preview_choices": "選択した設定のプレビュー", + "prefs.preview_tint_new_faces": "プレビューで新しい面に色を付ける", + "prefs.preview_tint_new_faces_help": "ボディを変更するフィーチャーのプレビューで、追加される面をプレビュー色で描画できます。オフにすると、ボディはそのままの色で描画されます。", "prefs.print_face_highlight": "造形面の強調", "prefs.print_face_highlight_tip": "ビューでボディの造形面を色付けし輪郭を描く強さ。0 % で強調しません。", "prefs.profile_active": "使用中のプロファイル", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 8a7c3d75a..e4ba8d98a 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -1553,6 +1553,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "곡면", "prefs.curves": "곡면", + "prefs.cut_preview_tint": "제거되는 재료를 빨간색으로 표시", + "prefs.cut_preview_tint_help": "미리 보기는 피처가 제거하는 재료와 대체되는 형상을 빨간색 반투명 고스트로 채웁니다. 끄면 이 채움이 완전히 투명해지고 윤곽선만 그려집니다.", "prefs.dark_parts_shading": "어두운 부품의 형태 유지", "prefs.dark_parts_shading_help": "선형 조명과 부드러운 하늘광으로 뷰를 음영 처리하여 어두운 면이 검게 뭉개지지 않고 그라데이션을 유지합니다", "prefs.dead_zone_note": "빗금 친 영역이 데드존입니다. 그 안의 움직임은 무시됩니다.", @@ -1639,6 +1641,8 @@ "prefs.persistent_ribbon_pressed_help": "효과가 켜져 있는 동안 리본 명령을 강조 표시합니다. 끄면 이전의 중립적인 모양과 명령 도움말을 유지합니다.", "prefs.perspective_fov": "시야각", "prefs.preview_choices": "선택 항목 미리보기", + "prefs.preview_tint_new_faces": "미리 보기에서 새 면에 색 입히기", + "prefs.preview_tint_new_faces_help": "바디를 변경하는 피처의 미리 보기에서 추가되는 면을 미리 보기 색으로 그릴 수 있습니다. 끄면 바디가 원래 색으로 그려집니다.", "prefs.print_face_highlight": "출력 바닥면 강조", "prefs.print_face_highlight_tip": "뷰에서 바디의 출력 바닥면을 색칠하고 윤곽을 그리는 강도입니다. 0 %이면 강조하지 않습니다.", "prefs.project_options_dialog": "Project 옵션 대화상자", diff --git a/assets/locales/pending/preview-tints.json b/assets/locales/pending/preview-tints.json deleted file mode 100644 index 86db8893b..000000000 --- a/assets/locales/pending/preview-tints.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "ar": { - "prefs.cut_preview_tint": "إظهار المادة المُزالة باللون الأحمر", - "prefs.cut_preview_tint_help": "تملأ المعاينة المادة التي تزيلها الميزة، والشكل الذي تستبدله، بطيف أحمر شبه شفاف. عند الإيقاف تكون هذه التعبئة شفافة تمامًا ولا تُرسم سوى مخططاتها.", - "prefs.preview_tint_new_faces": "تلوين السطح الجديد في المعاينة", - "prefs.preview_tint_new_faces_help": "يمكن لمعاينة ميزة تغيّر جسمًا أن ترسم السطح المضاف بلون المعاينة. عند الإيقاف يُرسم الجسم بلونه الأصلي." - }, - "de": { - "prefs.cut_preview_tint": "Entferntes Material rot anzeigen", - "prefs.cut_preview_tint_help": "Eine Vorschau füllt das Material, das ein Feature entfernt, sowie die ersetzte Form mit einem roten, durchscheinenden Geist. Wenn deaktiviert, sind diese Füllungen völlig transparent und es werden nur ihre Umrisse gezeichnet.", - "prefs.preview_tint_new_faces": "Neue Fläche in der Vorschau einfärben", - "prefs.preview_tint_new_faces_help": "Eine Vorschau eines Features, das einen Körper ändert, kann die hinzugefügte Fläche in der Vorschaufarbe zeichnen. Wenn deaktiviert, wird der Körper wie er ist gezeichnet." - }, - "en": { - "prefs.cut_preview_tint": "Show removed material in red", - "prefs.cut_preview_tint_help": "A preview fills the material a feature removes, and the shape it replaces, with a red see-through ghost. When off, those fills are fully transparent and only their outlines are drawn.", - "prefs.preview_tint_new_faces": "Tint new surface in a preview", - "prefs.preview_tint_new_faces_help": "A preview of a feature that changes a body can draw the surface it adds in the preview colour. When off, the body is drawn as itself." - }, - "he": { - "prefs.cut_preview_tint": "הצגת חומר שהוסר באדום", - "prefs.cut_preview_tint_help": "תצוגה מקדימה ממלאת את החומר שהפעולה מסירה, ואת הצורה שהיא מחליפה, ברוח אדומה שקופה. כשהאפשרות כבויה המילויים האלה שקופים לחלוטין ומצוירים רק קווי המתאר שלהם.", - "prefs.preview_tint_new_faces": "צביעת משטח חדש בתצוגה מקדימה", - "prefs.preview_tint_new_faces_help": "תצוגה מקדימה של פעולה שמשנה גוף יכולה לצבוע את המשטח שנוסף בצבע התצוגה המקדימה. כשהאפשרות כבויה הגוף מצויר בצבעו שלו." - }, - "ja": { - "prefs.cut_preview_tint": "除去される材料を赤で表示", - "prefs.cut_preview_tint_help": "プレビューでは、フィーチャーが除去する材料と置き換えられる形状を、赤い透過ゴーストで塗りつぶします。オフにすると、この塗りつぶしは完全に透明になり、輪郭のみが描画されます。", - "prefs.preview_tint_new_faces": "プレビューで新しい面に色を付ける", - "prefs.preview_tint_new_faces_help": "ボディを変更するフィーチャーのプレビューで、追加される面をプレビュー色で描画できます。オフにすると、ボディはそのままの色で描画されます。" - }, - "ko": { - "prefs.cut_preview_tint": "제거되는 재료를 빨간색으로 표시", - "prefs.cut_preview_tint_help": "미리 보기는 피처가 제거하는 재료와 대체되는 형상을 빨간색 반투명 고스트로 채웁니다. 끄면 이 채움이 완전히 투명해지고 윤곽선만 그려집니다.", - "prefs.preview_tint_new_faces": "미리 보기에서 새 면에 색 입히기", - "prefs.preview_tint_new_faces_help": "바디를 변경하는 피처의 미리 보기에서 추가되는 면을 미리 보기 색으로 그릴 수 있습니다. 끄면 바디가 원래 색으로 그려집니다." - }, - "vi": { - "prefs.cut_preview_tint": "Hiển thị vật liệu bị loại bỏ bằng màu đỏ", - "prefs.cut_preview_tint_help": "Bản xem trước tô vật liệu mà đặc trưng loại bỏ, và hình dạng mà nó thay thế, bằng một bóng mờ màu đỏ. Khi tắt, các phần tô này hoàn toàn trong suốt và chỉ vẽ đường viền của chúng.", - "prefs.preview_tint_new_faces": "Tô màu bề mặt mới trong bản xem trước", - "prefs.preview_tint_new_faces_help": "Bản xem trước của một đặc trưng làm thay đổi một khối có thể vẽ bề mặt được thêm vào bằng màu xem trước. Khi tắt, khối được vẽ bằng màu của chính nó." - }, - "zh": { - "prefs.cut_preview_tint": "以红色显示被移除的材料", - "prefs.cut_preview_tint_help": "预览会用红色半透明幻影填充特征所移除的材料以及被替换的形状。关闭时,这些填充完全透明,仅绘制其轮廓。", - "prefs.preview_tint_new_faces": "在预览中为新表面着色", - "prefs.preview_tint_new_faces_help": "更改实体的特征,其预览可以用预览颜色绘制新增的表面。关闭时,实体按自身颜色绘制。" - } -} diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 76ef51fd9..96a3d5a5c 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -2156,6 +2156,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "Các mặt cong", "prefs.curves": "Các đường cong", + "prefs.cut_preview_tint": "Hiển thị vật liệu bị loại bỏ bằng màu đỏ", + "prefs.cut_preview_tint_help": "Bản xem trước tô vật liệu mà đặc trưng loại bỏ, và hình dạng mà nó thay thế, bằng một bóng mờ màu đỏ. Khi tắt, các phần tô này hoàn toàn trong suốt và chỉ vẽ đường viền của chúng.", "prefs.dark_parts_shading": "Giữ hình dạng của chi tiết tối", "prefs.dark_parts_shading_help": "Tô bóng khung nhìn bằng ánh sáng tuyến tính với ánh sáng bầu trời dịu, để các mặt tối giữ được dải chuyển màu thay vì thành màu đen", "prefs.dead_zone_note": "Dải sọc chéo là vùng chết: các chuyển động bên trong vùng này sẽ bị bỏ qua.", @@ -2275,6 +2277,8 @@ "prefs.placement": "Vị trí đặt", "prefs.prefer_free_sketch_points": "Ưu tiên điểm phác thảo có thể di chuyển khi các điểm chồng lên nhau", "prefs.preview_choices": "Xem trước các lựa chọn của bạn", + "prefs.preview_tint_new_faces": "Tô màu bề mặt mới trong bản xem trước", + "prefs.preview_tint_new_faces_help": "Bản xem trước của một đặc trưng làm thay đổi một khối có thể vẽ bề mặt được thêm vào bằng màu xem trước. Khi tắt, khối được vẽ bằng màu của chính nó.", "prefs.print_face_highlight": "Tô sáng mặt in", "prefs.print_face_highlight_tip": "Mức tô màu và viền mặt in của thân trong khung nhìn. 0 % không tô sáng.", "prefs.profile_active": "Hồ sơ đang dùng", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 485a95b06..4cddb9f28 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -2156,6 +2156,8 @@ "prefs.ctrl_cmd": "Ctrl / Cmd", "prefs.curved_surfaces": "曲面", "prefs.curves": "曲面", + "prefs.cut_preview_tint": "以红色显示被移除的材料", + "prefs.cut_preview_tint_help": "预览会用红色半透明幻影填充特征所移除的材料以及被替换的形状。关闭时,这些填充完全透明,仅绘制其轮廓。", "prefs.dark_parts_shading": "保持深色零件的形状", "prefs.dark_parts_shading_help": "以线性光照和柔和的天空补光着色视图,使深色面保留渐变而不变成一片黑色", "prefs.dead_zone_note": "斜线区域为死区:此范围内的移动将被忽略。", @@ -2275,6 +2277,8 @@ "prefs.placement": "放置", "prefs.prefer_free_sketch_points": "草图点重合时优先选择可移动的点", "prefs.preview_choices": "所选设置预览", + "prefs.preview_tint_new_faces": "在预览中为新表面着色", + "prefs.preview_tint_new_faces_help": "更改实体的特征,其预览可以用预览颜色绘制新增的表面。关闭时,实体按自身颜色绘制。", "prefs.print_face_highlight": "打印底面高亮", "prefs.print_face_highlight_tip": "视图中实体打印底面的着色和轮廓强度。0 % 不显示高亮。", "prefs.profile_active": "当前配置文件", From 862807ffc9a96eb6acedb0a1fb2220d15c294d02 Mon Sep 17 00:00:00 2001 From: semmelrinde <124386289+semmelrinde@users.noreply.github.com> Date: Sun, 1 Nov 2026 18:20:40 +0000 Subject: [PATCH 10/55] Lost GPU: the per-frame probe meets a D3D12 device reset before the first upload does (#6528) (#7767) * claim: #6528 Co-Authored-By: Claude Opus 5.5 * Lost GPU: the per-frame probe opens a command list, as the upload would (#6528) On a reset D3D12 device the empty submission before a frame's uploads went through (it only signals a fence), and the first queue write then panicked inside wgpu-core (PendingWrites::activate unwrapping Lost). The probe now submits a command buffer with a debug marker: finishing it makes the same begin_encoding call, through a path where wgpu loses the device and runs its lost callback instead of panicking. The picture capturer's probe does the same. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/gpu/src/capture.rs | 10 ++++++--- crates/ui-egui/src/gpu.rs | 39 +++++++++++++++++++++++++++++++++-- vendor/README.md | 7 ++++--- vendor/egui-wgpu/src/lib.rs | 22 ++++++++++++++------ vendor/egui-wgpu/src/winit.rs | 11 ++++++---- 5 files changed, 71 insertions(+), 18 deletions(-) diff --git a/crates/gpu/src/capture.rs b/crates/gpu/src/capture.rs index c82e2bab3..3f139d7d0 100644 --- a/crates/gpu/src/capture.rs +++ b/crates/gpu/src/capture.rs @@ -106,13 +106,17 @@ impl Capturer { self.lost.load(Ordering::Acquire) } - /// [`Capturer::is_lost`], asking the driver first: an empty submission meets a loss the - /// driver reports and marks it, where the picture's first upload would panic inside wgpu. + /// [`Capturer::is_lost`], asking the driver first: a submission that opens a command list + /// meets a loss the driver reports and marks it, where the picture's first upload would + /// panic inside wgpu. As `egui_wgpu::DeviceLost::probe`: an empty submission only signals a + /// fence, which a reset D3D12 device let through (#6528). fn probe_lost(&self) -> bool { if self.is_lost() { return true; } - self.queue.submit([]); + let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("device lost probe") }); + encoder.insert_debug_marker("device lost probe"); + self.queue.submit([encoder.finish()]); self.is_lost() } diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index efc1dcbe4..bed4fe976 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -1189,7 +1189,7 @@ mod tests { let capturer = solidcraft_gpu::capture::Capturer::new(&adapter, device.clone(), queue.clone()).unwrap().watching(lost.flag()); let (scene, cam) = (solidcraft_engine::render::Scene::default(), solidcraft_engine::render::Camera::default()); assert_ne!(super::picture(&capturer, &scene, &cam, 16, 16).unwrap().renderer, "cpu"); - assert!(!lost.probe(&queue), "a working device isn't lost"); + assert!(!lost.probe(&device, &queue), "a working device isn't lost"); // egui's renderer is made with the window, before any loss (made on a lost device, its // uniform buffer's `create_buffer_init` panics). @@ -1197,7 +1197,7 @@ mod tests { device.destroy(); let _ = device.poll(wgpu::PollType::wait_indefinitely()); - assert!(lost.is_lost() && lost.probe(&queue), "the lost callback marked the device"); + assert!(lost.is_lost() && lost.probe(&device, &queue), "the lost callback marked the device"); assert!(lost.reason().is_some_and(|r| r.starts_with("Destroyed")), "{:?}", lost.reason()); // The next frame's uploads, as the painter would make them were it not skipping: wgpu @@ -1210,4 +1210,39 @@ mod tests { let picture = super::picture(&capturer, &scene, &cam, 16, 16).unwrap(); assert_eq!((picture.renderer, picture.rgba.len()), ("cpu", 16 * 16 * 4)); } + + /// The probe runs before every frame's uploads, so on a working device it must cost nothing + /// visible: no error for any scope or handler, and the uploads after it go through. On a + /// reset D3D12 device an empty submission went through and the upload after it panicked + /// inside wgpu (#6528); the probe now opens a command list, the driver call that upload's + /// queue write would make first. A driver reset can't be made here: `destroy` loses the + /// device in wgpu itself, before any driver call. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_lost_device_probe_is_clean_on_a_working_device() { + use egui_wgpu::wgpu; + let Some((adapter, device, queue)) = super::offscreen_device() else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let lost = egui_wgpu::DeviceLost::watch(&device); + let capturer = solidcraft_gpu::capture::Capturer::new(&adapter, device.clone(), queue.clone()).unwrap().watching(lost.flag()); + let mut renderer = egui_wgpu::Renderer::new(&device, wgpu::TextureFormat::Rgba8Unorm, Default::default()); + let image = egui::ImageData::Color(std::sync::Arc::new(egui::ColorImage::filled([4, 4], egui::Color32::WHITE))); + let delta = egui::epaint::ImageDelta::full(image, egui::TextureOptions::LINEAR); + let (scene, cam) = (solidcraft_engine::render::Scene::default(), solidcraft_engine::render::Camera::default()); + for frame in 0..3 { + // As the painter: the probe, then the frame's first queue write. + let (was_lost, error) = egui_wgpu::capture_errors(&device, || { + let was_lost = lost.probe(&device, &queue); + renderer.update_texture(&device, &queue, egui::TextureId::Managed(0), &delta); + was_lost + }); + assert!(!was_lost && error.is_none(), "frame {frame}: lost {was_lost}, {error:?}"); + // A save's thumbnail, which probes too, still comes from the GPU. + assert_ne!(super::picture(&capturer, &scene, &cam, 16, 16).unwrap().renderer, "cpu"); + } + let _ = device.poll(wgpu::PollType::wait_indefinitely()); + assert!(!lost.is_lost() && lost.reason().is_none(), "{:?}", lost.reason()); + } } diff --git a/vendor/README.md b/vendor/README.md index c48dd8133..3d4c19969 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -341,9 +341,10 @@ SolidCraft changes: compositor wasn't showing stalled the main window behind its present. - `src/lib.rs`, `src/winit.rs`: the device's lost callback marks `RenderState::device_lost` (`DeviceLost`), and the painter draws nothing on a lost device. Before a frame's uploads it - submits nothing (`DeviceLost::probe`), so a device the driver lost is found by that - submission rather than by the first queue write, which panicked inside wgpu-core - (`PendingWrites::activate`, #4172). + submits a command buffer holding a debug marker (`DeviceLost::probe`), so a device the + driver lost is found by opening that command list rather than by the first queue write, + which panicked inside wgpu-core (`PendingWrites::activate`, #4172). An empty submission + only signalled a fence, which a reset D3D12 device let through (#6528). - `src/lib.rs`, `src/winit.rs`: a surface configure that meets a lost device is not taken as configured (`configure_captured`): wgpu reports device-loss errors to no error scope, and on D3D12 a driver reset found by the configure has already dropped the surface's configuration. diff --git a/vendor/egui-wgpu/src/lib.rs b/vendor/egui-wgpu/src/lib.rs index 439e5400f..773207ea4 100644 --- a/vendor/egui-wgpu/src/lib.rs +++ b/vendor/egui-wgpu/src/lib.rs @@ -140,8 +140,8 @@ impl SurfaceConfig { /// A lost device can't be used again. wgpu only learns of the loss when a call into the driver /// fails: from then on every call on the device fails quietly, and the device's lost callback /// marks this. But a queue write that is the first call to meet the loss panics inside wgpu -/// (`PendingWrites::activate`), so the painter first submits nothing ([`DeviceLost::probe`]): -/// that submission meets the loss instead, and the frame's uploads are skipped. +/// (`PendingWrites::activate`), so the painter first probes the device ([`DeviceLost::probe`]): +/// the probe meets the loss instead, and the frame's uploads are skipped. #[derive(Clone, Debug, Default)] pub struct DeviceLost { lost: Arc, @@ -183,13 +183,23 @@ impl DeviceLost { self.lost.clone() } - /// Whether the device is lost, asking the driver first: an empty submission reaches the - /// driver, so a loss it reports is marked here rather than met by the next upload. - pub fn probe(&self, queue: &wgpu::Queue) -> bool { + /// Whether the device is lost, asking the driver first, so a loss it reports is marked here + /// rather than met by the next upload. + /// + /// The probe opens a command list, as the upload would: a queue write's first call into the + /// driver is `begin_encoding`, and on D3D12 that is where a reset device says so. An empty + /// submission only signals a fence: #6528 met a reset D3D12 device in the upload right after + /// one. wgpu handles a failed `begin_encoding` in a command encoder's `finish` (it loses the + /// device, and the lost callback marks it); only its queue writes unwrap it. + pub fn probe(&self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool { if self.is_lost() { return true; } - queue.submit([]); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("device lost probe"), + }); + encoder.insert_debug_marker("device lost probe"); + queue.submit([encoder.finish()]); self.is_lost() } } diff --git a/vendor/egui-wgpu/src/winit.rs b/vendor/egui-wgpu/src/winit.rs index 0784fefc1..bc671a80d 100644 --- a/vendor/egui-wgpu/src/winit.rs +++ b/vendor/egui-wgpu/src/winit.rs @@ -806,10 +806,13 @@ impl Painter { let texture = frame.texture.clone(); let output_frame = crate::AcquiredFrame::new(frame, texture); - // SolidCraft: before the uploads, an empty submission asks the driver whether the device - // is still there. The first queue write to meet a lost device panics inside wgpu (#4172); - // the submission meets it instead, marks it lost, and the frame is dropped unpresented. - if render_state.device_lost.probe(&render_state.queue) { + // SolidCraft: before the uploads, a probe asks the driver whether the device is still + // there. The first queue write to meet a lost device panics inside wgpu (#4172, #6528); + // the probe meets it instead, marks it lost, and the frame is dropped unpresented. + if render_state + .device_lost + .probe(&render_state.device, &render_state.queue) + { if let Some(effect) = &render_state.renderer.read().frame_compositor { effect.suspend(); } From bdce595fb3a60e38c43ae2f2ae33f68b7a18c47e Mon Sep 17 00:00:00 2001 From: Nathan Dane Date: Sun, 1 Nov 2026 18:30:11 +0000 Subject: [PATCH 11/55] Render results: retained renders, Live and render compare, render all shots (#6281) (#7375) * Render results: keep up to eight completed renders and select or discard them * Render results: Live and render compare with a divider, and render all shots * fix: use comparison theme tint and reveal reset test targets * fix: restore Unicode expectations in render workspace tests --- Cargo.lock | 1 + assets/locales/pending/render-results.json | 162 ++++++ crates/engine/src/cmd/render.rs | 12 +- crates/engine/src/cmd/render/job_tests.rs | 15 +- crates/engine/src/cmd/render/jobs.rs | 63 ++- crates/engine/src/cmd/render_ui.rs | 503 +++++++++++++++++- crates/engine/src/render_jobs.rs | 265 ++++++++- crates/engine/src/schema/render_ui.rs | 67 ++- crates/render/Cargo.toml | 1 + crates/render/src/job/host.rs | 11 + crates/render/src/job/host_tests.rs | 19 + crates/ui-egui/src/documents.rs | 17 + crates/ui-egui/src/lib.rs | 5 +- crates/ui-egui/src/render_ui/mod.rs | 9 + crates/ui-egui/src/render_workspace.rs | 197 ++++++- .../ui-egui/src/render_workspace_compare.rs | 291 ++++++++++ .../ui-egui/src/render_workspace_inspector.rs | 23 + crates/ui-egui/src/render_workspace_ribbon.rs | 35 +- crates/ui-egui/src/render_workspace_shots.rs | 4 + crates/ui-egui/src/render_workspace_tests.rs | 382 ++++++++++++- crates/ui-egui/src/ui_kit/compare.rs | 55 ++ crates/ui-egui/src/ui_kit/gallery.rs | 9 + crates/ui-egui/src/ui_kit/mod.rs | 2 + .../ui-egui/src/ui_kit/test_support_tests.rs | 23 + docs/render-workspace.md | 35 +- docs/ui-kit.md | 1 + 26 files changed, 2110 insertions(+), 97 deletions(-) create mode 100644 assets/locales/pending/render-results.json create mode 100644 crates/ui-egui/src/render_workspace_compare.rs create mode 100644 crates/ui-egui/src/ui_kit/compare.rs diff --git a/Cargo.lock b/Cargo.lock index 2a1f185ca..c98f5fa9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4399,6 +4399,7 @@ dependencies = [ "serde_json", "sha2 0.10.9", "solidcraft-geom", + "web-time", "weezl", ] diff --git a/assets/locales/pending/render-results.json b/assets/locales/pending/render-results.json new file mode 100644 index 000000000..4bbd18232 --- /dev/null +++ b/assets/locales/pending/render-results.json @@ -0,0 +1,162 @@ +{ + "en": { + "cmd.render.compare.divider": "Move Render Comparison Divider", + "cmd.render.result.discard": "Discard Render Result", + "cmd.render.result.select": "Select Render Result", + "render.batch_all_shots": "All shots ({count})", + "render.batch_empty": "Save a shot before rendering all shots.", + "render.batch_limit": "Render all shots is limited to 32 shots.", + "render.batch_status": "{running} running · {waiting} waiting", + "render.compare_divider": "Comparison divider", + "render.compare_live": "Live", + "render.compare_live_preview": "Live preview", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · captured at revision {revision}", + "render.compare_swap": "Swap", + "render.results_choose": "Retained results", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [stale]", + "render.results_unnamed": "Image" + }, + "de": { + "cmd.render.compare.divider": "Render-Vergleichstrenner verschieben", + "cmd.render.result.discard": "Renderergebnis verwerfen", + "cmd.render.result.select": "Renderergebnis auswählen", + "render.batch_all_shots": "Alle Ansichten ({count})", + "render.batch_empty": "Vor dem Rendern aller Ansichten eine Ansicht speichern.", + "render.batch_limit": "Es können höchstens 32 Ansichten gerendert werden.", + "render.batch_status": "{running} läuft · {waiting} warten", + "render.compare_divider": "Vergleichstrenner", + "render.compare_live": "Live", + "render.compare_live_preview": "Live-Vorschau", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · aufgenommen bei Revision {revision}", + "render.compare_swap": "Tauschen", + "render.results_choose": "Behaltene Ergebnisse", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [veraltet]", + "render.results_unnamed": "Bild" + }, + "ja": { + "cmd.render.compare.divider": "レンダー比較の境界を移動", + "cmd.render.result.discard": "レンダリング結果を破棄", + "cmd.render.result.select": "レンダリング結果を選択", + "render.batch_all_shots": "すべてのショット ({count})", + "render.batch_empty": "すべてのショットをレンダリングする前にショットを保存してください。", + "render.batch_limit": "一度にレンダリングできるショットは32個までです。", + "render.batch_status": "{running} 実行中 · {waiting} 待機中", + "render.compare_divider": "比較の境界", + "render.compare_live": "ライブ", + "render.compare_live_preview": "ライブプレビュー", + "render.compare_render": "レンダー {number}", + "render.compare_side": "レンダー {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · リビジョン {revision} で取得", + "render.compare_swap": "入れ替え", + "render.results_choose": "保持した結果", + "render.results_label": "レンダー {number} · {shot} · {seconds} 秒", + "render.results_stale_label": "{result} [更新前]", + "render.results_unnamed": "画像" + }, + "ko": { + "cmd.render.compare.divider": "렌더 비교 구분선 이동", + "cmd.render.result.discard": "렌더 결과 버리기", + "cmd.render.result.select": "렌더 결과 선택", + "render.batch_all_shots": "모든 샷 ({count})", + "render.batch_empty": "모든 샷을 렌더링하기 전에 샷을 저장하세요.", + "render.batch_limit": "한 번에 최대 32개의 샷을 렌더링할 수 있습니다.", + "render.batch_status": "{running}개 실행 중 · {waiting}개 대기 중", + "render.compare_divider": "비교 구분선", + "render.compare_live": "라이브", + "render.compare_live_preview": "라이브 미리보기", + "render.compare_render": "렌더 {number}", + "render.compare_side": "렌더 {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds}초 · {renderer} · 리비전 {revision}에서 캡처", + "render.compare_swap": "맞바꾸기", + "render.results_choose": "보관된 결과", + "render.results_label": "렌더 {number} · {shot} · {seconds}초", + "render.results_stale_label": "{result} [이전 버전]", + "render.results_unnamed": "이미지" + }, + "zh": { + "cmd.render.compare.divider": "移动渲染比较分隔线", + "cmd.render.result.discard": "丢弃渲染结果", + "cmd.render.result.select": "选择渲染结果", + "render.batch_all_shots": "所有镜头 ({count})", + "render.batch_empty": "渲染所有镜头前请先保存镜头。", + "render.batch_limit": "一次最多渲染32个镜头。", + "render.batch_status": "{running} 个运行中 · {waiting} 个等待中", + "render.compare_divider": "比较分隔线", + "render.compare_live": "实时", + "render.compare_live_preview": "实时预览", + "render.compare_render": "渲染 {number}", + "render.compare_side": "渲染 {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · 捕获于修订版 {revision}", + "render.compare_swap": "交换", + "render.results_choose": "保留的结果", + "render.results_label": "渲染 {number} · {shot} · {seconds} 秒", + "render.results_stale_label": "{result} [已过期]", + "render.results_unnamed": "图像" + }, + "ar": { + "cmd.render.compare.divider": "تحريك فاصل مقارنة التصيير", + "cmd.render.result.discard": "تجاهل نتيجة التصيير", + "cmd.render.result.select": "تحديد نتيجة التصيير", + "render.batch_all_shots": "كل اللقطات ({count})", + "render.batch_empty": "احفظ لقطة قبل تصيير كل اللقطات.", + "render.batch_limit": "تصيير كل اللقطات محدود بـ 32 لقطة.", + "render.batch_status": "{running} قيد التشغيل · {waiting} في الانتظار", + "render.compare_divider": "فاصل المقارنة", + "render.compare_live": "حي", + "render.compare_live_preview": "معاينة حية", + "render.compare_render": "التصيير {number}", + "render.compare_side": "التصيير {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} ث · {renderer} · التُقطت عند المراجعة {revision}", + "render.compare_swap": "تبديل", + "render.results_choose": "النتائج المحتفظ بها", + "render.results_label": "التصيير {number} · {shot} · {seconds} ث", + "render.results_stale_label": "{result} [قديم]", + "render.results_unnamed": "صورة" + }, + "he": { + "cmd.render.compare.divider": "הזז את מחיצת ההשוואה של הרינדור", + "cmd.render.result.discard": "השלך תוצאת רינדור", + "cmd.render.result.select": "בחר תוצאת רינדור", + "render.batch_all_shots": "כל הצילומים ({count})", + "render.batch_empty": "שמור צילום לפני רינדור כל הצילומים.", + "render.batch_limit": "רינדור כל הצילומים מוגבל ל-32 צילומים.", + "render.batch_status": "{running} רצים · {waiting} ממתינים", + "render.compare_divider": "מחיצת השוואה", + "render.compare_live": "חי", + "render.compare_live_preview": "תצוגה חיה", + "render.compare_render": "רינדור {number}", + "render.compare_side": "רינדור {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} שנ׳ · {renderer} · נקלט בגרסה {revision}", + "render.compare_swap": "החלף", + "render.results_choose": "תוצאות שנשמרו", + "render.results_label": "רינדור {number} · {shot} · {seconds} שנ׳", + "render.results_stale_label": "{result} [ישן]", + "render.results_unnamed": "תמונה" + }, + "vi": { + "cmd.render.compare.divider": "Di chuyển vạch so sánh kết xuất", + "cmd.render.result.discard": "Bỏ kết quả kết xuất", + "cmd.render.result.select": "Chọn kết quả kết xuất", + "render.batch_all_shots": "Mọi cảnh chụp ({count})", + "render.batch_empty": "Hãy lưu một cảnh chụp trước khi kết xuất mọi cảnh chụp.", + "render.batch_limit": "Kết xuất mọi cảnh chụp giới hạn ở 32 cảnh chụp.", + "render.batch_status": "{running} đang chạy · {waiting} đang chờ", + "render.compare_divider": "Vạch so sánh", + "render.compare_live": "Trực tiếp", + "render.compare_live_preview": "Xem trước trực tiếp", + "render.compare_render": "Kết xuất {number}", + "render.compare_side": "Kết xuất {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} giây · {renderer} · ghi tại bản sửa {revision}", + "render.compare_swap": "Hoán đổi", + "render.results_choose": "Kết quả được giữ lại", + "render.results_label": "Kết xuất {number} · {shot} · {seconds} giây", + "render.results_stale_label": "{result} [cũ]", + "render.results_unnamed": "Ảnh" + } +} diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs index de8a6f697..64001d6c0 100644 --- a/crates/engine/src/cmd/render.rs +++ b/crates/engine/src/cmd/render.rs @@ -68,7 +68,7 @@ pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("render.optics.unbind","Remove Optical Binding",optical_bindings::unbind).icon("appearance").doc_only() .params("name: saved setup; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that optical assignment in one undo without a device or file access."), CommandSpec::new("render.result.regrade", "Regrade Linear Master", jobs::regrade).icon("render_image").noundo().doc_only() - .params("job: exact completed JobId; presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."), + .params("job?: exact completed JobId (default selected result); presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."), CommandSpec::new("render.camera.set", "Set Render Camera", set_camera).icon("camera").noundo().doc_only() .params("camera: complete Render Camera snapshot (target, yaw, pitch, distance, fov; roll defaults to 0 and up to z). Validates the same finite mm/radian bounds as saved render intent, preserves explicit roll/up and changes only transient view state. No model evaluation, setup save, renderer, dirty flag or undo step. Design view.apply retains its separate up-axis policy."), CommandSpec::new("render.camera.get", "Inspect Render Camera", get_camera).icon("camera").noundo() @@ -102,7 +102,7 @@ CommandSpec::new("render.library.surface.bind", "Save Surface Binding", surface_ CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", surface_bindings::unbind).icon("appearance").doc_only() .params("name: setup, target: saved definition/feature/component/occurrence_path, set?: setup patch. Removes only that explicit binding in one undo; no device or current geometry required."), CommandSpec::new("render.result.pin", "Retain Displayed Render Result", jobs::pin).icon("inspect").noundo().doc_only() - .params("job: completed JobId, or null to release the displayed-result pin. Retains at most one completed result independently of a newer completion; preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."), + .params("job?: completed JobId (default selected result), or null to clear selection. Selects within the eight retained completed results; oldest is evicted first. Preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."), CommandSpec::new("render.library.targets", "Find Render Library Targets", library::targets).icon("list").noundo() .params("query?: exact-name substring; offset?:0; limit?:128 (1..128). Returns a bounded page of captured body ordinals/names, revision and scene bounds. Settles the model through ordinary command handling; never returns a large mesh payload."), CommandSpec::new("render.library.list", "Browse Render Library", library::list).icon("list").noundo().doc_only() @@ -128,13 +128,13 @@ CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).ic CommandSpec::new("render.start", "Render Image", jobs::start).key("R").noundo().doc_only().at("RENDER", "IMAGE").icon("render_image") .params("Same request as render.preflight. Captures an immutable product scene and queues a bounded image job. Returns its session-scoped job identity, captured scene_generation and progress. Does not change the design. See docs/render-jobs.md"), CommandSpec::new("render.status", "Render Progress", jobs::status).icon("list").noundo().doc_only() - .params("job: {session, serial, generation}. Non-blocking progress, error, optional CPU preview metadata {frame_sequence,samples_per_pixel,frame}, and completed frame metadata, optional sampling allocation/work counts and retained-master presentation provenance; no image bytes and no rendering in this call. Preview is separate from the exportable final image."), + .params("job?: {session, serial, generation}. Non-blocking progress, errors and captured frame metadata with queue:{running,waiting,job,shot,error}. Without job returns queue only. Advances an explicitly started render.batch through render.start as jobs finish; never pumps render work. Preview is separate from the exportable final image."), CommandSpec::new("render.cancel", "Cancel Render", jobs::cancel).icon("delete").noundo().doc_only() - .params("job: {session, serial, generation}. Requests cooperative cancellation; completed jobs remain completed. Late cancelled frames cannot be published."), + .params("job?: {session, serial, generation}, default the active render.batch job. Requests cooperative cancellation and drops its waiting shots; completed jobs remain completed. Late cancelled frames cannot be published."), CommandSpec::new("render.result.copy", "Copy Render Image", jobs::copy).icon("copy").noundo().doc_only() - .params("job: completed JobId. Validates the retained PNG for app clipboard copying (max 4096 per side, 4194304 pixels); headless returns frame metadata only. Never copies a provisional image or starts a job."), + .params("job?: completed JobId (default selected result). Validates the retained PNG for app clipboard copying (max 4096 per side, 4194304 pixels); headless returns frame metadata only. Never copies a provisional image or starts a job."), CommandSpec::new("render.export", "Export Render Image", jobs::export).icon("export").noundo().doc_only() - .params("job: {session, serial, generation}, path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"), + .params("job?: {session, serial, generation} (default selected result), path: destination matching format?: png (default) or exr, overwrite?: false. EXR requires an opt-in raw linear master retained by that completed GPU job; never converts PNG pixels. Exports a retained completed image atomically; an existing destination is preserved on failure. See docs/render-jobs.md"), CommandSpec::new("render.backends", "Render Backends", backends).icon("list") .noundo() .doc_only() diff --git a/crates/engine/src/cmd/render/job_tests.rs b/crates/engine/src/cmd/render/job_tests.rs index 02ee106a0..f15ddeff3 100644 --- a/crates/engine/src/cmd/render/job_tests.rs +++ b/crates/engine/src/cmd/render/job_tests.rs @@ -1052,6 +1052,14 @@ fn completed_png_content_identity_matches_status_and_exact_retained_export() { finish(&host); let newer = s.execute("render.status", &json!({"job":replacement})).unwrap(); assert_ne!(newer["frame"]["png_sha256"], metadata["png_sha256"]); + let still_retained = dir.join("still-retained.png"); + s.execute("render.export", &json!({"job":id,"path":still_retained})).unwrap(); + assert_eq!(std::fs::read(still_retained).unwrap(), bytes); + for _ in 0..7 { + let next = start(&mut s); + finish(&host); + s.execute("render.status", &json!({"job":next})).unwrap(); + } let evicted = dir.join("evicted.png"); assert!(s.execute("render.export", &json!({"job":id,"path":evicted})).is_err()); assert!(!evicted.exists()); @@ -1281,7 +1289,12 @@ fn output_viewer_copy_validates_completed_job_without_mutation_or_pixel_payloads assert_eq!(copied["frame"]["job"], json!(job)); assert_eq!(copied["frame"]["width"], 16); assert!(copied.get("png").is_none()); - for params in [json!({}), json!(null), json!({"job":job,"extra":true}), json!({"job":{"session":0,"serial":0,"generation":0}})] { + for params in [json!({}), json!(null)] { + assert_eq!(s.execute("render.result.copy", ¶ms).unwrap(), copied, "an omitted job uses the selected result"); + } + for params in + [json!({"job":1e300}), json!({"job":"selected"}), json!({"job":job,"extra":true}), json!({"job":{"session":0,"serial":0,"generation":0}})] + { assert!(s.execute("render.result.copy", ¶ms).is_err()); } assert!(Arc::ptr_eq(&document, &s.doc)); diff --git a/crates/engine/src/cmd/render/jobs.rs b/crates/engine/src/cmd/render/jobs.rs index b0b0b29de..86d4161db 100644 --- a/crates/engine/src/cmd/render/jobs.rs +++ b/crates/engine/src/cmd/render/jobs.rs @@ -675,7 +675,12 @@ pub(super) fn start(s: &mut Session, params: &Value) -> Result { p.scene, p.request, p.replace, - crate::render_jobs::Execution { executor: p.executor, options: p.options, environment: p.environment }, + crate::render_jobs::Execution { + executor: p.executor, + options: p.options, + environment: p.environment, + shot: params.get("setup").and_then(Value::as_str).map(str::to_owned), + }, ) .map_err(job_error)?; let mut status = json!(status); @@ -688,24 +693,32 @@ pub(super) fn start(s: &mut Session, params: &Value) -> Result { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Regrade { - job: JobId, + job: Option, presentation: solidcraft_render::job::presentation::Presentation, } pub(super) fn regrade(s: &mut Session, params: &Value) -> Result { let input: Regrade = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.regrade", e.to_string()))?; input.presentation.validate().map_err(job_error)?; - Ok(json!(s.render_jobs.regrade(input.job, input.presentation).map_err(job_error)?)) + let job = result_source(s, input.job, "render.result.regrade")?; + Ok(json!(s.render_jobs.regrade(job, input.presentation).map_err(job_error)?)) } -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Job { - job: JobId, +fn result_source(s: &mut Session, job: Option, command: &str) -> Result { + s.render_jobs.collect().map_err(job_error)?; + job.or_else(|| s.render_selected_result()).ok_or_else(|| bad(command, "no completed result is selected")) } pub(super) fn status(s: &mut Session, params: &Value) -> Result { - let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.status", e.to_string()))?; - Ok(json!(s.render_jobs.status(input.job).map_err(job_error)?)) + let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.status", e.to_string()))?; + s.advance_render_batch()?; + let Some(job) = input.job else { + return Ok(json!({"queue":s.render_queue_state()})); + }; + let mut reply = json!(s.render_jobs.status(job).map_err(job_error)?); + if let Some(object) = reply.as_object_mut() { + object.insert("queue".into(), json!(s.render_queue_state())); + } + Ok(reply) } #[derive(Deserialize)] @@ -714,18 +727,23 @@ struct Pin { job: Option, } pub(super) fn pin(s: &mut Session, params: &Value) -> Result { - if params.get("job").is_none() { - return Err(bad("render.result.pin", "job or explicit null is required")); - } let input: Pin = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.pin", e.to_string()))?; - Ok(json!({"frame":s.render_jobs.pin(input.job).map_err(job_error)?})) + let job = if params.get("job").is_some_and(Value::is_null) { None } else { Some(result_source(s, input.job, "render.result.pin")?) }; + Ok(json!({"frame":s.render_jobs.pin(job).map_err(job_error)?})) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ResultJob { + job: Option, } pub(super) fn copy(s: &mut Session, params: &Value) -> Result { - let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.copy", e.to_string()))?; + let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.copy", e.to_string()))?; + let job = result_source(s, input.job, "render.result.copy")?; let frame = s .render_jobs - .handle(input.job) + .handle(job) .map_err(job_error)? .frame() .map_err(job_error)? @@ -738,12 +756,14 @@ pub(super) fn copy(s: &mut Session, params: &Value) -> Result { } pub(super) fn cancel(s: &mut Session, params: &Value) -> Result { - let input: Job = serde_json::from_value(params.clone()).map_err(|e| bad("render.cancel", e.to_string()))?; - let status = s.render_jobs.status(input.job).map_err(job_error)?; + let input: ResultJob = serde_json::from_value(params.clone()).map_err(|e| bad("render.cancel", e.to_string()))?; + let job = input.job.or(s.render_queue_state().job).ok_or_else(|| bad("render.cancel", "job is required without an active shot queue"))?; + let status = s.render_jobs.status(job).map_err(job_error)?; + s.cancel_render_batch(job); if status.progress.phase.terminal() { return Ok(json!(status)); } - Ok(json!(s.render_jobs.handle(input.job).map_err(job_error)?.cancel().map_err(job_error)?)) + Ok(json!(s.render_jobs.handle(job).map_err(job_error)?.cancel().map_err(job_error)?)) } #[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize)] @@ -766,7 +786,7 @@ impl ExportFormat { struct Export { #[serde(default)] format: ExportFormat, - job: JobId, + job: Option, path: String, #[serde(default)] overwrite: bool, @@ -784,7 +804,8 @@ pub(super) fn export(s: &mut Session, params: &Value) -> Result { // Atomic native writers are also used for the app's own files and do not // apply a request's path scope. Check the caller's destination explicitly. solidcraft_io::vfs::check(&input.path).map_err(|e| bad("render.export", e.to_string()))?; - let frame = s.render_jobs.frame(input.job).map_err(job_error)?; + let job = result_source(s, input.job, "render.export")?; + let frame = s.render_jobs.frame(job).map_err(job_error)?; let bytes = match input.format { ExportFormat::Png => frame.png(), ExportFormat::Exr => frame @@ -797,7 +818,7 @@ pub(super) fn export(s: &mut Session, params: &Value) -> Result { if input.overwrite { solidcraft_io::write_atomic(path, bytes, false) } else { solidcraft_io::safe_write::create_atomic(path, bytes) }; result.map_err(|e| bad("render.export", format!("could not export completed {}: {e}", input.format.extension())))?; Ok( - json!({"job":input.job,"path":input.path,"bytes":bytes.len(),"format":input.format.extension(),"encoding":if input.format==ExportFormat::Exr {"scene_linear_srgb_d65"} else {"srgb"},"alpha":if input.format==ExportFormat::Exr {"coverage_premultiplied"} else {"straight"},"frame":frame.info,"linear_master":frame.linear_master_info(),"presentation":frame.presentation()}), + json!({"job":job,"path":input.path,"bytes":bytes.len(),"format":input.format.extension(),"encoding":if input.format==ExportFormat::Exr {"scene_linear_srgb_d65"} else {"srgb"},"alpha":if input.format==ExportFormat::Exr {"coverage_premultiplied"} else {"straight"},"frame":frame.info,"linear_master":frame.linear_master_info(),"presentation":frame.presentation()}), ) } diff --git a/crates/engine/src/cmd/render_ui.rs b/crates/engine/src/cmd/render_ui.rs index d6f4f28d2..261ee48d1 100644 --- a/crates/engine/src/cmd/render_ui.rs +++ b/crates/engine/src/cmd/render_ui.rs @@ -1,7 +1,10 @@ -//! Planned Render interactions, with explicit non-mutating refusals. +//! Transient Render view requests and explicit refusals for planned interactions. use super::CommandSpec; use crate::schema::render_lights::{MuteParams, SoloParams}; -use crate::schema::{TypedContract, output_schema_for, render_ui::CheckReport}; +use crate::schema::{ + TypedContract, output_schema_for, + render_ui::{BatchParams, BatchResult, CheckReport, CompareDivider, CompareParams, CompareSide, ResultIndex}, +}; use crate::{Result, Session, params::bad}; use serde::Deserialize; use serde_json::{Value, json}; @@ -33,19 +36,10 @@ fn mute(_: &mut crate::Session, params: &serde_json::Value) -> crate::Result { - CommandSpec::new($id, $label, |_, _| Err(crate::EngineError::Other(concat!("not supported yet: ", $reason).into()))) - .enabled(|_| Err(concat!("not supported yet: ", $reason).into())) - .planned("5493") - .noundo() - .doc_only() - .at($tab, $panel) - .icon($icon) - .params("No supported parameters. Always refuses without changing the design or history.") - }; -} +const RESULT_INDEX: TypedContract = TypedContract::new(); +const COMPARE: TypedContract = TypedContract::new(); +const DIVIDER: TypedContract = TypedContract::new(); +const BATCH: TypedContract = TypedContract::new(); const CHECK_REPORT: TypedContract = TypedContract::new(); @@ -57,6 +51,16 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .doc_only() .params("text: nonempty report, at most 65536 bytes. Validated clipboard request; headless echo only, never renders or edits a design."), + CommandSpec::new("render.result.select", "Select Render Result", crate::checked!("render.result.select", select_result)) + .icon("render_image").noundo().doc_only() + .enabled(results_ready) + .contract(&RESULT_INDEX).output(output_schema_for::) + .params("index: integer 0..7, oldest first; must be retained. Selects a completed result as transient per-document view state; echoes index."), + CommandSpec::new("render.result.discard", "Discard Render Result", crate::checked!("render.result.discard", discard_result)) + .icon("delete").noundo().doc_only() + .enabled(results_ready) + .contract(&RESULT_INDEX).output(output_schema_for::) + .params("index: integer 0..7, oldest first; must be retained. Drops only that transient result, selecting the newest remaining result if necessary; echoes index."), CommandSpec::new("render.output.size", "Set Render Output Size", output_size) .icon("settings") .noundo() @@ -88,8 +92,20 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo().doc_only().icon("render_scene").at("RENDER SCENE","LIGHTS") .contract(&MUTE).output(crate::schema::output_schema_for::) .params("id: kind:slot light address; mute:bool. Validates and echoes per-document UI view state, applied to live preview and captured render copies only. Never changes saved settings or history."), - waiting!("render.compare", "Compare Images", "RENDER", "RESULT", "compare", "retained image comparison"), - waiting!("render.batch", "Render All Shots", "RENDER", "BATCH", "render_image", "the saved-shot render queue"), + CommandSpec::new("render.compare", "Compare Images", crate::checked!("render.compare", compare)) + .icon("compare").noundo().doc_only().at("RENDER", "RESULT") + .enabled(results_ready) + .contract(&COMPARE).output(output_schema_for::) + .params("left, right: live or retained result index 0..7 (oldest first), distinct and retained; OR off:true. Validated per-document comparison view request; headless echo, no rendering or design/history change."), + CommandSpec::new("render.compare.divider", "Move Render Comparison Divider", crate::checked!("render.compare.divider", divider)) + .icon("compare").noundo().doc_only() + .contract(&DIVIDER).output(output_schema_for::) + .params("position: finite number, clamped to 0.05..0.95. Transient comparison divider request; headless echo only."), + CommandSpec::new("render.batch", "Render All Shots", crate::checked!("render.batch", batch)) + .icon("render_image").noundo().doc_only().at("RENDER", "BATCH") + .enabled(|s| s.render_batch_ready()) + .contract(&BATCH).output(output_schema_for::) + .params("request?: render.start parameters, shared across all saved shots except camera. Default: first saved setup in name order. Captures up to 32 shot cameras and queues sequentially through render.start; returns {queued:n}. Refuses active renders, no shots or stale geometry. render.status (also with {}) and the UI tick advance the queue; Cancel on the active job drops waiting shots. No design/history/revision change."), ]; fn copy_check(_: &mut Session, params: &Value) -> Result { @@ -100,6 +116,110 @@ fn copy_check(_: &mut Session, params: &Value) -> Result { Ok(json!({"text":report.text})) } +fn compare(s: &mut Session, params: &Value) -> Result { + let input: CompareParams = serde_json::from_value(params.clone()).map_err(|e| bad("render.compare", e.to_string()))?; + match input { + CompareParams::Off(off) if off.off => { + s.render_jobs.set_comparison(None); + Ok(json!({"off":true})) + } + CompareParams::Pair(pair) => { + if pair.left == pair.right { + return Err(bad("render.compare", "comparison sides must differ")); + } + let results = s.render_retained_results()?; + for side in [pair.left, pair.right] { + if let CompareSide::Result(index) = side + && (index > 7 || results.get(index as usize).is_none()) + { + return Err(bad("render.compare", "retained result index is out of bounds")); + } + } + let resolve = |side| match side { + CompareSide::Live(_) => None, + CompareSide::Result(index) => results.get(index as usize).map(|result| result.frame.job), + }; + s.render_jobs.set_comparison(Some([resolve(pair.left), resolve(pair.right)])); + Ok(json!({"left":pair.left,"right":pair.right})) + } + _ => Err(bad("render.compare", "off must be true")), + } +} + +fn divider(_: &mut Session, params: &Value) -> Result { + let input: CompareDivider = serde_json::from_value(params.clone()).map_err(|e| bad("render.compare.divider", e.to_string()))?; + if !input.position.is_finite() { + return Err(bad("render.compare.divider", "position must be finite")); + } + Ok(json!({"position":input.position.clamp(0.05,0.95)})) +} + +fn batch(s: &mut Session, params: &Value) -> Result { + let input: BatchParams = serde_json::from_value(params.clone()).map_err(|e| bad("render.batch", e.to_string()))?; + s.render_batch_ready().map_err(|reason| bad("render.batch", reason))?; + if s.model.is_stale() { + return Err(bad("render.batch", "finish the modelling gesture before rendering shots")); + } + for name in s.doc.render.setups.keys() { + solidcraft_doc::render_settings::RenderSettings::validate_name(name).map_err(|error| bad("render.batch", error.to_string()))?; + } + let common = if let Some(request) = input.request { + Value::Object(request.into_iter().collect()) + } else { + let setup = s.doc.render.setups.values().next().ok_or_else(|| bad("render.batch", "no saved shots"))?; + json!({"settings":setup}) + }; + let mut request = common.as_object().cloned().ok_or_else(|| bad("render.batch", "request must be an object"))?; + let settings = if let Some(name) = request.get("setup") { + let name = name.as_str().ok_or_else(|| bad("render.batch", "setup must be a saved name"))?; + if request.contains_key("settings") { + return Err(bad("render.batch", "choose either setup or settings")); + } + s.doc.render.setups.get(name).cloned().ok_or_else(|| bad("render.batch", "unknown saved setup"))? + } else if let Some(settings) = request.get("settings") { + serde_json::from_value(settings.clone()).map_err(|e| bad("render.batch", e.to_string()))? + } else { + s.doc.render.setups.values().next().cloned().ok_or_else(|| bad("render.batch", "no saved shots"))? + }; + request.remove("setup"); + // A batch never replaces an active job; malformed replace values must still refuse. + if request.get("replace").is_some_and(|value| value != &json!(false)) { + return Err(bad("render.batch", "replace must be false or omitted")); + } + request.insert("settings".into(), json!(settings)); + let request = std::sync::Arc::new(Value::Object(request)); + let shots = s + .doc + .render + .setups + .iter() + .map(|(name, shot)| crate::render_jobs::BatchShot { name: name.clone(), camera: shot.camera, request: request.clone() }) + .collect(); + let queued = s.start_render_batch(shots)?; + Ok(json!({"queued":queued})) +} + +fn results_ready(s: &Session) -> std::result::Result<(), String> { + if s.render_jobs.has_results() { Ok(()) } else { Err("no completed render results are retained".into()) } +} + +fn indexed_result(s: &mut Session, params: &Value, command: &str, discard: bool) -> Result { + let input: ResultIndex = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + if input.index > 7 { + return Err(bad(command, "index must be in 0..7")); + } + s.render_jobs.result_index(input.index as usize, discard).map_err(crate::render_jobs::job_error)?; + Ok(json!({"index":input.index})) +} + +fn select_result(s: &mut Session, params: &Value) -> Result { + indexed_result(s, params, "render.result.select", false) +} + +fn discard_result(s: &mut Session, params: &Value) -> Result { + indexed_result(s, params, "render.result.discard", true) +} + #[cfg(test)] #[test] fn render_lights_remaining_planned_commands_refuse_without_mutation() { @@ -149,17 +269,21 @@ fn output_size(_: &mut Session, params: &Value) -> Result { struct ResultView { view: String, } -fn result_view(_: &mut Session, params: &Value) -> Result { +fn result_view(s: &mut Session, params: &Value) -> Result { let input: ResultView = serde_json::from_value(params.clone()).map_err(|e| bad("render.result.view", e.to_string()))?; if !matches!(input.view.as_str(), "model" | "image" | "fit" | "actual") { return Err(bad("render.result.view", "view must be model, image, fit or actual")); } + if input.view == "model" { + s.render_jobs.set_comparison(None); + } Ok(json!({"view":input.view})) } -fn close_result(_: &mut Session, params: &Value) -> Result { +fn close_result(s: &mut Session, params: &Value) -> Result { if !params.as_object().is_some_and(|p| p.is_empty()) { return Err(bad("render.result.close", "expected no parameters")); } + s.render_jobs.set_comparison(None); Ok(json!({"view":"model"})) } @@ -210,3 +334,344 @@ fn output_sections_copy_report_validates_without_design_history_or_job_changes() assert!(std::sync::Arc::ptr_eq(&doc, &s.doc)); assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); } + +#[cfg(test)] +fn complete_result(s: &mut Session, shot: &str) -> solidcraft_render::job::JobId { + let reply = s.execute("render.start", &json!({"setup":shot})).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = s.render_job_host().unwrap().clone(); + for _ in 0..1000 { + host.pump(4096).unwrap(); + if s.execute("render.status", &json!({"job":job})).unwrap()["progress"]["phase"] == "completed" { + return job; + } + } + panic!("bounded result fixture did not complete"); +} + +#[cfg(test)] +#[test] +fn retained_results_cap_order_metadata_and_selection_never_edit_a_design() { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":16,"height":8}})).unwrap(); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":32}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.redo.len(), 1, "view commands must preserve an available redo step"); + let document = s.doc.clone(); + let before = (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty()); + let jobs: Vec<_> = (0..10).map(|_| complete_result(&mut s, "Hero")).collect(); + let results = s.render_retained_results().unwrap(); + assert_eq!(results.len(), 8); + assert_eq!(results.iter().map(|result| result.frame.job).collect::>(), jobs[2..]); + for result in &results { + assert_eq!(result.shot.as_deref(), Some("Hero")); + assert_eq!((result.frame.width, result.frame.height), (16, 8)); + assert!(result.seconds.is_finite() && result.seconds >= 0.0); + assert_eq!(result.frame.scene_generation, s.revision); + assert!(!result.stale); + } + assert!(s.render_job_handle(jobs[0]).is_err()); + assert!(s.render_job_handle(jobs[1]).is_err()); + assert_eq!(s.render_selected_result(), Some(jobs[9])); + assert_eq!(s.execute("render.result.select", &json!({"index":0})).unwrap(), json!({"index":0})); + assert_eq!(s.render_selected_result(), Some(jobs[2])); + assert_eq!(s.execute("render.result.copy", &json!({})).unwrap()["frame"]["job"], json!(jobs[2])); + assert_eq!(s.execute("render.result.pin", &json!({})).unwrap()["frame"]["job"], json!(jobs[2])); + s.execute("render.result.discard", &json!({"index":0})).unwrap(); + assert_eq!(s.render_selected_result(), Some(jobs[9])); + assert!(s.render_job_handle(jobs[2]).is_err()); + s.execute("render.result.select", &json!({"index":2})).unwrap(); + s.execute("render.result.discard", &json!({"index":0})).unwrap(); + assert_eq!(s.render_selected_result(), Some(jobs[5]), "discarding an earlier row preserves the selected identity"); + while !s.render_retained_results().unwrap().is_empty() { + s.execute("render.result.discard", &json!({"index":0})).unwrap(); + } + assert!(s.render_selected_result().is_none()); + assert!(s.execute("render.result.copy", &json!({})).is_err()); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty())); +} + +#[cfg(test)] +#[test] +fn retained_result_requests_refuse_hostile_and_missing_indices_atomically() { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + s.execute("render.settings.set", &json!({"name":"Front","set":{"width":8,"height":8}})).unwrap(); + let job = complete_result(&mut s, "Front"); + let document = s.doc.clone(); + let before = (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty()); + let retained = s.render_job_host().unwrap().admitted_bytes(); + for mode in [crate::schema::ParamCheck::Off, crate::schema::ParamCheck::Strict] { + s.param_check = mode; + for command in ["render.result.select", "render.result.discard"] { + let spec = super::find_command(command).unwrap(); + assert!(spec.contract.is_some() && spec.output.is_some()); + for request in [ + json!(null), + json!([]), + json!({}), + json!({"index":-1}), + json!({"index":0.5}), + json!({"index":1e300}), + json!({"index":u64::MAX}), + json!({"index":"0"}), + json!({"index":null}), + json!({"index":true}), + json!({"index":1}), + json!({"index":8}), + json!({"index":0,"extra":true}), + ] { + assert!(s.execute(command, &request).is_err(), "{command}: {request}"); + assert_eq!(s.render_retained_results().unwrap().len(), 1); + assert_eq!(s.render_selected_result(), Some(job)); + assert_eq!(s.render_job_host().unwrap().admitted_bytes(), retained); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.undo.len(), s.redo.len(), s.revision, s.evaluations, s.is_dirty())); + } + } + } + s.execute("render.settings.set", &json!({"name":"Front","set":{"width":16}})).unwrap(); + assert!(s.render_retained_results().unwrap()[0].stale); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.render_retained_results().unwrap()[0].stale, "undo does not recapture pixels"); + assert_eq!(s.render_retained_results().unwrap()[0].frame.scene_generation, before.2); + let mut other = Session::default(); + assert!(other.render_retained_results().unwrap().is_empty()); + assert!(other.execute("render.result.select", &json!({"index":0})).is_err()); + assert!(other.render_job_handle(job).is_err()); +} + +#[cfg(test)] +#[test] +fn render_results_compare_validates_both_sides_and_clamps_only_finite_dividers_without_mutation() { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":8,"height":8}})).unwrap(); + complete_result(&mut s, "Hero"); + complete_result(&mut s, "Hero"); + s.execute("render.settings.set", &json!({"name":"Hero","set":{"width":16}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + let selected = s.selection.clone(); + for mode in [crate::schema::ParamCheck::Off, crate::schema::ParamCheck::Strict] { + s.param_check = mode; + for request in [json!({"left":"live","right":0}), json!({"left":1,"right":0}), json!({"left":0,"right":"live"}), json!({"off":true})] { + assert_eq!(s.execute("render.compare", &request).unwrap(), request); + } + for request in [ + json!({}), + json!([]), + json!({"off":false}), + json!({"off":true,"left":0}), + json!({"left":"live","right":"live"}), + json!({"left":0,"right":0}), + json!({"left":"unknown","right":0}), + json!({"left":"live","right":2}), + json!({"left":8,"right":0}), + json!({"left":-1,"right":0}), + json!({"left":0.5,"right":0}), + json!({"left":1e300,"right":"live"}), + json!({"left":null,"right":0}), + json!({"left":"0","right":1}), + json!({"left":true,"right":0}), + json!({"left":"live","right":0,"extra":true}), + ] { + assert!(s.execute("render.compare", &request).is_err(), "{request}"); + } + for (position, expected) in [(-1e300, 0.05), (0.0, 0.05), (0.25, 0.25), (1.0, 0.95), (1e300, 0.95)] { + assert_eq!(s.execute("render.compare.divider", &json!({"position":position})).unwrap(), json!({"position":expected})); + } + for request in [json!({}), json!({"position":null}), json!({"position":"NaN"}), json!({"position":true}), json!({"position":0.5,"extra":1})] { + assert!(s.execute("render.compare.divider", &request).is_err()); + } + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + assert_eq!(s.selection, selected); + assert_eq!(s.render_retained_results().unwrap().len(), 2); + } + let mut empty = Session::default(); + assert!(empty.execute("render.compare", &json!({"left":"live","right":0})).is_err()); + assert!(empty.execute("render.compare", &json!({"off":true})).is_err()); + for id in ["render.compare", "render.compare.divider", "render.batch"] { + let command = super::find_command(id).unwrap(); + assert!(command.contract.is_some() && command.output.is_some() && command.planned.is_none()); + assert!(!command.undoable && !command.reads_model); + } +} + +#[cfg(test)] +fn batch_fixture(count: usize) -> Session { + let mut s = Session::default(); + s.set_render_job_host(Some(solidcraft_render::job::CpuHost::cooperative())).unwrap(); + for index in 0..count { + let camera = solidcraft_render::Camera { yaw: index as f64 * 0.2, roll: index as f64 * 0.01, ..Default::default() }; + s.execute("render.settings.set", &json!({"name":format!("Shot {index:02}"),"set":{"camera":camera,"width":8+index,"height":8}})).unwrap(); + } + s +} + +#[cfg(test)] +#[test] +fn render_results_batch_is_sequential_uses_snapshot_cameras_and_one_setup_without_design_or_history_changes() { + let mut s = batch_fixture(3); + s.execute("render.settings.set", &json!({"name":"Shot 00","set":{"width":64}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + let cameras: Vec<_> = s.doc.render.setups.values().map(|setup| setup.camera).collect(); + s.param_check = crate::schema::ParamCheck::Strict; + assert_eq!( + s.execute("render.batch", &json!({"request":{"settings":{"width":12,"height":10,"background":[7,8,9]}}})).unwrap(), + json!({"queued":3}) + ); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (1, 2)); + assert!(s.execute("render.batch", &json!({})).is_err()); + let host = s.render_job_host().unwrap().clone(); + let mut jobs = Vec::new(); + for (index, camera) in cameras.iter().enumerate() { + let queue = s.render_queue_state(); + assert_eq!((queue.running, queue.waiting), (1, 2 - index)); + let job = queue.job.unwrap(); + let status = s.render_job_handle(job).unwrap().status().unwrap(); + assert_eq!(status.request.camera, *camera); + assert_eq!((status.request.width, status.request.height, status.request.background), (12, 10, [7, 8, 9])); + assert_eq!(queue.shot, Some(format!("Shot {index:02}"))); + jobs.push(job); + for _ in 0..100 { + if !host.pump(4096).unwrap() { + break; + } + } + let reply = s.execute("render.status", &json!({"job":job})).unwrap(); + assert_eq!(reply["progress"]["phase"], "completed"); + } + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0)); + assert!(s.render_queue_state().job.is_none()); + let results = s.render_retained_results().unwrap(); + assert_eq!(results.iter().map(|result| result.frame.job).collect::>(), jobs); + assert_eq!(results.iter().map(|result| result.shot.clone().unwrap()).collect::>(), ["Shot 00", "Shot 01", "Shot 02"]); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); +} + +#[cfg(test)] +#[test] +fn render_results_batch_caps_at_32_and_cancel_discards_every_waiting_shot() { + let mut s = batch_fixture(32); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + assert_eq!(s.execute("render.batch", &json!({})).unwrap(), json!({"queued":32})); + let queue = s.render_queue_state(); + assert_eq!((queue.running, queue.waiting), (1, 31)); + let job = queue.job.unwrap(); + assert!(s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).is_err()); + s.execute("render.cancel", &json!({})).unwrap(); + assert_eq!(s.render_queue_state().waiting, 0); + assert!(s.render_queue_state().job.is_none()); + s.render_job_host().unwrap().pump(4096).unwrap(); + assert!(s.render_job_handle(job).unwrap().frame().unwrap().is_none()); + for _ in 0..3 { + assert_eq!(s.execute("render.status", &json!({})).unwrap()["queue"]["waiting"], 0); + } + assert!(s.render_retained_results().unwrap().is_empty()); + let next = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); + assert_eq!(next["job"]["serial"], 2, "Cancel must not start any waiting shot"); + s.execute("render.cancel", &json!({"job":next["job"]})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + std::sync::Arc::make_mut(&mut std::sync::Arc::make_mut(&mut s.doc).render).setups.insert("Over limit".into(), Default::default()); + assert!(s.execute("render.batch", &json!({})).unwrap_err().to_string().contains("32")); + assert_eq!(s.render_queue_state().waiting, 0); +} + +#[cfg(test)] +#[test] +fn render_results_batch_refuses_missing_shots_busy_hostile_and_failed_requests_without_queuing() { + let mut empty = batch_fixture(0); + assert!(empty.execute("render.batch", &json!({})).is_err()); + let mut s = batch_fixture(2); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); + for request in [ + json!([]), + json!({"request":1e300}), + json!({"request":[]}), + json!({"request":{"bogus":true}}), + json!({"request":{"replace":true}}), + json!({"request":{"settings":{"width":0}}}), + json!({"extra":true}), + ] { + assert!(s.execute("render.batch", &request).is_err(), "{request}"); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0)); + assert!(s.render_queue_state().job.is_none()); + } + let job = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap()["job"].clone(); + assert!(s.execute("render.batch", &json!({})).is_err()); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (1, 0)); + s.execute("render.cancel", &json!({"job":job})).unwrap(); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + s.set_render_job_host(None).unwrap(); + assert!(s.execute("render.batch", &json!({})).is_err()); + assert_eq!((s.render_queue_state().running, s.render_queue_state().waiting), (0, 0)); + assert!(s.render_queue_state().error.is_some()); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); +} + +#[cfg(test)] +#[test] +fn render_results_batch_cameras_and_common_setup_are_captured_before_later_shot_edits() { + let mut s = batch_fixture(2); + let original = s.doc.render.setups.get("Shot 01").unwrap().camera; + s.execute("render.batch", &json!({"request":{"setup":"Shot 00"}})).unwrap(); + let first = s.render_queue_state().job.unwrap(); + let changed = solidcraft_render::Camera { yaw: 2.0, ..Default::default() }; + s.execute("render.settings.set", &json!({"name":"Shot 01","set":{"camera":changed}})).unwrap(); + s.execute("render.settings.set", &json!({"name":"Shot 00","set":{"width":64}})).unwrap(); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations); + let host = s.render_job_host().unwrap().clone(); + for _ in 0..100 { + if !host.pump(4096).unwrap() { + break; + } + } + let reply = s.execute("render.status", &json!({})).unwrap(); + let next: solidcraft_render::job::JobId = serde_json::from_value(reply["queue"]["job"].clone()).unwrap(); + assert_ne!(next, first); + let request = s.render_job_handle(next).unwrap().status().unwrap().request; + assert_eq!(request.camera, original); + assert_eq!(request.width, 8); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations)); + s.execute("render.cancel", &json!({"job":next})).unwrap(); +} + +#[cfg(test)] +#[test] +fn render_results_compare_keeps_copy_on_the_visible_result_until_a_source_is_evicted() { + let mut s = batch_fixture(1); + let first = complete_result(&mut s, "Shot 00"); + complete_result(&mut s, "Shot 00"); + s.execute("render.compare", &json!({"left":"live","right":0})).unwrap(); + assert_eq!(s.render_comparison(), Some([None, Some(first)])); + assert_eq!(s.render_selected_result(), Some(first)); + let document = s.doc.clone(); + let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations); + let mut newest = first; + for index in 0..7 { + newest = complete_result(&mut s, "Shot 00"); + if index < 6 { + assert_eq!(s.execute("render.result.copy", &json!({})).unwrap()["frame"]["job"], json!(first)); + assert_eq!(s.render_comparison(), Some([None, Some(first)])); + } + } + assert!(s.render_comparison().is_none()); + assert_eq!(s.render_selected_result(), Some(newest)); + assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations)); +} diff --git a/crates/engine/src/render_jobs.rs b/crates/engine/src/render_jobs.rs index 7ea415311..b7d0d801a 100644 --- a/crates/engine/src/render_jobs.rs +++ b/crates/engine/src/render_jobs.rs @@ -36,6 +36,41 @@ pub(crate) struct Execution { pub executor: solidcraft_render::ExecutorId, pub options: solidcraft_render::job::JobOptions, pub environment: Option, + pub shot: Option, +} + +struct LiveJob { + handle: JobHandle, + shot: Option, +} + +/// Transient completed-image metadata. Neither pixels nor selection enter a design or undo. +#[derive(Clone, Debug, serde::Serialize)] +pub struct RetainedResult { + pub frame: solidcraft_render::job::FrameInfo, + pub shot: Option, + pub seconds: f64, + pub stale: bool, +} + +struct Completed { + handle: JobHandle, + info: RetainedResult, +} + +pub(crate) struct BatchShot { + pub name: String, + pub camera: solidcraft_render::Camera, + pub request: Arc, +} + +#[derive(Clone, Debug, serde::Serialize)] +pub struct RenderQueueState { + pub running: usize, + pub waiting: usize, + pub job: Option, + pub shot: Option, + pub error: Option, } pub(crate) struct Jobs { @@ -45,12 +80,14 @@ pub(crate) struct Jobs { pub(crate) host: Option, pub(crate) descriptor: Option, pub(crate) additional: Vec<(CpuHost, ExecutorDescriptor)>, - live: Vec, + live: Vec, history: VecDeque, - last_good: Option, - /// One explicitly displayed completed result, independent of a newer completion. - /// The existing frame Arc keeps its original host reservation accounted for. - pinned: Option, + completed: VecDeque, + selected: Option, + waiting: VecDeque, + batch_job: Option, + batch_error: Option, + comparison: Option<[Option; 2]>, } impl Default for Jobs { @@ -64,8 +101,12 @@ impl Default for Jobs { additional: Vec::new(), live: Vec::new(), history: VecDeque::new(), - last_good: None, - pinned: None, + completed: VecDeque::new(), + selected: None, + waiting: VecDeque::new(), + batch_job: None, + batch_error: None, + comparison: None, } } } @@ -73,12 +114,26 @@ impl Default for Jobs { impl Drop for Jobs { fn drop(&mut self) { for job in &self.live { - let _ = job.cancel(); + let _ = job.handle.cancel(); } } } impl Jobs { + pub(crate) fn set_comparison(&mut self, sides: Option<[Option; 2]>) { + self.comparison = sides; + if let Some([left, right]) = sides { + self.selected = right.or(left); + } + } + + fn valid_comparison(&self) -> Option<[Option; 2]> { + self.comparison.filter(|sides| sides.iter().flatten().all(|job| self.completed.iter().any(|result| result.handle.id() == *job))) + } + pub(crate) fn has_results(&self) -> bool { + !self.completed.is_empty() || self.live.iter().any(|job| job.handle.frame().ok().flatten().is_some()) + } + pub(crate) fn host_for(&self, executor: &solidcraft_render::ExecutorId) -> Option<&CpuHost> { if executor.as_str() == "cpu-raytrace" { return self @@ -103,14 +158,26 @@ impl Jobs { pub(crate) fn collect(&mut self) -> Result<(), JobError> { let mut i = 0; while i < self.live.len() { - let status = self.live.get(i).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing live job"))?.status()?; + let status = self.live.get(i).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing live job"))?.handle.status()?; if !status.progress.phase.terminal() { i += 1; continue; } - let handle = self.live.remove(i); - if status.progress.phase == Phase::Completed && self.last_good.as_ref().is_none_or(|old| old.id().serial < handle.id().serial) { - self.last_good = Some(handle); + let job = self.live.remove(i); + if let Some(frame) = status.frame.as_ref().filter(|_| status.progress.phase == Phase::Completed) { + let seconds = job.handle.completed_duration()?.map_or(0.0, |duration| duration.as_secs_f64()); + let completed_id = job.handle.id(); + self.completed.push_back(Completed { + handle: job.handle, + info: RetainedResult { frame: frame.clone(), shot: job.shot, seconds, stale: false }, + }); + while self.completed.len() > 8 { + self.completed.pop_front(); + } + if self.valid_comparison().is_none() { + self.comparison = None; + self.selected = Some(completed_id); + } } self.history.push_back(status); while self.history.len() > 4 { @@ -128,12 +195,19 @@ impl Jobs { replace: bool, execution: Execution, ) -> Result { - let Execution { executor, options, environment } = execution; + let Execution { executor, options, environment, shot } = execution; + if self.batch_job.is_some() { + if !replace { + return Err(JobError::new(ErrorCode::QueueFull, "cancel the shot queue before starting another render")); + } + self.waiting.clear(); + self.batch_job = None; + } self.collect()?; let host = self.host_for(&executor).ok_or_else(|| JobError::new(ErrorCode::HostUnavailable, "resolved image host is not installed"))?.clone(); if replace { for job in self.live.drain(..) { - let mut status = job.cancel()?; + let mut status = job.handle.cancel()?; // Replaced handles are deliberately abandoned: keep a cancellation tombstone, // not a permanently "cancelling" snapshot. The token already prevents any // publication; the host can finish releasing its buffers asynchronously. @@ -165,7 +239,7 @@ impl Jobs { let status = handle.status()?; self.serial = serial; self.generation = generation; - self.live.push(handle); + self.live.push(LiveJob { handle, shot }); Ok(status) } @@ -174,6 +248,9 @@ impl Jobs { source_id: JobId, presentation: solidcraft_render::job::presentation::Presentation, ) -> Result { + if self.batch_job.is_some() { + return Err(JobError::new(ErrorCode::QueueFull, "cancel the shot queue before regrading")); + } self.collect()?; let source = self.handle(source_id)?; let frame = source.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "regrade requires a completed frame"))?; @@ -194,7 +271,8 @@ impl Jobs { let status = handle.status()?; self.serial = serial; self.generation = generation; - self.live.push(handle); + let shot = self.completed.iter().find(|result| result.handle.id() == source_id).and_then(|result| result.info.shot.clone()); + self.live.push(LiveJob { handle, shot }); Ok(status) } @@ -209,8 +287,8 @@ impl Jobs { self.check_owner(id)?; self.live .iter() - .chain(self.last_good.iter()) - .chain(self.pinned.iter()) + .map(|job| &job.handle) + .chain(self.completed.iter().map(|result| &result.handle)) .find(|j| j.id() == id) .cloned() .ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "render job is no longer retained")) @@ -226,17 +304,35 @@ impl Jobs { } pub(crate) fn pin(&mut self, id: Option) -> Result, JobError> { + self.collect()?; let Some(id) = id else { - self.pinned = None; + self.selected = None; + self.comparison = None; return Ok(None); }; let handle = self.handle(id)?; let frame = handle.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "only a completed result can be pinned"))?; let info = frame.info.clone(); - self.pinned = Some(handle); + self.comparison = None; + self.selected = Some(id); Ok(Some(info)) } + pub(crate) fn result_index(&mut self, index: usize, discard: bool) -> Result<(), JobError> { + self.collect()?; + let id = self.completed.get(index).ok_or_else(|| JobError::new(ErrorCode::UnknownJob, "retained result index is out of bounds"))?.handle.id(); + if discard { + self.completed.remove(index); + if self.selected == Some(id) { + self.selected = self.completed.back().map(|result| result.handle.id()); + } + } else { + self.comparison = None; + self.selected = Some(id); + } + Ok(()) + } + pub(crate) fn frame(&mut self, id: JobId) -> Result, JobError> { self.collect()?; self.handle(id)?.frame()?.ok_or_else(|| JobError::new(ErrorCode::NotCompleted, "render has no completed image")) @@ -244,6 +340,126 @@ impl Jobs { } impl crate::Session { + pub fn render_comparison(&self) -> Option<[Option; 2]> { + self.render_jobs.valid_comparison() + } + + pub fn render_queue_state(&self) -> RenderQueueState { + let active = self.render_jobs.batch_job.and_then(|id| self.render_jobs.live.iter().find(|job| job.handle.id() == id)); + RenderQueueState { + running: self.render_jobs.live.iter().filter(|job| job.handle.status().is_ok_and(|status| !status.progress.phase.terminal())).count(), + waiting: self.render_jobs.waiting.len(), + job: self.render_jobs.batch_job, + shot: active.and_then(|job| job.shot.clone()), + error: self.render_jobs.batch_error.clone(), + } + } + + pub fn render_batch_ready(&self) -> std::result::Result<(), String> { + if self.doc.render.setups.is_empty() { + return Err("no saved shots to render".into()); + } + if self.doc.render.setups.len() > 32 { + return Err("render all shots is limited to 32 shots".into()); + } + if self.render_jobs.batch_job.is_some() || self.render_queue_state().running != 0 { + return Err("a render or shot queue is already active".into()); + } + Ok(()) + } + + pub(crate) fn start_render_batch(&mut self, shots: VecDeque) -> crate::Result { + self.render_batch_ready().map_err(crate::EngineError::Other)?; + if shots.is_empty() || shots.len() > 32 { + return Err(crate::EngineError::Other("shot queue must contain 1..32 shots".into())); + } + let queued = shots.len(); + self.render_jobs.waiting = shots; + self.render_jobs.batch_error = None; + self.start_next_batch_shot()?; + Ok(queued) + } + + fn start_next_batch_shot(&mut self) -> crate::Result<()> { + let Some(shot) = self.render_jobs.waiting.pop_front() else { return Ok(()) }; + let result: crate::Result<()> = (|| { + let mut params = (*shot.request).clone(); + let settings = params + .get_mut("settings") + .and_then(serde_json::Value::as_object_mut) + .ok_or_else(|| crate::EngineError::Other("queued render settings are missing".into()))?; + settings.insert("camera".into(), serde_json::json!(shot.camera)); + let reply = self.execute("render.start", ¶ms)?; + let job: JobId = serde_json::from_value(reply.get("job").cloned().unwrap_or_default()) + .map_err(|error| crate::EngineError::Other(format!("invalid queued render identity: {error}")))?; + self.label_render_job(job, &shot.name)?; + self.render_jobs.batch_job = Some(job); + Ok(()) + })(); + if let Err(error) = &result { + self.render_jobs.waiting.clear(); + self.render_jobs.batch_error = Some(error.to_string()); + } + result + } + + /// Non-blocking queue scheduling. The existing host still owns all render work. + pub fn advance_render_batch(&mut self) -> crate::Result<()> { + let Some(job) = self.render_jobs.batch_job else { return Ok(()) }; + let status = self.render_jobs.status(job).map_err(job_error)?; + if !status.progress.phase.terminal() { + return Ok(()); + } + self.render_jobs.batch_job = None; + if status.progress.phase != Phase::Completed { + self.render_jobs.waiting.clear(); + self.render_jobs.batch_error = status.error.map(|error| error.to_string()); + return Ok(()); + } + self.start_next_batch_shot() + } + + pub(crate) fn cancel_render_batch(&mut self, job: JobId) { + if self.render_jobs.batch_job == Some(job) { + self.render_jobs.waiting.clear(); + self.render_jobs.batch_job = None; + } + } + + /// Capture the UI draft's label alongside an unnamed active request, never in the design. + pub fn label_render_job(&mut self, id: JobId, shot: &str) -> crate::Result<()> { + solidcraft_doc::render_settings::RenderSettings::validate_name(shot).map_err(|error| crate::EngineError::Other(error.to_string()))?; + let job = self + .render_jobs + .live + .iter_mut() + .find(|job| job.handle.id() == id) + .ok_or_else(|| job_error(JobError::new(ErrorCode::UnknownJob, "render job is no longer active")))?; + if job.shot.is_none() { + job.shot = Some(shot.to_owned()); + } + Ok(()) + } + + /// Oldest first, capped at eight. Staleness follows the current design revision. + pub fn render_retained_results(&mut self) -> crate::Result> { + self.render_jobs.collect().map_err(job_error)?; + Ok(self + .render_jobs + .completed + .iter() + .map(|result| { + let mut info = result.info.clone(); + info.stale = info.frame.scene_generation != self.revision; + info + }) + .collect()) + } + + pub fn render_selected_result(&self) -> Option { + self.render_jobs.selected + } + /// A host is installed by the application, never by document data or a command. pub fn set_render_job_host(&mut self, host: Option) -> crate::Result<()> { if self.render_jobs.host.as_ref().zip(host.as_ref()).is_some_and(|(a, b)| a.same_host(b)) { @@ -350,7 +566,7 @@ mod displayed_result_tests { panic!("bounded result fixture did not finish") } #[test] - fn explicit_display_pin_preserves_the_old_exact_frame_without_unbounded_history() { + fn explicit_display_pin_selects_exact_bytes_within_bounded_retention() { let mut s = crate::Session::default(); let host = CpuHost::cooperative(); s.set_render_job_host(Some(host.clone())).unwrap(); @@ -368,10 +584,11 @@ mod displayed_result_tests { let foreign = JobId { session: old.session + 1, ..old }; assert!(s.execute("render.result.pin", &json!({"job":foreign})).is_err()); assert_eq!(host.admitted_bytes(), retained); - assert!(s.execute("render.result.pin", &json!({})).is_err()); + assert_eq!(s.execute("render.result.pin", &json!({})).unwrap()["frame"]["job"], json!(s.render_selected_result())); s.execute("render.result.pin", &json!({"job":null})).unwrap(); - assert!(s.render_job_handle(old).is_err()); - assert!(host.admitted_bytes() < retained); + assert!(s.render_selected_result().is_none()); + assert!(s.render_job_handle(old).is_ok(), "clearing selection does not discard retained results"); + assert_eq!(host.admitted_bytes(), retained); assert_eq!(s.doc.to_json(), before); assert_eq!(s.undo.len(), undo); let reply = s.execute("render.start", &json!({"settings":{"width":8,"height":8}})).unwrap(); diff --git a/crates/engine/src/schema/render_ui.rs b/crates/engine/src/schema/render_ui.rs index eef51c954..be7551493 100644 --- a/crates/engine/src/schema/render_ui.rs +++ b/crates/engine/src/schema/render_ui.rs @@ -1,4 +1,4 @@ -//! Clipboard requests for the Render workspace; headless calls only echo validated text. +//! Contracts for transient Render workspace clipboard and retained-result requests. use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -9,3 +9,68 @@ pub struct CheckReport { #[schemars(length(min = 1, max = 65536))] pub text: String, } + +/// Select or discard a retained result without editing a design. +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ResultIndex { + /// Zero-based index, oldest first. The result must still be retained. + #[schemars(range(min = 0, max = 7))] + pub index: u32, +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum LiveSide { + Live, +} + +/// A live product view or a retained result's zero-based index (oldest first). +#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)] +#[serde(untagged)] +pub enum CompareSide { + Live(LiveSide), + Result(#[schemars(range(min = 0, max = 7))] u32), +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ComparePair { + pub left: CompareSide, + pub right: CompareSide, +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CompareOff { + /// Must be true. Leave comparison without changing retained results. + pub off: bool, +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum CompareParams { + Off(CompareOff), + Pair(ComparePair), +} + +#[derive(Debug, Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CompareDivider { + /// Finite fraction of the canvas width, clamped to 0.05..0.95. + pub position: f64, +} + +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct BatchParams { + /// Optional render.start request. Its setup is shared, with each saved shot's camera. + /// Without a request, use the first saved shot's setup (name order). + pub request: Option>, +} + +#[derive(Debug, Serialize, JsonSchema)] +pub struct BatchResult { + /// Total accepted shots, including the first active job. At most 32. + pub queued: u32, +} diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 56a544cd9..68de22ec8 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -19,6 +19,7 @@ image = { workspace = true, features = ["jpeg"] } moxcms = { workspace = true } png = { workspace = true } sha2 = { workspace = true } +web-time = { workspace = true } weezl = { workspace = true } [dev-dependencies] diff --git a/crates/render/src/job/host.rs b/crates/render/src/job/host.rs index 8c06a153f..c8ee940df 100644 --- a/crates/render/src/job/host.rs +++ b/crates/render/src/job/host.rs @@ -362,6 +362,7 @@ pub struct JobStatus { } struct Data { + completed_duration: Option, punctual_diagnostics: Option, sampling: Option, progress: Progress, @@ -370,6 +371,7 @@ struct Data { preview: Option>, } struct Record { + started: web_time::Instant, presentation: Option>, textures: Option, options: JobOptions, @@ -399,6 +401,10 @@ impl JobHandle { pub fn id(&self) -> JobId { self.0.id } + /// Submission-to-publication time, captured once by the host, independent of UI polling. + pub fn completed_duration(&self) -> Result> { + self.0.data.lock().map(|data| data.completed_duration).map_err(|_| JobError::new(ErrorCode::Internal, "render duration lock poisoned")) + } pub fn status(&self) -> Result { let data = self.0.data.lock().map_err(|_| JobError::new(ErrorCode::Internal, "render status lock poisoned"))?; Ok(JobStatus { @@ -861,6 +867,7 @@ impl Running { })); data.preview = None; data.progress = Progress { phase: Phase::Completed, done: 1, total: 1 }; + data.completed_duration = Some(self.handle.0.started.elapsed()); self.handle.0.notify(); Ok(false) } @@ -1318,6 +1325,7 @@ impl ImageHost { (request, None) }; let handle = JobHandle(Arc::new(Record { + started: web_time::Instant::now(), presentation: None, textures, options, @@ -1329,6 +1337,7 @@ impl ImageHost { resolved, cancel: CancelToken::default(), data: Mutex::new(Data { + completed_duration: None, punctual_diagnostics: None, sampling: None, progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, @@ -1435,6 +1444,7 @@ impl ImageHost { let metadata = self.0.shared.budget.reserve(metadata_bytes)?; let origin = Arc::new(RetainedPresentation { info: origin, _reservation: metadata }); let handle = JobHandle(Arc::new(Record { + started: web_time::Instant::now(), presentation: Some(origin), textures: None, options, @@ -1446,6 +1456,7 @@ impl ImageHost { resolved, cancel: CancelToken::default(), data: Mutex::new(Data { + completed_duration: None, punctual_diagnostics: None, sampling: None, progress: Progress { phase: Phase::Queued, done: 0, total: 1 }, diff --git a/crates/render/src/job/host_tests.rs b/crates/render/src/job/host_tests.rs index 62afa6298..e18a5cd6b 100644 --- a/crates/render/src/job/host_tests.rs +++ b/crates/render/src/job/host_tests.rs @@ -348,6 +348,25 @@ fn native_job_finishes_without_any_poll_or_ui_pump() { assert_eq!(frame.info.png_bytes, frame.png().len() as u64); assert_eq!(frame.info.png_sha256, format!("{:x}", Sha256::digest(frame.png()))); assert_eq!(status.frame.unwrap().png_sha256, frame.info.png_sha256); + let duration = job.completed_duration().unwrap().unwrap(); + assert_eq!(job.completed_duration().unwrap(), Some(duration), "completed duration is independent of status polling"); +} + +#[test] +fn completed_duration_is_captured_at_publication_and_never_for_cancelled_work() { + let host = CpuHost::cooperative(); + let job = host.submit(id(1, 1), 12, empty(), request()).unwrap(); + assert!(job.completed_duration().unwrap().is_none()); + drain(&host); + let duration = job.completed_duration().unwrap().unwrap(); + assert!(duration.as_secs_f64().is_finite()); + job.status().unwrap(); + host.pump(1).unwrap(); + assert_eq!(job.completed_duration().unwrap(), Some(duration)); + let cancelled = host.submit(id(1, 2), 12, empty(), request()).unwrap(); + cancelled.cancel().unwrap(); + drain(&host); + assert!(cancelled.completed_duration().unwrap().is_none()); } /// Isolate the existing integrator-to-host completion boundary with a real PNG diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index 22562c4d2..a17a7efda 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -15,6 +15,23 @@ use crate::SolveApp; use crate::theme::Tokens; use crate::ui_kit; +/// Continue transient shot queues without adopting their document or view into the active tab. +pub(crate) fn advance_render_batches(app: &mut SolveApp, ctx: &egui::Context) { + let mut error = None; + for slot in app.docs.slots.iter_mut().flatten() { + if let Err(failure) = slot.session.advance_render_batch() { + error = Some(failure.to_string()); + } + let queue = slot.session.render_queue_state(); + if queue.running != 0 || queue.waiting != 0 { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + } + if let Some(error) = error { + app.set_status(error, true); + } +} + /// Most designs open at once. pub const MAX_OPEN: usize = 32; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e38f7ea7a..58674104c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3009,7 +3009,10 @@ impl SolveApp { (i.pointer.middle_down() || i.pointer.secondary_down()) && i.pointer.press_origin().is_some_and(|p| full.contains(p) && !shell::covered(self, p)) }); - let blocked = !continuing_navigation && ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| shell::covered(self, p)); + // A captured comparison divider also keeps its primary drag across floating cards. + let continuing_comparison = render_workspace::comparison_drag_captured(self) && ui.input(|i| i.pointer.primary_down()); + let blocked = + !continuing_navigation && !continuing_comparison && ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| shell::covered(self, p)); let mut viewport_ui = ui.new_child(egui::UiBuilder::new().max_rect(full).id_salt("floating_viewport")); if blocked { // Disabled only to shield the scene from input under a card or menu; it must diff --git a/crates/ui-egui/src/render_ui/mod.rs b/crates/ui-egui/src/render_ui/mod.rs index 4b6b9d4c1..b3c2dd007 100644 --- a/crates/ui-egui/src/render_ui/mod.rs +++ b/crates/ui-egui/src/render_ui/mod.rs @@ -198,6 +198,15 @@ pub(crate) fn overlays(app: &mut SolveApp, ui: &mut egui::Ui) { crate::render_workspace::assign::selection_bar(app, ui, free); crate::render_workspace::assign::replacement_dialog(app, ui.ctx()); crate::navigation_bar_view::show(app, ui, viewport); + crate::shell::register_panel(app, "render:compare-controls", None, None); + if !crate::render_workspace::result_active(app) && app.session.render_selected_result().is_some() { + let free = if crate::render_workspace::job_busy(app) { Container::below_navigation_row(free) } else { free }; + let card = + Container::navigation_card(ui.ctx(), egui::Id::new("sc_render_compare_controls"), free.center_top(), egui::Align2::CENTER_TOP, |ui| { + crate::render_workspace::comparison_controls(app, ui) + }); + crate::shell::register_panel(app, "render:compare-controls", Some(card.response.rect), None); + } if !focused(app) { shots_pill(app, ui, free); } diff --git a/crates/ui-egui/src/render_workspace.rs b/crates/ui-egui/src/render_workspace.rs index 8c2c7aae3..7a786a094 100644 --- a/crates/ui-egui/src/render_workspace.rs +++ b/crates/ui-egui/src/render_workspace.rs @@ -25,6 +25,9 @@ const MAX_GEOMETRY_BYTES: usize = #[path = "render_workspace_ribbon.rs"] mod ribbon; +#[path = "render_workspace_compare.rs"] +mod compare; + #[path = "render_workspace_cpu.rs"] mod cpu; @@ -145,6 +148,7 @@ pub struct State { preview_image: Option, clipboard_image: Option, clipboard_text: Option, + comparison_images: Vec<(solidcraft_engine::render::job::JobId, Result)>, } /// Provisional pixels are never an export source and never replace the retained final image. @@ -361,6 +365,9 @@ pub struct ViewState { clean_setup: Option, job: Option, completed: Option, + retained: Vec, + follow_job: bool, + compare: Option, transparent: bool, method: ImageMethod, raytrace: RaytraceOptions, @@ -426,6 +433,9 @@ impl Default for ViewState { clean_setup: None, job: None, completed: None, + retained: Vec::new(), + follow_job: true, + compare: None, transparent: false, method: ImageMethod::Raster, raytrace: RaytraceOptions::default(), @@ -474,6 +484,7 @@ impl Default for State { preview_image: None, clipboard_image: None, clipboard_text: None, + comparison_images: Vec::new(), } } } @@ -509,6 +520,10 @@ pub(crate) fn result_active(app: &SolveApp) -> bool { active(app) && app.render_workspace.view.result } +pub(crate) fn comparison_drag_captured(app: &SolveApp) -> bool { + active(app) && app.render_workspace.view.compare.as_ref().is_some_and(|view| view.dragging) +} + pub(crate) fn fit_result(app: &mut SolveApp) { app.render_workspace.view.result_scale = ResultScale::Fit; } @@ -526,6 +541,9 @@ pub(crate) fn inspect_state(app: &SolveApp) -> serde_json::Value { json!({ "active": active(app), "stage": view.stage.key(), "setup": view.name, "draft_dirty": view.dirty, "method": method, "job": view.job, "completed": view.completed, + "results": view.retained, + "comparison": view.compare, + "queue": app.session.render_queue_state(), "showing_result": view.result, "export_format": if view.studio.export_exr {"exr"} else {"png"}, }) } @@ -614,6 +632,15 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) { Err(e) => app.set_status(e.to_string(), true), } } + crate::documents::advance_render_batches(app, ctx); + if let Err(error) = app.session.advance_render_batch() { + app.set_status(error.to_string(), true); + } + follow_batch(app); + let queue = app.session.render_queue_state(); + if queue.running != 0 || queue.waiting != 0 { + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } if app.render_workspace.view.job.is_some() { cache_render_images(app, ctx); } @@ -640,6 +667,7 @@ pub(crate) fn invalidate_images(app: &mut SolveApp) { app.render_workspace.image = None; app.render_workspace.image_info = None; app.render_workspace.preview_image = None; + app.render_workspace.comparison_images.clear(); } pub fn invalidate_scene(app: &mut SolveApp) { @@ -1136,9 +1164,6 @@ fn job_controls(app: &mut SolveApp, ui: &mut egui::Ui, compact: bool) { Ok(status) => { let phase = status["progress"]["phase"].as_str().unwrap_or(crate::i18n::tr("render.property_unknown")); busy = matches!(phase, "queued" | "preparing" | "running" | "encoding" | "cancelling"); - if phase == "completed" { - app.render_workspace.view.completed = Some(job); - } state = Some(status); } Err(error) => { @@ -1278,6 +1303,11 @@ fn cache_completed_image(app: &mut SolveApp, ctx: &egui::Context) { let result = (|| -> Result { let handle = app.session.render_job_handle(job).map_err(|e| e.to_string())?; let frame = handle.frame().map_err(|e| e.to_string())?.ok_or(crate::i18n::tr("render.error_no_completed_image"))?; + if let Some((_, cached)) = app.render_workspace.comparison_images.iter().find(|(id, _)| *id == job) { + let texture = cached.clone()?; + app.render_workspace.image_info = Some(frame.info.clone()); + return Ok(texture); + } let captured = handle.status().map_err(|e| e.to_string())?; let budget = if frame.info.executor.as_str() == "gpu-path" { solidcraft_engine::render::job::GPU_PATH_LIMITS @@ -1285,7 +1315,6 @@ fn cache_completed_image(app: &mut SolveApp, ctx: &egui::Context) { captured_image_limits(&captured.request) }; let image = decode_render_image(frame.png(), frame.info.width, frame.info.height, budget, ctx.input(|i| i.max_texture_side))?; - app.session.execute("render.result.pin", &json!({"job":job})).map_err(|e| e.to_string())?; app.render_workspace.image_info = Some(frame.info.clone()); Ok(ctx.load_texture("sc_render_image", image, egui::TextureOptions::LINEAR)) })(); @@ -1341,16 +1370,17 @@ fn cache_preview_frame(app: &mut SolveApp, ctx: &egui::Context, info: &PreviewIn } fn cache_preview_image(app: &mut SolveApp, ctx: &egui::Context) { - if let Some(job) = app.render_workspace.view.job + if app.render_workspace.view.follow_job + && let Some(job) = app.render_workspace.view.job && let Ok(handle) = app.session.render_job_handle(job) { let preview = handle.preview().ok().flatten(); // Read the final after the checkpoint: completion may occur after the panel's // earlier status query. Promote the real final before dropping its preview, // rather than briefly falling back to an older job and losing result framing. - if handle.frame().ok().flatten().is_some() { - app.render_workspace.view.completed = Some(job); - } else if let Some(preview) = preview { + if handle.frame().ok().flatten().is_none() + && let Some(preview) = preview + { cache_preview_frame(app, ctx, &preview.info, preview.png()); return; } @@ -1373,11 +1403,44 @@ fn cache_render_images(app: &mut SolveApp, ctx: &egui::Context) { app.render_workspace.view.result_job == Some(preview.info.frame.job) && app.render_workspace.view.job == Some(preview.info.frame.job) }); cache_preview_image(app, ctx); + sync_results(app); cache_completed_image(app, ctx); // Checkpoint updates and preview→final/cancel transitions preserve shared pan/zoom. remember_displayed_job(app, preserve_view); } +fn sync_results(app: &mut SolveApp) { + let Ok(mut results) = app.session.render_retained_results() else { return }; + let view = &mut app.render_workspace.view; + for result in &mut results { + if result.shot.is_none() { + result.shot = view.retained.iter().find(|old| old.frame.job == result.frame.job).and_then(|old| old.shot.clone()); + if result.shot.is_none() && view.job == Some(result.frame.job) { + result.shot = view.job_shot.clone(); + } + } + } + view.retained = results; + view.completed = app.session.render_selected_result(); + if view.compare.as_ref().is_some_and(|comparison| { + [comparison.left, comparison.right].into_iter().flatten().any(|job| !view.retained.iter().any(|result| result.frame.job == job)) + }) { + view.compare = None; + app.render_workspace.comparison_images.clear(); + } +} + +fn follow_batch(app: &mut SolveApp) { + let queue = app.session.render_queue_state(); + if let Some(job) = queue.job { + if app.render_workspace.view.job != Some(job) { + app.render_workspace.view.follow_job = app.render_workspace.view.compare.is_none(); + } + app.render_workspace.view.job = Some(job); + app.render_workspace.view.job_shot = queue.shot; + } +} + fn captured_image_limits(request: &solidcraft_engine::render::job::ImageRequest) -> RenderLimits { if request.integrator == Integrator::Raytrace { request.cpu_budget().image_limits(request.raytrace.as_ref().is_some_and(|o| o.progressive.is_some())) @@ -1489,6 +1552,35 @@ fn result_rect(camera: Camera, size: [u32; 2], canvas: egui::Rect) -> egui::Rect } fn result_actions(app: &mut SolveApp, ui: &mut egui::Ui) { + compare::controls(app, ui); + let results = app.render_workspace.view.retained.clone(); + if !results.is_empty() { + let selected = results.iter().position(|result| Some(result.frame.job) == app.render_workspace.view.completed); + let label = selected.and_then(|index| results.get(index)).map(result_label).unwrap_or_else(|| app.tr("render.results_choose").to_string()); + let mut chosen = None; + let picker = crate::ui_kit::compact_dropdown_menu(ui, "render_results", &label, |ui| { + for (index, result) in results.iter().enumerate().rev() { + let response = crate::ui_kit::list_picker(ui, &format!("result:{index}"), &result_label(result), selected == Some(index)); + crate::scenario::publish_target(&format!("render:result:select:{index}"), response.rect); + if response.clicked() { + chosen = Some(index); + ui.close(); + } + } + }); + crate::scenario::publish_target("render:results", picker.rect); + if let Some(index) = chosen { + let _ = app.run("render.result.select", json!({"index":index})); + } + let discard = + ui.add_enabled_ui(selected.is_some(), |ui| crate::ui_kit::StageBar::icon_action(ui, "delete", app.tr("cmd.render.result.discard"))).inner; + crate::scenario::publish_target("render:result-discard", discard.rect); + if discard.clicked() + && let Some(index) = selected + { + let _ = app.run("render.result.discard", json!({"index":index})); + } + } for (view, key) in [("model", "render.state_model"), ("fit", "render.output_fit"), ("actual", "render.result_actual")] { let enabled = view != "actual" || !reduced_display(app); if crate::ui_kit::button(ui, app.tr(key), crate::ui_kit::Button::Enabled(enabled)).clicked() { @@ -1517,6 +1609,15 @@ fn result_actions(app: &mut SolveApp, ui: &mut egui::Ui) { } } +fn result_label(result: &solidcraft_engine::render_jobs::RetainedResult) -> String { + let name = result.shot.as_deref().unwrap_or_else(|| crate::i18n::tr("render.results_unnamed")); + let label = crate::i18n::format( + "render.results_label", + &[("number", &result.frame.job.serial.to_string()), ("shot", name), ("seconds", &format!("{:.0}", result.seconds))], + ); + if result.stale { crate::i18n::format("render.results_stale_label", &[("result", &label)]) } else { label } +} + fn show_result(app: &mut SolveApp, ui: &mut egui::Ui) { cache_render_images(app, ui.ctx()); let t = Tokens::get(); @@ -1966,6 +2067,12 @@ fn preview_background(app: &SolveApp) -> Tokens { } pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { + if app.render_workspace.view.compare.is_some() { + app.render_workspace.view.environment_ring = environment::RingView::default(); + assign::stop(app); + compare::show(app, ui); + return; + } if app.render_workspace.view.result { app.render_workspace.view.environment_ring = environment::RingView::default(); assign::stop(app); @@ -2019,8 +2126,26 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { } else { app.viewport.hover = None; } + crate::gpu::paint_background(ui.painter(), viewport, &preview_background(app)); + paint_product(app, ui, rect, app.cam, None); + shot::overlay(app, ui, viewport); + crate::viewport::axis_view(app, ui, viewport); + crate::navigation_bar_view::show(app, ui, viewport); +} + +fn product_projection(camera: Camera, radius: f64, canvas: egui::Rect, image: Option) -> solidcraft_engine::render::Mat4 { + let image = image.unwrap_or(canvas); + let projection = camera.view_proj(f64::from(image.width() / image.height().max(1.0)), radius); + let sx = f64::from(image.width() / canvas.width().max(1.0)); + let sy = f64::from(image.height() / canvas.height().max(1.0)); + let tx = f64::from(2.0 * (image.center().x - canvas.center().x) / canvas.width().max(1.0)); + let ty = f64::from(2.0 * (canvas.center().y - image.center().y) / canvas.height().max(1.0)); + solidcraft_engine::render::Mat4([[sx, 0.0, 0.0, 0.0], [0.0, sy, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [tx, ty, 0.0, 1.0]]).mul(&projection) +} + +fn paint_product(app: &mut SolveApp, ui: &mut egui::Ui, rect: egui::Rect, camera: Camera, image: Option) { let background = preview_background(app); - crate::gpu::paint_background(ui.painter(), viewport, &background); + crate::gpu::paint_background(ui.painter(), rect, &background); let result = (|| -> Result<(), String> { if app.viewport.gpu.is_none() { return Err(crate::i18n::tr("render.error_gpu_preview").into()); @@ -2077,7 +2202,6 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if scene.bounds.is_empty() { return Err(crate::i18n::tr("render.error_visible_solid").into()); } - let camera = app.cam; let radius = scene.bounds.diagonal().max(10.0) + scene.bounds.center().dist(camera.target); let eye = camera.eye(); let highlight_key = crate::viewport::highlight_key(app); @@ -2102,7 +2226,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { pv_key: 0, pv_slot: slot, pv_hide: false, - view_proj: camera.view_proj(f64::from(rect.width() / rect.height().max(1.0)), radius).to_f32(), + view_proj: product_projection(camera, radius, rect, image).to_f32(), back: camera.back().to_f32(), size_px: [rect.width() * ppp, rect.height() * ppp], clip: [0.0; 4], @@ -2125,15 +2249,12 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { [f32::from(c.r()) / 255.0, f32::from(c.g()) / 255.0, f32::from(c.b()) / 255.0] }, }); - crate::blur::viewport(ui.painter(), rect, callback, viewport, [background.viewport_top, background.viewport_bottom]); + crate::blur::viewport(ui.painter(), rect, callback, rect, [background.viewport_top, background.viewport_bottom]); Ok(()) })(); if let Err(error) = result { preview_error(app, ui, rect, &error); } - shot::overlay(app, ui, viewport); - crate::viewport::axis_view(app, ui, viewport); - crate::navigation_bar_view::show(app, ui, viewport); } /// Apply validated UI requests after the same registry call used by automation. @@ -2142,6 +2263,45 @@ pub(crate) fn apply_command(app: &mut SolveApp, id: &str, reply: &serde_json::Va "render.preflight.copy" => { app.render_workspace.clipboard_text = Some(reply["text"].as_str().ok_or("invalid check report")?.to_string()); } + "render.compare" => compare::apply(app, reply)?, + "render.compare.divider" => { + let position = reply["position"].as_f64().ok_or("invalid comparison divider position")?; + if let Some(view) = &mut app.render_workspace.view.compare { + view.position = crate::ui_kit::comparison_position(position as f32); + } + } + "render.batch" => follow_batch(app), + "render.start" | "render.result.regrade" => { + let job = serde_json::from_value(reply["job"].clone()).map_err(|e| format!("invalid render job identity: {e}"))?; + let shot = if id == "render.result.regrade" { + app.render_workspace + .view + .retained + .iter() + .find(|result| Some(result.frame.job) == app.render_workspace.view.completed) + .and_then(|result| result.shot.clone()) + } else { + Some(app.render_workspace.view.name.clone()) + }; + if let Some(shot) = &shot { + let _ = app.session.label_render_job(job, shot); + } + app.render_workspace.view.job = Some(job); + app.render_workspace.view.job_shot = shot; + app.render_workspace.view.follow_job = app.render_workspace.view.compare.is_none(); + } + "render.result.select" | "render.result.discard" | "render.result.pin" => { + sync_results(app); + app.render_workspace.preview_image = None; + app.render_workspace.view.follow_job = false; + if matches!(id, "render.result.select" | "render.result.pin") { + app.render_workspace.view.compare = None; + app.render_workspace.comparison_images.clear(); + } + if id == "render.result.select" { + app.render_workspace.view.result = true; + } + } "render.output.size" => { let width = reply["width"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid output width")?; let height = reply["height"].as_u64().and_then(|v| u32::try_from(v).ok()).ok_or("invalid output height")?; @@ -2159,6 +2319,10 @@ pub(crate) fn apply_command(app: &mut SolveApp, id: &str, reply: &serde_json::Va return Err(app.tr("render.result_reduced_display").into()); } app.render_workspace.view.result = view != "model"; + if matches!(view, "model") || id == "render.result.close" { + app.render_workspace.view.compare = None; + app.render_workspace.comparison_images.clear(); + } match view { "fit" => fit_result(app), "actual" => app.render_workspace.view.result_scale = ResultScale::Actual, @@ -2224,6 +2388,9 @@ pub(crate) fn interactive_command_info(app: &SolveApp, command: &solidcraft_engi } info } +pub(crate) fn comparison_controls(app: &mut SolveApp, ui: &mut egui::Ui) { + compare::controls(app, ui); +} pub(crate) fn start_interactive(app: &mut SolveApp, id: &str) -> bool { let handled = assign::start(app, id) || ribbon::start(app, id); // Opening Appearance Advanced must still reach its atmosphere controls after leaving Wear. diff --git a/crates/ui-egui/src/render_workspace_compare.rs b/crates/ui-egui/src/render_workspace_compare.rs new file mode 100644 index 000000000..ed28ed33b --- /dev/null +++ b/crates/ui-egui/src/render_workspace_compare.rs @@ -0,0 +1,291 @@ +//! Result comparison composition. The kit owns controls, chips and the divider. +use super::*; +use crate::ui_kit; +use solidcraft_engine::render::job::JobId; + +#[derive(Clone, Debug, serde::Serialize)] +pub(super) struct View { + pub left: Option, + pub right: Option, + pub position: f32, + pub reference: JobId, + #[serde(skip)] + pub dragging: bool, +} + +fn side_value(app: &SolveApp, side: Option) -> Option { + match side { + None => Some(json!("live")), + Some(job) => app.render_workspace.view.retained.iter().position(|result| result.frame.job == job).map(|index| json!(index)), + } +} + +pub(super) fn apply(app: &mut SolveApp, reply: &serde_json::Value) -> Result<(), String> { + if reply.get("off").and_then(serde_json::Value::as_bool) == Some(true) { + app.render_workspace.view.compare = None; + app.render_workspace.comparison_images.clear(); + return Ok(()); + } + sync_results(app); + let [left, right] = app.session.render_comparison().ok_or("comparison result is no longer retained")?; + let position = app.render_workspace.view.compare.as_ref().map_or(0.5, |view| view.position); + let reference = app + .render_workspace + .view + .compare + .as_ref() + .map(|view| view.reference) + .filter(|job| [left, right].contains(&Some(*job))) + .or(right) + .or(left) + .ok_or("comparison needs a retained result")?; + if app.render_workspace.view.compare.as_ref().is_none_or(|view| view.reference != reference) { + app.render_workspace.view.result_scale = ResultScale::Fit; + } + app.render_workspace.view.compare = Some(View { left, right, position, reference, dragging: false }); + app.render_workspace.view.result = true; + app.render_workspace.view.follow_job = false; + app.render_workspace.preview_image = None; + app.cancel_view_animation(); + app.viewport.nav = None; + app.viewport.key_hold = None; + app.viewport.orbit_free = None; + Ok(()) +} + +pub(super) fn start_default(app: &mut SolveApp) -> Result<(), String> { + sync_results(app); + if app.render_workspace.view.compare.is_some() { + app.run("render.compare", json!({"off":true}))?; + } else { + let index = app + .render_workspace + .view + .retained + .iter() + .position(|result| Some(result.frame.job) == app.render_workspace.view.completed) + .ok_or_else(|| app.tr("render.ribbon_no_result").to_string())?; + app.run("render.compare", json!({"left":"live","right":index}))?; + } + Ok(()) +} + +pub(super) fn controls(app: &mut SolveApp, ui: &mut egui::Ui) { + let results = &app.render_workspace.view.retained; + if results.is_empty() { + return; + } + let mut labels = vec![app.tr("render.compare_live").to_owned()]; + labels.extend(results.iter().map(|result| crate::i18n::format("render.compare_render", &[("number", &result.frame.job.serial.to_string())]))); + let mut targets = vec!["render:compare:live".to_string()]; + targets.extend(results.iter().enumerate().map(|(index, _)| format!("render:compare:result:{index}"))); + let choices: Vec<_> = std::iter::once(None).chain(results.iter().map(|result| Some(result.frame.job))).collect(); + let current = if app.render_workspace.view.result { app.render_workspace.view.completed } else { None }; + let comparison = app.render_workspace.view.compare.clone(); + let states: Vec<_> = + choices.iter().map(|side| comparison.as_ref().map_or(*side == current, |view| *side == view.left || *side == view.right)).collect(); + let mut selected = usize::MAX; + if ui_kit::segmented( + ui, + &mut selected, + &labels.iter().map(String::as_str).collect::>(), + ui_kit::Segments { + targets: &targets.iter().map(String::as_str).collect::>(), + states: &states, + intrinsic: true, + dense: true, + compact: true, + workspace_accent: true, + ..Default::default() + }, + ) && let Some(chosen) = choices.get(selected).copied() + { + if let Some(view) = comparison { + if chosen == view.left || chosen == view.right { + let remaining = if chosen == view.left { view.right } else { view.left }; + let _ = app.run("render.compare", json!({"off":true})); + choose_single(app, remaining); + } else if let (Some(left), Some(right)) = (side_value(app, view.left), side_value(app, chosen)) { + let _ = app.run("render.compare", json!({"left":left,"right":right})); + } + } else if chosen != current { + let (left, right) = if chosen.is_none() { (chosen, current) } else { (current, chosen) }; + if let (Some(left), Some(right)) = (side_value(app, left), side_value(app, right)) { + let _ = app.run("render.compare", json!({"left":left,"right":right})); + } + } + } + if let Some(view) = app.render_workspace.view.compare.clone() { + let swap = ui_kit::compact_icon_label_button(ui, app.tr("render.compare_swap"), "compare", true); + crate::scenario::publish_target("render:compare:swap", swap.rect); + if swap.clicked() + && let (Some(left), Some(right)) = (side_value(app, view.right), side_value(app, view.left)) + { + let _ = app.run("render.compare", json!({"left":left,"right":right})); + } + } +} + +fn choose_single(app: &mut SolveApp, side: Option) { + match side { + None => { + let _ = app.run("render.result.view", json!({"view":"model"})); + } + Some(job) => { + if let Some(index) = app.render_workspace.view.retained.iter().position(|result| result.frame.job == job) { + let _ = app.run("render.result.select", json!({"index":index})); + } + } + } +} + +fn texture(app: &mut SolveApp, ctx: &egui::Context, job: JobId) -> Result { + if let Some((_, image)) = app.render_workspace.comparison_images.iter().find(|(id, _)| *id == job) { + return image.clone(); + } + if let Some((id, image)) = &app.render_workspace.image + && *id == job + { + let image = image.clone(); + app.render_workspace.comparison_images.push((job, image.clone())); + return image; + } + let image: Result = (|| { + let handle = app.session.render_job_handle(job).map_err(|error| error.to_string())?; + let frame = handle.frame().map_err(|error| error.to_string())?.ok_or("comparison image is not completed")?; + let captured = handle.status().map_err(|error| error.to_string())?; + let limits = if frame.info.executor.as_str() == "gpu-path" { + solidcraft_engine::render::job::GPU_PATH_LIMITS + } else { + captured_image_limits(&captured.request) + }; + let image = decode_render_image(frame.png(), frame.info.width, frame.info.height, limits, ctx.input(|input| input.max_texture_side))?; + Ok(ctx.load_texture("sc_render_compare", image, egui::TextureOptions::LINEAR)) + })(); + app.render_workspace.comparison_images.push((job, image.clone())); + image +} + +fn label(app: &SolveApp, side: Option) -> String { + side.and_then(|job| app.render_workspace.view.retained.iter().find(|result| result.frame.job == job)).map_or_else( + || app.tr("render.compare_live_preview").to_owned(), + |result| { + crate::i18n::format( + "render.compare_side", + &[ + ("number", &result.frame.job.serial.to_string()), + ("shot", result.shot.as_deref().unwrap_or_else(|| crate::i18n::tr("render.results_unnamed"))), + ], + ) + }, + ) +} + +pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { + cache_render_images(app, ui.ctx()); + if app.render_workspace.view.compare.is_none() { + show_result(app, ui); + return; + } + ui.painter().rect_filled(ui.max_rect(), 0.0, Tokens::get().viewport_bottom); + let mut free = crate::render_ui::canvas(app, ui.max_rect()); + if ribbon::busy(app) { + free = ui_kit::Container::below_navigation_row(free); + } + let mut content = ui.new_child(egui::UiBuilder::new().max_rect(free).id_salt("render_compare_content")); + let ui = &mut content; + ui_kit::Container::navigation_contents(ui, |ui| { + ui.horizontal_wrapped(|ui| result_actions(app, ui)); + }); + let Some(view) = app.render_workspace.view.compare.clone() else { return }; + app.render_workspace.comparison_images.retain(|(job, _)| [view.left, view.right].contains(&Some(*job))); + let Some(reference) = app.render_workspace.view.retained.iter().find(|result| result.frame.job == view.reference).cloned() else { return }; + let stale = app.render_workspace.view.retained.iter().any(|result| [view.left, view.right].contains(&Some(result.frame.job)) && result.stale); + // Keep freshness and the capture summary below the image, as in the result board. + ui_kit::Panel::pinned_footer(ui, "render_compare_summary", 2, |ui| { + ui_kit::completion_text(ui, app.tr(if stale { "render.image_stale" } else { "render.result_current" }), !stale); + let summary = crate::i18n::format( + "render.compare_summary", + &[ + ("shot", reference.shot.as_deref().unwrap_or_else(|| crate::i18n::tr("render.results_unnamed"))), + ("width", &reference.frame.width.to_string()), + ("height", &reference.frame.height.to_string()), + ("seconds", &format!("{:.0}", reference.seconds)), + ("renderer", reference.frame.executor.as_str()), + ("revision", &reference.frame.scene_generation.to_string()), + ], + ); + ui_kit::text(ui, &summary, ui_kit::Text::Inline); + }); + let canvas = ui.available_rect_before_wrap(); + if !canvas.is_positive() { + return; + } + let response = ui.allocate_rect(canvas, Sense::click_and_drag()); + app.viewport.rect = Some(canvas); + crate::viewport::refresh_layout(app, ui.ctx()); + let size = [reference.frame.width, reference.frame.height]; + if app.render_workspace.view.result_scale != ResultScale::Free { + app.render_workspace.view.result_camera = result_camera(size, canvas, ui.ctx().pixels_per_point(), app.render_workspace.view.result_scale); + } + // Reserve the divider before navigation; captured drags cannot reach any camera path. + let mut position = view.position; + let divider = ui_kit::comparison_divider(ui, canvas, &mut position, app.tr("render.compare_divider")); + let captured = divider.dragged() || divider.is_pointer_button_down_on() || divider.drag_stopped(); + if let Some(view) = &mut app.render_workspace.view.compare { + view.dragging = divider.is_pointer_button_down_on() || divider.dragged(); + } + if divider.changed() + && let Err(error) = app.run("render.compare.divider", json!({"position":position})) + { + app.set_status(error, true); + } + if !captured { + with_result_camera(app, |app| { + crate::navigation::handle(app, ui, canvas, &response, crate::navigation::NavCaps { orbit: false, pick: false }); + }); + } + let image = result_rect(app.render_workspace.view.result_camera, size, canvas); + let split = canvas.left() + canvas.width() * position; + let halves = [ + egui::Rect::from_min_max(canvas.min, egui::pos2(split, canvas.bottom())), + egui::Rect::from_min_max(egui::pos2(split, canvas.top()), canvas.max), + ]; + let camera = app.session.render_job_handle(reference.frame.job).ok().and_then(|handle| handle.status().ok()).map(|status| status.request.camera); + // Paint sources behind the already registered handle, then raise its shared chrome. + for ((side, half), right) in [view.left, view.right].into_iter().zip(halves).zip([false, true]) { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(canvas).id_salt(("compare_side", right))); + child.set_clip_rect(half.intersect(image).intersect(ui.clip_rect())); + if child.clip_rect().is_positive() { + match side { + None => { + if let Some(camera) = camera { + paint_product(app, &mut child, canvas, camera, Some(image)); + } + } + Some(job) => match texture(app, ui.ctx(), job) { + Ok(texture) => { + let source = app.render_workspace.view.retained.iter().find(|result| result.frame.job == job); + let aspect = source.map_or(1.0, |result| result.frame.width as f32 / result.frame.height.max(1) as f32); + let height = image.height().min(image.width() / aspect); + let destination = egui::Rect::from_center_size(image.center(), egui::vec2(height * aspect, height)); + child.painter().image( + texture.id(), + destination, + egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), + Tokens::get().file_image_tint, + ); + } + Err(error) => { + ui_kit::text(&mut child, &error, ui_kit::Text::Inline); + } + }, + } + } + ui_kit::comparison_badge(ui, half, &label(app, side), right); + } + // The line and handle must stay above both source callbacks and label chips. + ui_kit::comparison_divider_chrome(ui, canvas, position); + crate::scenario::publish_rect("render:compare:canvas", canvas); + crate::scenario::publish_rect("render:compare:image", image); +} diff --git a/crates/ui-egui/src/render_workspace_inspector.rs b/crates/ui-egui/src/render_workspace_inspector.rs index ffc21d715..307729afd 100644 --- a/crates/ui-egui/src/render_workspace_inspector.rs +++ b/crates/ui-egui/src/render_workspace_inspector.rs @@ -279,6 +279,29 @@ pub(super) fn panel(app: &mut SolveApp, ui: &mut egui::Ui) { } }, |ui| { + if output { + ui_kit::Panel::pinned_footer(ui, "render_output_footer", 1, |ui| { + ui.horizontal_wrapped(|ui| { + for (id, label, target) in [ + ("render.start", app.tr("cmd.render_start").to_owned(), "render:output:render"), + ( + "render.batch", + crate::i18n::format("render.batch_all_shots", &[("count", &app.session.doc.render.setups.len().to_string())]), + "render:output:all-shots", + ), + ] { + let ready = super::ribbon::action_ready(app, id); + let response = ui_kit::icon_label_action(ui, &label, Some("play"), ready.is_ok(), id == "render.start"); + let response = if let Err(reason) = ready { response.on_disabled_hover_text(reason) } else { response }; + crate::scenario::publish_target(target, response.rect); + if response.clicked() { + app.start(id); + } + } + }); + crate::scenario::publish_rect("render:output-footer", ui.min_rect()); + }); + } if !appearance_editor && !output && !standalone { header(app, ui); ui_kit::Panel::pinned_footer(ui, "render_job_footer", 4, |ui| { diff --git a/crates/ui-egui/src/render_workspace_ribbon.rs b/crates/ui-egui/src/render_workspace_ribbon.rs index ce8ec02f8..ff8cb4f20 100644 --- a/crates/ui-egui/src/render_workspace_ribbon.rs +++ b/crates/ui-egui/src/render_workspace_ribbon.rs @@ -7,7 +7,10 @@ use solidcraft_engine::render::job::Phase; use solidcraft_engine::{CommandInfo, CommandSpec}; fn is_job_action(id: &str) -> bool { - matches!(id, "render.preflight" | "render.start" | "render.cancel" | "render.export" | "render.result.regrade" | "render.result.copy") + matches!( + id, + "render.preflight" | "render.start" | "render.batch" | "render.cancel" | "render.export" | "render.result.regrade" | "render.result.copy" + ) } fn handled(id: &str) -> bool { is_job_action(id) @@ -47,10 +50,15 @@ fn handled(id: &str) -> bool { | "render.backends" | "render.result.view" | "render.result.close" + | "render.compare" ) } pub(super) fn busy(app: &SolveApp) -> bool { + let queue = app.session.render_queue_state(); + if queue.running != 0 || queue.waiting != 0 { + return true; + } app.render_workspace .view .job @@ -66,6 +74,19 @@ pub(super) fn action_ready(app: &SolveApp, id: &str) -> Result<(), String> { return Err(app.tr("render.ribbon_finish_dialog").into()); } match id { + "render.batch" => { + if app.session.doc.render.setups.is_empty() { + return Err(app.tr("render.batch_empty").into()); + } + if app.session.doc.render.setups.len() > 32 { + return Err(app.tr("render.batch_limit").into()); + } + if busy(app) { + return Err(app.tr("render.ribbon_job_active").into()); + } + super::image_params(app).map(|_| ()) + } + "render.compare" if app.render_workspace.view.retained.is_empty() => Err(app.tr("render.ribbon_no_result").into()), "render.preflight" | "render.start" => { if id == "render.start" && busy(app) { return Err(app.tr("render.ribbon_job_active").into()); @@ -128,6 +149,10 @@ pub(super) fn command_info(app: &SolveApp, command: &CommandSpec) -> CommandInfo pub(super) fn perform_job(app: &mut SolveApp, id: &str) -> Result<(), String> { action_ready(app, id)?; match id { + "render.batch" => { + let request = super::image_params(app)?; + app.run(id, json!({"request":request}))?; + } "render.preflight" => { let request = super::image_params(app)?; let reply = match app.run(id, request.clone()) { @@ -161,7 +186,12 @@ pub(super) fn perform_job(app: &mut SolveApp, id: &str) -> Result<(), String> { app.render_workspace.view.job = Some(job); } "render.cancel" => { - let job = app.render_workspace.view.job.ok_or_else(|| app.tr("render.ribbon_no_active_job").to_string())?; + let job = app + .session + .render_queue_state() + .job + .or(app.render_workspace.view.job) + .ok_or_else(|| app.tr("render.ribbon_no_active_job").to_string())?; app.run(id, json!({"job":job}))?; } "render.export" => { @@ -238,6 +268,7 @@ fn navigate(app: &mut SolveApp, id: &str) -> Result<(), String> { focus(app, Page::Appearance, None); inspector::reveal(app, "render:appearance:advanced"); } + "render.compare" => super::compare::start_default(app)?, "render.result.close" => { app.run(id, json!({}))?; } diff --git a/crates/ui-egui/src/render_workspace_shots.rs b/crates/ui-egui/src/render_workspace_shots.rs index ef4879d8a..48fe8b1ce 100644 --- a/crates/ui-egui/src/render_workspace_shots.rs +++ b/crates/ui-egui/src/render_workspace_shots.rs @@ -45,6 +45,8 @@ pub(crate) fn contents(app: &mut SolveApp, ui: &mut egui::Ui) { ) }) .unwrap_or_else(|| app.tr("render.shots_no_result").to_string()); + let queue = app.session.render_queue_state(); + let queue_label = crate::i18n::format("render.batch_status", &[("running", &queue.running.to_string()), ("waiting", &queue.waiting.to_string())]); let (mut hide, mut start, mut save, mut chosen, mut size) = (false, false, false, None, None); let mut visible = Vec::new(); ui_kit::Panel::strip_contents( @@ -53,6 +55,8 @@ pub(crate) fn contents(app: &mut SolveApp, ui: &mut egui::Ui) { let response = ui_kit::strip_toggle(ui, true, crate::i18n::tr_label("Hide Shots strip")); crate::scenario::publish_target("render:shots:hide", response.rect); hide = response.clicked(); + let response = ui_kit::completion_text(ui, &queue_label, false); + crate::scenario::publish_rect("render:shots:queue", response.rect); let response = ui_kit::icon_label_action(ui, app.tr("cmd.render_start"), Some("play"), ready.is_ok(), true); let response = if let Err(reason) = &ready { response.on_disabled_hover_text(reason) } else { response }; crate::scenario::publish_target("render:shots:render", response.rect); diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs index ea6a4f01e..42703667a 100644 --- a/crates/ui-egui/src/render_workspace_tests.rs +++ b/crates/ui-egui/src/render_workspace_tests.rs @@ -2353,6 +2353,7 @@ fn delayed_image_export_never_substitutes_a_newer_retained_image() { use crate::picker_test_support::{Slot, save}; let (mut h, job) = async_export_fixture(); let path = h.dir.join("old-image.png"); + let bytes = h.app.session.render_job_handle(job).unwrap().frame().unwrap().unwrap().png().to_vec(); let ctx = crate::fonts::test_context(); let slot: Slot = Default::default(); save(&mut h.app, &slot); @@ -2362,9 +2363,18 @@ fn delayed_image_export_never_substitutes_a_newer_retained_image() { h.app.render_workspace.view.completed = Some(newer); *slot.borrow_mut() = Some(Some(path.to_string_lossy().into_owned())); crate::file_picker::tick(&mut h.app, &ctx); - assert!(!path.exists(), "the evicted requested image must fail instead of exporting the newer image"); - assert!(matches!(&h.app.status, Some((_, _, true)))); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "an older retained image remains the exact pending export source"); assert_eq!(h.app.render_workspace.view.completed, Some(newer)); + let evicted = h.dir.join("evicted.png"); + export_image(&mut h.app, job, false); + crate::file_picker::tick(&mut h.app, &ctx); + for _ in 0..7 { + completed_preview(&mut h, [50, 60, 70]); + } + *slot.borrow_mut() = Some(Some(evicted.to_string_lossy().into_owned())); + crate::file_picker::tick(&mut h.app, &ctx); + assert!(!evicted.exists(), "an evicted requested image fails without substituting a newer image"); + assert!(matches!(&h.app.status, Some((_, _, true)))); let newer_path = h.dir.join("new-image.png"); h.app.run("render.export", json!({"job":newer,"path":newer_path})).unwrap(); assert!(newer_path.is_file()); @@ -5838,6 +5848,117 @@ fn output_viewer_r_starts_active_setup_and_escape_returns_to_model_without_cance assert_ne!(crate::keymap::command_for(&h.app, "R"), Some("render.start")); } +#[test] +fn retained_results_picker_and_discard_dispatch_the_selected_index() { + let mut h = output_viewer_fixture(); + let first = completed_preview(&mut h, [20, 40, 60]); + let second = completed_preview(&mut h, [80, 100, 120]); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + h.app.run("render.result.select", json!({"index":1})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:results"}})).unwrap(); + h.frames(2); + h.step(&json!({"click":{"handle":"render:result:select:0"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.completed, Some(first)); + h.step(&json!({"click":{"handle":"render:result-discard"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.completed, Some(second)); + assert_eq!(h.app.render_workspace.view.retained.len(), 1); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); +} + +#[test] +fn retained_results_select_discard_copy_export_and_repaint_keep_exact_selected_pixels() { + let mut h = output_viewer_fixture(); + let ctx = crate::fonts::test_context(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let mut jobs = Vec::new(); + for shade in 0..10 { + let job = completed_preview(&mut h, [shade * 20, 40, 60]); + h.app.render_workspace.view.job = Some(job); + h.app.render_workspace.view.job_shot = Some(format!("Shot {shade}")); + cache_render_images(&mut h.app, &ctx); + jobs.push(job); + } + assert_eq!(h.app.render_workspace.view.retained.len(), 8); + assert_eq!(h.app.render_workspace.view.retained.iter().map(|result| result.frame.job).collect::>(), jobs[2..]); + assert_eq!(h.app.render_workspace.view.retained[0].shot.as_deref(), Some("Shot 2")); + h.app.run("render.result.select", json!({"index":0})).unwrap(); + assert!(h.app.render_workspace.view.result); + for _ in 0..3 { + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(jobs[2])); + assert_eq!(h.app.render_workspace.image_info.as_ref().unwrap().job, jobs[2]); + } + h.app.run("render.result.copy", json!({})).unwrap(); + assert!(h.app.render_workspace.clipboard_image.as_ref().unwrap().pixels.iter().all(|pixel| *pixel == Color32::from_rgb(40, 40, 60))); + let frame = h.app.session.render_job_handle(jobs[2]).unwrap().frame().unwrap().unwrap(); + let path = h.dir.join("selected-result.png"); + h.app.run("render.export", json!({"path":path})).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), frame.png()); + h.app.run("render.result.discard", json!({"index":0})).unwrap(); + cache_render_images(&mut h.app, &ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(jobs[9])); + assert!(h.app.session.render_job_handle(jobs[2]).is_err()); + assert!(h.app.run("render.result.select", json!({"index":7})).is_err()); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); + ctx.run_ui(Default::default(), |_| {}).textures_delta.clear(); +} + +#[test] +fn retained_results_and_selection_stay_with_the_document_tab_and_clear_on_reset() { + let mut h = output_viewer_fixture(); + let first = completed_preview(&mut h, [20, 40, 60]); + let second = completed_preview(&mut h, [80, 100, 120]); + h.app.render_workspace.view.job = Some(second); + cache_render_images(&mut h.app, &h.ctx); + h.app.run("render.result.select", json!({"index":0})).unwrap(); + h.app.run("solid.box", json!({"length":1,"width":1,"height":1})).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.retained.iter().all(|result| result.stale)); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + assert!(h.app.render_workspace.view.retained.is_empty()); + assert!(h.app.run("render.result.select", json!({"index":0})).is_err()); + crate::documents::switch(&mut h.app, 0); + cache_render_images(&mut h.app, &h.ctx); + assert_eq!(h.app.render_workspace.view.completed, Some(first)); + assert_eq!(h.app.render_workspace.view.retained.len(), 2); + h.app.run("render.result.discard", json!({"index":0})).unwrap(); + h.app.run("render.result.discard", json!({"index":0})).unwrap(); + cache_render_images(&mut h.app, &h.ctx); + assert!(h.app.render_workspace.view.completed.is_none()); + assert!(displayed_image(&h.app).is_none(), "polling the discarded active job cannot resurrect its image"); + reset_document(&mut h.app); + assert!(h.app.render_workspace.view.retained.is_empty()); +} + +#[test] +fn retained_results_capture_the_draft_shot_name_before_the_user_switches_shots() { + let mut h = output_viewer_fixture(); + h.app.render_workspace.view.name = "Hero".into(); + let reply = h.app.run("render.start", json!({"settings":{"width":8,"height":8}})).unwrap(); + let job = serde_json::from_value(reply["job"].clone()).unwrap(); + let host = h.app.session.render_job_host().unwrap().clone(); + for _ in 0..100 { + if !host.pump(16384).unwrap() { + break; + } + } + let duration = h.app.session.render_job_handle(job).unwrap().completed_duration().unwrap().unwrap().as_secs_f64(); + h.app.render_workspace.view.name = "Front".into(); + h.app.run("render.start", json!({"settings":{"width":8,"height":8}})).unwrap(); + sync_results(&mut h.app); + assert_eq!(h.app.render_workspace.view.retained[0].shot.as_deref(), Some("Hero")); + assert_eq!(h.app.render_workspace.view.retained[0].seconds, duration); + assert_eq!(h.app.render_workspace.view.completed, Some(job)); + assert!(h.app.dialog.is_none()); +} + /// Actual app controls and retained pixels, rasterized from egui without a window. #[test] fn output_viewer_evidence() { @@ -5938,8 +6059,9 @@ fn output_viewer_evidence() { } #[test] -fn output_viewer_radial_defaults_enable_lights_and_keep_planned_compare_disabled() { - let h = output_viewer_fixture(); +fn output_viewer_radial_defaults_enable_lights_and_compare_requires_a_result() { + let mut h = render_lights_fixture(); + h.app.session.set_render_job_host(Some(solidcraft_engine::render::job::CpuHost::cooperative())).unwrap(); let expected = [ "render.start", "appearance.assign", @@ -5951,8 +6073,12 @@ fn output_viewer_radial_defaults_enable_lights_and_keep_planned_compare_disabled "undo", ]; assert_eq!(crate::mouse_gesture::Studio::Render.defaults(), expected); + assert!(solidcraft_engine::find_command("render.lights.add").unwrap().planned.is_none()); assert!(crate::mouse_gesture::item(&h.app, "render.lights.add").unwrap().enabled); assert!(!crate::mouse_gesture::item(&h.app, "render.compare").unwrap().enabled); + completed_preview(&mut h, [20, 40, 60]); + assert!(crate::mouse_gesture::item(&h.app, "render.compare").unwrap().enabled); + assert!(crate::mouse_gesture::item(&h.app, "render.lights.add").unwrap().enabled); } #[test] @@ -5980,7 +6106,7 @@ fn output_viewer_presets_are_commands_with_limits_and_custom_keeps_the_size() { } #[test] -fn output_viewer_has_sections_without_pages_or_footer_and_selected_row_routes_to_output() { +fn output_viewer_has_sections_and_shared_footer_without_pages_and_selected_row_routes_to_output() { for dark in [false, true] { let mut h = output_viewer_fixture(); h.app.preferences.theme = if dark { "dark" } else { "light" }.into(); @@ -5991,6 +6117,10 @@ fn output_viewer_has_sections_without_pages_or_footer_and_selected_row_routes_to assert!(crate::scenario::rect_of(&format!("dialog:section:{}", h.app.tr(key))).is_some(), "{key}"); } assert!(crate::scenario::rect_of("render:job-footer").is_none()); + let footer = crate::scenario::rect_of("render:output-footer").unwrap(); + for target in ["render:output:render", "render:output:all-shots"] { + assert!(footer.contains_rect(crate::scenario::rect_of(target).unwrap())); + } for page in ["output", "effects", "all"] { assert!(crate::scenario::rect_of(&format!("render:page:{page}")).is_none()); } @@ -6464,6 +6594,145 @@ fn render_lights_each_kind_contains_design_sections_and_real_parameter_fields_in } } +fn render_results_compare_fixture() -> (Harness, solidcraft_engine::render::job::JobId, solidcraft_engine::render::job::JobId) { + let mut h = output_viewer_fixture(); + h.call("ui.resize", json!({"width":1440,"height":900})); + let first = completed_preview(&mut h, [20, 40, 60]); + h.app.render_workspace.view.job = Some(first); + h.app.render_workspace.view.job_shot = Some("Front".into()); + cache_render_images(&mut h.app, &h.ctx); + let second = completed_preview(&mut h, [80, 100, 120]); + h.app.render_workspace.view.job = Some(second); + h.app.render_workspace.view.job_shot = Some("Hero".into()); + cache_render_images(&mut h.app, &h.ctx); + (h, first, second) +} + +#[test] +fn render_results_compare_live_two_renders_swap_labels_and_common_framing_use_the_shared_controls() { + let (mut h, first, second) = render_results_compare_fixture(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + h.app.run("render.compare", json!({"left":"live","right":1})).unwrap(); + h.frames(3); + let view = h.app.render_workspace.view.compare.as_ref().unwrap(); + assert_eq!((view.left, view.right, view.reference), (None, Some(second), second)); + let image = crate::scenario::rect_of("render:compare:image").unwrap(); + let canvas = crate::scenario::rect_of("render:compare:canvas").unwrap(); + for target in ["render:compare:left-label", "render:compare:right-label", "render:compare:divider"] { + assert!(canvas.contains_rect(crate::scenario::rect_of(target).unwrap()), "{target}"); + } + assert!( + h.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == h.app.tr("render.compare_live_preview"))) + ); + h.step(&json!({"click":{"handle":"render:compare:swap"}})).unwrap(); + h.frames(2); + let view = h.app.render_workspace.view.compare.as_ref().unwrap(); + assert_eq!((view.left, view.right, view.reference), (Some(second), None, second)); + assert_eq!(crate::scenario::rect_of("render:compare:image"), Some(image)); + h.app.run("render.compare", json!({"left":0,"right":1})).unwrap(); + h.frames(2); + let first_texture = h.app.render_workspace.comparison_images.iter().find(|(job, _)| *job == first).unwrap().1.as_ref().unwrap().id(); + let second_texture = h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(); + let vertices = |texture| { + h.shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Mesh(mesh) if mesh.texture_id == texture => Some(mesh.vertices.iter().map(|vertex| vertex.pos).collect::>()), + _ => None, + }) + .unwrap() + }; + assert_eq!(vertices(first_texture), vertices(second_texture), "both rendered sources use the same image framing"); + h.step(&json!({"click":{"handle":"render:compare:swap"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.image.as_ref().unwrap().1.as_ref().unwrap().id(), first_texture); + assert!(h.app.render_workspace.comparison_images.iter().any(|(job, image)| *job == second && image.as_ref().unwrap().id() == second_texture)); + assert!(h.app.render_workspace.comparison_images.len() <= 2); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); + h.app.run("render.compare", json!({"off":true})).unwrap(); + assert!(h.app.render_workspace.view.compare.is_none()); + assert!(h.app.render_workspace.comparison_images.is_empty()); +} + +#[test] +fn render_results_compare_divider_drag_clamps_and_blocks_all_camera_input() { + use egui::{Event, Modifiers, MouseWheelUnit, PointerButton, vec2}; + let (mut h, _, _) = render_results_compare_fixture(); + h.app.run("render.compare", json!({"left":0,"right":1})).unwrap(); + let pending = h.app.run("render.start", json!({"settings":{"width":16,"height":16}})).unwrap()["job"].clone(); + assert!(!h.app.render_workspace.view.follow_job, "new job previews must not replace comparison framing"); + h.frames(3); + h.app.preferences.nav = "maya".into(); + h.app.render_workspace.view.result_scale = ResultScale::Free; + let product = h.app.cam; + let result = h.app.render_workspace.view.result_camera; + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let canvas = crate::scenario::rect_of("render:compare:canvas").unwrap(); + let start = crate::scenario::rect_of("render:compare:handle").unwrap().center(); + h.frame_with(vec![ + Event::ModifiersChanged(Modifiers::ALT), + Event::PointerMoved(start), + Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT }, + ]); + let end = egui::pos2(canvas.right() + 100.0, start.y); + h.frame_with(vec![ + Event::PointerMoved(end), + Event::MouseWheel { unit: MouseWheelUnit::Point, delta: vec2(0.0, -300.0), modifiers: Modifiers::ALT, phase: egui::TouchPhase::Move }, + ]); + assert!( + (h.app.render_workspace.view.compare.as_ref().unwrap().position - 0.95).abs() < 1e-6, + "divider position {:?}, canvas {canvas:?}, press {start:?}, pointer {end:?}, captured {:?}", + h.app.render_workspace.view.compare.as_ref().unwrap().position, + h.ctx.dragged_id() + ); + assert_eq!(h.app.render_workspace.view.result_camera, result); + assert_eq!(h.app.cam, product); + let end = egui::pos2(canvas.left() - 100.0, start.y); + h.frame_with(vec![Event::PointerMoved(end)]); + assert!((h.app.render_workspace.view.compare.as_ref().unwrap().position - 0.05).abs() < 1e-6); + assert_eq!(h.app.render_workspace.view.result_camera, result); + assert_eq!(h.app.cam, product); + h.frame_with(vec![ + Event::PointerButton { pos: end, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT }, + Event::ModifiersChanged(Modifiers::NONE), + ]); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); + h.app.run("render.cancel", json!({"job":pending})).unwrap(); +} + +#[test] +fn render_results_compare_live_projection_matches_image_fit_zoom_and_pan_without_an_oversized_gpu_viewport() { + use solidcraft_engine::geom::Vec3; + let canvas = egui::Rect::from_min_size(egui::pos2(100.0, 200.0), egui::vec2(800.0, 600.0)); + for fov in [0.0, 0.6] { + let camera = Camera { fov, roll: 0.25, ..Default::default() }; + for image in [ + egui::Rect::from_center_size(canvas.center(), egui::vec2(400.0, 400.0)), + egui::Rect::from_center_size(canvas.center(), egui::vec2(1600.0, 1200.0)), + egui::Rect::from_min_size(egui::pos2(-200.0, 350.0), egui::vec2(1200.0, 900.0)), + ] { + let projection = product_projection(camera, 100.0, canvas, Some(image)); + for point in [camera.target, camera.target + Vec3::X * 5.0, camera.target + Vec3::Z * 10.0] { + let (x, y, _) = camera.to_screen(point, f64::from(image.width()), f64::from(image.height()), 100.0).unwrap(); + let expected = egui::pos2(image.left() + x as f32, image.top() + y as f32); + let clip = projection.apply(point); + let actual = egui::pos2( + canvas.left() + ((clip[0] / clip[3] + 1.0) * 0.5) as f32 * canvas.width(), + canvas.top() + ((1.0 - clip[1] / clip[3]) * 0.5) as f32 * canvas.height(), + ); + assert!(actual.distance(expected) < 0.001, "{actual:?} != {expected:?}"); + } + } + assert_eq!(product_projection(camera, 100.0, canvas, None), camera.view_proj(f64::from(canvas.width() / canvas.height()), 100.0)); + } +} + #[test] fn render_lighting_preset_materialises_values_and_replacement_requires_review_consent() { let mut h = render_lights_fixture(); @@ -6713,3 +6982,106 @@ fn entering_render_fits_a_saved_portrait_setup_inside_its_final_frame() { assert_eq!((h.app.cam, h.app.ui.perspective), design, "fov {fov}: leaving Render restores the Design camera"); } } + +#[test] +fn render_results_compare_segments_work_from_live_and_close_safely_when_a_source_is_discarded() { + let (mut h, first, second) = render_results_compare_fixture(); + h.app.run("render.result.view", json!({"view":"model"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"render:compare:result:0"}})).unwrap(); + h.frames(2); + let view = h.app.render_workspace.view.compare.as_ref().unwrap(); + assert_eq!((view.left, view.right), (None, Some(first))); + h.step(&json!({"click":{"handle":"render:compare:result:1"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.render_workspace.view.compare.as_ref().unwrap().right, Some(second)); + h.step(&json!({"click":{"handle":"render:compare:live"}})).unwrap(); + h.frames(2); + assert!(h.app.render_workspace.view.compare.is_none()); + assert_eq!(h.app.render_workspace.view.completed, Some(second)); + h.app.run("render.compare", json!({"left":0,"right":1})).unwrap(); + h.frames(2); + h.app.run("render.result.discard", json!({"index":0})).unwrap(); + h.frames(2); + assert!(h.app.render_workspace.view.compare.is_none()); + assert_eq!(h.app.render_workspace.view.completed, Some(second)); + let third = completed_preview(&mut h, [100, 120, 140]); + let fourth = completed_preview(&mut h, [140, 160, 180]); + h.app.run("render.compare", json!({"left":1,"right":2})).unwrap(); + h.app.run("render.result.discard", json!({"index":0})).unwrap(); + h.frames(2); + let view = h.app.render_workspace.view.compare.as_ref().unwrap(); + assert_eq!((view.left, view.right), (Some(third), Some(fourth)), "discarding an unrelated earlier row must not retarget comparison"); + assert_eq!(h.app.session.render_comparison(), Some([Some(third), Some(fourth)])); + assert!(h.app.run("render.compare", json!({"left":"live","right":99})).is_err()); +} + +fn render_results_batch_fixture() -> Harness { + let mut h = output_viewer_fixture(); + h.call("ui.resize", json!({"width":1440,"height":900})); + for (index, name) in ["Front", "Hero", "Top"].iter().enumerate() { + let camera = Camera { yaw: index as f64 * 0.3, ..Default::default() }; + h.app.run("render.settings.set", json!({"name":name,"set":{"camera":camera,"width":8,"height":8}})).unwrap(); + } + h.frames(3); + h +} + +#[test] +fn render_results_batch_output_footer_only_starts_on_click_and_cancel_drops_waiting_shots() { + let mut h = render_results_batch_fixture(); + assert!(h.app.render_workspace.view.job.is_none()); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + h.app.render_workspace.view.draft.width = 128; + h.app.render_workspace.view.draft.height = 128; + h.app.render_workspace.view.dirty = true; + h.frames(2); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision); + let camera = h.app.cam; + h.step(&json!({"click":{"handle":"render:output:all-shots"}})).unwrap(); + h.frames(1); + let queue = h.app.session.render_queue_state(); + assert_eq!((queue.running, queue.waiting), (1, 2)); + assert_eq!(h.app.render_workspace.view.job, queue.job); + let status = crate::i18n::format("render.batch_status", &[("running", "1"), ("waiting", "2")]); + assert!(h.shapes.iter().any(|shape| matches!(&shape.shape,egui::Shape::Text(text) if text.galley.text()==status))); + assert!(crate::scenario::rect_of("render:shots:queue").is_some()); + h.step(&json!({"click":{"handle":"render:stage:render.cancel"}})).unwrap(); + h.frames(3); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + assert_eq!(h.app.cam, camera); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.revision)); +} + +#[test] +fn render_results_batch_continues_in_background_tabs_and_keeps_each_shot_result_with_its_document() { + let mut h = render_results_batch_fixture(); + let document = h.app.session.doc.clone(); + let before = (h.app.session.undo.len(), h.app.session.redo.len()); + let captured_revision = h.app.session.revision; + let host = h.app.session.render_job_host().unwrap().clone(); + h.app.run("render.batch", json!({"request":{"settings":{"width":8,"height":8}}})).unwrap(); + crate::documents::open_tab(&mut h.app, Session::default()).unwrap(); + let other = h.app.session.doc.clone(); + for _ in 0..3 { + for _ in 0..100 { + if !host.pump(4096).unwrap() { + break; + } + } + h.frames(1); + } + assert!(Arc::ptr_eq(&other, &h.app.session.doc)); + assert!(h.app.session.render_retained_results().unwrap().is_empty()); + crate::documents::switch(&mut h.app, 0); + h.frames(2); + let results = h.app.session.render_retained_results().unwrap(); + assert_eq!(results.iter().map(|result| result.shot.as_deref().unwrap()).collect::>(), ["Front", "Hero", "Top"]); + assert_eq!((h.app.session.render_queue_state().running, h.app.session.render_queue_state().waiting), (0, 0)); + assert!(Arc::ptr_eq(&document, &h.app.session.doc)); + assert_eq!(before, (h.app.session.undo.len(), h.app.session.redo.len())); + assert!(results.iter().all(|result| result.frame.scene_generation == captured_revision)); +} diff --git a/crates/ui-egui/src/ui_kit/compare.rs b/crates/ui-egui/src/ui_kit/compare.rs new file mode 100644 index 000000000..e28c3d98f --- /dev/null +++ b/crates/ui-egui/src/ui_kit/compare.rs @@ -0,0 +1,55 @@ +//! Shared image-comparison divider and corner chips. Geometry and ink use kit tokens. +use crate::{scenario, theme::Tokens}; +use egui::{Rect, Sense, Ui, pos2, vec2}; + +pub(crate) fn comparison_position(position: f32) -> f32 { + if position.is_finite() { position.clamp(0.05, 0.95) } else { 0.5 } +} + +/// A vertical wipe handle. The caller owns its command and suppresses canvas navigation while captured. +pub(crate) fn comparison_divider(ui: &mut Ui, canvas: Rect, position: &mut f32, label: &str) -> egui::Response { + let t = Tokens::get(); + *position = comparison_position(*position); + let x = canvas.left() + canvas.width() * *position; + let rail = Rect::from_center_size(pos2(x, canvas.center().y), vec2(t.space_16, canvas.height())); + let mut response = ui.interact(rail, ui.id().with("comparison_divider"), Sense::drag()).on_hover_cursor(egui::CursorIcon::ResizeHorizontal); + if response.dragged() + && let Some(pointer) = response.interact_pointer_pos() + { + *position = comparison_position((pointer.x - canvas.left()) / canvas.width().max(1.0)); + response.mark_changed(); + } + comparison_divider_chrome(ui, canvas, *position); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Slider, ui.is_enabled(), label)); + scenario::publish_target("render:compare:divider", rail); + response +} + +pub(crate) fn comparison_divider_chrome(ui: &Ui, canvas: Rect, position: f32) { + let t = Tokens::get(); + let x = canvas.left() + canvas.width() * comparison_position(position); + let painter = ui.painter().with_clip_rect(canvas.intersect(ui.clip_rect())); + let accent = crate::theme::TabAccent::current(ui.ctx()); + painter.vline(x, canvas.y_range(), egui::Stroke::new(t.space_2, accent.ink)); + let handle = Rect::from_center_size(pos2(x, canvas.center().y), vec2(t.space_16, t.space_24 + t.space_8)); + painter.rect_filled(handle, t.control_radius, t.panel); + painter.rect_stroke(handle, t.control_radius, t.control_border_stroke(accent.ink), egui::StrokeKind::Inside); + for offset in [-t.space_6, 0.0, t.space_6] { + painter.circle_filled(handle.center() + vec2(0.0, offset), t.space_2, accent.ink); + } + scenario::publish_rect("render:compare:handle", handle); +} + +/// Token-painted chip anchored inside either clipped half of the image canvas. +pub(crate) fn comparison_badge(ui: &mut Ui, bounds: Rect, label: &str, right: bool) { + let t = Tokens::get(); + let galley = ui.painter().layout_no_wrap(label.to_owned(), egui::FontId::proportional(t.font_label), t.form_ink); + let size = vec2((galley.size().x + t.space_16).min((bounds.width() - t.space_16).max(0.0)), t.control_height); + let x = if right { bounds.right() - size.x - t.space_8 } else { bounds.left() + t.space_8 }; + let rect = Rect::from_min_size(pos2(x, bounds.top() + t.space_8), size); + let painter = ui.painter().with_clip_rect(bounds.intersect(ui.clip_rect())); + painter.rect_filled(rect, t.control_radius, t.panel); + painter.rect_stroke(rect, t.control_radius, t.control_border_stroke(t.control_border), egui::StrokeKind::Inside); + painter.with_clip_rect(rect).galley(pos2(rect.left() + t.space_8, rect.center().y - galley.size().y * 0.5), galley, t.form_ink); + scenario::publish_rect(if right { "render:compare:right-label" } else { "render:compare:left-label" }, rect); +} diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs index 3027ff092..608422d42 100644 --- a/crates/ui-egui/src/ui_kit/gallery.rs +++ b/crates/ui-egui/src/ui_kit/gallery.rs @@ -171,6 +171,15 @@ const ELEMENTS: &[Element] = &[ let (viewport, _) = ui.allocate_exact_size(vec2(200.0, 150.0), egui::Sense::hover()); frame_guides(ui, viewport, viewport.shrink(20.0), FrameGuides { thirds: true, safe_area: true, centre_mark: true }); }), + element!("comparison_divider", |ui, _| { + let (rect, _) = ui.allocate_exact_size(vec2(220.0, 100.0), egui::Sense::hover()); + let mut position = 0.5; + comparison_divider(ui, rect, &mut position, "Comparison divider"); + }), + element!("comparison_badge", |ui, _| { + let (rect, _) = ui.allocate_exact_size(vec2(220.0, 100.0), egui::Sense::hover()); + comparison_badge(ui, rect, "Live preview", false); + }), element!("tree_row_rect", |ui, _| { for (index, row) in [ Row { label: "Objects", ..Default::default() }, diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rs index 4e5d5eede..c280159ca 100644 --- a/crates/ui-egui/src/ui_kit/mod.rs +++ b/crates/ui-egui/src/ui_kit/mod.rs @@ -7,6 +7,7 @@ mod assistant_entry; mod checks; mod choice; mod color; +mod compare; mod confirm; pub mod container; mod details; @@ -57,6 +58,7 @@ pub(crate) use checks::tests::{raster as test_raster, textures_update as test_te pub(crate) use checks::*; pub(crate) use choice::*; pub(crate) use color::*; +pub(crate) use compare::*; pub(crate) use confirm::{Confirm, Tone}; pub use container::{Container, DockEdges, Edge, Surface}; pub(crate) use details::*; diff --git a/crates/ui-egui/src/ui_kit/test_support_tests.rs b/crates/ui-egui/src/ui_kit/test_support_tests.rs index 216894e92..f288a8536 100644 --- a/crates/ui-egui/src/ui_kit/test_support_tests.rs +++ b/crates/ui-egui/src/ui_kit/test_support_tests.rs @@ -4,6 +4,29 @@ use egui::{Ui, vec2}; pub(crate) use crate::test_support::{key, pointer}; +#[test] +fn render_results_shared_divider_clamps_hostile_positions_and_uses_bounded_chrome() { + for (input, expected) in [(f32::NAN, 0.5), (f32::INFINITY, 0.5), (f32::NEG_INFINITY, 0.5), (-1e30, 0.05), (0.25, 0.25), (1e30, 0.95)] { + assert_eq!(comparison_position(input), expected); + } + let ctx = crate::fonts::test_context(); + let position = std::cell::Cell::new(0.5); + let mut draw = |ui: &mut Ui| { + let (canvas, _) = ui.allocate_exact_size(vec2(240.0, 180.0), egui::Sense::hover()); + let mut value = position.get(); + comparison_divider(ui, canvas, &mut value, "Comparison divider"); + comparison_badge(ui, canvas, "Live preview", false); + position.set(value); + }; + frame(&ctx, vec![], &mut draw); + let handle = scenario::rect_of("render:compare:handle").unwrap().center(); + frame(&ctx, pointer(handle, true), &mut draw); + let end = egui::pos2(1000.0, handle.y); + frame(&ctx, vec![egui::Event::PointerMoved(end)], &mut draw); + assert_eq!(position.get(), 0.95); + frame(&ctx, pointer(end, false), &mut draw); +} + fn draw_frame(ctx: &egui::Context, events: Vec, mut add: impl FnMut(&mut Ui)) -> egui::FullOutput { scenario::clear_handles(); crate::test_support::frame( diff --git a/docs/render-workspace.md b/docs/render-workspace.md index 2284dd96b..b9092f5b4 100644 --- a/docs/render-workspace.md +++ b/docs/render-workspace.md @@ -14,6 +14,35 @@ The current integrated GPU renderer shows a separate product scene. Return to De restores its camera, projection preference and existing viewport drawing policy. The live product preview remains independent of the selected image method. +## Retained comparisons and all-shot rendering + +The result viewer retains up to eight completed images per document tab, outside +the design and undo history. `render.compare {left, right}` accepts `"live"` or a +zero-based retained-result index (oldest first); the sides must differ. It resolves +indices to job identities so later index shifts cannot retarget an open comparison. +`render.compare {off:true}` leaves comparison. The shared segments toggle the two +sources, Swap exchanges them, and the shared divider stays within 5–95%. Both sides +share image pan/zoom; the live product uses the captured camera and current design. +Dragging the divider cannot navigate either camera. Copy, export and regrade use +the compared result on the right (or the left when the right is Live). That selection +remains stable while new results arrive; evicting a source ends its comparison. + +The Output footer's **All shots (n)** runs `render.batch`. The command snapshots up +to 32 saved shot cameras and names and uses one common image setup. The UI supplies +the current draft as `request` (the existing `render.start` parameters); a headless +`render.batch {}` uses the first saved setup in name order. Each queued shot keeps its +own captured camera while all other options remain the same. Each admission runs +through `render.start`, one job at a time. No shots, an active render/queue or stale +geometry refuses without editing the design or history. + +`render.status {}` advances an explicitly started queue and returns +`{queue:{running,waiting,job,shot,error}}`; a status call with a job also includes +that queue metadata. The UI ticks advance queues in active and background tabs. +`render.cancel {}` cancels the active batch job and drops all waiting shots; an +explicit job ID retains the single-job cancellation API. Opening a stage, editor +or queue readout never starts a batch. The Shots strip reports running and waiting +counts, and completed shots enter the same retained-result list. + ## Stage bar and floating docks Render has no ribbon. A shared 88 pt two-row stage bar sits 8 pt to the right of @@ -544,8 +573,10 @@ The stage bar's Check chip and Output's note count open Check. Check now runs th read-only `render.preflight` without admitting a job. Notes offer links to their owning editor. Copy report and diagnostic JSON use `render.preflight.copy` and the platform clipboard queue; headless calls only validate and echo bounded text. -Named quality presets, EXR export and rendering all shots remain faded with their -existing reasons. Destination selection uses the completed-image export picker. +Named quality presets and EXR export remain faded with their existing reasons. +Destination selection uses the completed-image export picker. The pinned Render +Image / All shots footer starts the active setup or queues all saved shots through +`render.batch`; opening the editor never starts a job. Render and Cancel stay in the stage bar. Active jobs also show a single-row progress pill with Cancel. The result viewer retains Copy, export, close, Fit/100% and shared diff --git a/docs/ui-kit.md b/docs/ui-kit.md index d5fcf35ad..742314845 100644 --- a/docs/ui-kit.md +++ b/docs/ui-kit.md @@ -199,6 +199,7 @@ table. Panel/Window/Confirm compositions also have dedicated geometry and intera | Module / element | Use and options | Main tokens | | --- | --- | --- | +| compare: `comparison_divider`, `comparison_divider_chrome`, `comparison_badge` | Clamped vertical image wipe handle and bounded corner labels. The caller owns commands, shared framing and navigation suppression while the handle captures input; the paint-only chrome can be raised above source callbacks. | `control_height/radius/border`, `space_2/6/8/16/24`, `font_label`, `form_ink`, `panel`, active `TabAccent` | | assistant: `assistant_header`, `assistant_controls`, `assistant_badge`, `assistant_bubble`, `assistant_prose`, `assistant_tool_frame/row/detail/status`, `AssistantToolState`, `assistant_approval/actions`, `assistant_composer/footer`, `assistant_input`, `assistant_send`, `assistant_empty`, `assistant_banner`/`banner`, `AssistantTone` | Shared Assistant presentation: 40 pt header, 22 pt state pill, right-aligned user messages limited to 86% width, unboxed assistant prose, bordered tool groups and command detail, tinted approval heading, rounded focused composer with one unframed growing editor and pinned footer, centred setup copy and semantic notices. Closures preserve existing permission choices, protocol routing, queue actions and scenario handles. | `form_header_height/close_size`, `font_label/small/body`, `dialog_body/footer/rule`, `control_fill/border/radius`, `form_ink/dim/primary/success/error`, `accent_soft/selected_ink`, `warning`, radii and spacing | | history: `StripHeading`, `HistoryChip`, `HistoryStyle`, `history_drop_bar`, `history_marker`, `HistorySeam`, `history_seam` | Shared strip headings use semibold `font_heading`, `text`, a centred baseline and `space_12` trailing gap. One painter family for bottom chips, 38 pt vertical icon chips and single-line 26 pt name rows (the browser's shared `TREE_ROW_HEIGHT`). Selected items use the active tab tint/ink/border; all variants retain multi-tone feature artwork using one shared kind-to-accent rule (Sketch green, Surface orange, Mesh yellow, Form purple, solids base blue); rolled-back items have 42% opacity; a reference row (a sketch listed under another feature, #6489) has its name in secondary text. Error/warning badges, suppression strikes, horizontal/vertical drop bars and rollback line/hollow circle are shared. No connector lines. | `control_height`, `space_2/3/4/6/8/10/12/14/16/24`, radii, typography, `TabAccent`, `timeline_item`, `control_border`, `text/dim`, `form_error/fill` | | tree: `tree_row`, `Row`, `TreeAction` | Shared Browser rows with disclosure, visibility (an eye column at the row's end, clear of a floating scroll bar, with a gap between the disclosure and the activation radio; or beside the disclosure with `eye_left`), activation, selection, appearance swatches, optional subtitle and trailing actions. Compact scene rows are 28 pt, with inline right-aligned summaries, circular swatches, trailing eyes and full-width selection tint. Actions use quiet icons and can appear on hover. Disabled actions retain their reasons and cannot select or fold the row. Browser automation records the same row geometry. | `TREE_ROW_HEIGHT`, `font_label/small`, spacing, control radius/border, `text/dim`, workspace selection tint | From 251573a5a477aa926df0dbc1e98ce2b6c93a870f Mon Sep 17 00:00:00 2001 From: Dahak Builds Date: Sun, 1 Nov 2026 18:30:18 +0000 Subject: [PATCH 12/55] MCP: compare the model with a reference picture (#1486) (#6416) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * claim: #1486 * Compare picture: overlap and edge offsets of the model against a reference picture (#1486) inspect.compare_picture lays the model's silhouette over the part found in a PNG or JPEG and slides it to the best overlap: overlap (0..1), the model's edges against the picture's in mm at nine stations, and an overlay PNG. The MCP tool compare_picture runs it and hands the overlay back as an image block. inspect.silhouette grows a reusable silhouette::outline for the model side. * chore: re-trigger checks (defaults line already present in PR body) Co-Authored-By: Claude Opus 5.5 * i18n: carry the Compare Picture label in Arabic, Hebrew and Vietnamese too The complete-catalog guard (every_complete_catalog_carries_every_english_message) failed because the pending file covered only en/ja/zh; ar, he and vi are complete catalogs and need the key as well. * Compare picture: one uniform scale, capped fit, sturdier part finding Review on #6416: fit no longer stretches the axes apart (width is the default, both scales uniformly by width and reports aspect_mismatch); the fitted model takes the same MAX_GRID cap as the picture; the border flood seeds only from border pixels near the border's main colour, reads alpha, retries at a stricter step, and says which case failed; the slide searches the whole placement range instead of a tenth around the centre; the model's holes get the picture's fill rule; crop becomes crop_px / crop_fraction with explicit units. Pins #1486's bracket (overlap 0.865, bottom -10 mm at the upright) and adds a regression test per problem. * Compare picture: alpha only for a see-through border, part_fills_crop, outline-only wording Review re-test on #6416: one translucent backdrop pixel no longer switches the read to alpha — alpha decides only when most of the border is see-through, and any ink is then part, so a part drawn at alpha 100 survives; part_fills_crop: true takes the crop box as the part itself, for one view cropped tight off a board where the part takes most of the border and the flood would keep the backdrop strip instead; a third backdrop pass compares each pixel to the border's main colour, so a white part on (245, 245, 245) JPEG at quality 75 separates; the command, tool and docs descriptions now say the compare is outline only: holes are not compared. A banded light backdrop stays a follow-up. A test per case. * MCP compare: format the picture tests Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Dahak Builds Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- Cargo.lock | 1 + assets/locales/pending/compare-picture.json | 20 + crates/engine/Cargo.toml | 1 + crates/engine/src/cmd/compare_picture.rs | 692 ++++++++++++++++++ .../engine/src/cmd/compare_picture_tests.rs | 490 +++++++++++++ crates/engine/src/cmd/mod.rs | 4 + crates/engine/src/cmd/silhouette.rs | 77 +- crates/mcp/Cargo.toml | 2 + crates/mcp/src/tests.rs | 41 ++ crates/mcp/src/tools.rs | 62 +- docs/mcp.md | 8 +- 11 files changed, 1371 insertions(+), 27 deletions(-) create mode 100644 assets/locales/pending/compare-picture.json create mode 100644 crates/engine/src/cmd/compare_picture.rs create mode 100644 crates/engine/src/cmd/compare_picture_tests.rs diff --git a/Cargo.lock b/Cargo.lock index c98f5fa9b..2d6fe07de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4383,6 +4383,7 @@ dependencies = [ name = "solidcraft-mcp" version = "0.29.0" dependencies = [ + "image", "serde_json", "solidcraft-engine", "solidcraft-gpu", diff --git a/assets/locales/pending/compare-picture.json b/assets/locales/pending/compare-picture.json new file mode 100644 index 000000000..d6966b2d4 --- /dev/null +++ b/assets/locales/pending/compare-picture.json @@ -0,0 +1,20 @@ +{ + "en": { + "cmd.inspect_compare_picture": "Compare Picture" + }, + "ar": { + "cmd.inspect_compare_picture": "مقارنة بصورة مرجعية" + }, + "he": { + "cmd.inspect_compare_picture": "השוואה לתמונת ייחוס" + }, + "ja": { + "cmd.inspect_compare_picture": "参考画像と比較" + }, + "vi": { + "cmd.inspect_compare_picture": "So sánh với ảnh tham chiếu" + }, + "zh": { + "cmd.inspect_compare_picture": "比较参考图" + } +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 4239cc0ae..075c37fd3 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -37,6 +37,7 @@ solidcraft-kernel = { workspace = true } solidcraft-doc = { workspace = true } solidcraft-io = { workspace = true } solidcraft-render = { workspace = true } +# reference pictures for inspect.compare_picture (PNG and JPEG decode, PNG encode) image = { workspace = true, features = ["jpeg"] } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/engine/src/cmd/compare_picture.rs b/crates/engine/src/cmd/compare_picture.rs new file mode 100644 index 000000000..6dce661b0 --- /dev/null +++ b/crates/engine/src/cmd/compare_picture.rs @@ -0,0 +1,692 @@ +//! Compare the model with a reference picture (#1486): agents model to a picture, and an +//! overlap score plus per-edge mm offsets tell the agent which edge to move and by how much. + +use std::collections::{HashMap, VecDeque}; +use std::io::Cursor; + +use serde_json::{Value, json}; +use solidcraft_doc::canvas::base64_encode; + +use super::CommandSpec; +use super::silhouette::{self, Silhouette}; +use crate::params::bad; +use crate::{Result, Session}; + +const CMD: &str = "inspect.compare_picture"; +/// A reference picture is read through the vfs with a byte cap, like `screenshot` output. +const MAX_REFERENCE_BYTES: usize = 32 << 20; +/// Decoded pixels are capped as well, so a small file cannot unfold into a huge raster. +const MAX_DECODED_PIXELS: u64 = 16 << 20; +/// The comparison grid each mask is fitted into at most — the picture's and the fitted +/// model's alike; keeps the slide search and the memory it needs bounded. +const MAX_GRID: usize = 1024; +/// Background grows from the border only through steps of at most this per channel, so a +/// backdrop's gradual shading belongs to it and the step at the part's outline stops it. +const BG_STEP: u16 = 12; +/// When the first pass finds no part, the flood retries at this stricter step: a white part +/// on a (245, 245, 245) studio backdrop is a step of 10, which BG_STEP lets through. +const BG_STEP_STRICT: u16 = 4; +/// A picture whose border is mostly transparent: a pixel below this alpha is see-through. +const ALPHA_BG: u8 = 128; +/// The global retry's backdrop: a pixel within this of the border's main colour is +/// background. A light JPEG (white on (245, 245, 245) at quality 75) blurs the step at the +/// part's outline below any local limit, so that pass compares to the backdrop's colour. +const BG_NEAR: u16 = 8; +/// Stations per side for the edge offsets. +const STATIONS: usize = 9; + +// For agents modelling to a picture; nothing to show a person, so no toolbar button. +pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Compare Picture", run).noundo().icon("compare").params( + "reference: path to a PNG or JPEG the model should match; view?/camera?/bodies?/rows? as inspect.silhouette; \ + crop_px?: [x, y, w, h] in pixels, or crop_fraction?: [x, y, w, h] as fractions 0..1 of the picture \ + (to take one view off a board); part_fills_crop?: false — with true the crop box is the part itself \ + and no background search runs, for a crop that tightly frames the part; \ + fit?: \"width\" | \"height\" | \"both\" (default \"width\"): one uniform scale, taken from the named \ + dimension (\"both\" claims both and scales by width, reporting aspect_mismatch when the shapes differ); \ + overlay?: false leaves the overlay PNG out → overlap (0..1), edges: top|bottom|left|right in mm at nine stations \ + (positive where the model reaches past the picture, null where a station misses one of the two), the grid and its \ + mm_per_px, and overlay_png (red model, blue picture) as base64 PNG. The compare is outline only: \ + holes are not compared — both the picture's and the model's holes are filled", +)]; + +fn run(s: &mut Session, p: &Value) -> Result { + let reference = p + .get("reference") + .and_then(Value::as_str) + .filter(|v| !v.trim().is_empty()) + .ok_or_else(|| bad(CMD, "`reference` is required: a path to a PNG or JPEG"))?; + let fit = match p.get("fit") { + None => Fit::Width, + Some(Value::String(v)) => match v.as_str() { + "width" => Fit::Width, + "height" => Fit::Height, + "both" => Fit::Both, + other => return Err(bad(CMD, format!("`fit` must be \"width\", \"height\" or \"both\", not `{other}`"))), + }, + Some(_) => return Err(bad(CMD, "`fit` must be a string")), + }; + let overlay = p.get("overlay").map(|v| v.as_bool().unwrap_or(false)).unwrap_or(true); + let part_fills_crop = p.get("part_fills_crop").and_then(Value::as_bool).unwrap_or(false); + + // The model side: the same outline inspect.silhouette returns, as filled rows. + let camera = silhouette::camera(p)?; + let rows = silhouette::rows(p)?; + let wanted = silhouette::body_names(p)?; + let model = silhouette::outline(s, &camera, wanted.as_deref(), rows)?; + + // The picture side: decode, crop, and find the part. + let bytes = solidcraft_io::vfs::read(reference, MAX_REFERENCE_BYTES).map_err(|e| bad(CMD, format!("{reference}: {e}")))?; + let img = decode(&bytes)?; + let img = apply_crop(img, p.get("crop_px"), p.get("crop_fraction"))?; + let picture = if part_fills_crop { + part_from_box(&img).map_err(|reason| bad(CMD, format!("the crop cannot be the part: {reason}")))? + } else { + find_part(&img).map_err(|reason| bad(CMD, format!("no part found in the picture: {reason}")))? + }; + + // Fit the model outline to the picture's scale, then slide it to the best overlap. + let (mw, mh, mmpp_x, mmpp_y) = fit_model(&model, picture.width, picture.height, fit); + let mut model_scaled = resample(&model.mask, model.width, model.height, mw, mh); + // The same hole rule the picture side has: a through-hole in the model counts as its + // outline, not as a hole the picture has to match. + fill_holes(&mut model_scaled); + let best = best_overlap(&model_scaled, &picture); + let placed = Placed { dx: best.dx, dy: best.dy, mask: &model_scaled }; + let aspect_mismatch = (picture.width as f64 * mh as f64) / (picture.height as f64 * mw as f64); + + let mut out = json!({ + "overlap": round4(best.overlap), + "stations": STATIONS, + "edges": { + "top": edge_offsets(&placed, &picture, Edge::Top, mmpp_y), + "bottom": edge_offsets(&placed, &picture, Edge::Bottom, mmpp_y), + "left": edge_offsets(&placed, &picture, Edge::Left, mmpp_x), + "right": edge_offsets(&placed, &picture, Edge::Right, mmpp_x), + }, + "fit": match fit { Fit::Width => "width", Fit::Height => "height", Fit::Both => "both" }, + "aspect_mismatch": round4(aspect_mismatch), + "mm_per_px": {"x": round4(mmpp_x), "y": round4(mmpp_y)}, + "model": {"width": model.width, "height": model.height, "box_mm": [[round4(model.lo[0]), round4(model.lo[1])], [round4(model.hi[0]), round4(model.hi[1])]], "bodies": model.bodies}, + "picture": {"width": picture.width, "height": picture.height, "source": reference}, + }); + if overlay { + out["overlay_png"] = json!(base64_encode(&overlay_png(&picture, &placed))); + } + Ok(out) +} + +#[derive(Clone, Copy)] +enum Fit { + Width, + Height, + Both, +} + +#[derive(Clone, Copy)] +enum Edge { + Top, + Bottom, + Left, + Right, +} + +/// A picture mask, tightly framed to the found part. +struct Part { + width: usize, + height: usize, + mask: Vec>, +} + +/// A model mask placed relative to the picture: its top-left sits at (dx, dy) in the +/// picture's own pixel coordinates, which may be negative. +struct Placed<'a> { + dx: i64, + dy: i64, + mask: &'a [Vec], +} + +/// Decode PNG or JPEG to RGBA8, refusing anything else and anything that unfolds too large. +fn decode(bytes: &[u8]) -> Result { + let guess = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?; + if !matches!(guess.format(), Some(image::ImageFormat::Png) | Some(image::ImageFormat::Jpeg)) { + return Err(bad(CMD, "the reference must be a PNG or a JPEG")); + } + let (w, h) = guess.into_dimensions().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?; + if w as u64 * h as u64 > MAX_DECODED_PIXELS { + return Err(bad(CMD, format!("the picture is {w}x{h}: over the {} megapixel limit", MAX_DECODED_PIXELS >> 20))); + } + let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().map_err(|e| bad(CMD, format!("cannot read the picture: {e}")))?; + let img = reader.decode().map_err(|e| bad(CMD, format!("cannot decode the picture: {e}")))?; + Ok(img.to_rgba8()) +} + +/// Apply `crop_px: [x, y, w, h]` (pixels) or `crop_fraction: [x, y, w, h]` (fractions 0..1 +/// of the picture). Explicit units: a crop of `[0, 0, 1, 1]` means one pixel, not the whole. +fn apply_crop(img: image::RgbaImage, crop_px: Option<&Value>, crop_fraction: Option<&Value>) -> Result { + match (crop_px, crop_fraction) { + (Some(_), Some(_)) => Err(bad(CMD, "give `crop_px` or `crop_fraction`, not both")), + (None, None) => Ok(img), + (Some(v), None) => { + let nums = crop_nums(v, "crop_px")?; + let (w, h) = img.dimensions(); + crop_to(img, nums[0].round() as usize, nums[1].round() as usize, nums[2].round() as usize, nums[3].round() as usize, w, h) + } + (None, Some(v)) => { + let nums = crop_nums(v, "crop_fraction")?; + if nums.iter().any(|f| *f > 1.0) { + return Err(bad(CMD, "`crop_fraction` values must be 0..1")); + } + let (w, h) = img.dimensions(); + crop_to( + img, + (nums[0] * w as f64).round() as usize, + (nums[1] * h as f64).round() as usize, + (nums[2] * w as f64).round() as usize, + (nums[3] * h as f64).round() as usize, + w, + h, + ) + } + } +} + +fn crop_nums(v: &Value, name: &str) -> Result> { + let nums: Vec = v + .as_array() + .filter(|a| a.len() == 4) + .and_then(|a| a.iter().map(|v| v.as_f64()).collect()) + .ok_or_else(|| bad(CMD, format!("`{name}` must be [x, y, w, h]")))?; + if nums.iter().any(|v| !v.is_finite() || *v < 0.0) { + return Err(bad(CMD, format!("`{name}` values must be non-negative"))); + } + Ok(nums) +} + +fn crop_to(img: image::RgbaImage, x: usize, y: usize, cw: usize, ch: usize, w: u32, h: u32) -> Result { + if x >= w as usize || y >= h as usize { + return Err(bad(CMD, "the crop starts outside the picture")); + } + let cw = cw.max(1).min(w as usize - x); + let ch = ch.max(1).min(h as usize - y); + Ok(image::imageops::crop_imm(&img, x as u32, y as u32, cw as u32, ch as u32).to_image()) +} + +/// Find the part. Alpha decides only when the backdrop really is transparent — most border +/// pixels see-through — so one stray translucent pixel cannot switch the read; then any ink +/// is part, so a part drawn at a faint alpha survives. Otherwise grow the background in from +/// the border through small colour steps only — seeded from the border pixels close to the +/// border's main colour, so a part touching the border is not eaten by its own edge — keep +/// what the background did not reach, and keep the largest 4-connected piece. On a retry the +/// step is stricter, so a white part on a (245, 245, 245) backdrop (a step of 10) still +/// separates; on a second retry the backdrop is taken globally — within BG_NEAR of the +/// border's main colour — because a light JPEG blurs the step at the part's outline below +/// any local limit. Says which happened when no part is found. +fn find_part(img: &image::RgbaImage) -> std::result::Result { + let (w, h) = (img.width() as usize, img.height() as usize); + if w < 2 || h < 2 { + return Err("the picture is smaller than 2 x 2 pixels".to_string()); + } + let px = |x: usize, y: usize| -> [u16; 3] { + let p = img.get_pixel(x as u32, y as u32).0; + [p[0] as u16, p[1] as u16, p[2] as u16] + }; + let step = |a: [u16; 3], b: [u16; 3]| (a[0].abs_diff(b[0])).max(a[1].abs_diff(b[1])).max(a[2].abs_diff(b[2])); + + // Alpha decides only when the border is mostly see-through: a single backdrop pixel at + // alpha 254 in an otherwise opaque picture must not turn the whole read into alpha. + let mut border = 0usize; + let mut see_through = 0usize; + for x in 0..w { + for y in [0, h - 1] { + border += 1; + if img.get_pixel(x as u32, y as u32)[3] < ALPHA_BG { + see_through += 1; + } + } + } + for y in 0..h { + for x in [0, w - 1] { + border += 1; + if img.get_pixel(x as u32, y as u32)[3] < ALPHA_BG { + see_through += 1; + } + } + } + let uses_alpha = see_through * 2 > border; + + let (part, too_small): (Vec, String) = if uses_alpha { + let mask: Vec = img.pixels().map(|p| p[3] > 0).collect(); + (mask, "the picture is transparent: no pixel holds any ink".to_string()) + } else { + let bg = flood_background(&px, w, h, BG_STEP, &step); + let mask: Vec = (0..w * h).map(|i| !bg[i]).collect(); + if largest_piece(&mask, w, h).len() >= 16 { + (mask, "the picture holds no piece big enough to be a part".to_string()) + } else { + let bg = flood_background(&px, w, h, BG_STEP_STRICT, &step); + let mask: Vec = (0..w * h).map(|i| !bg[i]).collect(); + if largest_piece(&mask, w, h).len() >= 16 { + (mask, "the picture holds no piece big enough to be a part".to_string()) + } else { + // The local step fails on a light JPEG: the codec blurs the 10-level step + // at the part's outline into steps of a few levels each, under any limit. + // Take the backdrop globally instead: near the border's main colour. + let main = border_main_colour(&px, w, h); + let mask: Vec = (0..w * h).map(|i| step(main, px(i % w, i / w)) > BG_NEAR).collect(); + (mask, "the background grew from the border over the whole picture, even with a stricter colour step: the part's colour is too close to the backdrop's".to_string()) + } + } + }; + + let best = largest_piece(&part, w, h); + if best.len() < 16 { + return Err(too_small); + } + // Tight frame, then downscale to the comparison grid at need. + let (x0, y0, x1, y1) = frame(&best, w); + let (pw, ph) = (x1 - x0 + 1, y1 - y0 + 1); + let mut mask = vec![vec![false; pw]; ph]; + for &i in &best { + let (x, y) = (i % w, i / w); + mask[y - y0][x - x0] = true; + } + let (dw, dh) = fit_grid(pw, ph); + let mut mask = if (dw, dh) == (pw, ph) { mask } else { resample(&mask, pw, ph, dw, dh) }; + fill_holes(&mut mask); + Ok(Part { width: dw, height: dh, mask }) +} + +/// The crop box is the part itself (`part_fills_crop`): no background search. This is how +/// one view cropped tight off a board says so — a part touching three sides leaves the +/// border's main colour the part's own, and the flood would keep the backdrop strip instead. +fn part_from_box(img: &image::RgbaImage) -> std::result::Result { + let (w, h) = (img.width() as usize, img.height() as usize); + if w < 2 || h < 2 { + return Err("the crop is smaller than 2 x 2 pixels".to_string()); + } + let (dw, dh) = fit_grid(w, h); + Ok(Part { width: dw, height: dh, mask: vec![vec![true; dw]; dh] }) +} + +/// The border's main colour: the border colour it has most of. A part crossing the border +/// is in the border too, but the backdrop is what most of the border shows. +fn border_main_colour(px: &impl Fn(usize, usize) -> [u16; 3], w: usize, h: usize) -> [u16; 3] { + let mut counts: HashMap<[u16; 3], usize> = HashMap::new(); + for x in 0..w { + for y in [0, h - 1] { + *counts.entry(px(x, y)).or_default() += 1; + } + } + for y in 0..h { + for x in [0, w - 1] { + *counts.entry(px(x, y)).or_default() += 1; + } + } + counts.into_iter().max_by_key(|(_, n)| *n).map(|(c, _)| c).unwrap_or([0; 3]) +} + +/// The background mask: grown from every border pixel whose colour is close to the border's +/// main colour, crossing only steps of at most `limit` per channel. +fn flood_background(px: &impl Fn(usize, usize) -> [u16; 3], w: usize, h: usize, limit: u16, step: &impl Fn([u16; 3], [u16; 3]) -> u16) -> Vec { + let main = border_main_colour(px, w, h); + + let mut bg = vec![false; w * h]; + let mut queue: VecDeque<(usize, usize)> = VecDeque::new(); + let mut seed = |x: usize, y: usize| { + if step(main, px(x, y)) <= limit && !bg[y * w + x] { + bg[y * w + x] = true; + queue.push_back((x, y)); + } + }; + for x in 0..w { + seed(x, 0); + seed(x, h - 1); + } + for y in 0..h { + seed(0, y); + seed(w - 1, y); + } + while let Some((x, y)) = queue.pop_front() { + let here = px(x, y); + for (nx, ny) in neighbours(x, y, w, h) { + if !bg[ny * w + nx] && step(here, px(nx, ny)) <= limit { + bg[ny * w + nx] = true; + queue.push_back((nx, ny)); + } + } + } + bg +} + +/// The largest 4-connected piece of a mask, as indices into `w`-wide rows. +fn largest_piece(mask: &[bool], w: usize, h: usize) -> Vec { + let mut best: Vec = Vec::new(); + let mut seen = vec![false; w * h]; + for start in 0..w * h { + if !mask[start] || seen[start] { + continue; + } + let mut piece: Vec = Vec::new(); + let mut queue: VecDeque = VecDeque::new(); + seen[start] = true; + queue.push_back(start); + while let Some(i) = queue.pop_front() { + piece.push(i); + let (x, y) = (i % w, i / w); + for (nx, ny) in neighbours(x, y, w, h) { + let j = ny * w + nx; + if mask[j] && !seen[j] { + seen[j] = true; + queue.push_back(j); + } + } + } + if piece.len() > best.len() { + best = piece; + } + } + best +} + +/// Fill the holes: pixels the outside never reaches become part — the rule the picture's +/// border flood gives the picture side for free, given to the model's mask as well. +fn fill_holes(mask: &mut [Vec]) { + let (h, w) = (mask.len(), mask.first().map_or(0, Vec::len)); + if w < 2 || h < 2 { + return; + } + let mut outside = vec![false; w * h]; + let mut queue: VecDeque = VecDeque::new(); + for x in 0..w { + for y in [0, h - 1] { + if !mask[y][x] && !outside[y * w + x] { + outside[y * w + x] = true; + queue.push_back(y * w + x); + } + } + } + for y in 0..h { + for x in [0, w - 1] { + if !mask[y][x] && !outside[y * w + x] { + outside[y * w + x] = true; + queue.push_back(y * w + x); + } + } + } + while let Some(i) = queue.pop_front() { + let (x, y) = (i % w, i / w); + for (nx, ny) in neighbours(x, y, w, h) { + let j = ny * w + nx; + if !mask[ny][nx] && !outside[j] { + outside[j] = true; + queue.push_back(j); + } + } + } + for y in 0..h { + for x in 0..w { + if !mask[y][x] && !outside[y * w + x] { + mask[y][x] = true; + } + } + } +} + +fn neighbours(x: usize, y: usize, w: usize, h: usize) -> impl Iterator { + [(x.wrapping_sub(1), y), (x + 1, y), (x, y.wrapping_sub(1)), (x, y + 1)].into_iter().filter(move |(nx, ny)| *nx < w && *ny < h) +} + +fn frame(pixels: &[usize], w: usize) -> (usize, usize, usize, usize) { + let mut x0 = usize::MAX; + let mut y0 = usize::MAX; + let mut x1 = 0; + let mut y1 = 0; + for &i in pixels { + let (x, y) = (i % w, i / w); + x0 = x0.min(x); + y0 = y0.min(y); + x1 = x1.max(x); + y1 = y1.max(y); + } + (x0, y0, x1, y1) +} + +fn fit_grid(w: usize, h: usize) -> (usize, usize) { + let scale = (MAX_GRID as f64 / w.max(h) as f64).min(1.0); + (((w as f64 * scale).round() as usize).max(2), ((h as f64 * scale).round() as usize).max(2)) +} + +/// Nearest-neighbour resample of a mask to (w1, h1). +fn resample(mask: &[Vec], w0: usize, h0: usize, w1: usize, h1: usize) -> Vec> { + (0..h1) + .map(|y| { + let row = &mask[((y * h0) / h1.max(1)).min(h0 - 1)]; + (0..w1).map(|x| row[((x * w0) / w1.max(1)).min(w0 - 1)]).collect() + }) + .collect() +} + +/// The model outline's size in picture pixels and the mm per pixel that follows. One +/// uniform scale, taken from the dimension the two share — the axes are never stretched +/// apart, which would hide the very mismatch the tool is for. `both` claims both dimensions +/// and scales by width; the result's `aspect_mismatch` says how far the shapes are apart. +/// The fitted size takes the same MAX_GRID cap as the picture's: a narrow model fitted by +/// width against a wide picture would otherwise ask for hundreds of megabytes of mask. +fn fit_model(model: &Silhouette, pw: usize, ph: usize, fit: Fit) -> (usize, usize, f64, f64) { + let s = match fit { + Fit::Width | Fit::Both => pw as f64 / model.width as f64, + Fit::Height => ph as f64 / model.height as f64, + }; + let mw = ((model.width as f64 * s).round() as usize).max(2); + let mh = ((model.height as f64 * s).round() as usize).max(2); + let (mw, mh) = fit_grid(mw, mh); + (mw, mh, model.width as f64 * model.mm_per_px / mw as f64, model.height as f64 * model.mm_per_px / mh as f64) +} + +struct Best { + overlap: f64, + dx: i64, + dy: i64, +} + +/// Slide the model mask over the picture mask to the best intersection-over-union. The +/// coarse pass covers the whole range of placements where the two frames can share a +/// pixel — a tenth of the picture around the centre is not enough when the heights differ — +/// and the fine pass walks every offset around its winner. +fn best_overlap(model: &[Vec], picture: &Part) -> Best { + let pic = spans_of(&picture.mask); + let mdl = spans_of(model); + let model_area: i64 = mdl.iter().flatten().map(|[a, b]| (b - a) as i64).sum(); + let pic_area: i64 = pic.iter().flatten().map(|[a, b]| (b - a) as i64).sum(); + + let (mw, mh) = (model[0].len() as i64, model.len() as i64); + let (lo_x, hi_x) = (1 - mw, picture.width as i64); + let (lo_y, hi_y) = (1 - mh, picture.height as i64); + // About 64 coarse samples per axis, never finer than 4 px, never coarser than 32. + let step_x = ((hi_x - lo_x) / 64).clamp(4, 32); + let step_y = ((hi_y - lo_y) / 64).clamp(4, 32); + + // The frames' aligned corners: both masks are tightly framed, so the best placement of a + // matching picture is at or near here. + let (mut bx, mut by) = (0i64, 0i64); + for round in 0..2 { + // Coarse: the whole range at the step; fine: every offset within one coarse step + // of the coarse winner. + let (sx, sy, x0, x1, y0, y1) = if round == 0 { + (step_x, step_y, lo_x, hi_x, lo_y, hi_y) + } else { + (1, 1, (bx - step_x).max(lo_x), (bx + step_x).min(hi_x), (by - step_y).max(lo_y), (by + step_y).min(hi_y)) + }; + let (mut best_score, mut best_x, mut best_y) = (i64::MIN, bx, by); + let mut dy = y0; + while dy <= y1 { + let mut dx = x0; + while dx <= x1 { + let hits = intersection(&mdl, &pic, dx, dy); + let union = model_area + pic_area - hits; + let score = if union <= 0 { i64::MIN } else { hits * 1_000_000 / union }; + if score > best_score { + best_score = score; + best_x = dx; + best_y = dy; + } + dx += sx; + } + dy += sy; + } + bx = best_x; + by = best_y; + } + + let hits = intersection(&mdl, &pic, bx, by); + let union = model_area + pic_area - hits; + Best { overlap: if union <= 0 { 0.0 } else { hits as f64 / union as f64 }, dx: bx, dy: by } +} + +fn spans_of(mask: &[Vec]) -> Vec> { + mask.iter().map(|row| silhouette::spans(row)).collect() +} + +/// Pixels the model shares with the picture at model offset (dx, dy), from run-length rows. +fn intersection(mdl: &[Vec<[usize; 2]>], pic: &[Vec<[usize; 2]>], dx: i64, dy: i64) -> i64 { + let mut hits = 0i64; + for (r, spans) in mdl.iter().enumerate() { + if spans.is_empty() { + continue; + } + let Some(y) = (dy + r as i64).try_into().ok().and_then(|y: usize| pic.get(y)) else { continue }; + if y.is_empty() { + continue; + } + for &[a, b] in spans { + let (mut lo, hi) = ((a as i64 + dx).max(0), b as i64 + dx); + if hi <= lo { + continue; + } + for &[pa, pb] in y { + let (s, e) = (lo.max(pa as i64), hi.min(pb as i64)); + if e > s { + hits += e - s; + } + lo = lo.max(pb as i64); + if lo >= hi || pb as i64 >= hi { + break; + } + } + } + } + hits +} + +/// The model's edge against the picture's, in mm, at nine stations along one side; positive +/// where the model reaches past the picture, null where a station misses one of the two. +fn edge_offsets(model: &Placed, picture: &Part, side: Edge, mmpp: f64) -> Vec { + (1..=STATIONS) + .map(|i| { + let station = match side { + Edge::Top | Edge::Bottom => (picture.width as u64 * i as u64 / (STATIONS as u64 + 1)) as usize, + Edge::Left | Edge::Right => (picture.height as u64 * i as u64 / (STATIONS as u64 + 1)) as usize, + }; + let offset = match side { + Edge::Top | Edge::Bottom => { + let pic = column_edge(&picture.mask, station, matches!(side, Edge::Top)); + let mdl = (station as i64 - model.dx) + .try_into() + .ok() + .and_then(|mx: usize| column_edge(model.mask, mx, matches!(side, Edge::Top))) + .map(|e| e as i64 + model.dy); + match (mdl, pic) { + (Some(m), Some(p)) => Some(match side { + Edge::Top => (p as f64 - m as f64) * mmpp, + _ => (m as f64 - p as f64) * mmpp, + }), + _ => None, + } + } + Edge::Left | Edge::Right => { + let pic = row_edge(&picture.mask, station, matches!(side, Edge::Left)); + let mdl = (station as i64 - model.dy) + .try_into() + .ok() + .and_then(|my: usize| row_edge(model.mask, my, matches!(side, Edge::Left))) + .map(|e| e as i64 + model.dx); + match (mdl, pic) { + (Some(m), Some(p)) => Some(match side { + Edge::Left => (p as f64 - m as f64) * mmpp, + _ => (m as f64 - p as f64) * mmpp, + }), + _ => None, + } + } + }; + offset.map(|mm| json!(round3(mm))).unwrap_or(Value::Null) + }) + .collect() +} + +/// The first (or last, when `first` is false) row holding column `x`; None if none does. +fn column_edge(mask: &[Vec], x: usize, first: bool) -> Option { + let mut found = None; + for (y, row) in mask.iter().enumerate() { + if row.get(x).copied().unwrap_or(false) { + if first { + return Some(y); + } + found = Some(y); + } + } + found +} + +/// The first (or last) column set in row `y`; None if the row is empty or missing. +fn row_edge(mask: &[Vec], y: usize, first: bool) -> Option { + let row = mask.get(y)?; + if first { row.iter().position(|&on| on) } else { row.iter().rposition(|&on| on) } +} + +/// The overlay PNG: the picture in blue, the model in red, on a canvas that holds both. +fn overlay_png(picture: &Part, model: &Placed) -> Vec { + // A margin so a model that hangs off the picture still fits the canvas. + let m = 8i64; + let (x0, y0) = (0.min(model.dx) - m, 0.min(model.dy) - m); + let (x1, y1) = ( + (picture.width as i64).max(model.dx + model.mask.first().map_or(0, |r| r.len()) as i64) + m, + (picture.height as i64).max(model.dy + model.mask.len() as i64) + m, + ); + let (w, h) = ((x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32); + let mut img = image::RgbaImage::from_pixel(w, h, image::Rgba([250, 250, 250, 255])); + for (y, row) in picture.mask.iter().enumerate() { + for (x, &on) in row.iter().enumerate() { + if on { + img.put_pixel((x as i64 - x0) as u32, (y as i64 - y0) as u32, image::Rgba([70, 110, 230, 255])); + } + } + } + for (r, row) in model.mask.iter().enumerate() { + for (c, &on) in row.iter().enumerate() { + if !on { + continue; + } + let (x, y) = (model.dx + c as i64 - x0, model.dy + r as i64 - y0); + if (0..w as i64).contains(&x) && (0..h as i64).contains(&y) { + img.put_pixel(x as u32, y as u32, image::Rgba([235, 60, 60, 255])); + } + } + } + let mut out = Cursor::new(Vec::new()); + // Encoding a mask-sized PNG cannot realistically fail; if it ever does, no overlay. + let enc = image::codecs::png::PngEncoder::new(&mut out); + use image::ImageEncoder as _; + if enc.write_image(img.as_raw(), img.width(), img.height(), image::ExtendedColorType::Rgba8).is_err() { + return Vec::new(); + } + out.into_inner() +} + +fn round4(v: f64) -> f64 { + if v.abs() < 1e12 { (v * 10_000.0).round() / 10_000.0 } else { v } +} + +fn round3(v: f64) -> f64 { + if v.abs() < 1e12 { (v * 1_000.0).round() / 1_000.0 } else { v } +} diff --git a/crates/engine/src/cmd/compare_picture_tests.rs b/crates/engine/src/cmd/compare_picture_tests.rs new file mode 100644 index 000000000..fe8f44390 --- /dev/null +++ b/crates/engine/src/cmd/compare_picture_tests.rs @@ -0,0 +1,490 @@ +//! Tests for `inspect.compare_picture` (#1486): synthetic reference pictures drawn in code, +//! written to the temp dir and read back through the vfs like any other reference. + +use std::io::Cursor; + +use serde_json::{Value, json}; + +use super::super::Session; +use image::ImageEncoder as _; + +fn run(s: &mut Session, cmd: &str, params: Value) -> Value { + s.execute(cmd, ¶ms).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +fn box_body(s: &mut Session, name: &str, x1: f64, y1: f64, z: f64) { + let sketch = format!("{name}Sketch"); + run(s, "sketch.create", json!({"plane": "XY", "name": sketch})); + run(s, "sketch.rectangle.two_point", json!({"p0": [0.0, 0.0], "p1": [x1, y1]})); + run(s, "sketch.finish", json!({})); + run(s, "solid.extrude", json!({"sketch": sketch, "distance": z, "operation": "new_body", "body_name": name})); +} + +/// A PNG whose pixels come from `paint`. +fn png(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + png_rgba(w, h, |x, y| { + let [r, g, b] = paint(x, y); + [r, g, b, 255] + }) +} + +/// A PNG with alpha, whose pixels come from `paint`. +fn png_rgba(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 4]) -> Vec { + let mut img = image::RgbaImage::new(w as u32, h as u32); + for y in 0..h { + for x in 0..w { + img.put_pixel(x as u32, y as u32, image::Rgba(paint(x, y))); + } + } + let mut out = Cursor::new(Vec::new()); + image::codecs::png::PngEncoder::new(&mut out).write_image(img.as_raw(), w as u32, h as u32, image::ExtendedColorType::Rgba8).unwrap(); + out.into_inner() +} + +fn jpeg(w: usize, h: usize, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + jpeg_q(w, h, 90, paint) +} + +fn jpeg_q(w: usize, h: usize, q: u8, paint: impl Fn(usize, usize) -> [u8; 3]) -> Vec { + let mut img = image::RgbaImage::new(w as u32, h as u32); + for y in 0..h { + for x in 0..w { + let [r, g, b] = paint(x, y); + img.put_pixel(x as u32, y as u32, image::Rgba([r, g, b, 255])); + } + } + let rgb = image::DynamicImage::ImageRgba8(img).to_rgb8(); + let mut out = Cursor::new(Vec::new()); + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, q) + .write_image(rgb.as_raw(), w as u32, h as u32, image::ExtendedColorType::Rgb8) + .unwrap(); + out.into_inner() +} + +/// Write a reference into the temp dir and return its path. +fn reference(name: &str, bytes: &[u8]) -> String { + let path = std::env::temp_dir().join(format!("solidcraft-compare-picture-{}-{name}", std::process::id())); + std::fs::write(&path, bytes).unwrap(); + path.to_string_lossy().into_owned() +} + +/// A white rectangle on a grey backdrop: `x0..x1, y0..y1` in pixels. +fn rect_picture(w: usize, h: usize, x0: usize, y0: usize, x1: usize, y1: usize) -> Vec { + png(w, h, |x, y| if (x0..x1).contains(&x) && (y0..y1).contains(&y) { [255, 255, 255] } else { [200, 200, 200] }) +} + +fn edges(v: &Value) -> Vec>> { + ["top", "bottom", "left", "right"] + .iter() + .map(|side| v["edges"][side].as_array().unwrap().iter().map(|e| e.as_f64()).collect::>>()) + .collect() +} + +fn near(v: Option, want: f64, tol: f64) -> bool { + v.is_some_and(|e| (e - want).abs() <= tol) +} + +#[test] +fn a_matching_picture_scores_high_with_flat_edges() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); // front view: 20 wide, 30 tall + let path = reference("match.png", &rect_picture(200, 280, 20, 20, 180, 260)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + for side in edges(&out) { + for e in side { + assert!(near(e, 0.0, 0.6), "edge {e:?}"); + } + } + assert!(!out["overlay_png"].as_str().unwrap().is_empty()); +} + +#[test] +fn a_step_in_the_bottom_edge_shows_up_in_mm() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // The aligned picture: a plain part 160 x 240 px — the model's own shape at 8 px per mm. + let aligned_path = reference("aligned.png", &rect_picture(200, 280, 20, 20, 180, 260)); + let aligned = run(&mut s, "inspect.compare_picture", json!({"reference": aligned_path, "view": "front"})); + // The stepped picture: over its right half the part's bottom edge sits 35 px higher. + // The width fit gives 8 px per mm, so 35 px is 4.375 mm of the model reaching past + // the picture. + let stepped_path = reference( + "stepped.png", + &png(200, 280, |x, y| { + let bottom = if x >= 100 { 225 } else { 260 }; + if (20..180).contains(&x) && (20..bottom).contains(&y) { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let stepped = run(&mut s, "inspect.compare_picture", json!({"reference": stepped_path, "view": "front"})); + let flat = edges(&aligned)[1].clone(); + let step = edges(&stepped)[1].clone(); + for e in flat.iter() { + assert!(near(*e, 0.0, 0.6), "flat bottom {e:?}"); + } + // Stations sit at local x = 16..144 px; the notch starts at local x = 80 (global 100), + // so stations 5..9 are over it. + for e in step.iter().take(4) { + assert!(near(*e, 0.0, 0.6), "step bottom left {e:?}"); + } + for e in step.iter().skip(4) { + assert!(near(*e, 4.375, 0.6), "step bottom right {e:?}"); + } + assert!(stepped["overlap"].as_f64().unwrap() < aligned["overlap"].as_f64().unwrap()); +} + +/// #1486's example, pinned: `examples/bracket.json` as it is (upright 30 mm) against the +/// same bracket at 40 mm, both from the front, scaled by the 40 mm arm they share. +/// The issue's prototype numbers: overlap 0.865, bottom −9.9 mm at the upright (6 % across), +/// 0.0 mm everywhere else. +#[test] +fn the_issue_bracket_pins_overlap_and_the_short_upright() { + let mut s = Session::default(); + // The bracket profile of examples/bracket.json: a 40 x 6 arm with a 6-wide upright to + // 30 mm, on XZ so the front view shows the upright hanging below the arm. + run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Profile"})); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0], [40, 6], [6, 6], [6, 30], [0, 30]], "closed": true})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 20.0, "direction": "negative", "body_name": "Bracket"})); + // The same bracket with the upright at 40 mm, at 20 px per mm: an 800 x 800 part, the + // 800 x 120 arm on top and the 120-wide upright down to 800, on a grey margin. + let path = reference( + "bracket.png", + &png(840, 840, |x, y| { + let part = ((20..820).contains(&x) && (20..140).contains(&y)) || ((20..140).contains(&x) && (20..820).contains(&y)); + if part { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "rows": 480, "overlay": false})); + let overlap = out["overlap"].as_f64().unwrap(); + assert!((overlap - 0.865).abs() <= 0.01, "overlap {overlap}"); + let e = edges(&out); + // The upright is the first station (x = 80 of 800): the model is 10 mm short there. + assert!(near(e[1][0], -10.0, 0.2), "bottom at the upright {:?}", e[1][0]); + for side in 1..9 { + assert!(near(e[1][side], 0.0, 0.1), "bottom elsewhere {:?}", e[1]); + } + for i in 0..9 { + assert!(near(e[0][i], 0.0, 0.1), "top {:?}", e[0]); + // Below the model's 30 mm upright the model has no row to answer with: those + // side stations are null, as documented. + for side in [e[2].clone(), e[3].clone()] { + match side[i] { + None => {} + Some(v) => assert!(v.abs() <= 0.1, "side {side:?}"), + } + } + } +} + +#[test] +fn a_gradient_backdrop_still_separates_from_the_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // A backdrop that shifts one step per row: the border flood follows it; the step at the + // part's outline (to white) stops it. + let path = reference( + "gradient.png", + &png(200, 300, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [200 + (y / 30) as u8, 200, 200] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); +} + +#[test] +fn a_jpeg_reference_works_too() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + let path = + reference("match.jpg", &jpeg(200, 300, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [40, 40, 40] })); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); +} + +#[test] +fn crop_takes_one_part_off_the_board() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // Two parts side by side; the crop keeps the left one, a plain rectangle that matches + // the model. The right part is bigger overall but L-shaped, so without the crop the + // largest piece wins and the score drops. + let path = reference( + "two.png", + &png(400, 300, |x, y| { + let left = (20..180).contains(&x) && (20..260).contains(&y); + let right = (210..390).contains(&x) && (5..295).contains(&y) && !((300..390).contains(&x) && (100..200).contains(&y)); + if left || right { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "crop_fraction": [0.0, 0.0, 0.5, 1.0]})); + // The picture size is the found part's tight frame: the left rectangle is 160 x 240 px. + assert_eq!(out["picture"]["width"], 160); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + let whole = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front"})); + assert!(whole["overlap"].as_f64().unwrap() < out["overlap"].as_f64().unwrap()); +} + +#[test] +fn crop_px_has_explicit_units() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + let path = reference("px.png", &rect_picture(200, 280, 20, 20, 180, 260)); + // Pixels mean pixels: [10, 10, 180, 260] keeps the part with a margin, and a crop of + // one pixel is one pixel, not the whole picture. + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "crop_px": [10, 10, 180, 260]})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + let dot = reference("dot.png", &rect_picture(200, 280, 100, 100, 101, 101)); + assert!( + s.execute("inspect.compare_picture", &json!({"reference": dot, "crop_px": [0, 0, 1, 1]})).unwrap_err().to_string().contains("no part found") + ); + // Giving both spellings is refused, and so is a fraction above 1. + assert!( + s.execute("inspect.compare_picture", &json!({"reference": path, "crop_px": [0, 0, 10, 10], "crop_fraction": [0.0, 0.0, 0.1, 0.1]})) + .unwrap_err() + .to_string() + .contains("not both") + ); + assert!( + s.execute("inspect.compare_picture", &json!({"reference": path, "crop_fraction": [0.0, 0.0, 1.5, 1.0]})) + .unwrap_err() + .to_string() + .contains("0..1") + ); +} + +#[test] +fn fit_both_never_stretches_the_axes_apart() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); // front view: 20 wide, 30 tall + // A 20 x 20 mm square picture of a 20 x 30 mm model: `both` used to stretch the model + // to the square and report a perfect 1.000 with every edge at 0.0 mm. One uniform + // scale (from the width they share) leaves the 10 mm of overhang visible instead. + let path = reference("square.png", &rect_picture(220, 220, 10, 10, 210, 210)); + let both = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "fit": "both", "overlay": false})); + assert!((both["overlap"].as_f64().unwrap() - 200.0 / 300.0).abs() < 0.02, "overlap {}", both["overlap"]); + assert!((both["aspect_mismatch"].as_f64().unwrap() - 1.5).abs() < 0.01, "aspect_mismatch {}", both["aspect_mismatch"]); + // And `width` is the default: leaving `fit` out answers the same as naming it. + let plain = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + assert_eq!(plain["overlap"], both["overlap"]); + assert_eq!(plain["edges"], both["edges"]); +} + +#[test] +fn fit_width_keeps_the_models_aspect() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // The picture part is 160 x 160 px: fit=width scales the model uniformly to 160 x 240, + // so it hangs 80 px (10 mm) over the picture's height in total, wherever the slide puts + // it. The overlap of a contained model is 160/240 wherever it sits. + let path = reference("short.png", &rect_picture(200, 220, 20, 20, 180, 180)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "fit": "width"})); + assert!((out["overlap"].as_f64().unwrap() - 160.0 / 240.0).abs() < 0.05, "overlap {}", out["overlap"]); + let bottom: Vec> = out["edges"]["bottom"].as_array().unwrap().iter().map(|e| e.as_f64()).collect(); + let top: Vec> = out["edges"]["top"].as_array().unwrap().iter().map(|e| e.as_f64()).collect(); + for i in 0..9 { + // The overhang splits between top and bottom but always totals the extra 10 mm. + assert!(bottom[i].unwrap() >= 0.0 && top[i].unwrap() >= 0.0, "bottom {:?} top {:?}", bottom[i], top[i]); + assert!((bottom[i].unwrap() + top[i].unwrap() - 10.0).abs() < 0.6, "bottom {:?} top {:?}", bottom[i], top[i]); + } +} + +#[test] +fn a_narrow_model_fits_the_grid_not_the_memory() { + let mut s = Session::default(); + // A 2 mm x 1000 mm sliver seen from the front: fitted by width against a 1024-wide + // picture it used to become 1024 x 524 288 booleans. The fitted model now takes the + // same MAX_GRID cap as the picture, so the comparison just runs. + box_body(&mut s, "Sliver", 2.0, 1.0, 1000.0); + let path = reference("sliver.png", &rect_picture(1030, 1010, 3, 5, 1027, 1005)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + // The shapes are nothing alike (the sliver is 1:500, the picture 1024:1000), and the + // capped model grid keeps the overlap small — what matters is that it ran at all. + assert!(out["overlap"].as_f64().unwrap() < 0.1, "overlap {}", out["overlap"]); +} + +#[test] +fn ordinary_pictures_keep_their_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + // A part touching the picture's border: only border pixels close to the border's main + // colour seed the background, so the part's own border pixels do not flood it. + let border = reference("border.png", &rect_picture(200, 280, 0, 20, 160, 260)); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": border, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "border overlap {}", out["overlap"]); + // A white part on a (245, 245, 245) studio backdrop: the step of 10 is below BG_STEP, + // but the stricter retry separates it. + let studio = reference( + "studio.png", + &png(200, 280, |x, y| if (20..180).contains(&x) && (20..260).contains(&y) { [255, 255, 255] } else { [245, 245, 245] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": studio, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "studio overlap {}", out["overlap"]); + // A part on a transparent background: alpha below 128 is background. + let alpha = reference( + "alpha.png", + &png_rgba(200, 280, |x, y| if (20..180).contains(&x) && (20..260).contains(&y) { [90, 90, 90, 255] } else { [0, 0, 0, 0] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": alpha, "view": "front"})); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "alpha overlap {}", out["overlap"]); +} + +#[test] +fn a_through_hole_counts_the_same_on_both_sides() { + let mut s = Session::default(); + // A 200 x 200 mm plate with a 100 x 100 mm through-hole, against a picture of itself + // at 1 px per mm, seen from the top (the hole goes through the plate's faces). The + // picture's hole is filled by the border flood; the model's hole now gets the same + // rule, so the plate scores ~1.0 instead of 0.75. + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Plate"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0.0, 0.0], "p1": [200.0, 200.0]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Plate", "distance": 10.0, "operation": "new_body", "body_name": "Plate"})); + run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Hole"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [50.0, 50.0], "p1": [150.0, 150.0]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"sketch": "Hole", "distance": 20.0, "operation": "cut"})); + let path = reference( + "plate.png", + &png(220, 220, |x, y| { + let plate = (10..210).contains(&x) && (10..210).contains(&y); + let hole = (60..160).contains(&x) && (60..160).contains(&y); + if plate && !hole { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "top", "overlay": false})); + assert!(out["overlap"].as_f64().unwrap() > 0.98, "overlap {}", out["overlap"]); + for side in edges(&out) { + for e in side { + assert!(near(e, 0.0, 0.6), "edge {e:?}"); + } + } +} + +#[test] +fn hostile_and_empty_references_fail_cleanly() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + assert!(s.execute("inspect.compare_picture", &json!({})).is_err()); + // Not an image at all. + let text = reference("not.png", b"just text, not a picture"); + assert!(s.execute("inspect.compare_picture", &json!({"reference": text})).unwrap_err().to_string().contains("PNG or a JPEG")); + // A uniform picture: the background eats everything, and says so. + let flat = reference("flat.png", &png(64, 64, |_, _| [200, 200, 200])); + assert!(s.execute("inspect.compare_picture", &json!({"reference": flat})).unwrap_err().to_string().contains("no part found")); + // A fully transparent picture: alpha says there is nothing there. + let clear = reference("clear.png", &png_rgba(64, 64, |_, _| [0, 0, 0, 0])); + assert!(s.execute("inspect.compare_picture", &json!({"reference": clear})).unwrap_err().to_string().contains("transparent")); + // A missing file. + assert!(s.execute("inspect.compare_picture", &json!({"reference": "no-such-file.png"})).is_err()); + // A bad fit name. + let path = reference("match2.png", &rect_picture(200, 280, 20, 20, 180, 260)); + assert!(s.execute("inspect.compare_picture", &json!({"reference": path, "fit": "diagonal"})).is_err()); + // overlay: false leaves the PNG out. + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + assert!(out.get("overlay_png").is_none()); +} + +/// Reviewer re-test case: a 60 x 60 opaque PNG with a white 40 x 40 square and a single +/// backdrop pixel at alpha 254 used to be read as all part — 1.000 against the 40 x 40 +/// square at 0.067 mm/px instead of 0.1. Alpha now decides only when the border is mostly +/// see-through, and a part drawn at alpha 100 on a transparent backdrop is still the part. +#[test] +fn one_translucent_pixel_does_not_switch_to_alpha() { + let mut s = Session::default(); + box_body(&mut s, "Square", 4.0, 1.0, 4.0); // front view: 4 x 4 mm + let path = reference( + "speck.png", + &png_rgba(60, 60, |x, y| { + let alpha = if x == 5 && y == 55 { 254 } else { 255 }; + let c = if (10..50).contains(&x) && (10..50).contains(&y) { 255u8 } else { 128 }; + [c, c, c, alpha] + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + // The part is the 40 x 40 square: 4 mm over 40 px is 0.1 mm/px, not 4/60 = 0.067. + let mmpp = out["mm_per_px"]["x"].as_f64().unwrap(); + assert!((mmpp - 0.1).abs() < 0.01, "mm_per_px {mmpp}"); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); + // A part drawn at alpha 100 on a transparent backdrop is the part, not the background. + let faint = reference( + "faint.png", + &png_rgba(60, 60, |x, y| if (10..50).contains(&x) && (10..50).contains(&y) { [255, 255, 255, 100] } else { [0, 0, 0, 0] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": faint, "view": "front", "overlay": false})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "faint overlap {}", out["overlap"]); + let mmpp = out["mm_per_px"]["x"].as_f64().unwrap(); + assert!((mmpp - 0.1).abs() < 0.01, "faint mm_per_px {mmpp}"); +} + +/// Reviewer re-test case: one view cropped off a board — the part touches three sides and +/// takes 270 of the 400 border samples, so the border's main colour is the part's own and +/// the flood eats it: the 15 px backdrop strip becomes "the part" and an exact model scores +/// 0.18. `part_fills_crop: true` says the crop box is the part: no flood, exact model ~1.0. +#[test] +fn a_tight_crop_can_declare_the_box_is_the_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 17.0, 10.0, 20.0); // front view: 17 wide, 20 tall + // The tight crop: the white part fills x 0..85 of a 100 x 100 box, touching three + // sides — 270 of the border samples — with a 15 px backdrop strip down the right. + let path = reference("tight.png", &png(100, 100, |x, _| if x < 85 { [255, 255, 255] } else { [200, 200, 200] })); + let flood = run(&mut s, "inspect.compare_picture", json!({"reference": path.clone(), "view": "front", "overlay": false})); + assert!(flood["overlap"].as_f64().unwrap() < 0.5, "the flood keeps the strip: overlap {}", flood["overlap"]); + let out = run( + &mut s, + "inspect.compare_picture", + json!({"reference": path, "view": "front", "crop_px": [0, 0, 85, 100], "part_fills_crop": true, "overlay": false}), + ); + assert!(out["overlap"].as_f64().unwrap() > 0.95, "overlap {}", out["overlap"]); + // 17 mm over the 85 px the part fills: 0.2 mm/px. + assert!((out["mm_per_px"]["x"].as_f64().unwrap() - 0.2).abs() < 0.01, "mm_per_px {}", out["mm_per_px"]); + // A crop of a 2 x 2 box is the part; a 1 px box is refused. + let dot = reference("tight-dot.png", &png(4, 4, |_, _| [255, 255, 255])); + assert!( + s.execute("inspect.compare_picture", &json!({"reference": dot, "part_fills_crop": true, "crop_px": [0, 0, 1, 1]})) + .unwrap_err() + .to_string() + .contains("2 x 2") + ); +} + +/// Reviewer re-test case: holes are filled on both sides, so a model missing a 100 x 100 +/// through-hole scores ~1.000 against a picture that shows the hole. That is the contract — +/// outline only — and the command description must say so, so an agent does not read 1.000 +/// as "matches". +#[test] +fn the_compare_is_outline_only_holes_are_not_compared() { + assert!( + crate::cmd::compare_picture::COMMANDS[0].params.contains("holes are not compared"), + "the command description must say the compare is outline only" + ); + let mut s = Session::default(); + // A solid 200 x 200 mm plate against a picture of a plate with a 100 x 100 through-hole. + box_body(&mut s, "Plate", 200.0, 10.0, 200.0); + let path = reference( + "hole-only.png", + &png(220, 220, |x, y| { + let plate = (10..210).contains(&x) && (10..210).contains(&y); + let hole = (60..160).contains(&x) && (60..160).contains(&y); + if plate && !hole { [255, 255, 255] } else { [200, 200, 200] } + }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + // The outlines match: the hole is not compared, as the description says. + assert!(out["overlap"].as_f64().unwrap() > 0.98, "overlap {}", out["overlap"]); +} + +/// Reviewer re-test case: a white part on (245, 245, 245) saved as JPEG at quality 75 gave +/// "no part" even on the stricter retry — the codec blurs the 10-level step at the part's +/// outline into steps of a few levels each, under any local limit. The third pass takes the +/// backdrop globally: near the border's main colour. +#[test] +fn a_light_jpeg_keeps_its_part() { + let mut s = Session::default(); + box_body(&mut s, "Box", 20.0, 10.0, 30.0); + let path = reference( + "light.jpg", + &jpeg_q(200, 300, 75, |x, y| if (20..180).contains(&x) && (20..280).contains(&y) { [255, 255, 255] } else { [245, 245, 245] }), + ); + let out = run(&mut s, "inspect.compare_picture", json!({"reference": path, "view": "front", "overlay": false})); + assert!(out["overlap"].as_f64().unwrap() > 0.9, "overlap {}", out["overlap"]); +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index ca96a6199..c76ed7bd8 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -26,6 +26,9 @@ pub(crate) mod clearance; mod clipboard; mod clipboard_foreign; mod compare; +mod compare_picture; +#[cfg(test)] +mod compare_picture_tests; mod component; mod component_clone; mod component_clone_assembly; @@ -346,6 +349,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> { v.extend(metadata::COMMANDS.iter()); v.extend(inspect::COMMANDS.iter()); v.extend(compare::COMMANDS.iter()); + v.extend(compare_picture::COMMANDS.iter()); v.extend(silhouette::COMMANDS.iter()); v.extend(materials::COMMANDS.iter()); v.extend(material_properties::COMMANDS.iter()); diff --git a/crates/engine/src/cmd/silhouette.rs b/crates/engine/src/cmd/silhouette.rs index f44a9f02f..17b3f9b0a 100644 --- a/crates/engine/src/cmd/silhouette.rs +++ b/crates/engine/src/cmd/silhouette.rs @@ -20,19 +20,50 @@ fn run(s: &mut Session, p: &Value) -> Result { let camera = camera(p)?; let rows = rows(p)?; let wanted = body_names(p)?; + let out = outline(s, &camera, wanted.as_deref(), rows)?; + let mask: Vec> = out.mask.iter().map(|row| spans(row)).collect(); + Ok(json!({ + "width": out.width, + "height": out.height, + "mm_per_px": round4(out.mm_per_px), + "box_mm": [[round4(out.lo[0]), round4(out.lo[1])], [round4(out.hi[0]), round4(out.hi[1])]], + "right": [clean(out.right.x), clean(out.right.y), clean(out.right.z)], + "up": [clean(out.up.x), clean(out.up.y), clean(out.up.z)], + "projection": if out.perspective { "perspective" } else { "parallel" }, + "bodies": out.bodies, + "triangles": out.triangles, + "mask": mask, + })) +} + +/// A projected, tightly framed silhouette: the pixel grid, its scale and placement, and the +/// filled mask as one row of booleans per pixel row. `inspect.silhouette` renders this as +/// run-length rows; `inspect.compare_picture` uses the filled rows directly. +pub(crate) struct Silhouette { + pub width: usize, + pub height: usize, + pub mm_per_px: f64, + /// The view-plane box the mask frames, in mm (u along `right`, v along `up`). + pub lo: [f64; 2], + pub hi: [f64; 2], + pub right: Vec3, + pub up: Vec3, + pub perspective: bool, + pub bodies: usize, + pub triangles: usize, + pub mask: Vec>, +} + +pub(crate) fn outline(s: &Session, camera: &Camera, wanted: Option<&[String]>, rows: usize) -> Result { let state = s.world_state(); - if let Some(names) = &wanted { + if let Some(names) = wanted { for name in names { if !state.bodies.iter().any(|b| b.name == *name) { return Err(bad(CMD, format!("unknown body name `{name}`"))); } } } - let bodies: Vec<_> = state - .bodies - .iter() - .filter(|b| wanted.as_ref().map_or_else(|| s.body_visible(&b.name), |names| names.iter().any(|name| name == &b.name))) - .collect(); + let bodies: Vec<_> = state.bodies.iter().filter(|b| wanted.map_or_else(|| s.body_visible(&b.name), |names| names.contains(&b.name))).collect(); if bodies.is_empty() { return Err(bad(CMD, "nothing visible to outline")); } @@ -133,22 +164,22 @@ fn run(s: &mut Session, p: &Value) -> Result { } } - let mask: Vec> = covered.chunks_exact(width).map(spans).collect(); - Ok(json!({ - "width": width, - "height": height, - "mm_per_px": round4(mm_per_px), - "box_mm": [[round4(lo[0]), round4(lo[1])], [round4(hi[0]), round4(hi[1])]], - "right": [clean(right.x), clean(right.y), clean(right.z)], - "up": [clean(up.x), clean(up.y), clean(up.z)], - "projection": if perspective { "perspective" } else { "parallel" }, - "bodies": bodies.len(), - "triangles": triangle_count, - "mask": mask, - })) + Ok(Silhouette { + width, + height, + mm_per_px, + lo, + hi, + right, + up, + perspective, + bodies: bodies.len(), + triangles: triangle_count, + mask: covered.chunks_exact(width).map(|row| row.to_vec()).collect(), + }) } -fn camera(p: &Value) -> Result { +pub(crate) fn camera(p: &Value) -> Result { if p.get("view").is_some() && p.get("camera").is_some() { return Err(bad(CMD, "give `view` or `camera`, not both")); } @@ -171,7 +202,7 @@ fn camera(p: &Value) -> Result { Ok(camera) } -fn body_names(p: &Value) -> Result>> { +pub(crate) fn body_names(p: &Value) -> Result>> { match p.get("bodies") { None => Ok(None), Some(Value::String(name)) => Ok(Some(vec![name.clone()])), @@ -184,7 +215,7 @@ fn body_names(p: &Value) -> Result>> { } } -fn rows(p: &Value) -> Result { +pub(crate) fn rows(p: &Value) -> Result { match p.get("rows") { None => Ok(240), Some(v) => { @@ -209,7 +240,7 @@ fn edge(a: [f64; 2], b: [f64; 2], p: [f64; 2]) -> f64 { (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) } -fn spans(row: &[bool]) -> Vec<[usize; 2]> { +pub(crate) fn spans(row: &[bool]) -> Vec<[usize; 2]> { let mut out = Vec::new(); let mut start = None; for (x, &on) in row.iter().enumerate() { diff --git a/crates/mcp/Cargo.toml b/crates/mcp/Cargo.toml index 057cca258..47c03f4da 100644 --- a/crates/mcp/Cargo.toml +++ b/crates/mcp/Cargo.toml @@ -15,3 +15,5 @@ serde_json = { workspace = true } [dev-dependencies] # The renderer `solidcraft-cli mcp` installs, so the tests' screenshots are drawn as the server's. solidcraft-gpu = { workspace = true } +# Synthetic reference pictures for the compare_picture test. +image = { workspace = true } diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 23957f826..4a0e6cc0a 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -137,6 +137,7 @@ fn handshake_and_tools_list() { "set_parameter", "check_parameters", "screenshot", + "compare_picture", "export", "undo", "redo", @@ -1469,6 +1470,46 @@ fn legacy_design_files_and_resource_uris() { let _ = std::fs::remove_dir_all(&dir); } +/// `compare_picture` (#1486): the overlay comes back as an image block and the numbers as text. +#[test] +fn compare_picture_returns_the_overlay_as_an_image() { + use image::ImageEncoder as _; + use std::io::Cursor; + // A scoped server, like `solidcraft-cli mcp`: the reference must be inside the folders. + let base = solidcraft_engine::io::vfs::temp_dir().join(format!("solidcraft-mcp-compare-{}", std::process::id())); + let recovery = base.join("recovery"); + std::fs::create_dir_all(&recovery).unwrap(); + let scope = crate::agent_scope_with(Some(recovery.clone()), []); + let mut s = Server::new(Box::new(Headless::default())).with_path_scope(Some(scope)); + tool(&mut s, "execute", json!({"command": "solid.box", "params": {"length": 20, "width": 10, "height": 30}})); + // A white rectangle on grey with the box's front-view proportions (20 x 30 mm). + let (w, h) = (200u32, 300u32); + let mut img = image::RgbaImage::from_pixel(w, h, image::Rgba([200, 200, 200, 255])); + for y in 20..280 { + for x in 20..180 { + img.put_pixel(x, y, image::Rgba([255, 255, 255, 255])); + } + } + let mut png = Cursor::new(Vec::new()); + image::codecs::png::PngEncoder::new(&mut png).write_image(img.as_raw(), w, h, image::ExtendedColorType::Rgba8).unwrap(); + let path = recovery.join("target.png"); + std::fs::write(&path, png.into_inner()).unwrap(); + + let r = raw_tool(&mut s, "compare_picture", json!({"reference": path.to_string_lossy(), "view": "front"})); + assert_ne!(r["result"]["isError"], json!(true), "{r}"); + let content = r["result"]["content"].as_array().unwrap().clone(); + assert_eq!(content[0]["type"], "image", "{content:?}"); + assert_eq!(content[0]["mimeType"], "image/png"); + assert!(content[0]["data"].as_str().unwrap().starts_with("iVBORw0KGgo"), "not a PNG"); + let info: Value = serde_json::from_str(content[1]["text"].as_str().unwrap()).unwrap(); + assert!(info["overlap"].as_f64().unwrap() > 0.9, "{info}"); + assert!(info.get("overlay_png").is_none(), "the base64 blob belongs in the image block only"); + // A reference outside the server's folders is refused through the existing path rules. + let outside = raw_tool(&mut s, "compare_picture", json!({"reference": "/etc/hostname"})); + assert_eq!(outside["result"]["isError"], json!(true), "{outside}"); + let _ = std::fs::remove_dir_all(&base); +} + /// The default folders (#205): the recovery folder works out of the box, `screenshot` without a /// `path` uses the server's own scratch folder, and the open design's folder counts while the /// design is open there, without its hidden files. The working folder doesn't count at all. diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 4c8c57cba..10edfe085 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -147,7 +147,7 @@ pub fn tool_definitions() -> Vec { (as list_commands lists them). A step may also name one of these tools with that tool's arguments as params, \ and runs the engine command it stands for: set_parameter (parameters.change; `value` or `expression`), \ list_commands (engine.commands, with `filter`), describe_command (engine.describe), execute ({command, params}), \ - measure (inspect.measure), \ + measure (inspect.measure), compare_picture (inspect.compare_picture, numbers only: no overlay PNG), \ inspect_design (document.inspect), undo, redo, export, save, open, new_design, crash_reports; screenshot, \ body_topology, batch and pending can't be steps. On an error the steps already run are undone (unless \ rollback: false), so the batch is all-or-nothing; the reply names the failing step (index from 0), its error, \ @@ -307,6 +307,34 @@ pub fn tool_definitions() -> Vec { ), Effect::Files, ), + tool( + "compare_picture", + "Compare with a reference picture", + "Compare the model's outline with the part in a reference picture — a concept render, a product photo, one view off a design board. \ + The model's outline is `inspect.silhouette` from `view` (default front), `camera` and `bodies`; the picture's part is found by growing \ + the background in from the border, so a backdrop's gradual shading stays background. The compare is outline only: holes are not \ + compared — both the picture's and the model's holes are filled. `reference` is a PNG or JPEG inside the server's \ + folders. `crop_px` / `crop_fraction` take one view off a board: [x, y, w, h] in pixels or as fractions 0..1 of the picture; \ + `part_fills_crop: true` says the crop box is the part itself, for a crop that tightly frames it. `fit` names \ + the dimension the scale comes from (\"width\", \"height\", \"both\"; default \"width\") — one uniform scale, never stretched per axis; \ + \"both\" scales by width and reports `aspect_mismatch` when the shapes differ. Returns as text the overlap (0..1) and the model's top, \ + bottom, left and right edges against the picture's in mm at nine stations (positive where the model reaches past the picture), and as \ + an image the overlay PNG: model red, picture blue.", + obj( + json!({ + "reference": string("PNG or JPEG to match, inside the server's folders"), + "view": string("Standard view (front, top, right, iso, ...) the picture is seen from (default front)"), + "camera": {"type": "object", "description": "Look from this camera instead: {target: [x,y,z], yaw, pitch, distance, fov?} (radians, mm; as view.apply). A photo taken in perspective gets an fov"}, + "bodies": {"type": "array", "items": {"type": "string"}, "description": "Body names to outline (default: the visible bodies)"}, + "crop_px": {"type": "array", "items": {"type": "number"}, "description": "[x, y, w, h] in pixels"}, + "crop_fraction": {"type": "array", "items": {"type": "number"}, "description": "[x, y, w, h] as fractions 0..1 of the picture"}, + "fit": {"type": "string", "enum": ["width", "height", "both"], "description": "The dimension the one uniform scale comes from (default width); both scales by width and reports aspect_mismatch"}, + "rows": {"type": "integer", "description": "The model outline's height in pixels (default 240)"}, + }), + &["reference"], + ), + Effect::Files, + ), tool( "export", "Export", @@ -497,6 +525,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Value { let a = args.as_object().unwrap_or(&empty); let r = match name { "screenshot" => return screenshot(b, a), + "compare_picture" => return compare_picture(b, a), "batch" => return batch(b, a), "check_parameters" => return check_parameters(b, a), "execute" => return execute(b, a), @@ -992,6 +1021,14 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option), String> { Some(items) => mapped("inspect.measure", json!({"items": items})), None => Ok(("inspect.measure".into(), measure_params(a), measure_summary_wanted(a).then_some(Narrow::MeasureSummary))), }, + "compare_picture" => { + // A batch step gets the numbers; the overlay PNG would be a base64 blob in text. + let mut p = pick(a, &["reference", "view", "camera", "bodies", "crop_px", "crop_fraction", "fit", "rows"]); + if let Some(obj) = p.as_object_mut() { + obj.entry("overlay".to_string()).or_insert(json!(false)); + } + mapped("inspect.compare_picture", p) + } "inspect_design" => mapped("document.inspect", json!({"measure": a.get("measure").and_then(Value::as_bool).unwrap_or(true)})), "undo" => mapped("edit.undo", json!({})), "redo" => mapped("edit.redo", json!({})), @@ -1020,6 +1057,7 @@ const TOOL_STEPS: &[&str] = &[ "batch", "body_topology", "check_parameters", + "compare_picture", "crash_reports", "describe_command", "execute", @@ -1777,6 +1815,28 @@ fn screenshot(b: &mut dyn Backend, a: &Map) -> Value { } } +/// `compare_picture`: run the engine comparison and hand the overlay PNG back as an MCP +/// image block, the numbers as text — an agent sees the picture, not a base64 blob. +fn compare_picture(b: &mut dyn Backend, a: &Map) -> Value { + let mut params = pick(a, &["reference", "view", "camera", "bodies", "crop_px", "crop_fraction", "fit", "rows"]); + params["overlay"] = json!(true); + match exec(b, "inspect.compare_picture", params) { + Ok(v) => { + let overlay = v.get("overlay_png").and_then(Value::as_str).unwrap_or_default().to_string(); + let mut info = v; + if let Some(obj) = info.as_object_mut() { + obj.remove("overlay_png"); + } + let mut content = vec![json!({"type": "text", "text": info.to_string()})]; + if !overlay.is_empty() { + content.insert(0, json!({"type": "image", "data": overlay, "mimeType": "image/png"})); + } + json!({"content": content}) + } + Err(e) => text_result(&Value::String(e), true), + } +} + fn capture(b: &mut dyn Backend, a: &Map) -> Result<(Vec, Value), String> { // `grid` and `axes` shape a model render; the window shows what it shows. let guides: Vec<(&str, bool)> = ["grid", "axes"].into_iter().filter_map(|k| a.get(k).and_then(Value::as_bool).map(|v| (k, v))).collect(); diff --git a/docs/mcp.md b/docs/mcp.md index 8260913a3..a12f8f442 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -154,8 +154,9 @@ Each tool says what it may do, for clients that ask before running tools (or aut these hints). `list_commands`, `describe_command`, `inspect_design`, `measure`, `body_topology`, `skill_reference`, `crash_reports`, `pending` and `running` are read-only. `set_parameter`, `undo` and `redo` change the design undoably, and so does `check_parameters` (it changes the design and puts it back: -not read-only, not destructive). `new_design` replaces it (destructive). `execute`, `batch`, `open`, `save`, `export` and -`screenshot` (whose `path` writes a file) can read, write, overwrite or delete files: they are +not read-only, not destructive). `new_design` replaces it (destructive). `execute`, `batch`, `open`, `save`, `export`, +`screenshot` (whose `path` writes a file) and `compare_picture` (which reads the reference picture) can read, +write, overwrite or delete files: they are not read-only, `destructiveHint` and `openWorldHint` are true. ### Client configuration @@ -288,7 +289,7 @@ The `skill_reference` tool returns these documents from the copies built into So | `list_commands` | `filter?` | The command catalog: id, label, tab/panel, shortcut, parameter docs, enabled now. `filter` matches id, label, tab and panel. | | `describe_command` | `id` | One command's parameter docs (`params`) and, for commands with a typed contract (every new command, and more of the older ones as they are converted), the JSON Schemas (2020-12) of its parameters (`input`) and of a successful result (`output`); `null` for the others. The same as `execute` `engine.describe {command}`. | | `execute` | `command`, `params?`, `verbose?` (default true), `expect?` | Run any command with JSON parameters (`list_commands` shows them). Failures leave the design unchanged. A feature command replies with the feature (`feature`, `name`), every body (`bodies`) and the bodies it created, changed and removed (`created_bodies`, `changed_bodies`, `removed_bodies`). `verbose: false` uses the same compact reply as `batch`. `expect` checks the design after the command, as it does for `batch` (see below). | -| `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?`, `coalesce_parameters?` (default false), `expect?` | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`), every result before it, `rolled_back` (true only when the design really went back to where the batch started), `undone`, `applied` (the indices of the steps whose changes are in the design) and `not_run` (the steps never sent). A step may name a tool instead of a command, with that tool's arguments as `params`: `set_parameter` (runs `parameters.change`; `value` or `expression`), `list_commands` (`engine.commands`, filtered by `filter` as the tool filters it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure` (`summary: true` summarised as the tool summarises it), `inspect_design` (`document.inspect`: each sketch as its counts, not its full contents, and no joints), `undo`, `redo`, `export`, `save`, `open`, `new_design` and `crash_reports`. `screenshot`, `body_topology` (use `model.edges` and `model.faces`), `batch`, `check_parameters`, `pending`, `running` and `skill_reference` can't be steps, nor can `component.edit_in_place` and `component.finish_edit`, however a step names them, as they go to another design's tab (send them with the `execute` tool on their own): such a batch fails before anything is sent. So does a step the batch would certainly refuse at its turn (#5853): a step without a command, an unknown command id (the error names the closest ids) or, with `--param-check strict`, parameters that break a command's contract. A headless session checks this itself; an app checks it against its own commands when it gets the batch, and a bridged server at `--param-check strict` checks the contracts before it sends the batch. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. `coalesce_parameters: true` sets each run of consecutive plain parameter edits (`parameters.change` or `set_parameter` with a name and a value, or `changes`) together, so the design rebuilds once per run instead of once per edit. Steps between runs see the design up to date. Each step keeps its own result (`coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits, so an edit refused on its own can go through with the run's later ones. A refused run goes step by step, naming the refused step. | +| `batch` | `commands: [{command, params}]`, `rollback?` (default true), `verbose?` (default true), `timings?`, `profile?`, `coalesce_parameters?` (default false), `expect?` | Run steps in order, stop at the first error and undo the completed steps. The reply names the failing step (`failed.index`, `failed.command`, `failed.error`), every result before it, `rolled_back` (true only when the design really went back to where the batch started), `undone`, `applied` (the indices of the steps whose changes are in the design) and `not_run` (the steps never sent). A step may name a tool instead of a command, with that tool's arguments as `params`: `set_parameter` (runs `parameters.change`; `value` or `expression`), `list_commands` (`engine.commands`, filtered by `filter` as the tool filters it), `describe_command` (`engine.describe`), `execute` (`{command, params}`), `measure` (`summary: true` summarised as the tool summarises it), `compare_picture` (`inspect.compare_picture`, numbers only: no overlay PNG), `inspect_design` (`document.inspect`: each sketch as its counts, not its full contents, and no joints), `undo`, `redo`, `export`, `save`, `open`, `new_design` and `crash_reports`. `screenshot`, `body_topology` (use `model.edges` and `model.faces`), `batch`, `check_parameters`, `pending`, `running` and `skill_reference` can't be steps, nor can `component.edit_in_place` and `component.finish_edit`, however a step names them, as they go to another design's tab (send them with the `execute` tool on their own): such a batch fails before anything is sent. So does a step the batch would certainly refuse at its turn (#5853): a step without a command, an unknown command id (the error names the closest ids) or, with `--param-check strict`, parameters that break a command's contract. A headless session checks this itself; an app checks it against its own commands when it gets the batch, and a bridged server at `--param-check strict` checks the contracts before it sends the batch. `verbose: false` keeps the reply small in large designs: feature steps leave out the full body list (`created_bodies`, `changed_bodies`, `removed_bodies` stay) and sketch steps the ids they repeat outside `created`. Bridged to an app that has `engine.batch`, the whole batch is one control request (one frame of the app). Older apps, and apps showing the agent cursor, get the steps one by one. `timings: true` adds `timings: [{index, command, ms}]` for every step run, the failing one included, and `total_ms`. `profile: true` also adds each step's `profile: {boolean_ms, tessellate_ms, other_ms}`, its time in kernel booleans, in tessellation and the rest. Steps are timed where they run: in the app when bridged. An app without `engine.batch` is timed step by step, without `profile`. `coalesce_parameters: true` sets each run of consecutive plain parameter edits (`parameters.change` or `set_parameter` with a name and a value, or `changes`) together, so the design rebuilds once per run instead of once per edit. Steps between runs see the design up to date. Each step keeps its own result (`coalesced`: the run's length), and the run is one undo step. The run skips the states between its edits, so an edit refused on its own can go through with the run's later ones. A refused run goes step by step, naming the refused step. | **`expect`** on `batch` and `execute` turns the verify step into part of the build. An agent computes the volume, body count or bounding box a stage should produce before building it; @@ -315,6 +316,7 @@ builds it. | `set_parameter` | `name`, `value` or `expression` (number or expression), `unit?`, `comment?` | Create or change a user parameter and recompute. `expression` is another name for `value` (the one `parameters.change` uses): give one of them, or both only when they agree; neither, or two that differ, is an error. Reports `recomputed` (features rebuilt), `restored` (features whose earlier result for the same inputs was reused, e.g. a value set back) and features that now fail. An expression `new_name = expression` renames the parameter as it sets it; in any other tool's expression parameter it adds the user parameter `new_name` and the input uses it (`defined`, `definitions` in the reply). | | `check_parameters` | `set: {name: value}` (a number or an expression each, as `set_parameter`'s `value`), `report?` (`measure`, `cylinders`, `errors`; default all three) | Try parameter values without keeping them: one `edit.checkpoint`, every value set in one `parameters.change {changes}` (one rebuild; an app without `changes` gets one change per name), the reports read, then `edit.restore_checkpoint`, so the design, its parameters and its undo history are exactly as before. The reply has `values` (each parameter's value with the tried expressions in), `recomputed`, `measure` (volume, bbox, bodies and faces per body, as the `measure` tool reports them), `errors` and `warnings` (the features that fail or warn: `{feature, name, error}`) with `parameter_errors` (the parameters that don't evaluate), `cylinders` (every cylindrical face of every body as `{body, radius, origin, axis, faces, name, area}`; the halves a kernel splits one cylinder into are one entry, `origin` is the axis point closest to the world origin and `axis` points so that its first non-zero component is positive) and `restored: true`. A name the design has no parameter of, a value that is not a number or a string, an expression that does not evaluate or an unknown report item is an error, and nothing changes. If the checkpoint cannot be restored the call is an error with `restored: false`, `restore_error` and a note that the tried values are still in the design: set them back before saving. Replaces the loop `set_parameter`, `measure`, `body_topology`, `set_parameter` back, which cost every agent session three to five calls and up to 16 s of rebuilds. Not a `batch` step. | | `screenshot` | `view?` (iso, top, front, back, bottom, left, right, home, fit, or a named view saved with `view.save`), `camera?` (`{target, yaw, pitch, distance, fov?}`, as `view.apply`), `path?`, `width?`, `height?`, `source?` (window, model), `grid?`, `axes?` | A PNG image content block. Headless: a render with the viewport's pipelines on a headless GPU device (see `solidcraft-cli gpu`; with no adapter, the CPU rasterizer, without analysis colours), fitted to the model, or from the named view or camera; the reply's `renderer` says which (`gpu`, `gpu-software`, `cpu`, with a `warning` for `cpu`). Bridged: the app window (default) or a model render with the app's camera; a named view or camera moves the app's viewport there first (`execute` `view.apply` does the same without a screenshot). `grid: false` and `axes: false` leave the ground grid (it lies on Z 0 and cuts through a part that straddles it) and the origin's axes out of a model render; axes hidden with `browser.visibility` stay out whatever `axes` says. Bridged, a screenshot that gives `grid` or `axes` is a model render, which follows the app's Grid and Origin switches for what it does not give; `source: "window"` with either is an error. A window that is minimised or on another macOS Space presents no frame: with no `source` the reply is a model render and says so (`fallback`); `source: "window"` is an error saying why, at once. Agents that don't need the app's chrome can ask for `source: "model"`. | +| `compare_picture` | `reference`, `view?`, `camera?`, `bodies?`, `crop_px?`, `crop_fraction?`, `part_fills_crop?`, `fit?` (width, height, both; default width), `rows?` | Compare the model's outline with the part in a reference picture (a PNG or JPEG inside the server's folders, read through the same path rules as `screenshot`). The compare is outline only: holes are not compared — both the picture's and the model's holes are filled. The model's outline is `inspect.silhouette` seen from `view` (default front) or `camera`; the picture's part is found by growing the background in from the border through small colour steps, filling holes and keeping the largest piece, so a backdrop's shading stays background and labels on a board drop out; a part touching the border, a white part on a light grey backdrop, and a part on a transparent background all separate. `crop_px` (`[x, y, w, h]` in pixels) or `crop_fraction` (the same as fractions 0..1) takes one view off a board; with `part_fills_crop: true` the crop box is the part itself and no background search runs, for a crop that tightly frames the part; `fit` names the dimension the one uniform scale comes from, never stretched per axis (`both` scales by width and reports `aspect_mismatch`). Returns an image content block (the overlay PNG: model red, picture blue) and text: `overlap` (0..1) and the model's top, bottom, left and right edges against the picture's in mm at nine stations, positive where the model reaches past the picture, null where a station misses one of the two. As a `batch` step it runs `inspect.compare_picture` without the overlay. | | `export` | `path`, `format?` (step, 3mf, 3mf-tagged, stl, stla, obj, urdf), `bodies?`, `mesh_prefix?`, `effort?`, `velocity?` | STEP, 3MF or mesh export; URDF writes the whole assembly with its meshes next to it (`docs/urdf.md`). | | `undo`, `redo` | — | Undo / redo one change. | | `pending` | — | Bridged: the result of a request that was still running when its call returned (an error starting `still running:`), waiting up to 60 s for it; `done: false` while it runs (call again), `pending: null` when nothing runs. See [Long-running requests](#long-running-requests). | From 90c09eaaf947c6669dfb377cccf82f2ebeb207f2 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:48:15 +0000 Subject: [PATCH 13/55] Regenerate generated files and fold pending files [skip ci] --- assets/locales/ar.json | 18 +++ assets/locales/de.json | 18 +++ assets/locales/en.json | 18 +++ assets/locales/he.json | 18 +++ assets/locales/ja.json | 18 +++ assets/locales/ko.json | 18 +++ assets/locales/pending/render-results.json | 162 --------------------- assets/locales/vi.json | 18 +++ assets/locales/zh.json | 18 +++ docs/features.md | 7 +- 10 files changed, 149 insertions(+), 164 deletions(-) delete mode 100644 assets/locales/pending/render-results.json diff --git a/assets/locales/ar.json b/assets/locales/ar.json index 41a51c841..e0c08fd3d 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -1048,6 +1048,9 @@ "cmd.pointcloud_edit": "تحرير سحابة النقاط", "cmd.pointcloud_insert": "إدراج سحابة نقاط", "cmd.pointcloud_list": "سحب النقاط", + "cmd.render.compare.divider": "تحريك فاصل مقارنة التصيير", + "cmd.render.result.discard": "تجاهل نتيجة التصيير", + "cmd.render.result.select": "تحديد نتيجة التصيير", "cmd.render_aging_describe": "تقادم السطح بالطبقات", "cmd.render_backends": "محركات التصيير", "cmd.render_batch": "تصيير كل اللقطات", @@ -2576,6 +2579,10 @@ "render.base_color": "اللون الأساسي · sRGB", "render.base_metallic": "النسبة المعدنية", "render.base_opaque_only": "يحافظ هذا المحرر على دلالات الجسم المعتم. استخدم عناصر التحكم الصريحة للزجاج من أجل النفاذ البصري.", + "render.batch_all_shots": "كل اللقطات ({count})", + "render.batch_empty": "احفظ لقطة قبل تصيير كل اللقطات.", + "render.batch_limit": "تصيير كل اللقطات محدود بـ 32 لقطة.", + "render.batch_status": "{running} قيد التشغيل · {waiting} في الانتظار", "render.bloom_enable": "توهج العرض", "render.bloom_help": "توهج إبداعي للإخراج فقط من الإضاءات الخطية الموجبة، يُنشر بثلاث تمريرات صندوقية مُطبّعة. نصف القطر ببكسلات الإخراج. يُضاف في ضوء العرض الخطي قبل sRGB؛ وليس عدسة ولا تأثيرًا حجميًا ولا تحسينًا للتقارب. يبقى EXR الخام دون تغيير.", "render.bloom_opaque": "يتطلب التوهج إخراجًا معتمًا. يُرفض PNG الشفاف بدل تسطيحه بصمت.", @@ -2686,6 +2693,13 @@ "render.choose_look": "اختر مظهرًا من المظاهر أولًا", "render.chromatic_offset": "إزاحة لونية عند الحواف", "render.clear_stage": "إزالة المنصة المحفوظة", + "render.compare_divider": "فاصل المقارنة", + "render.compare_live": "حي", + "render.compare_live_preview": "معاينة حية", + "render.compare_render": "التصيير {number}", + "render.compare_side": "التصيير {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} ث · {renderer} · التُقطت عند المراجعة {revision}", + "render.compare_swap": "تبديل", "render.copy_request": "نسخ JSON", "render.cpu_aa_help": "العيّنات المكانية: المزيد منها يحسّن الحواف ويزيد زمن التصيير.", "render.cpu_area_add": "إضافة ضوء مستطيل على CPU", @@ -3435,6 +3449,10 @@ "render.result_retained": "تُعرض آخر صورة مكتملة؛ ولم يستبدلها تصيير أحدث.", "render.result_sequence": "نقطة التحقق", "render.result_title": "نتيجة التصيير", + "render.results_choose": "النتائج المحتفظ بها", + "render.results_label": "التصيير {number} · {shot} · {seconds} ث", + "render.results_stale_label": "{result} [قديم]", + "render.results_unnamed": "صورة", "render.return_design": "العودة إلى التصميم", "render.review_stale": "هذه المراجعة قديمة. حُلّها أو افحص مرة أخرى قبل التطبيق.", "render.ribbon_aging": "التقادم", diff --git a/assets/locales/de.json b/assets/locales/de.json index 3385d3f21..e50bc40dd 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -1046,6 +1046,9 @@ "cmd.pointcloud_edit": "Punktwolke bearbeiten", "cmd.pointcloud_insert": "Punktwolke einfügen", "cmd.pointcloud_list": "Punktwolken", + "cmd.render.compare.divider": "Render-Vergleichstrenner verschieben", + "cmd.render.result.discard": "Renderergebnis verwerfen", + "cmd.render.result.select": "Renderergebnis auswählen", "cmd.render_aging_describe": "Mehrschichtige Oberflächenalterung", "cmd.render_backends": "Render-Backends", "cmd.render_batch": "Alle Aufnahmen rendern", @@ -2572,6 +2575,10 @@ "render.base_color": "Grundfarbe · sRGB", "render.base_metallic": "Metallanteil", "render.base_opaque_only": "Dieser Editor lässt Körper undurchsichtig. Für optische Transmission verwenden Sie die gesonderten Glaseinstellungen.", + "render.batch_all_shots": "Alle Ansichten ({count})", + "render.batch_empty": "Vor dem Rendern aller Ansichten eine Ansicht speichern.", + "render.batch_limit": "Es können höchstens 32 Ansichten gerendert werden.", + "render.batch_status": "{running} läuft · {waiting} warten", "render.bloom_enable": "Darstellungs-Bloom", "render.bloom_help": "Kreativer Ausgabeglanz aus linearen Glanzlichtern mit drei normierten Durchläufen. Radius in Ausgabepixeln; Addition vor sRGB. Keine Linsen-, Volumen- oder Konvergenzsimulation. Das rohe EXR bleibt unverändert.", "render.bloom_opaque": "Bloom benötigt eine deckende Ausgabe. Transparentes PNG wird abgelehnt, nicht still abgeflacht.", @@ -2682,6 +2689,13 @@ "render.choose_look": "Zuerst einen Look in der Bibliothek wählen", "render.chromatic_offset": "Chromatischer Kantenversatz", "render.clear_stage": "Remove saved stage", + "render.compare_divider": "Vergleichstrenner", + "render.compare_live": "Live", + "render.compare_live_preview": "Live-Vorschau", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · aufgenommen bei Revision {revision}", + "render.compare_swap": "Tauschen", "render.copy_request": "JSON kopieren", "render.cpu_aa_help": "Räumliche Samples: Mehr Samples verbessern die Kantenglättung, verlängern jedoch die Renderzeit.", "render.cpu_area_add": "Rechteckiges CPU-Flächenlicht hinzufügen", @@ -3431,6 +3445,10 @@ "render.result_retained": "Das zuletzt fertiggestellte Bild wird angezeigt; ein neueres Rendering hat es noch nicht ersetzt.", "render.result_sequence": "Prüfpunkt", "render.result_title": "Render-Ergebnis", + "render.results_choose": "Behaltene Ergebnisse", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [veraltet]", + "render.results_unnamed": "Bild", "render.return_design": "Zurück zu Design", "render.review_stale": "Diese Prüfung ist veraltet. Lösen Sie sie auf oder prüfen Sie erneut, bevor Sie sie anwenden.", "render.ribbon_aging": "Alterung", diff --git a/assets/locales/en.json b/assets/locales/en.json index e1745eebf..88d26e787 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1048,6 +1048,9 @@ "cmd.pointcloud_edit": "Edit Point Cloud", "cmd.pointcloud_insert": "Insert Point Cloud", "cmd.pointcloud_list": "Point Clouds", + "cmd.render.compare.divider": "Move Render Comparison Divider", + "cmd.render.result.discard": "Discard Render Result", + "cmd.render.result.select": "Select Render Result", "cmd.render_aging_describe": "Layered Surface Aging", "cmd.render_backends": "Render Backends", "cmd.render_batch": "Render All Shots", @@ -2576,6 +2579,10 @@ "render.base_color": "Base color · sRGB", "render.base_metallic": "Metallic fraction", "render.base_opaque_only": "This editor preserves opaque body semantics. Use the explicit glass controls for optical transmission.", + "render.batch_all_shots": "All shots ({count})", + "render.batch_empty": "Save a shot before rendering all shots.", + "render.batch_limit": "Render all shots is limited to 32 shots.", + "render.batch_status": "{running} running · {waiting} waiting", "render.bloom_enable": "Display bloom", "render.bloom_help": "Creative output-only glow from positive linear highlights, spread with three normalized box passes. Radius is in output pixels. Added in linear display light before sRGB; not a lens, volumetric effect or convergence improvement. The raw EXR is unchanged.", "render.bloom_opaque": "Bloom requires opaque output. Transparent PNG is refused, not silently flattened.", @@ -2686,6 +2693,13 @@ "render.choose_look": "Choose a look in Appearances first", "render.chromatic_offset": "Chromatic edge offset", "render.clear_stage": "Remove saved stage", + "render.compare_divider": "Comparison divider", + "render.compare_live": "Live", + "render.compare_live_preview": "Live preview", + "render.compare_render": "Render {number}", + "render.compare_side": "Render {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · captured at revision {revision}", + "render.compare_swap": "Swap", "render.copy_request": "Copy JSON", "render.cpu_aa_help": "Spatial samples: more samples improve edges and increase render time.", "render.cpu_area_add": "Add rectangular CPU light", @@ -3435,6 +3449,10 @@ "render.result_retained": "Showing the last completed image; a newer render has not replaced it.", "render.result_sequence": "Checkpoint", "render.result_title": "Render Result", + "render.results_choose": "Retained results", + "render.results_label": "Render {number} · {shot} · {seconds} s", + "render.results_stale_label": "{result} [stale]", + "render.results_unnamed": "Image", "render.return_design": "Return to Design", "render.review_stale": "This review is stale. Resolve or check again before applying.", "render.ribbon_aging": "Aging", diff --git a/assets/locales/he.json b/assets/locales/he.json index 6fc55a7ff..0ad343692 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -1048,6 +1048,9 @@ "cmd.pointcloud_edit": "עריכת ענן נקודות", "cmd.pointcloud_insert": "הוספת ענן נקודות", "cmd.pointcloud_list": "ענני נקודות", + "cmd.render.compare.divider": "הזז את מחיצת ההשוואה של הרינדור", + "cmd.render.result.discard": "השלך תוצאת רינדור", + "cmd.render.result.select": "בחר תוצאת רינדור", "cmd.render_aging_describe": "הזדקנות משטח בשכבות", "cmd.render_backends": "מנועי הדמיה", "cmd.render_batch": "רינדור כל הצילומים", @@ -2576,6 +2579,10 @@ "render.base_color": "צבע בסיס · sRGB", "render.base_metallic": "שיעור מתכתיות", "render.base_opaque_only": "עורך זה שומר על משמעות של גוף אטום. להעברה אופטית יש להשתמש בפקדי הזכוכית המפורשים.", + "render.batch_all_shots": "כל הצילומים ({count})", + "render.batch_empty": "שמור צילום לפני רינדור כל הצילומים.", + "render.batch_limit": "רינדור כל הצילומים מוגבל ל-32 צילומים.", + "render.batch_status": "{running} רצים · {waiting} ממתינים", "render.bloom_enable": "זוהר בתצוגה", "render.bloom_help": "זוהר יצירתי לפלט בלבד מהבהרות ליניאריות חיוביות, המתפשט בשלושה מעברי תיבה מנורמלים. הרדיוס בפיקסלים של הפלט. נוסף באור תצוגה ליניארי לפני sRGB; אינו עדשה, אינו אפקט נפחי ואינו שיפור התכנסות. ה־EXR הגולמי אינו משתנה.", "render.bloom_opaque": "זוהר דורש פלט אטום. PNG שקוף נדחה, ואינו משוטח בשקט.", @@ -2686,6 +2693,13 @@ "render.choose_look": "בחר קודם מראה במראות", "render.chromatic_offset": "היסט כרומטי בקצוות", "render.clear_stage": "הסרת הבמה השמורה", + "render.compare_divider": "מחיצת השוואה", + "render.compare_live": "חי", + "render.compare_live_preview": "תצוגה חיה", + "render.compare_render": "רינדור {number}", + "render.compare_side": "רינדור {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} שנ׳ · {renderer} · נקלט בגרסה {revision}", + "render.compare_swap": "החלף", "render.copy_request": "העתקת JSON", "render.cpu_aa_help": "דגימות מרחביות: יותר דגימות משפרות קצוות ומאריכות את זמן ההדמיה.", "render.cpu_area_add": "הוספת אור מלבני ב־CPU", @@ -3435,6 +3449,10 @@ "render.result_retained": "מוצגת התמונה הגמורה האחרונה; הדמיה חדשה יותר לא החליפה אותה.", "render.result_sequence": "נקודת ביקורת", "render.result_title": "תוצאת הדמיה", + "render.results_choose": "תוצאות שנשמרו", + "render.results_label": "רינדור {number} · {shot} · {seconds} שנ׳", + "render.results_stale_label": "{result} [ישן]", + "render.results_unnamed": "תמונה", "render.return_design": "חזרה לתכן", "render.review_stale": "סקירה זו אינה עדכנית. יש לפתור או לבדוק שוב לפני ההחלה.", "render.ribbon_aging": "הזדקנות", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 90a4794bb..9232598e0 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1048,6 +1048,9 @@ "cmd.pointcloud_edit": "点群を編集", "cmd.pointcloud_insert": "点群を挿入", "cmd.pointcloud_list": "点群", + "cmd.render.compare.divider": "レンダー比較の境界を移動", + "cmd.render.result.discard": "レンダリング結果を破棄", + "cmd.render.result.select": "レンダリング結果を選択", "cmd.render_aging_describe": "レイヤー式表面エイジング", "cmd.render_backends": "レンダリング バックエンド", "cmd.render_batch": "すべてのショットをレンダリング", @@ -2576,6 +2579,10 @@ "render.base_color": "ベースカラー・sRGB", "render.base_metallic": "金属成分の割合", "render.base_opaque_only": "この編集では不透明ボディの意味を保持します。透過には明示的なガラス設定を使用してください。", + "render.batch_all_shots": "すべてのショット ({count})", + "render.batch_empty": "すべてのショットをレンダリングする前にショットを保存してください。", + "render.batch_limit": "一度にレンダリングできるショットは32個までです。", + "render.batch_status": "{running} 実行中 · {waiting} 待機中", "render.bloom_enable": "表示ブルーム", "render.bloom_help": "正の線形ハイライトを3回の正規化フィルターで広げる表示専用の効果です。半径は出力ピクセル単位。sRGB変換前に加算され、レンズ・体積・収束の改善ではありません。生EXRは変わりません。", "render.bloom_opaque": "ブルームには不透明な出力が必要です。透明PNGを暗黙に統合せず拒否します。", @@ -2686,6 +2693,13 @@ "render.choose_look": "まず外観ライブラリで外観を選択", "render.chromatic_offset": "色収差のずれ", "render.clear_stage": "保存済みステージを削除", + "render.compare_divider": "比較の境界", + "render.compare_live": "ライブ", + "render.compare_live_preview": "ライブプレビュー", + "render.compare_render": "レンダー {number}", + "render.compare_side": "レンダー {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · リビジョン {revision} で取得", + "render.compare_swap": "入れ替え", "render.copy_request": "JSONをコピー", "render.cpu_aa_help": "空間サンプル数を増やすと輪郭が滑らかになりますが、描画時間も増えます。", "render.cpu_area_add": "CPU矩形ライトを追加", @@ -3435,6 +3449,10 @@ "render.result_retained": "最後に完成した画像を表示しています。新しいレンダリングにはまだ置き換わっていません。", "render.result_sequence": "中間結果", "render.result_title": "レンダリング結果", + "render.results_choose": "保持した結果", + "render.results_label": "レンダー {number} · {shot} · {seconds} 秒", + "render.results_stale_label": "{result} [更新前]", + "render.results_unnamed": "画像", "render.return_design": "設計に戻る", "render.review_stale": "この確認結果は古くなっています。適用前に再解決または再確認してください。", "render.ribbon_aging": "エイジング", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index e4ba8d98a..a8b8a68a8 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -905,6 +905,9 @@ "cmd.pointcloud_edit": "포인트 클라우드 편집", "cmd.pointcloud_insert": "포인트 클라우드 삽입", "cmd.pointcloud_list": "포인트 클라우드", + "cmd.render.compare.divider": "렌더 비교 구분선 이동", + "cmd.render.result.discard": "렌더 결과 버리기", + "cmd.render.result.select": "렌더 결과 선택", "cmd.render_backends": "렌더링 백엔드", "cmd.render_batch": "모든 샷 렌더링", "cmd.render_camera_fit": "렌더 대상 화면 맞춤", @@ -1833,6 +1836,10 @@ "render.appearances": "외관", "render.assign_help": "클릭하여 선택 항목에 적용하거나 드래그하여 미리 보고 놓으세요. 선택이 없으면 칠하기를 시작합니다.", "render.background": "장면 배경", + "render.batch_all_shots": "모든 샷 ({count})", + "render.batch_empty": "모든 샷을 렌더링하기 전에 샷을 저장하세요.", + "render.batch_limit": "한 번에 최대 32개의 샷을 렌더링할 수 있습니다.", + "render.batch_status": "{running}개 실행 중 · {waiting}개 대기 중", "render.bloom_enable": "표시 블룸", "render.bloom_help": "양의 선형 하이라이트를 세 번의 정규화 필터로 확산하는 출력 전용 효과입니다. 반경은 출력 픽셀 단위이며 sRGB 전에 더합니다. 렌즈·볼륨·수렴 개선이 아니며 원본 EXR은 변하지 않습니다.", "render.bloom_opaque": "블룸에는 불투명 출력이 필요합니다. 투명 PNG를 몰래 합성하지 않고 거부합니다.", @@ -1924,6 +1931,13 @@ "render.children.workstation": "워크스테이션", "render.choose_look": "먼저 외관 라이브러리에서 외관을 선택하세요", "render.clear_stage": "Remove saved stage", + "render.compare_divider": "비교 구분선", + "render.compare_live": "라이브", + "render.compare_live_preview": "라이브 미리보기", + "render.compare_render": "렌더 {number}", + "render.compare_side": "렌더 {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds}초 · {renderer} · 리비전 {revision}에서 캡처", + "render.compare_swap": "맞바꾸기", "render.cpu_budget": "CPU 리소스 프로필", "render.cpu_budget_bodies": "바디 수 상한", "render.cpu_budget_compact": "컴팩트 (기존 제한)", @@ -2392,6 +2406,10 @@ "render.result_actual": "100%", "render.result_actual_size": "100%", "render.result_reduced_display": "표시 미리보기를 뷰포트 장치 또는 캐시 제한에 맞춰 축소했습니다. 보관된 PNG와 내보내기는 전체 해상도를 유지합니다. 이 축소 보기에서는 원본 100% 검사가 불가능합니다.", + "render.results_choose": "보관된 결과", + "render.results_label": "렌더 {number} · {shot} · {seconds}초", + "render.results_stale_label": "{result} [이전 버전]", + "render.results_unnamed": "이미지", "render.return_design": "설계로 돌아가기", "render.ribbon_backgrounds": "배경", "render.ribbon_check": "검사", diff --git a/assets/locales/pending/render-results.json b/assets/locales/pending/render-results.json deleted file mode 100644 index 4bbd18232..000000000 --- a/assets/locales/pending/render-results.json +++ /dev/null @@ -1,162 +0,0 @@ -{ - "en": { - "cmd.render.compare.divider": "Move Render Comparison Divider", - "cmd.render.result.discard": "Discard Render Result", - "cmd.render.result.select": "Select Render Result", - "render.batch_all_shots": "All shots ({count})", - "render.batch_empty": "Save a shot before rendering all shots.", - "render.batch_limit": "Render all shots is limited to 32 shots.", - "render.batch_status": "{running} running · {waiting} waiting", - "render.compare_divider": "Comparison divider", - "render.compare_live": "Live", - "render.compare_live_preview": "Live preview", - "render.compare_render": "Render {number}", - "render.compare_side": "Render {number} · {shot}", - "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · captured at revision {revision}", - "render.compare_swap": "Swap", - "render.results_choose": "Retained results", - "render.results_label": "Render {number} · {shot} · {seconds} s", - "render.results_stale_label": "{result} [stale]", - "render.results_unnamed": "Image" - }, - "de": { - "cmd.render.compare.divider": "Render-Vergleichstrenner verschieben", - "cmd.render.result.discard": "Renderergebnis verwerfen", - "cmd.render.result.select": "Renderergebnis auswählen", - "render.batch_all_shots": "Alle Ansichten ({count})", - "render.batch_empty": "Vor dem Rendern aller Ansichten eine Ansicht speichern.", - "render.batch_limit": "Es können höchstens 32 Ansichten gerendert werden.", - "render.batch_status": "{running} läuft · {waiting} warten", - "render.compare_divider": "Vergleichstrenner", - "render.compare_live": "Live", - "render.compare_live_preview": "Live-Vorschau", - "render.compare_render": "Render {number}", - "render.compare_side": "Render {number} · {shot}", - "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} s · {renderer} · aufgenommen bei Revision {revision}", - "render.compare_swap": "Tauschen", - "render.results_choose": "Behaltene Ergebnisse", - "render.results_label": "Render {number} · {shot} · {seconds} s", - "render.results_stale_label": "{result} [veraltet]", - "render.results_unnamed": "Bild" - }, - "ja": { - "cmd.render.compare.divider": "レンダー比較の境界を移動", - "cmd.render.result.discard": "レンダリング結果を破棄", - "cmd.render.result.select": "レンダリング結果を選択", - "render.batch_all_shots": "すべてのショット ({count})", - "render.batch_empty": "すべてのショットをレンダリングする前にショットを保存してください。", - "render.batch_limit": "一度にレンダリングできるショットは32個までです。", - "render.batch_status": "{running} 実行中 · {waiting} 待機中", - "render.compare_divider": "比較の境界", - "render.compare_live": "ライブ", - "render.compare_live_preview": "ライブプレビュー", - "render.compare_render": "レンダー {number}", - "render.compare_side": "レンダー {number} · {shot}", - "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · リビジョン {revision} で取得", - "render.compare_swap": "入れ替え", - "render.results_choose": "保持した結果", - "render.results_label": "レンダー {number} · {shot} · {seconds} 秒", - "render.results_stale_label": "{result} [更新前]", - "render.results_unnamed": "画像" - }, - "ko": { - "cmd.render.compare.divider": "렌더 비교 구분선 이동", - "cmd.render.result.discard": "렌더 결과 버리기", - "cmd.render.result.select": "렌더 결과 선택", - "render.batch_all_shots": "모든 샷 ({count})", - "render.batch_empty": "모든 샷을 렌더링하기 전에 샷을 저장하세요.", - "render.batch_limit": "한 번에 최대 32개의 샷을 렌더링할 수 있습니다.", - "render.batch_status": "{running}개 실행 중 · {waiting}개 대기 중", - "render.compare_divider": "비교 구분선", - "render.compare_live": "라이브", - "render.compare_live_preview": "라이브 미리보기", - "render.compare_render": "렌더 {number}", - "render.compare_side": "렌더 {number} · {shot}", - "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds}초 · {renderer} · 리비전 {revision}에서 캡처", - "render.compare_swap": "맞바꾸기", - "render.results_choose": "보관된 결과", - "render.results_label": "렌더 {number} · {shot} · {seconds}초", - "render.results_stale_label": "{result} [이전 버전]", - "render.results_unnamed": "이미지" - }, - "zh": { - "cmd.render.compare.divider": "移动渲染比较分隔线", - "cmd.render.result.discard": "丢弃渲染结果", - "cmd.render.result.select": "选择渲染结果", - "render.batch_all_shots": "所有镜头 ({count})", - "render.batch_empty": "渲染所有镜头前请先保存镜头。", - "render.batch_limit": "一次最多渲染32个镜头。", - "render.batch_status": "{running} 个运行中 · {waiting} 个等待中", - "render.compare_divider": "比较分隔线", - "render.compare_live": "实时", - "render.compare_live_preview": "实时预览", - "render.compare_render": "渲染 {number}", - "render.compare_side": "渲染 {number} · {shot}", - "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · 捕获于修订版 {revision}", - "render.compare_swap": "交换", - "render.results_choose": "保留的结果", - "render.results_label": "渲染 {number} · {shot} · {seconds} 秒", - "render.results_stale_label": "{result} [已过期]", - "render.results_unnamed": "图像" - }, - "ar": { - "cmd.render.compare.divider": "تحريك فاصل مقارنة التصيير", - "cmd.render.result.discard": "تجاهل نتيجة التصيير", - "cmd.render.result.select": "تحديد نتيجة التصيير", - "render.batch_all_shots": "كل اللقطات ({count})", - "render.batch_empty": "احفظ لقطة قبل تصيير كل اللقطات.", - "render.batch_limit": "تصيير كل اللقطات محدود بـ 32 لقطة.", - "render.batch_status": "{running} قيد التشغيل · {waiting} في الانتظار", - "render.compare_divider": "فاصل المقارنة", - "render.compare_live": "حي", - "render.compare_live_preview": "معاينة حية", - "render.compare_render": "التصيير {number}", - "render.compare_side": "التصيير {number} · {shot}", - "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} ث · {renderer} · التُقطت عند المراجعة {revision}", - "render.compare_swap": "تبديل", - "render.results_choose": "النتائج المحتفظ بها", - "render.results_label": "التصيير {number} · {shot} · {seconds} ث", - "render.results_stale_label": "{result} [قديم]", - "render.results_unnamed": "صورة" - }, - "he": { - "cmd.render.compare.divider": "הזז את מחיצת ההשוואה של הרינדור", - "cmd.render.result.discard": "השלך תוצאת רינדור", - "cmd.render.result.select": "בחר תוצאת רינדור", - "render.batch_all_shots": "כל הצילומים ({count})", - "render.batch_empty": "שמור צילום לפני רינדור כל הצילומים.", - "render.batch_limit": "רינדור כל הצילומים מוגבל ל-32 צילומים.", - "render.batch_status": "{running} רצים · {waiting} ממתינים", - "render.compare_divider": "מחיצת השוואה", - "render.compare_live": "חי", - "render.compare_live_preview": "תצוגה חיה", - "render.compare_render": "רינדור {number}", - "render.compare_side": "רינדור {number} · {shot}", - "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} שנ׳ · {renderer} · נקלט בגרסה {revision}", - "render.compare_swap": "החלף", - "render.results_choose": "תוצאות שנשמרו", - "render.results_label": "רינדור {number} · {shot} · {seconds} שנ׳", - "render.results_stale_label": "{result} [ישן]", - "render.results_unnamed": "תמונה" - }, - "vi": { - "cmd.render.compare.divider": "Di chuyển vạch so sánh kết xuất", - "cmd.render.result.discard": "Bỏ kết quả kết xuất", - "cmd.render.result.select": "Chọn kết quả kết xuất", - "render.batch_all_shots": "Mọi cảnh chụp ({count})", - "render.batch_empty": "Hãy lưu một cảnh chụp trước khi kết xuất mọi cảnh chụp.", - "render.batch_limit": "Kết xuất mọi cảnh chụp giới hạn ở 32 cảnh chụp.", - "render.batch_status": "{running} đang chạy · {waiting} đang chờ", - "render.compare_divider": "Vạch so sánh", - "render.compare_live": "Trực tiếp", - "render.compare_live_preview": "Xem trước trực tiếp", - "render.compare_render": "Kết xuất {number}", - "render.compare_side": "Kết xuất {number} · {shot}", - "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} giây · {renderer} · ghi tại bản sửa {revision}", - "render.compare_swap": "Hoán đổi", - "render.results_choose": "Kết quả được giữ lại", - "render.results_label": "Kết xuất {number} · {shot} · {seconds} giây", - "render.results_stale_label": "{result} [cũ]", - "render.results_unnamed": "Ảnh" - } -} diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 96a3d5a5c..69d5bf8d7 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -1048,6 +1048,9 @@ "cmd.pointcloud_edit": "Chỉnh sửa đám mây điểm", "cmd.pointcloud_insert": "Chèn đám mây điểm", "cmd.pointcloud_list": "Đám mây điểm", + "cmd.render.compare.divider": "Di chuyển vạch so sánh kết xuất", + "cmd.render.result.discard": "Bỏ kết quả kết xuất", + "cmd.render.result.select": "Chọn kết quả kết xuất", "cmd.render_aging_describe": "Lão hóa bề mặt phân lớp", "cmd.render_backends": "Kết xuất hình ảnh Sauends", "cmd.render_batch": "Kết xuất mọi cảnh chụp", @@ -2576,6 +2579,10 @@ "render.base_color": "Màu cơ sở · sRGB", "render.base_metallic": "Tỷ lệ kim loại", "render.base_opaque_only": "Trình chỉnh sửa này giữ nguyên ngữ nghĩa khối đục. Dùng các điều khiển thủy tinh riêng biệt để chỉnh độ truyền quang học.", + "render.batch_all_shots": "Mọi cảnh chụp ({count})", + "render.batch_empty": "Hãy lưu một cảnh chụp trước khi kết xuất mọi cảnh chụp.", + "render.batch_limit": "Kết xuất mọi cảnh chụp giới hạn ở 32 cảnh chụp.", + "render.batch_status": "{running} đang chạy · {waiting} đang chờ", "render.bloom_enable": "Hiển thị lóe sáng (Bloom)", "render.bloom_help": "Hiệu ứng phát sáng sáng tạo cho đầu ra từ các điểm nhấn tuyến tính dương, được khuếch tán qua ba lượt lọc chuẩn hóa. Bán kính tính theo pixel đầu ra. Được cộng vào ánh sáng tuyến tính hiển thị trước sRGB; không phải ống kính thực tế, hiệu ứng thể tích hay cải thiện hội tụ. Tệp EXR thô không đổi.", "render.bloom_opaque": "Hiệu ứng lóe sáng yêu cầu đầu ra đục. PNG trong suốt sẽ bị từ chối chứ không âm thầm làm phẳng nền.", @@ -2686,6 +2693,13 @@ "render.choose_look": "Hãy chọn một diện mạo trong Diện mạo trước", "render.chromatic_offset": "Độ lệch sắc sai viền", "render.clear_stage": "Xóa sân khấu đã lưu", + "render.compare_divider": "Vạch so sánh", + "render.compare_live": "Trực tiếp", + "render.compare_live_preview": "Xem trước trực tiếp", + "render.compare_render": "Kết xuất {number}", + "render.compare_side": "Kết xuất {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} giây · {renderer} · ghi tại bản sửa {revision}", + "render.compare_swap": "Hoán đổi", "render.copy_request": "Sao chép JSON", "render.cpu_aa_help": "Số mẫu không gian: tăng số mẫu giúp cạnh mượt hơn nhưng tăng thời gian kết xuất.", "render.cpu_area_add": "Thêm nguồn sáng vùng chữ nhật CPU", @@ -3435,6 +3449,10 @@ "render.result_retained": "Đang hiển thị hình ảnh hoàn thành gần nhất; kết xuất mới hơn chưa thay thế nó.", "render.result_sequence": "Điểm kiểm tra trung gian", "render.result_title": "Kết quả kết xuất", + "render.results_choose": "Kết quả được giữ lại", + "render.results_label": "Kết xuất {number} · {shot} · {seconds} giây", + "render.results_stale_label": "{result} [cũ]", + "render.results_unnamed": "Ảnh", "render.return_design": "Quay lại thiết kế", "render.review_stale": "Kết quả xem xét này đã cũ. Hãy xử lý hoặc kiểm tra lại trước khi áp dụng.", "render.ribbon_aging": "Lão hóa", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 4cddb9f28..3eb13f1ed 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1048,6 +1048,9 @@ "cmd.pointcloud_edit": "编辑点云", "cmd.pointcloud_insert": "插入点云", "cmd.pointcloud_list": "点云", + "cmd.render.compare.divider": "移动渲染比较分隔线", + "cmd.render.result.discard": "丢弃渲染结果", + "cmd.render.result.select": "选择渲染结果", "cmd.render_aging_describe": "分层表面老化", "cmd.render_backends": "渲染后端", "cmd.render_batch": "渲染所有镜头", @@ -2576,6 +2579,10 @@ "render.base_color": "基础颜色 · sRGB", "render.base_metallic": "金属比例", "render.base_opaque_only": "此编辑器保留不透明实体语义;光学透射请使用明确的玻璃控件。", + "render.batch_all_shots": "所有镜头 ({count})", + "render.batch_empty": "渲染所有镜头前请先保存镜头。", + "render.batch_limit": "一次最多渲染32个镜头。", + "render.batch_status": "{running} 个运行中 · {waiting} 个等待中", "render.bloom_enable": "显示泛光", "render.bloom_help": "仅用于输出的创意辉光,将正线性高光经过三次归一化滤波扩散。半径以输出像素计,在 sRGB 前叠加;不模拟镜头或体积,也不改善收敛。原始 EXR 不变。", "render.bloom_opaque": "泛光需要不透明输出;会拒绝透明 PNG,而非暗中合成背景。", @@ -2686,6 +2693,13 @@ "render.choose_look": "请先在外观库中选择外观", "render.chromatic_offset": "边缘色差偏移", "render.clear_stage": "移除已保存的舞台", + "render.compare_divider": "比较分隔线", + "render.compare_live": "实时", + "render.compare_live_preview": "实时预览", + "render.compare_render": "渲染 {number}", + "render.compare_side": "渲染 {number} · {shot}", + "render.compare_summary": "{shot} · {width} × {height} · PNG · {seconds} 秒 · {renderer} · 捕获于修订版 {revision}", + "render.compare_swap": "交换", "render.copy_request": "复制 JSON", "render.cpu_aa_help": "增加空间采样可改善边缘,但会增加渲染时间。", "render.cpu_area_add": "添加 CPU 矩形光源", @@ -3435,6 +3449,10 @@ "render.result_retained": "正在显示最后完成的图像;较新的渲染尚未替换它。", "render.result_sequence": "中间结果", "render.result_title": "渲染结果", + "render.results_choose": "保留的结果", + "render.results_label": "渲染 {number} · {shot} · {seconds} 秒", + "render.results_stale_label": "{result} [已过期]", + "render.results_unnamed": "图像", "render.return_design": "返回设计", "render.review_stale": "此审阅结果已过期;应用前请重新解析或检查。", "render.ribbon_aging": "老化", diff --git a/docs/features.md b/docs/features.md index 23a63024c..174268e92 100644 --- a/docs/features.md +++ b/docs/features.md @@ -643,12 +643,13 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm |---|---|---| | Layered Surface Aging | `render.aging.describe` | – | | Render Backends | `render.backends` | – | -| Render All Shots *(planned: [#5493](https://github.com/bherbruck/solidcraft/issues/5493))* | `render.batch` | RENDER › BATCH | +| Render All Shots | `render.batch` | RENDER › BATCH | | Frame Render Subject | `render.camera.fit` | – | | Inspect Render Camera | `render.camera.get` | – | | Set Render Camera | `render.camera.set` | – | | Cancel Render | `render.cancel` | – | -| Compare Images *(planned: [#5493](https://github.com/bherbruck/solidcraft/issues/5493))* | `render.compare` | RENDER › RESULT | +| Compare Images | `render.compare` | RENDER › RESULT | +| Move Render Comparison Divider | `render.compare.divider` | – | | Lens and Creative Effects | `render.effects.describe` | – | | Set Render Environment | `render.environment.set` | – | | Export Render Image | `render.export` | – | @@ -682,8 +683,10 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Review Fixed Sampling Budget | `render.quality.prepare` | – | | Close Render Image (Escape) | `render.result.close` | – | | Copy Render Image | `render.result.copy` | – | +| Discard Render Result | `render.result.discard` | – | | Retain Displayed Render Result | `render.result.pin` | – | | Regrade Linear Master | `render.result.regrade` | – | +| Select Render Result | `render.result.select` | – | | View Render Image | `render.result.view` | – | | Inspect Render Scene | `render.scene` | RENDER › SCENE | | Apply Render Camera | `render.settings.apply` | – | From 17b9a8e67f9c4e8b7c5f4f5c24692292383402c7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:55:56 +0000 Subject: [PATCH 14/55] Regenerate generated files and fold pending files [skip ci] --- assets/locales/ar.json | 1 + assets/locales/en.json | 1 + assets/locales/he.json | 1 + assets/locales/ja.json | 1 + assets/locales/pending/compare-picture.json | 20 -------------------- assets/locales/vi.json | 1 + assets/locales/zh.json | 1 + docs/features.md | 1 + 8 files changed, 7 insertions(+), 20 deletions(-) delete mode 100644 assets/locales/pending/compare-picture.json diff --git a/assets/locales/ar.json b/assets/locales/ar.json index e0c08fd3d..4cf4ffdb5 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -958,6 +958,7 @@ "cmd.inspect_colored_components": "تفعيل ألوان المكوّنات", "cmd.inspect_colored_components_disable": "تعطيل ألوان المكوّنات", "cmd.inspect_compare": "مقارنة الأجسام", + "cmd.inspect_compare_picture": "مقارنة بصورة مرجعية", "cmd.inspect_continuity": "تحليل الاستمرارية", "cmd.inspect_curvature_comb": "تحليل مشط الانحناء", "cmd.inspect_curvature_map": "تحليل خريطة الانحناء", diff --git a/assets/locales/en.json b/assets/locales/en.json index 88d26e787..9824d4a5c 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -958,6 +958,7 @@ "cmd.inspect_colored_components": "Enable Component Colors", "cmd.inspect_colored_components_disable": "Disable Component Colors", "cmd.inspect_compare": "Compare Bodies", + "cmd.inspect_compare_picture": "Compare Picture", "cmd.inspect_continuity": "Continuity Analysis", "cmd.inspect_curvature_comb": "Curvature Comb Analysis", "cmd.inspect_curvature_map": "Curvature Map Analysis", diff --git a/assets/locales/he.json b/assets/locales/he.json index 0ad343692..1a63962bd 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -958,6 +958,7 @@ "cmd.inspect_colored_components": "הפעלת צבעי רכיבים", "cmd.inspect_colored_components_disable": "ביטול צבעי רכיבים", "cmd.inspect_compare": "השוואת גופים", + "cmd.inspect_compare_picture": "השוואה לתמונת ייחוס", "cmd.inspect_continuity": "ניתוח רציפות", "cmd.inspect_curvature_comb": "ניתוח מסרק עקמומיות", "cmd.inspect_curvature_map": "ניתוח מפת עקמומיות", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 9232598e0..17424db1a 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -958,6 +958,7 @@ "cmd.inspect_colored_components": "コンポーネントの色分けを有効化", "cmd.inspect_colored_components_disable": "コンポーネントの色分けを無効化", "cmd.inspect_compare": "ボディを比較", + "cmd.inspect_compare_picture": "参考画像と比較", "cmd.inspect_continuity": "連続性解析", "cmd.inspect_curvature_comb": "曲率コーム解析", "cmd.inspect_curvature_map": "曲率マップ解析", diff --git a/assets/locales/pending/compare-picture.json b/assets/locales/pending/compare-picture.json deleted file mode 100644 index d6966b2d4..000000000 --- a/assets/locales/pending/compare-picture.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "en": { - "cmd.inspect_compare_picture": "Compare Picture" - }, - "ar": { - "cmd.inspect_compare_picture": "مقارنة بصورة مرجعية" - }, - "he": { - "cmd.inspect_compare_picture": "השוואה לתמונת ייחוס" - }, - "ja": { - "cmd.inspect_compare_picture": "参考画像と比較" - }, - "vi": { - "cmd.inspect_compare_picture": "So sánh với ảnh tham chiếu" - }, - "zh": { - "cmd.inspect_compare_picture": "比较参考图" - } -} diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 69d5bf8d7..a57861425 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -958,6 +958,7 @@ "cmd.inspect_colored_components": "Bật màu cụm chi tiết", "cmd.inspect_colored_components_disable": "Tắt màu cụm chi tiết", "cmd.inspect_compare": "So sánh các thân khối", + "cmd.inspect_compare_picture": "So sánh với ảnh tham chiếu", "cmd.inspect_continuity": "Phân tích độ liên tục mặt", "cmd.inspect_curvature_comb": "Phân tích lược độ cong (Curvature Comb)", "cmd.inspect_curvature_map": "Phân tích bản đồ độ cong (Curvature Map)", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 3eb13f1ed..f4522dc84 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -958,6 +958,7 @@ "cmd.inspect_colored_components": "启用组件颜色", "cmd.inspect_colored_components_disable": "禁用组件颜色", "cmd.inspect_compare": "比较实体", + "cmd.inspect_compare_picture": "比较参考图", "cmd.inspect_continuity": "连续性分析", "cmd.inspect_curvature_comb": "曲率梳分析", "cmd.inspect_curvature_map": "曲率图分析", diff --git a/docs/features.md b/docs/features.md index 174268e92..e3512845f 100644 --- a/docs/features.md +++ b/docs/features.md @@ -361,6 +361,7 @@ SolidCraft's commands by area, generated by `cargo xtask features` from the comm | Clearance | `inspect.clearance` | – | | Enable Component Colors | `inspect.colored_components` | SOLID › INSPECT | | Compare Bodies | `inspect.compare` | – | +| Compare Picture | `inspect.compare_picture` | – | | Continuity Analysis | `inspect.continuity` | SURFACE › INSPECT | | Curvature Comb Analysis | `inspect.curvature_comb` | SKETCH › INSPECT | | Curvature Map Analysis | `inspect.curvature_map` | SKETCH › INSPECT | From 3017641b414bcd24a733d666f777aa25fcd0961c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=27tite=20T=C3=AAte?= Date: Sun, 1 Nov 2026 19:41:32 +0000 Subject: [PATCH 15/55] =?UTF-8?q?fix:=20Projection=20d'une=20silhouette=20?= =?UTF-8?q?=C3=A0=20cong=C3=A9s=20coniques=20ferm=C3=A9e=20en=20un=20profi?= =?UTF-8?q?l=20(#10773)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - snap_tangent_arcs : chaque extrémité d'arc prend la ligne la plus proche - une ligne ne prend qu'une extrémité d'un arc ; l'autre passe à sa ligne suivante - une ligne plus loin sur le contour est ignorée quand l'extrémité touche déjà une autre pièce - tests : 4 unitaires (project_order.rs) et the_silhouette_of_conic_rounds_closes Co-authored-by: P'tite Tête --- crates/doc/src/project.rs | 43 +++++-- crates/doc/src/project_order.rs | 111 ++++++++++++++++++ crates/engine/src/cmd/sketch_project_tests.rs | 43 +++++++ 3 files changed, 187 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index 780099e06..b705ea326 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -1543,8 +1543,9 @@ fn snap_tangent_arcs(out: &mut [LinkGeom], tol: f64) { for i in 0..out.len() { let Some(LinkGeom::Arc { c, a, b }) = out.get(i).cloned() else { continue }; let r = (c.dist(a) + c.dist(b)) / 2.0; - // (arc end, line index, line end index, tangent point, unit normal towards the centre, centre distance) - let mut hits: Vec<(usize, usize, usize, Vec2, Vec2, f64)> = Vec::new(); + // Per arc end: (gap to the line's end, line index, line end index, tangent point, unit + // normal towards the centre, centre distance) + let mut hits: [Vec<(f64, usize, usize, Vec2, Vec2, f64)>; 2] = [Vec::new(), Vec::new()]; for (end, e) in [a, b].into_iter().enumerate() { for (j, g) in out.iter().enumerate() { let LinkGeom::Line(p, q) = g else { continue }; @@ -1562,17 +1563,39 @@ fn snap_tangent_arcs(out: &mut [LinkGeom], tol: f64) { if (foot - far).dot(near_pt - far) <= 0.0 || near_pt.dist(foot) > 0.25 * r { continue; } - hits.push((end, j, near, foot, n, d)); + // When this end of the arc already meets another piece of the outline and the line + // doesn't end there, the line lies further along (past that piece, as along a + // conic fitted with several arcs): moving the end onto it would leave a gap. + let gap = near_pt.dist(e); + let meets = |g: &LinkGeom| match *g { + LinkGeom::Line(s, t) | LinkGeom::Arc { a: s, b: t, .. } => s.dist(e) <= tol || t.dist(e) <= tol, + _ => false, + }; + if gap > tol && out.iter().enumerate().any(|(k, g)| k != i && k != j && meets(g)) { + continue; + } + if let Some(h) = hits.get_mut(end) { + h.push((gap, j, near, foot, n, d)); + } } } - let mut hits_by_end: [Option<(usize, usize, Vec2, Vec2, f64)>; 2] = [None, None]; - for (end, j, near, foot, n, d) in hits { - if let Some(slot) = hits_by_end.get_mut(end) - && slot.is_none() - { - *slot = Some((j, near, foot, n, d)); - } + for h in &mut hits { + h.sort_by(|x, y| x.0.total_cmp(&y.0)); } + // Each end takes the line ending nearest it. Both ends on one line would pull the arc down + // to a point: the end nearer that line's end keeps it, the other takes its next line. + let [ha, hb] = &hits; + let (ta, tb) = match (ha.first(), hb.first()) { + (Some(x), Some(y)) if x.1 == y.1 => { + if x.0 <= y.0 { + (Some(x), hb.iter().find(|h| h.1 != x.1)) + } else { + (ha.iter().find(|h| h.1 != y.1), Some(y)) + } + } + pair => pair, + }; + let hits_by_end: [Option<(usize, usize, Vec2, Vec2, f64)>; 2] = [ta, tb].map(|h| h.map(|&(_, j, near, foot, n, d)| (j, near, foot, n, d))); let (mut c, mut r) = (c, r); if let [Some((_, _, _, n1, d1)), Some((_, _, _, n2, d2))] = hits_by_end { // One circle tangent to both lines: equal distance to each. diff --git a/crates/doc/src/project_order.rs b/crates/doc/src/project_order.rs index f59cdfa79..979cdcf4a 100644 --- a/crates/doc/src/project_order.rs +++ b/crates/doc/src/project_order.rs @@ -235,6 +235,117 @@ mod tests { let (Some(LinkGeom::Arc { a, .. }), Some(LinkGeom::Line(p, _))) = (out.get(1), out.get(2)) else { panic!("{out:?}") }; assert!(a.dist(*p) < 1e-9, "{out:?}"); } + + #[test] + fn tangent_snapping_leaves_a_line_further_along_alone() { + use solidcraft_geom::Vec2; + use solidcraft_sketch::LinkGeom; + let v = Vec2::new; + let y = |x: f64| 2.0 - (4.0 - x * x).sqrt(); + // The arc's end at x = 0.5 already meets the next piece; the line along y = 0 ends at + // x = 0.3, further along the outline the other way. Snapping onto it would pull the end + // off the piece it meets. + let mut out = vec![ + LinkGeom::Arc { c: v(0., 2.), a: v(0.5, y(0.5)), b: v(-1.5, y(-1.5)) }, + LinkGeom::Line(v(0.3, 0.), v(10., 0.)), + LinkGeom::Line(v(0.5, y(0.5)), v(3., 3.)), + ]; + let before = out.clone(); + super::super::snap_tangent_arcs(&mut out, 0.05); + assert_eq!(out.get(1), before.get(1), "{out:?}"); + let (Some(LinkGeom::Arc { a, .. }), Some(LinkGeom::Line(p, _))) = (out.first(), out.get(2)) else { panic!("{out:?}") }; + assert!(a.dist(*p) < 1e-9, "{out:?}"); + } + + #[test] + fn tangent_snapping_gives_one_line_to_one_end_of_an_arc() { + use solidcraft_geom::Vec2; + use solidcraft_sketch::LinkGeom; + let v = Vec2::new; + let y = |x: f64| 2.0 - (4.0 - x * x).sqrt(); + // A short arc whose two ends both lie near the end of one line: both snapping onto it + // would shrink the arc to the tangent point. + let mut out = vec![LinkGeom::Arc { c: v(0., 2.), a: v(-0.2, y(-0.2)), b: v(0.2, y(0.2)) }, LinkGeom::Line(v(-10., 0.), v(0., 0.))]; + super::super::snap_tangent_arcs(&mut out, 0.05); + let Some(LinkGeom::Arc { a, b, .. }) = out.first() else { panic!("{out:?}") }; + assert!(a.dist(*b) > 0.1, "{out:?}"); + } + + #[test] + fn tangent_snapping_moves_the_other_end_of_an_arc_to_its_next_line() { + use solidcraft_geom::Vec2; + use solidcraft_sketch::LinkGeom; + let v = Vec2::new; + let y = |x: f64| 2.0 - (4.0 - x * x).sqrt(); + let (a, b) = (v(-0.2, y(-0.2)), v(0.2, y(0.2))); + // The line along y = 0 ends nearest both ends of the arc but nearer b, which keeps it; a + // takes the next line, tangent to the circle at a and ending a little past it. + let back = (v(0., 2.) - a).normalized().map(|n| v(-n.y, n.x)).unwrap_or(Vec2::X); + let mut out = + vec![LinkGeom::Arc { c: v(0., 2.), a, b }, LinkGeom::Line(v(0.1, 0.), v(10., 0.)), LinkGeom::Line(a + back * 10., a + back * 0.35)]; + super::super::snap_tangent_arcs(&mut out, 0.05); + let (Some(LinkGeom::Arc { a, b, .. }), Some(LinkGeom::Line(p, _)), Some(LinkGeom::Line(_, q))) = (out.first(), out.get(1), out.get(2)) else { + panic!("{out:?}") + }; + assert!(b.dist(*p) < 1e-9 && a.dist(*q) < 1e-9 && a.dist(*b) > 0.1, "{out:?}"); + } + + #[test] + fn tangent_snapping_closes_a_conic_corner_in_any_order() { + use solidcraft_geom::Vec2; + use solidcraft_sketch::LinkGeom; + // A square of side 150 with a conic round of 10 mm legs at each corner, fitted with lines + // and arcs the way a silhouette is, then snapped with the pieces in each order. + for rho in [0.1, 0.15, 0.5, 0.8, 0.9] { + let w = rho / (1. - rho); + let conic = |s: Vec2, apex: Vec2, e: Vec2, t: f64| { + let (b0, b1, b2) = ((1. - t) * (1. - t), 2. * t * (1. - t) * w, t * t); + (s * b0 + apex * b1 + e * b2) * (1. / (b0 + b1 + b2)) + }; + let v = Vec2::new; + let corners = [ + (v(-75., 65.), v(-75., 75.), v(-65., 75.)), + (v(65., 75.), v(75., 75.), v(75., 65.)), + (v(75., -65.), v(75., -75.), v(65., -75.)), + (v(-65., -75.), v(-75., -75.), v(-75., -65.)), + ]; + let mut chain = Vec::new(); + for (s, apex, e) in corners { + chain.extend((0..=40).map(|k| conic(s, apex, e, f64::from(k) / 40.))); + } + if let Some(&first) = chain.first() { + chain.push(first); + } + let mut fitted = Vec::new(); + super::super::fit_chain_with_arcs(&chain, Some(212. * 1e-5), &mut fitted, true); + assert!(fitted.iter().any(|g| matches!(g, LinkGeom::Arc { .. })), "{fitted:?}"); + let ends = |g: &LinkGeom| match *g { + LinkGeom::Line(s, t) | LinkGeom::Arc { a: s, b: t, .. } => vec![s, t], + _ => Vec::new(), + }; + for k in 0..fitted.len() { + let mut out = fitted.clone(); + out.rotate_left(k); + super::super::snap_tangent_arcs(&mut out, 212. * 1e-3); + // Every end still meets another piece's end. An end left without a line moves a little + // when the arc's radius is set from the lines (well under 0.01 mm here); before, ends + // pulled onto lines further along left gaps of 0.25 to 0.55 mm. + for (i, g) in out.iter().enumerate() { + for e in ends(g) { + let gap = out + .iter() + .enumerate() + .filter(|(j, _)| *j != i) + .flat_map(|(_, h)| ends(h)) + .map(|x| x.dist(e)) + .fold(f64::INFINITY, f64::min); + assert!(gap < 212. * 1e-3 * 0.02, "rho {rho}, rotation {k}: gap {gap} at {e:?}: {out:?}"); + } + } + } + } + } + #[test] fn boundaries_touching_at_a_vertex_project() { // Two squares of one face family meet only at the corner (1, 1): four boundary edges meet diff --git a/crates/engine/src/cmd/sketch_project_tests.rs b/crates/engine/src/cmd/sketch_project_tests.rs index 556555457..c76c364e7 100644 --- a/crates/engine/src/cmd/sketch_project_tests.rs +++ b/crates/engine/src/cmd/sketch_project_tests.rs @@ -1298,3 +1298,46 @@ fn a_thicker_angle_moves_the_projected_face_of_the_sketch_on_it() { check(&s); check(&Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap())); } + +/// The silhouette of a square with a conic round at each corner (rho 0.19, 0.4, 0.5 and 0.7) is +/// one closed outline of the square's true area. Fitted arcs along a conic were snapped onto lines +/// that ended further along the outline, which left gaps of up to 3.6 mm: no profile. +#[test] +fn the_silhouette_of_conic_rounds_closes() { + let mut s = Session::default(); + let corners = [ + ([-75., 65.], [-75., 75.], [-65., 75.], 0.19), + ([65., 75.], [75., 75.], [75., 65.], 0.4), + ([75., -65.], [75., -75.], [65., -75.], 0.5), + ([-65., -75.], [-75., -75.], [-75., -65.], 0.7), + ]; + run(&mut s, "sketch.create", json!({"plane": "XZ"})); + for (i, (start, apex, end, rho)) in corners.iter().enumerate() { + run(&mut s, "sketch.conic", json!({"start": start, "apex": apex, "end": end, "rho": rho})); + let next = corners[(i + 1) % 4].0; + run(&mut s, "sketch.line", json!({"points": [end, next]})); + } + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 55, "body_name": "Part"})); + run(&mut s, "sketch.create", json!({"plane": "XZ", "offset": -10})); + run(&mut s, "sketch.project", json!({"refs": [{"body": "Part"}]})); + // The true area: the outline through the four rational quadratic Béziers (apex weight + // rho / (1 - rho)), finely sampled, and the straight sides between them. + let mut outline: Vec<[f64; 2]> = Vec::new(); + for (start, apex, end, rho) in corners { + let w = rho / (1. - rho); + for k in 0..=2000 { + let t = f64::from(k) / 2000.; + let (b0, b1, b2) = ((1. - t) * (1. - t), 2. * t * (1. - t) * w, t * t); + let sum = b0 + b1 + b2; + outline.push([(b0 * start[0] + b1 * apex[0] + b2 * end[0]) / sum, (b0 * start[1] + b1 * apex[1] + b2 * end[1]) / sum]); + } + } + let n = outline.len(); + let exact = (0..n).map(|i| outline[i][0] * outline[(i + 1) % n][1] - outline[(i + 1) % n][0] * outline[i][1]).sum::().abs() / 2.; + let si = inspect(&mut s); + let profiles = si["profiles"].as_array().unwrap(); + assert_eq!(profiles.len(), 1, "{}", si["profiles"]); + let area = profiles[0]["area_mm2"].as_f64().unwrap(); + assert!((area - exact).abs() < exact * 2e-4, "area {area}, exact {exact}"); +} From 1ae93218a7c479110a4b38944b06caba0db447bb Mon Sep 17 00:00:00 2001 From: ABDULLAH <149819669+A-AL-ANAZI@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:50:21 +0000 Subject: [PATCH 16/55] Arabic: outline term in the cut preview tint help (#10801) --- assets/locales/ar.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets/locales/ar.json b/assets/locales/ar.json index 4cf4ffdb5..22a35f53d 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -2161,7 +2161,7 @@ "prefs.curved_surfaces": "الأسطح المنحنية", "prefs.curves": "الأسطح المنحنية", "prefs.cut_preview_tint": "إظهار المادة المُزالة باللون الأحمر", - "prefs.cut_preview_tint_help": "تملأ المعاينة المادة التي تزيلها الميزة، والشكل الذي تستبدله، بطيف أحمر شبه شفاف. عند الإيقاف تكون هذه التعبئة شفافة تمامًا ولا تُرسم سوى مخططاتها.", + "prefs.cut_preview_tint_help": "تملأ المعاينة المادة التي تزيلها الميزة، والشكل الذي تستبدله، بطيف أحمر شبه شفاف. عند الإيقاف تكون هذه التعبئة شفافة تمامًا ولا يُرسم سوى محيطها.", "prefs.dark_parts_shading": "الحفاظ على شكل الأجزاء الداكنة", "prefs.dark_parts_shading_help": "تظليل العرض بإضاءة خطية مع إضاءة سماء ناعمة، لتحتفظ الأوجه الداكنة بتدرج بدل أن تصبح سوداء", "prefs.dead_zone_note": "الشريط المخطط هو المنطقة الميتة: تُتجاهل الحركة داخلها.", From 52f0b52b452777c6de4927453e10d783e4f11465 Mon Sep 17 00:00:00 2001 From: Rec0iL Date: Sun, 1 Nov 2026 20:01:26 +0000 Subject: [PATCH 17/55] Agent chat: a searchable model picker with a custom entry, listed from every provider, and OpenClaw and OpenRouter presets (#2582) (#10255) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ui_kit: search_picker, a filtered dropdown with a custom entry Co-Authored-By: Claude Opus 5.5 * Agent chat: endpoints list their models with names, say when listing fails, and OpenClaw and OpenRouter presets (#2582) Co-Authored-By: Claude Opus 5.5 * Agent chat: a typed model goes to endpoints and to agents that offer a model option Co-Authored-By: Claude Opus 5.5 * Agent chat: the header's model pickers search and take a custom model The popup can't grow once it is open, so search_picker now fixes the height of what changes below its box when it opens: the custom row or a late list could otherwise end up out of reach. Co-Authored-By: Claude Opus 5.5 * AI preferences: pick an endpoint's model when adding it and on its card (#2582) Co-Authored-By: Claude Opus 5.5 * Agent chat: model picker rows read from the left, and a refused typed model says which From running it: list_picker centres its text, which reads badly for a long list of ids, and an agent's own refusal can say no more than "Internal error". The search box also asks for a repaint while it waits for the focus, so an idle window does not stop short of it. Co-Authored-By: Claude Opus 5.5 * Agent chat: docs for the model picker Co-Authored-By: Claude Opus 5.5 * Agent chat: an endpoint's answer that is no model list says so, an empty list too, and editing lists with the kept key A 200 without a `data` array (a web page where the endpoint should be, as OpenClaw's gateway serves until its chat endpoint is enabled) was cached as a successful, empty listing, so the picker stayed blank with nothing to say and never asked again. Now it is an error with its own note, an empty list says so, and both are asked for again the next time. The Edit dialog lists its endpoint's models when it opens, with the kept key read from the keychain on the listing's thread, as the card does; the key stays out of the field. The method-not-found test expects the refusal notice that names the model, as every refused model gets since this branch. Co-Authored-By: Claude Fable 5.1 * Agent chat: models from several providers fold under their providers inside the picker As Chemiseblanc does in #10187: with two or more groups, `search_picker` draws each group as a header with a chevron, the name and how many of its choices are listed, and a click folds or opens it. Before anything is typed only the current value's group (and the one the caller asks for) is open; a group with a match opens once something is typed; a fold made by hand stays until the popup closes. Enter takes the first row shown, so never one folded away. A lone group keeps its plain heading. The header's model picker feeds its providers in as groups, so the separate provider drop-down goes; the control channel's `provider` now says which group opens first. A header click gives the focus back to the search box, so typing goes on filtering. The dialog's listing test checks what kind of listing it got rather than translated words, which the listing thread may render in another language than the test's. Co-Authored-By: Claude Fable 5.1 * Agent chat: rustfmt the provider groups Co-Authored-By: Claude Fable 5.1 * Agent chat: an endpoint's models named `Vendor: Model` fold under their vendors OpenRouter lists `openai/gpt-6.1-terra` as "OpenAI: GPT-6.1 Terra". A listing whose ids read `vendor/model` and whose names read `Vendor: Model` now names its providers, so the picker folds it under its vendors like a multi-provider agent; the rows read the model's name, and the id stays in the tooltip and in the search. An agent's own `Provider: …` word still comes first. One vendor is one flat list, as before. The Add dialog's picker has no current model to prefer, so with nothing to prefer every group starts open; folding is a click away. Co-Authored-By: Claude Fable 5.1 --------- Co-authored-by: Claude Opus 5.5 --- .../pending/agent-chat-model-picker.json | 90 +++ crates/ui-egui/src/agent_chat/acp_client.rs | 24 + crates/ui-egui/src/agent_chat/agents.rs | 16 +- crates/ui-egui/src/agent_chat/api_client.rs | 165 ++++-- crates/ui-egui/src/agent_chat/backend.rs | 5 + crates/ui-egui/src/agent_chat/mod.rs | 252 ++++++++- crates/ui-egui/src/agent_chat/panel.rs | 222 ++++---- crates/ui-egui/src/agent_chat/settings.rs | 511 +++++++++++++++++- crates/ui-egui/src/agent_chat/tests.rs | 467 +++++++++++++++- crates/ui-egui/src/ui_kit/fields.rs | 391 ++++++++++++++ crates/ui-egui/src/ui_kit/fields_tests.rs | 357 ++++++++++++ crates/ui-egui/src/ui_kit/gallery.rs | 19 + docs/agent-chat.md | 33 +- docs/control-protocol.md | 8 +- docs/design/in-app-agent-chat.md | 8 +- docs/ui-kit.md | 1 + 16 files changed, 2394 insertions(+), 175 deletions(-) create mode 100644 assets/locales/pending/agent-chat-model-picker.json diff --git a/assets/locales/pending/agent-chat-model-picker.json b/assets/locales/pending/agent-chat-model-picker.json new file mode 100644 index 000000000..c97b17710 --- /dev/null +++ b/assets/locales/pending/agent-chat-model-picker.json @@ -0,0 +1,90 @@ +{ + "en": { + "ui.agent_chat_custom_heading": "Custom model", + "ui.agent_chat_model_custom": "Use custom: {model}", + "ui.agent_chat_model_rejected": "The agent did not accept {model}: {error}", + "ui.agent_chat_model_search": "Search models…", + "ui.agent_chat_models_failed": "Couldn't list models: {error}", + "ui.agent_chat_models_heading": "Available models", + "ui.agent_chat_models_listing": "Listing models…", + "ui.agent_chat_models_none": "The endpoint lists no models", + "ui.agent_chat_models_not_a_list": "The answer was no model list" + }, + "de": { + "ui.agent_chat_custom_heading": "Eigenes Modell", + "ui.agent_chat_model_custom": "Eigenes verwenden: {model}", + "ui.agent_chat_model_rejected": "Der Agent hat {model} nicht akzeptiert: {error}", + "ui.agent_chat_model_search": "Modelle suchen…", + "ui.agent_chat_models_failed": "Modelle konnten nicht abgerufen werden: {error}", + "ui.agent_chat_models_heading": "Verfügbare Modelle", + "ui.agent_chat_models_listing": "Modelle werden abgerufen…", + "ui.agent_chat_models_none": "Der Endpunkt listet keine Modelle", + "ui.agent_chat_models_not_a_list": "Die Antwort war keine Modellliste" + }, + "ko": { + "ui.agent_chat_custom_heading": "사용자 지정 모델", + "ui.agent_chat_model_custom": "직접 입력 사용: {model}", + "ui.agent_chat_model_rejected": "에이전트가 {model}을(를) 받아들이지 않았습니다: {error}", + "ui.agent_chat_model_search": "모델 검색…", + "ui.agent_chat_models_failed": "모델 목록을 가져올 수 없습니다: {error}", + "ui.agent_chat_models_heading": "사용 가능한 모델", + "ui.agent_chat_models_listing": "모델 목록을 가져오는 중…", + "ui.agent_chat_models_none": "엔드포인트에 나열된 모델이 없습니다", + "ui.agent_chat_models_not_a_list": "응답이 모델 목록이 아닙니다" + }, + "ar": { + "ui.agent_chat_custom_heading": "نموذج مخصص", + "ui.agent_chat_model_custom": "استخدام المخصص: {model}", + "ui.agent_chat_model_rejected": "لم يقبل الوكيل {model}: {error}", + "ui.agent_chat_model_search": "البحث عن النماذج…", + "ui.agent_chat_models_failed": "تعذّر جلب قائمة النماذج: {error}", + "ui.agent_chat_models_heading": "النماذج المتاحة", + "ui.agent_chat_models_listing": "جارٍ جلب قائمة النماذج…", + "ui.agent_chat_models_none": "لا تسرد نقطة النهاية أي نماذج", + "ui.agent_chat_models_not_a_list": "لم يكن الرد قائمة نماذج" + }, + "he": { + "ui.agent_chat_custom_heading": "מודל מותאם אישית", + "ui.agent_chat_model_custom": "שימוש במותאם אישית: {model}", + "ui.agent_chat_model_rejected": "הסוכן לא קיבל את {model}: {error}", + "ui.agent_chat_model_search": "חיפוש מודלים…", + "ui.agent_chat_models_failed": "לא ניתן היה לטעון את רשימת המודלים: {error}", + "ui.agent_chat_models_heading": "מודלים זמינים", + "ui.agent_chat_models_listing": "טוען רשימת מודלים…", + "ui.agent_chat_models_none": "נקודת הקצה אינה מציגה מודלים", + "ui.agent_chat_models_not_a_list": "התשובה לא הייתה רשימת מודלים" + }, + "ja": { + "ui.agent_chat_custom_heading": "カスタムモデル", + "ui.agent_chat_model_custom": "カスタムを使用: {model}", + "ui.agent_chat_model_rejected": "エージェントは {model} を受け付けませんでした: {error}", + "ui.agent_chat_model_search": "モデルを検索…", + "ui.agent_chat_models_failed": "モデルを一覧表示できませんでした: {error}", + "ui.agent_chat_models_heading": "利用可能なモデル", + "ui.agent_chat_models_listing": "モデルを一覧表示中…", + "ui.agent_chat_models_none": "エンドポイントにモデルがありません", + "ui.agent_chat_models_not_a_list": "応答はモデル一覧ではありませんでした" + }, + "vi": { + "ui.agent_chat_custom_heading": "Mô hình tùy chỉnh", + "ui.agent_chat_model_custom": "Dùng tùy chỉnh: {model}", + "ui.agent_chat_model_rejected": "Tác tử không chấp nhận {model}: {error}", + "ui.agent_chat_model_search": "Tìm mô hình…", + "ui.agent_chat_models_failed": "Không thể lấy danh sách mô hình: {error}", + "ui.agent_chat_models_heading": "Các mô hình có sẵn", + "ui.agent_chat_models_listing": "Đang lấy danh sách mô hình…", + "ui.agent_chat_models_none": "Điểm cuối không liệt kê mô hình nào", + "ui.agent_chat_models_not_a_list": "Phản hồi không phải là danh sách mô hình" + }, + "zh": { + "ui.agent_chat_custom_heading": "自定义模型", + "ui.agent_chat_model_custom": "使用自定义:{model}", + "ui.agent_chat_model_rejected": "智能体未接受 {model}:{error}", + "ui.agent_chat_model_search": "搜索模型…", + "ui.agent_chat_models_failed": "无法列出模型:{error}", + "ui.agent_chat_models_heading": "可用模型", + "ui.agent_chat_models_listing": "正在列出模型…", + "ui.agent_chat_models_none": "该端点未列出任何模型", + "ui.agent_chat_models_not_a_list": "响应不是模型列表" + } +} diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index e9f88f4bb..6b453964c 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -166,6 +166,8 @@ impl AcpBackend { out.push(Event::TurnEnded { reason: "auth".into() }); } out.push(Event::AuthRequired { methods: self.auth.clone() }); + } else if what == Pending::SetModel { + out.push(Event::ModelRejected(message)); } else if !config_error { if what == Pending::Prompt { out.push(Event::TurnEnded { reason: "error".into() }); @@ -382,4 +384,26 @@ mod tests { assert!(matches!(events.as_slice(), [Event::ConfigOptionFinished { result: Ok(options), .. }] if options[0].current_value == "smart")); backend.shutdown(true); } + + /// A refused model is the picker's business, not an error of the chat; signing in stays as it was. + #[test] + fn a_refused_model_is_reported_as_such() { + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut backend = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx).unwrap(); + let mut events = Vec::new(); + backend.handle(Incoming::Reply { id: 1, result: Ok(json!({"agentInfo":{"name":"fake"}})) }, &mut events); + backend.handle(Incoming::Reply { id: 2, result: Ok(json!({"sessionId":"s1"})) }, &mut events); + events.clear(); + backend.set_model("zzz"); + backend.handle(Incoming::Reply { id: backend.next_id, result: Err((-32602, "no such model".into())) }, &mut events); + assert!(matches!(events.as_slice(), [Event::ModelRejected(message)] if message == "no such model"), "{events:?}"); + events.clear(); + backend.set_model("fast"); + backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({})) }, &mut events); + assert!(events.is_empty(), "{events:?}"); + backend.set_model("zzz"); + backend.handle(Incoming::Reply { id: backend.next_id, result: Err((acp::AUTH_REQUIRED, "sign in".into())) }, &mut events); + assert!(matches!(events.as_slice(), [Event::AuthRequired { .. }]), "{events:?}"); + backend.shutdown(true); + } } diff --git a/crates/ui-egui/src/agent_chat/agents.rs b/crates/ui-egui/src/agent_chat/agents.rs index b7d6b8a81..51e49b973 100644 --- a/crates/ui-egui/src/agent_chat/agents.rs +++ b/crates/ui-egui/src/agent_chat/agents.rs @@ -76,7 +76,7 @@ impl Kind { } /// The wire protocol of an endpoint the user added. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum Protocol { /// `{base}/chat/completions`, as Ollama, LM Studio, OpenAI and their kin speak. #[default] @@ -303,9 +303,11 @@ pub struct ApiPreset { pub const OPENAI_PRESETS: &[ApiPreset] = &[ ApiPreset { name: "Ollama", base_url: "http://localhost:11434/v1" }, ApiPreset { name: "LM Studio", base_url: "http://localhost:1234/v1" }, + ApiPreset { name: "OpenClaw", base_url: "http://localhost:18789/v1" }, ApiPreset { name: "OpenAI", base_url: "https://api.openai.com/v1" }, ApiPreset { name: "Mammouth AI", base_url: "https://api.mammouth.ai/v1" }, ApiPreset { name: "OpenCode Go", base_url: "https://opencode.ai/zen/go/v1" }, + ApiPreset { name: "OpenRouter", base_url: "https://openrouter.ai/api/v1" }, ]; /// Anthropic-compatible endpoints people use. The base URL is the one their documentation calls @@ -400,6 +402,18 @@ mod tests { assert!(presets(Protocol::Anthropic).iter().any(|p| p.base_url == "https://api.anthropic.com/v1")); } + /// The first preset is the one an Add dialog opens with, and the one taken for Ollama. + #[test] + fn ollama_stays_the_first_preset_and_every_preset_can_take_a_key() { + assert_eq!(OPENAI_PRESETS.first().map(|p| p.name), Some("Ollama")); + assert_eq!(OPENAI_PRESETS.last().map(|p| p.name), Some("OpenRouter")); + assert!(OPENAI_PRESETS.iter().any(|p| p.name == "OpenClaw")); + for preset in OPENAI_PRESETS.iter().chain(ANTHROPIC_PRESETS) { + assert_eq!(normalize_url(preset.base_url).as_deref(), Ok(preset.base_url), "{}", preset.name); + assert!(key_safe_for(preset.base_url), "{}", preset.name); + } + } + #[test] fn request_timeouts_default_to_300_s_and_stay_between_30_s_and_an_hour() { assert_eq!(AgentConfig::default().request_timeout_s, 300); diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs index 88c38e39a..e3bc37ecb 100644 --- a/crates/ui-egui/src/agent_chat/api_client.rs +++ b/crates/ui-egui/src/agent_chat/api_client.rs @@ -15,6 +15,7 @@ use std::time::Duration; use serde_json::{Map, Value, json}; +use super::MODEL_LIST_CAP; use super::acp::ModelInfo; use super::agents::Protocol; use super::backend::{ChatBackend, Event, HttpFn, HttpRequest, PromptPart, StartContext, ToolStatus}; @@ -22,6 +23,8 @@ use super::process::{AgentProcess, FromAgent, ProcessHandle}; /// Longest tool result handed back to the model. const MAX_TOOL_TEXT: usize = 20_000; +/// Longest name kept for a listed model. +const MODEL_NAME_CAP: usize = 256; /// Messages kept in the conversation (the system note stays). const MAX_HISTORY: usize = 240; /// Pictures of the view kept in the conversation. The whole history goes with every request @@ -795,15 +798,24 @@ impl Worker { } self.emit(Event::ToolsAvailable(!self.tools.is_empty())); self.emit(Event::Ready { agent: format!("{} · {}", self.cfg.name, self.cfg.model), images: true }); - // The endpoint's models for the picker; an endpoint that does not list them shows none. - if let Ok(list) = self.model_list() { - let mut available = list; - if !self.cfg.model.is_empty() && !available.iter().any(|m| m.id == self.cfg.model) { - available.insert(0, ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() }); + // The endpoint's models for the picker. An endpoint that does not list them still shows the + // configured model, and says why there are no others. + let configured = ModelInfo { id: self.cfg.model.clone(), name: self.cfg.model.clone(), description: String::new() }; + let available = match self.model_list() { + Ok(mut list) => { + self.emit(Event::ModelsNote(None)); + if !self.cfg.model.is_empty() && !list.iter().any(|m| m.id == self.cfg.model) { + list.insert(0, configured); + } + list } - if !available.is_empty() { - self.emit(Event::Models { current: self.cfg.model.clone(), available }); + Err(e) => { + self.emit(Event::ModelsNote(Some(e))); + if self.cfg.model.is_empty() { Vec::new() } else { vec![configured] } } + }; + if !available.is_empty() { + self.emit(Event::Models { current: self.cfg.model.clone(), available }); } for cmd in cmds { match cmd { @@ -1628,7 +1640,7 @@ fn anthropic_headers(base_url: &str, key: Option<&str>) -> Result) -> Result, String> { let req = HttpRequest { method: "GET", url: endpoint(base_url, "models"), headers: anthropic_headers(base_url, key)?, body: None, timeout_s: 15 }; let (status, bytes) = http(&req)?; @@ -1636,19 +1648,10 @@ pub fn anthropic_model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> if status != 200 { return Err(http_error(status, &v)); } - Ok(v.get("data") - .and_then(Value::as_array) - .map(|a| { - a.iter() - .take(500) - .filter_map(|m| { - let id = m.get("id").and_then(Value::as_str)?.to_string(); - let name = m.get("display_name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| id.clone()); - Some(ModelInfo { id, name, description: String::new() }) - }) - .collect() - }) - .unwrap_or_default()) + Ok(listed_models(&v, "display_name")? + .into_iter() + .map(|(id, name)| ModelInfo { name: name.unwrap_or_else(|| id.clone()), id, description: String::new() }) + .collect()) } /// Test an Anthropic-compatible endpoint: send the smallest message there is, so the check covers @@ -1721,18 +1724,35 @@ fn tool_title(name: &str, args: &Value) -> String { } } -/// `GET {base_url}/models`: the model ids, in the order the endpoint lists them. -fn model_ids(http: &HttpFn, base_url: &str, headers: Vec<(String, String)>) -> Result, String> { +/// The ids of a `/models` body and the names the endpoint gives them (when not just the id), in +/// its order. The body is the endpoint's to write: an id that could not be sent back is left out, +/// and a name is cut. A body without a `data` array is no model list (a web page where the +/// endpoint should be, say): an error, so the picker says so and asks again later. +fn listed_models(body: &Value, name_key: &str) -> Result)>, String> { + let Some(entries) = body.get("data").and_then(Value::as_array) else { + return Err(crate::i18n::tr("ui.agent_chat_models_not_a_list").to_string()); + }; + Ok(entries + .iter() + .filter_map(|m| { + let id = m.get("id").and_then(Value::as_str).filter(|id| super::model_id_valid(id))?; + let name = m.get(name_key).and_then(Value::as_str).filter(|name| *name != id).map(|name| name.chars().take(MODEL_NAME_CAP).collect()); + Some((id.to_string(), name)) + }) + .take(MODEL_LIST_CAP) + .collect()) +} + +/// `GET {base_url}/models`: the models, in the order the endpoint lists them. The picker shows the +/// ids, so an endpoint's own name for a model is its description. +fn model_entries(http: &HttpFn, base_url: &str, headers: Vec<(String, String)>) -> Result, String> { let req = HttpRequest { method: "GET", url: format!("{base_url}/models"), headers, body: None, timeout_s: 15 }; let (status, bytes) = http(&req)?; let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); if status != 200 { return Err(http_error(status, &v)); } - Ok(v.get("data") - .and_then(Value::as_array) - .map(|a| a.iter().take(500).filter_map(|m| m.get("id").and_then(Value::as_str).map(String::from)).collect()) - .unwrap_or_default()) + Ok(listed_models(&v, "name")?.into_iter().map(|(id, name)| ModelInfo { name: id.clone(), id, description: name.unwrap_or_default() }).collect()) } /// The endpoint's models for the picker. @@ -1744,7 +1764,7 @@ pub fn model_list(http: &HttpFn, base_url: &str, key: Option<&str>) -> Result, model: &s } headers.push(("Authorization".to_string(), format!("Bearer {k}"))); } - let ids = model_ids(http, base_url, headers)?; - let ids: Vec<&str> = ids.iter().map(String::as_str).collect(); - let found = model.is_empty() || ids.contains(&model); - Ok(crate::i18n::format(if found { "ui.ai_test_ok" } else { "ui.ai_test_no_model" }, &[("count", &ids.len().to_string()), ("model", model)])) + let models = model_entries(http, base_url, headers)?; + let found = model.is_empty() || models.iter().any(|m| m.id == model); + Ok(crate::i18n::format(if found { "ui.ai_test_ok" } else { "ui.ai_test_no_model" }, &[("count", &models.len().to_string()), ("model", model)])) } #[cfg(test)] @@ -2059,6 +2078,7 @@ mod tests { let Some(Event::Models { current, available }) = events.iter().find(|e| matches!(e, Event::Models { .. })) else { panic!("{events:?}") }; assert_eq!(current, "local"); assert_eq!(available.iter().map(|m| m.id.as_str()).collect::>(), ["local", "big", "small"]); + assert!(events.iter().any(|e| matches!(e, Event::ModelsNote(None))), "{events:?}"); b.set_model("big"); b.prompt(&[PromptPart::Text("hi".into())]); wait_for_seen(&seen); @@ -2561,6 +2581,87 @@ mod tests { assert!(tools[0].pointer("/parameters/additionalProperties").is_none(), "{tools:?}"); } + /// An endpoint that refuses the listing still shows the configured model, and says why first. + #[test] + fn a_refused_listing_keeps_the_configured_model_and_says_why() { + let http: HttpFn = Arc::new(|r: &HttpRequest| { + assert_eq!(r.method, "GET"); + Ok((401, json!({"error": {"message": "No auth credentials"}}).to_string().into_bytes())) + }); + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::OpenAi, + base_url: "http://localhost:1/v1".into(), + model: "local".into(), + key: None, + http, + request_timeout_s: 300, + reasoning_effort: String::new(), + }; + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut b = ApiBackend::start(cfg, ctx).unwrap(); + let mut events = Vec::new(); + let start = std::time::Instant::now(); + while !events.iter().any(|e| matches!(e, Event::Models { .. })) && start.elapsed() < Duration::from_secs(10) { + events.extend(b.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + let listing: Vec<&Event> = events.iter().filter(|e| matches!(e, Event::Models { .. } | Event::ModelsNote(_))).collect(); + let [Event::ModelsNote(Some(note)), Event::Models { current, available }] = listing[..] else { panic!("{events:?}") }; + assert!(note.contains("No auth credentials"), "{note}"); + assert_eq!(current, "local"); + assert_eq!(available.iter().map(|m| m.id.as_str()).collect::>(), ["local"]); + b.shutdown(true); + } + + /// OpenRouter's shape: the name is the description, whatever else an entry holds is ignored, an + /// id that could not be sent back is left out, and the list stays within its caps. + #[test] + fn a_listing_keeps_the_names_and_stays_within_its_caps() { + let mut data = vec![ + json!({"id": "openai/gpt-x", "name": "OpenAI: GPT X", "description": "Long text", "supported_parameters": ["tools"]}), + json!({"id": "same", "name": "same", "display_name": "Same One"}), + json!({"id": "long", "name": "n".repeat(MODEL_NAME_CAP + 10), "display_name": "d".repeat(MODEL_NAME_CAP + 10)}), + json!({"id": "x".repeat(super::super::MODEL_ID_CAP + 1)}), + json!({"id": "bell\u{7}"}), + json!({"id": ""}), + json!({"id": 7}), + json!({"name": "no id"}), + ]; + data.extend((0..MODEL_LIST_CAP + 500).map(|i| json!({"id": format!("m{i}")}))); + let body = json!({"data": data}).to_string().into_bytes(); + let http: HttpFn = Arc::new(move |_: &HttpRequest| Ok((200, body.clone()))); + let list = model_list(&http, "https://openrouter.ai/api/v1", None).unwrap(); + assert_eq!(list.len(), MODEL_LIST_CAP); + let [first, same, long, next] = &list[..4] else { panic!("{}", list.len()) }; + assert_eq!((first.id.as_str(), first.name.as_str(), first.description.as_str()), ("openai/gpt-x", "openai/gpt-x", "OpenAI: GPT X")); + assert_eq!((same.id.as_str(), same.description.as_str()), ("same", "")); + assert_eq!(long.description.chars().count(), MODEL_NAME_CAP); + assert_eq!(next.id, "m0"); + let list = anthropic_model_list(&http, "https://openrouter.ai/api/v1", None).unwrap(); + assert_eq!(list.len(), MODEL_LIST_CAP); + let [first, same, long] = &list[..3] else { panic!("{}", list.len()) }; + assert_eq!(first.name, "openai/gpt-x"); + assert_eq!(same.name, "Same One"); + assert_eq!(long.name.chars().count(), MODEL_NAME_CAP); + assert!(test_endpoint(&http, "https://openrouter.ai/api/v1", None, "openai/gpt-x").unwrap().contains(&MODEL_LIST_CAP.to_string())); + } + + /// A 200 that is no model list (a web page where the endpoint should be) is an error, so the + /// picker says why and asks again later; a list with nothing in it is a list. + #[test] + fn an_answer_that_is_no_model_list_is_an_error() { + let expected = crate::i18n::tr("ui.agent_chat_models_not_a_list").to_string(); + let page: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, b"Control UI".to_vec()))); + assert_eq!(model_list(&page, "http://localhost:18789/v1", None).unwrap_err(), expected); + assert_eq!(anthropic_model_list(&page, "http://localhost:18789/v1", None).unwrap_err(), expected); + assert_eq!(test_endpoint(&page, "http://localhost:18789/v1", None, "").unwrap_err(), expected); + let object: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, json!({"object": "list"}).to_string().into_bytes()))); + assert_eq!(model_list(&object, "http://localhost:18789/v1", None).unwrap_err(), expected); + let empty: HttpFn = Arc::new(|_: &HttpRequest| Ok((200, json!({"data": []}).to_string().into_bytes()))); + assert!(model_list(&empty, "http://localhost:18789/v1", None).unwrap().is_empty()); + } + #[test] fn tool_arguments_are_an_object_or_an_error() { assert_eq!(tool_arguments(None), Ok(json!({}))); diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs index c7976a8d5..ccd404c09 100644 --- a/crates/ui-egui/src/agent_chat/backend.rs +++ b/crates/ui-egui/src/agent_chat/backend.rs @@ -96,6 +96,11 @@ pub enum Event { current: String, available: Vec, }, + /// Why an endpoint's models could not be listed (`None`: they could). It comes before the + /// [`Event::Models`] of that listing, which then holds only the configured model. + ModelsNote(Option), + /// The agent refused the model it was just sent, and says why. + ModelRejected(String), ConfigOptions(Vec), ConfigOptionFinished { id: String, diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index b1554a06c..9292af175 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -316,6 +316,15 @@ impl Loading { } } +/// The model before an ACP agent was sent another, for when it refuses that one. +struct ModelRevert { + model: String, + /// The one sent was not listed, so it leaves the list again. + unlisted: bool, + /// The model remembered for this agent. + saved: Option, +} + #[derive(Default)] pub struct AgentChat { /// The panel is shown (View menu, the application bar's chat button, Ctrl+Shift+A). @@ -402,6 +411,12 @@ pub struct AgentChat { /// The provider picked in the header when the models come from several providers (`None`: the /// current model's). It only narrows the model list; the agent keeps its model until one is chosen. pub model_provider: Option, + /// Why the running endpoint's models could not be listed, for the picker. + pub models_note: Option, + /// What to put back if the running ACP agent refuses the model it was last sent. + model_revert: Option, + /// The typed model an agent's model option was sent, until it answers. + typed_model: Option, pub config_options: Option>, pub config_pending: bool, /// An API endpoint's models, kept per endpoint (its base URL) for the next connection. @@ -484,6 +499,7 @@ impl AgentChat { self.model_provider = None; } self.config_pending = false; + self.typed_model = None; } fn apply_config_snapshot(&mut self, options: Vec) { @@ -575,6 +591,11 @@ impl AgentChat { pictures.push(Picture::shared(Arc::new(png), "", true)); } } + /// Say that the agent refused a model, and in its words why. + fn model_refused(&mut self, model: &str, error: &str) { + let text = trf("ui.agent_chat_model_rejected", &[("model", model), ("error", error)]); + self.notice(text.chars().take(MODELS_NOTE_CAP).collect::(), true); + } fn notice(&mut self, text: impl Into, error: bool) { self.push(Item::Notice { text: text.into(), error }); } @@ -718,11 +739,21 @@ impl AgentChat { } } Event::Models { current, available } => { + self.model_revert = None; if self.config_options.is_none() && !available.is_empty() { - if !self.running_endpoint.is_empty() { - self.models_cache.insert(self.running_endpoint.clone(), available.clone()); + if self.models_note.is_some() { + // The listing failed: last time's list stays, with the configured model in it. + for model in available { + if !self.models.iter().any(|m| m.id == model.id) { + self.models.insert(0, model); + } + } + } else { + if !self.running_endpoint.is_empty() { + self.models_cache.insert(self.running_endpoint.clone(), available.clone()); + } + self.models = available; } - self.models = available; } if self.config_options.is_none() { if current != self.model { @@ -731,16 +762,36 @@ impl AgentChat { self.model = current; } } + // Formatted here: the listing's thread has no language of its own. + Event::ModelsNote(error) => { + self.models_note = + error.map(|error| trf("ui.agent_chat_models_failed", &[("error", &error)]).chars().take(MODELS_NOTE_CAP).collect()); + } + Event::ModelRejected(message) => { + let refused = self.model.clone(); + self.model_refused(&refused, &message); + if let Some(revert) = self.model_revert.take() { + if revert.unlisted { + let refused = std::mem::take(&mut self.model); + self.models.retain(|m| m.id != refused); + } + self.model = revert.model; + self.model_provider = None; + } + } Event::ConfigOptions(options) => { self.apply_config_snapshot(options); } Event::ConfigOptionFinished { result, .. } => { self.config_pending = false; - match result { - Ok(options) => { + let typed = self.typed_model.take(); + match (result, typed) { + (Ok(options), _) => { self.apply_config_snapshot(options); } - Err(message) => self.notice(message, true), + // An agent's own words may not say what it refused ("Internal error"). + (Err(message), Some(model)) => self.model_refused(&model, &message), + (Err(message), None) => self.notice(message, true), } } Event::AuthRequired { methods } => { @@ -986,6 +1037,8 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { chat.mode.clear(); chat.models.clear(); chat.model.clear(); + chat.models_note = None; + chat.model_revert = None; chat.running_endpoint = if entry.kind.is_api() { entry.base_url.clone() } else { String::new() }; // An endpoint's models from the last time, until the new list arrives. if let Some(list) = chat.models_cache.get(&chat.running_endpoint) { @@ -1352,6 +1405,7 @@ pub fn new_chat(app: &mut SolveApp) { chat.stopped = false; chat.ended = None; chat.discard_end = running; + chat.model_revert = None; if matches!(chat.state(), State::Ready | State::Busy) { chat.restore_mode = Some(chat.mode.clone()).filter(|m| !m.is_empty()); chat.state = Some(State::Starting); @@ -1880,6 +1934,7 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { } _ => None, }; + let refused = if matches!(e, Event::ModelRejected(_)) { app.agent_chat.model_revert.as_ref().map(|r| r.saved.clone()) } else { None }; match app.agent_chat.on_event(e) { Some(Outcome::TurnEnd) => { end_turn(app); @@ -1895,10 +1950,19 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { } if let Some(model) = confirmed_model { app.preferences.agent_models.insert(app.agent_chat.running_id.clone(), model.clone()); - if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == app.agent_chat.running_id && a.kind == agents::Kind::Api) { + if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == app.agent_chat.running_id && a.kind.is_api()) { a.model = model; } } + match refused { + Some(Some(saved)) => { + app.preferences.agent_models.insert(app.agent_chat.running_id.clone(), saved); + } + Some(None) => { + app.preferences.agent_models.remove(&app.agent_chat.running_id); + } + None => {} + } if ready { apply_saved_model(app); } @@ -1919,6 +1983,7 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { settings::poll_capabilities(app, ctx); + settings::poll_listing(app, ctx); connect_at_start(app, ctx); } pump_tools(app); @@ -1953,15 +2018,66 @@ pub fn set_model(app: &mut SolveApp, model: &str) { set_config_option(app, &id, model); return; } - if !app.agent_chat.models.iter().any(|m| m.id == model) { - return; + if app.agent_chat.models.iter().any(|m| m.id == model) { + send_model(app, model); } - if let Some(b) = app.agent_chat.backend.as_mut() { +} + +/// Whether a model the agent did not list can be sent: an endpoint, an ACP agent with a model +/// option, or a legacy ACP agent that listed models. +pub fn custom_models_accepted(app: &SolveApp) -> bool { + let chat = &app.agent_chat; + if chat.backend.is_none() || !chat.state().running() { + return false; + } + match chat.config_options.as_ref() { + Some(options) => options.iter().any(|o| o.category == "model"), + None => !chat.running_endpoint.is_empty() || !chat.models.is_empty(), + } +} + +/// A typed model (the pickers' custom row). A listed id goes the usual way, others by the agent's +/// kind; an agent that refuses it keeps its model and the chat says so. Returns whether it was sent. +pub fn set_custom_model(app: &mut SolveApp, text: &str) -> bool { + let model = text.trim(); + if !model_id_valid(model) || !custom_models_accepted(app) { + return false; + } + let option = app.agent_chat.config_options.as_ref().and_then(|options| options.iter().find(|o| o.category == "model")); + if let Some(id) = option.map(|o| o.id.clone()) { + let sent = set_config_option_checked(app, &id, model, false); + if sent { + app.agent_chat.typed_model = Some(model.to_string()); + } + return sent; + } + send_model(app, model); + true +} + +/// Switch a legacy ACP agent or an endpoint to `model`: it shows as current at once and is +/// remembered for this agent; an endpoint also keeps it as its default model. +fn send_model(app: &mut SolveApp, model: &str) { + let agent = app.agent_chat.running_id.clone(); + let chat = &mut app.agent_chat; + let unlisted = !chat.models.iter().any(|m| m.id == model); + let entry = || acp::ModelInfo { id: model.to_string(), name: model.to_string(), description: String::new() }; + if unlisted { + chat.models.insert(0, entry()); + chat.models.truncate(MODEL_LIST_CAP); + } + if chat.running_endpoint.is_empty() { + chat.model_revert = Some(ModelRevert { model: chat.model.clone(), unlisted, saved: app.preferences.agent_models.get(&agent).cloned() }); + } else if unlisted { + let cached = chat.models_cache.entry(chat.running_endpoint.clone()).or_default(); + cached.insert(0, entry()); + cached.truncate(MODEL_LIST_CAP); + } + if let Some(b) = chat.backend.as_mut() { b.set_model(model); } - app.agent_chat.model = model.to_string(); - app.agent_chat.model_provider = None; - let agent = app.agent_chat.running_id.clone(); + chat.model = model.to_string(); + chat.model_provider = None; if let Some(a) = app.preferences.agents.iter_mut().find(|a| a.id == agent && a.kind.is_api()) { a.model = model.to_string(); } @@ -1984,10 +2100,22 @@ pub fn models_shown(app: &SolveApp) -> bool { /// Longest provider name kept from an agent's model list. const PROVIDER_NAME_CAP: usize = 128; +/// Most models kept for a picker, whether listed or typed. +const MODEL_LIST_CAP: usize = 2000; +/// Longest model id kept from a listing or sent to an agent. +pub const MODEL_ID_CAP: usize = 256; +/// Longest note about a listing that failed or a model the agent refused. +const MODELS_NOTE_CAP: usize = 1024; + +/// Whether a model id can go to an agent: not empty, not too long, no control characters. +fn model_id_valid(id: &str) -> bool { + !id.is_empty() && id.chars().count() <= MODEL_ID_CAP && !id.chars().any(char::is_control) +} /// A model's provider and its name at that provider, when the agent says which provider serves it: -/// a name `Provider · model` (Hermes, OpenCode) or a description `Provider: …` (up to a ` • `). -/// `None`: the agent names no provider. +/// a name `Provider · model` (Hermes, OpenCode), a description `Provider: …` (up to a ` • `), or +/// an endpoint's listing whose id reads `vendor/model` and whose description (the endpoint's own +/// name for it) reads `Vendor: Model` (OpenRouter). `None`: the agent names no provider. pub fn model_provider(m: &acp::ModelInfo) -> Option<(String, String)> { let cap = |s: &str| s.trim().chars().take(PROVIDER_NAME_CAP).collect::(); if let Some((provider, name)) = m.name.split_once(" · ") @@ -1996,9 +2124,48 @@ pub fn model_provider(m: &acp::ModelInfo) -> Option<(String, String)> { { return Some((cap(provider), name.trim().to_string())); } - let rest = m.description.strip_prefix("Provider:")?; - let provider = rest.lines().next().unwrap_or("").split(" • ").next().unwrap_or(""); - (!provider.trim().is_empty()).then(|| (cap(provider), m.name.clone())) + if let Some(rest) = m.description.strip_prefix("Provider:") { + let provider = rest.lines().next().unwrap_or("").split(" • ").next().unwrap_or(""); + return (!provider.trim().is_empty()).then(|| (cap(provider), m.name.clone())); + } + let first_line = m.description.lines().next().unwrap_or(""); + if m.id.contains('/') + && let Some((vendor, name)) = first_line.split_once(": ") + && !vendor.trim().is_empty() + && vendor.chars().count() <= PROVIDER_NAME_CAP + && !name.trim().is_empty() + { + return Some((cap(vendor), name.trim().to_string())); + } + None +} + +/// How a picker shows `models`: each one's label, the group it folds under and its tooltip. With +/// models from two or more providers the label is the name at the provider, the group the +/// provider and the tooltip the id (or the description where the label already is the id); +/// otherwise the name as it is, no group, and the description. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub fn model_rows(models: &[acp::ModelInfo]) -> Vec<(String, Option, String)> { + let mut providers: Vec = Vec::new(); + for m in models { + let p = provider_of(m); + if !providers.contains(&p) { + providers.push(p); + } + } + let grouped = providers.len() >= 2; + models + .iter() + .map(|m| { + if grouped { + let (provider, name) = model_provider(m).unwrap_or_else(|| (provider_of(m), m.name.clone())); + let tip = if name == m.id { m.description.clone() } else { m.id.clone() }; + (name, Some(provider), tip) + } else { + (m.name.clone(), None, m.description.clone()) + } + }) + .collect() } /// The provider a model is listed under: its own, or "Other" when the agent names none. @@ -2051,8 +2218,17 @@ pub fn listed_models(app: &SolveApp) -> Vec<(acp::ModelInfo, String)> { .collect() } -/// Show one provider's models in the model picker (the header's provider picker). The agent keeps -/// its model until one of them is chosen. A provider the agent does not offer is ignored. +/// Every model the header's picker lists, with its label, the group it folds under and its tooltip +/// ([`model_rows`]). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub fn grouped_models(app: &SolveApp) -> Vec<(acp::ModelInfo, String, Option, String)> { + let rows = model_rows(&app.agent_chat.models); + app.agent_chat.models.iter().cloned().zip(rows).map(|(m, (label, group, tip))| (m, label, group, tip)).collect() +} + +/// The provider whose group the header's model picker opens first (the control channel's +/// `provider`). The agent keeps its model until one is chosen. A provider the agent does not offer +/// is ignored. pub fn set_model_provider(app: &mut SolveApp, provider: &str) { if model_providers(app).iter().any(|(n, _)| n == provider) { app.agent_chat.model_provider = Some(provider.to_string()); @@ -2079,19 +2255,25 @@ pub fn set_mode(app: &mut SolveApp, mode: &str) { /// Change a reported modern ACP configuration option; only acknowledged snapshots change state. pub fn set_config_option(app: &mut SolveApp, id: &str, value: &str) { + set_config_option_checked(app, id, value, true); +} + +/// [`set_config_option`], with a choice the agent did not list (`listed_only` false: a typed +/// model, which the agent may refuse). Returns whether it was sent. +fn set_config_option_checked(app: &mut SolveApp, id: &str, value: &str, listed_only: bool) -> bool { let Some(option) = app.agent_chat.config_options.as_ref().and_then(|xs| xs.iter().find(|x| x.id == id)) else { - return; + return false; }; if app.agent_chat.config_pending || !matches!(app.agent_chat.state(), State::Ready | State::Busy) - || !option.options.iter().any(|x| x.value == value) + || (listed_only && !option.options.iter().any(|x| x.value == value)) { - return; - } - if let Some(b) = app.agent_chat.backend.as_mut() { - b.set_config_option(id, value); - app.agent_chat.config_pending = true; + return false; } + let Some(b) = app.agent_chat.backend.as_mut() else { return false }; + b.set_config_option(id, value); + app.agent_chat.config_pending = true; + true } /// `ui.agent_chat` on the control channel (tests and screenshots): `enabled`, `command`, @@ -2186,7 +2368,11 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result Value { #[cfg(target_arch = "wasm32")] let detection: Option = None; let pid = c.backend.as_ref().and_then(|b| b.pid()); - json!({ + let mut state = json!({ "features": app.preferences.ai_features, "configOptions": c.config_options, "configPending": c.config_pending, @@ -2355,7 +2541,13 @@ pub fn status(app: &SolveApp) -> Value { "turnWarning": c.turn_warning, "detection": detection, "items": items, - }) + }); + // Added apart: `json!` has reached the compiler's recursion limit above. + if let Some(state) = state.as_object_mut() { + state.insert("modelsNote".into(), json!(c.models_note)); + state.insert("customModels".into(), json!(custom_models_accepted(app))); + } + state } #[cfg(test)] diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 389a20148..8b69a7e89 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -1044,11 +1044,8 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { ); let models = !modern && models_shown(app); let providers = if models { model_providers(app) } else { Vec::new() }; - let w = (ui.available_width() - - if modern || app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 } - - if models { 146.0 } else { 0.0 } - - if providers.is_empty() { 0.0 } else { 146.0 }) - .clamp(90.0, 260.0); + let w = (ui.available_width() - if modern || app.agent_chat.modes.is_empty() { 4.0 } else { 116.0 } - if models { 146.0 } else { 0.0 }) + .clamp(90.0, 260.0); let mut picked: Option = None; let mut add = false; let combo = ui @@ -1109,61 +1106,47 @@ fn switcher(app: &mut SolveApp, ui: &mut egui::Ui) { set_mode(app, &m); } } - // Models from several providers: pick the provider first, then one of its models. - if let Some(shown) = shown_provider(app).filter(|_| !providers.is_empty()) { - let mut pick: Option = None; - let width = picker_width(ui, &shown); - let r = ui - .allocate_ui(vec2(width, t.control_height), |ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - ui_kit::dropdown_menu(ui, "sc_agent_provider", &shown, |ui| { - for (name, count) in &providers { - let row = ui_kit::list_picker(ui, &format!("provider:{name}"), name, *name == shown) - .on_hover_text(trf("ui.agent_chat_provider_models", &[("count", &count.to_string())])); - crate::scenario::publish_handle(&format!("agent_chat:provider:{name}"), row.rect.center()); - if row.clicked() { - pick = Some(name.clone()); - } - } - }) - }) - .inner; - crate::scenario::publish_rect("agent_chat:provider", r.rect); - crate::scenario::publish_handle("agent_chat:provider", r.rect.center()); - r.on_hover_text(tr("ui.agent_chat_provider_tip")); - if let Some(p) = pick { - set_model_provider(app, &p); - } - } // The agent's models (ACP `models`, or an endpoint's list): shown only when it reports some. if models { - let list = listed_models(app); - let cur = list.iter().find(|(m, _)| m.id == app.agent_chat.model).map_or_else( - || if providers.is_empty() { app.agent_chat.model.clone() } else { tr("ui.agent_chat_choose_model").to_string() }, - |(_, name)| name.clone(), - ); - let mut pick: Option = None; + // Models from several providers fold under their providers inside the picker, the + // current model's provider open. + let list = grouped_models(app); + let open = shown_provider(app).filter(|_| !providers.is_empty()); + let cur = list + .iter() + .find(|(m, _, _, _)| m.id == app.agent_chat.model) + .map_or_else(|| app.agent_chat.model.clone(), |(_, name, _, _)| name.clone()); let width = if providers.is_empty() { t.form_label_width } else { picker_width(ui, &cur) }; - let r = ui + let choices: Vec> = + list.iter().map(|(m, name, group, tip)| ui_kit::SearchChoice { value: &m.id, label: name, tip, group: group.as_deref() }).collect(); + let custom = custom_models_accepted(app); + let picker = ui .allocate_ui(vec2(width, t.control_height), |ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - ui_kit::dropdown_menu(ui, "sc_agent_model", &cur, |ui| { - for (m, name) in &list { - let row = ui_kit::list_picker(ui, &m.id, name, m.id == app.agent_chat.model); - let row = if m.description.is_empty() { row } else { row.on_hover_text(&m.description) }; - crate::scenario::publish_handle(&format!("agent_chat:model:{}", m.id), row.rect.center()); - if row.clicked() { - pick = Some(m.id.clone()); - } - } - }) + ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: "sc_agent_model", + handles: "agent_chat:model", + current: &cur, + current_value: &app.agent_chat.model, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom, + note: app.agent_chat.models_note.as_deref(), + open_group: open.as_deref(), + enabled: true, + }, + ) }) .inner; - crate::scenario::publish_rect("agent_chat:model", r.rect); - crate::scenario::publish_handle("agent_chat:model", r.rect.center()); - r.on_hover_text(tr("ui.agent_chat_model_tip")); - if let Some(m) = pick { - set_model(app, &m); + picker.response.on_hover_text(tr("ui.agent_chat_model_tip")); + match picker.inner { + Some(ui_kit::Picked::Listed(m)) => set_model(app, &m), + Some(ui_kit::Picked::Custom(m)) => { + set_custom_model(app, &m); + } + None => {} } } }); @@ -1288,52 +1271,95 @@ fn config_select(app: &mut SolveApp, ui: &mut egui::Ui, option: &acp::ConfigOpti .collect::>() .join("\n"); let mut picked = None; - let response = ui - .add_enabled_ui(!pending && !option.options.is_empty(), |ui| { - ui.allocate_ui(vec2(width, t.control_height), |ui| { - ui_kit::dropdown_menu(ui, ("sc_agent_config", &option.id), &displayed, |ui| { - let mut previous_group: Option<&str> = None; - for choice in &option.options { - let group = choice.group.as_deref().filter(|g| !g.is_empty()); - if let Some(group) = group - && previous_group != Some(group) - { - ui.label(RichText::new(compact_text(group, 32)).color(t.text_dim).size(t.font_small)).on_hover_text(group); - } - previous_group = group; - let row = ui_kit::list_picker(ui, &choice.value, &compact_text(&choice.name, 32), choice.value == option.current_value); - let row = row.on_hover_text( - [choice.name.as_str(), choice.description.as_str()] - .into_iter() - .filter(|part| !part.is_empty()) - .collect::>() - .join("\n"), - ); - crate::scenario::publish_handle(&format!("agent_chat:config:{}:{}", option.id, choice.value), row.rect.center()); - if option.category == "model" { - crate::scenario::publish_handle(&format!("agent_chat:model:{}", choice.value), row.rect.center()); - } - if row.clicked() { - picked = Some(choice.value.clone()); - } - } - }) + let enabled = !pending && !option.options.is_empty(); + let handles = format!("agent_chat:config:{}", option.id); + let response = if option.category == "model" { + let choices: Vec> = option + .options + .iter() + .map(|choice| ui_kit::SearchChoice { + value: &choice.value, + label: &choice.name, + tip: &choice.description, + group: choice.group.as_deref(), }) - .inner - }) - .inner; - crate::scenario::publish_handle(&format!("agent_chat:config:{}", option.id), response.rect.center()); - crate::scenario::publish_rect(&format!("agent_chat:config:{}", option.id), response.rect); - if option.category == "model" { - crate::scenario::publish_handle("agent_chat:model", response.rect.center()); - } else if option.category == "mode" { - crate::scenario::publish_handle("agent_chat:mode", response.rect.center()); - } - response - .widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, !pending && !option.options.is_empty(), format!("{name}: {selected}"))); + .collect(); + let id = format!("sc_agent_config:{}", option.id); + let picker = ui + .allocate_ui(vec2(width, t.control_height), |ui| { + ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: &id, + handles: &handles, + current: &displayed, + current_value: &option.current_value, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom: true, + note: None, + open_group: None, + enabled, + }, + ) + }) + .inner; + picked = picker.inner; + // Under the names every kind of agent's model picker goes by. + let rows = format!("{handles}:"); + for (name, at) in crate::scenario::handles(&rows) { + if let Some(row) = name.strip_prefix(&rows) { + crate::scenario::publish_handle(&format!("agent_chat:model:{row}"), at); + } + } + crate::scenario::publish_target("agent_chat:model", picker.response.rect); + picker.response + } else { + let response = ui + .add_enabled_ui(enabled, |ui| { + ui.allocate_ui(vec2(width, t.control_height), |ui| { + ui_kit::dropdown_menu(ui, ("sc_agent_config", &option.id), &displayed, |ui| { + let mut previous_group: Option<&str> = None; + for choice in &option.options { + let group = choice.group.as_deref().filter(|g| !g.is_empty()); + if let Some(group) = group + && previous_group != Some(group) + { + ui.label(RichText::new(compact_text(group, 32)).color(t.text_dim).size(t.font_small)).on_hover_text(group); + } + previous_group = group; + let row = ui_kit::list_picker(ui, &choice.value, &compact_text(&choice.name, 32), choice.value == option.current_value); + let row = row.on_hover_text( + [choice.name.as_str(), choice.description.as_str()] + .into_iter() + .filter(|part| !part.is_empty()) + .collect::>() + .join("\n"), + ); + crate::scenario::publish_handle(&format!("{handles}:{}", choice.value), row.rect.center()); + if row.clicked() { + picked = Some(ui_kit::Picked::Listed(choice.value.clone())); + } + } + }) + }) + .inner + }) + .inner; + crate::scenario::publish_target(&handles, response.rect); + if option.category == "mode" { + crate::scenario::publish_handle("agent_chat:mode", response.rect.center()); + } + response + }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, enabled, format!("{name}: {selected}"))); response.on_hover_text(tip); - if let Some(value) = picked { - super::set_config_option(app, &option.id, &value); + match picked { + Some(ui_kit::Picked::Listed(value)) => super::set_config_option(app, &option.id, &value), + Some(ui_kit::Picked::Custom(value)) => { + super::set_custom_model(app, &value); + } + None => {} } } @@ -2347,7 +2373,7 @@ mod tests { ui_kit::scope(ui, |ui| switcher(&mut app, ui)); }); output.textures_delta.clear(); - let rects: Vec<_> = ["switcher", "mode", "provider", "model"] + let rects: Vec<_> = ["switcher", "mode", "model"] .into_iter() .map(|name| { let rect = crate::scenario::rect_of(&format!("agent_chat:{name}")).expect("picker retained"); diff --git a/crates/ui-egui/src/agent_chat/settings.rs b/crates/ui-egui/src/agent_chat/settings.rs index 98527212b..07f584e70 100644 --- a/crates/ui-egui/src/agent_chat/settings.rs +++ b/crates/ui-egui/src/agent_chat/settings.rs @@ -38,6 +38,10 @@ pub struct AddState { /// Editing an endpoint whose key is in the keychain: an empty key field keeps it. pub saved_key: bool, test: Option, + /// The endpoint the model picker lists: what the fields said when they were last left. + listing: Option, + /// The fields were left, or the picker opened: take what they say now. + list_again: bool, } /// A connection test running or done. @@ -80,6 +84,147 @@ pub struct State { capabilities: std::collections::HashMap<(String, String), Option>, #[cfg(not(target_arch = "wasm32"))] checking: Option, + /// Endpoints' models as they were last listed here, or why they could not be. + endpoint_models: std::collections::HashMap, String>>, + #[cfg(not(target_arch = "wasm32"))] + listing: Option, + /// An agent card's picker asked for this listing (with the agent whose key goes along). + #[cfg(not(target_arch = "wasm32"))] + card_listing: Option<(ListingKey, String)>, +} + +/// What an endpoint's models are listed by: its protocol, its base URL, and whether a key goes along. +type ListingKey = (Protocol, String, bool); + +/// Most endpoints' listings kept. +const ENDPOINT_LISTINGS_CAP: usize = 128; + +/// The listing of `base_url`, if that is an address. A key goes along only where it may be sent. +fn listing_key(protocol: Protocol, base_url: &str, with_key: bool) -> Option { + let url = agents::normalize_url(base_url).ok().filter(|url| url.len() <= 4096)?; + let with_key = with_key && agents::key_safe_for(&url); + Some((protocol, url, with_key)) +} + +/// The models listed for `key`, and the note for under them: still listing, or why it could not. +fn listed_for<'a>( + listings: &'a std::collections::HashMap, String>>, + key: Option<&ListingKey>, +) -> (&'a [acp::ModelInfo], Option) { + match key.and_then(|key| listings.get(key)) { + Some(Ok(models)) if models.is_empty() => (&[], Some(tr("ui.agent_chat_models_none").to_string())), + Some(Ok(models)) => (models, None), + Some(Err(error)) => (&[], Some(trf("ui.agent_chat_models_failed", &[("error", error)]))), + None => (&[], key.map(|_| tr("ui.agent_chat_models_listing").to_string())), + } +} + +/// Whether a listing is worth asking for again: it failed, or it listed nothing. +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +fn listing_wants_retry(listing: Option<&Result, String>>) -> bool { + match listing { + Some(Err(_)) => true, + Some(Ok(models)) => models.is_empty(), + None => false, + } +} + +/// `models` as a model picker's rows: the id chooses, the endpoint's name for it is searched too. +fn model_choices<'a>(models: &'a [acp::ModelInfo], rows: &'a [(String, Option, String)]) -> Vec> { + models.iter().zip(rows).map(|(m, (label, group, tip))| ui_kit::SearchChoice { value: &m.id, label, tip, group: group.as_deref() }).collect() +} + +#[cfg(not(target_arch = "wasm32"))] +struct ModelListing { + key: ListingKey, + rx: std::sync::mpsc::Receiver, String>>, +} + +/// List an endpoint's models in the background, one listing at a time; a finished one stays until +/// it is asked for again. `secret` runs on that thread too: a keychain may take its time to answer. +#[cfg(not(target_arch = "wasm32"))] +fn start_listing(app: &mut SolveApp, ctx: &egui::Context, key: ListingKey, secret: impl FnOnce() -> Result, String> + Send + 'static) { + let state = &mut app.agent_chat.settings; + if state.listing.is_some() || state.endpoint_models.contains_key(&key) { + return; + } + if state.endpoint_models.len() >= ENDPOINT_LISTINGS_CAP { + state.endpoint_models.clear(); + } + let Some(http) = app.services.agent_http.clone() else { + state.endpoint_models.insert(key, Err(tr("ui.ai_no_http").to_string())); + return; + }; + let (tx, rx) = std::sync::mpsc::channel(); + let (protocol, url) = (key.0, key.1.clone()); + let language = crate::i18n::language(); + let wake = ctx.clone(); + let spawned = std::thread::Builder::new().name("endpoint-models".into()).spawn(move || { + let _language = crate::i18n::scope(language); + let list = secret().and_then(|secret| match protocol { + Protocol::OpenAi => super::api_client::model_list(&http, &url, secret.as_deref()), + Protocol::Anthropic => super::api_client::anthropic_model_list(&http, &url, secret.as_deref()), + }); + let _ = tx.send(list); + wake.request_repaint(); + }); + match spawned { + Ok(_) => state.listing = Some(ModelListing { key, rx }), + Err(e) => { + state.endpoint_models.insert(key, Err(e.to_string())); + } + } +} + +/// Take in a finished listing, and start the one an agent card asked for. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn poll_listing(app: &mut SolveApp, ctx: &egui::Context) { + use std::sync::mpsc::TryRecvError; + let state = &mut app.agent_chat.settings; + if let Some(listing) = &state.listing { + let result = match listing.rx.try_recv() { + Ok(result) => result, + Err(TryRecvError::Disconnected) => Err(tr("ui.ai_no_answer").to_string()), + Err(TryRecvError::Empty) => return, + }; + state.endpoint_models.insert(listing.key.clone(), result); + state.listing = None; + } + let Some((key, agent)) = state.card_listing.take() else { return }; + let secrets = app.services.secrets.clone().filter(|_| key.2); + start_listing(app, ctx, key, move || match secrets { + Some(secrets) => secrets.get(&agent).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)])), + None => Ok(None), + }); +} + +/// The Add dialog's listing, of what its fields said when last left, never of a half-typed address. +#[cfg(not(target_arch = "wasm32"))] +fn list_for_dialog(app: &mut SolveApp, ctx: &egui::Context) { + let state = &mut app.agent_chat.settings; + let Some(s) = state.add.as_mut().filter(|s| s.kind == AddKind::Api) else { return }; + let typed = Some(s.key.trim().to_string()).filter(|typed| !typed.is_empty()); + // Editing an agent whose key is kept: the listing goes with that key, read on its thread. + let stored = s.editing.clone().filter(|_| s.saved_key && typed.is_none()); + if std::mem::take(&mut s.list_again) { + s.listing = listing_key(s.protocol, &s.base_url, typed.is_some() || stored.is_some()); + // Asked again: what failed may work now, with another key or the server back up. + if let Some(key) = &s.listing + && listing_wants_retry(state.endpoint_models.get(key)) + { + state.endpoint_models.remove(key); + } + } + let Some(key) = s.listing.clone() else { return }; + if state.listing.is_some() || state.endpoint_models.contains_key(&key) { + return; + } + let typed = typed.filter(|_| key.2); + let stored = stored.filter(|_| key.2).and_then(|agent| app.services.secrets.clone().map(|secrets| (secrets, agent))); + start_listing(app, ctx, key, move || match stored { + Some((secrets, agent)) => secrets.get(&agent).map_err(|e| trf("ui.ai_keychain_error", &[("error", &e)])), + None => Ok(typed), + }); } #[cfg(not(target_arch = "wasm32"))] @@ -171,6 +316,7 @@ pub fn open_add(app: &mut SolveApp) { base_url: preset.map(|p| p.base_url.to_string()).unwrap_or_default(), name: preset.map(|p| p.name.to_string()).unwrap_or_default(), request_timeout_s: agents::DEFAULT_REQUEST_TIMEOUT_S, + list_again: true, ..Default::default() }); } @@ -185,6 +331,7 @@ pub fn open_edit(app: &mut SolveApp, id: &str) -> bool { request_timeout_s: c.request_timeout_s.clamp(agents::MIN_REQUEST_TIMEOUT_S, agents::MAX_REQUEST_TIMEOUT_S), reasoning_effort: c.reasoning_effort.clone(), editing: Some(c.id.clone()), + list_again: true, ..Default::default() }; if c.kind.is_api() { @@ -222,6 +369,7 @@ pub(super) fn choose_preset(s: &mut AddState, protocol: Protocol, index: usize) } s.error = None; s.test = None; + s.list_again = true; } /// Run a connection test in the background (it starts the agent briefly, or asks the endpoint @@ -455,6 +603,7 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { let mut edit: Option = None; let mut retimed: Option<(String, u64)> = None; let mut reeffort: Option<(String, String)> = None; + let mut picked_model: Option<(String, ui_kit::Picked)> = None; let t = crate::theme::Tokens::get(); ui_kit::settings_section(ui, "agents", tr("ui.ai_agents"), |ui| { if app.agent_chat.detecting.is_some() { @@ -545,6 +694,55 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { None => {} } }); + if let Some(protocol) = entry.kind.protocol() { + ui_kit::row(ui, tr("ui.ai_model"), |ui| { + let chat = &mut app.agent_chat; + let running = chat.running_id == entry.id && chat.backend.is_some(); + let key = listing_key(protocol, &entry.base_url, entry.key); + let (models, note) = if running { + (chat.models.as_slice(), chat.models_note.clone()) + } else if let Some(models) = chat.models_cache.get(&entry.base_url).filter(|models| !models.is_empty()) { + (models.as_slice(), None) + } else { + listed_for(&chat.settings.endpoint_models, key.as_ref()) + }; + let listed = !models.is_empty(); + let rows = super::model_rows(models); + let choices = model_choices(models, &rows); + let id = format!("sc_ai_model:{}", entry.id); + let handles = format!("prefs:ai_model:{}", entry.id); + let picker = ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: &id, + handles: &handles, + current: &entry.model, + current_value: &entry.model, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom: true, + note: note.as_deref(), + open_group: None, + enabled: true, + }, + ); + // Nobody is asked until the picker opens: not for looking at this page. + if picker.response.clicked() + && !running + && !listed + && let Some(key) = key + { + // Asked again: what failed may work now. + if listing_wants_retry(chat.settings.endpoint_models.get(&key)) { + chat.settings.endpoint_models.remove(&key); + } + chat.settings.card_listing = Some((key, entry.id.clone())); + } + if let Some(pick) = picker.inner { + picked_model = Some((entry.id.clone(), pick)); + } + }); + } }); if entry.kind == Kind::Api && let Some(c) = app.preferences.agents.iter_mut().find(|c| c.id == entry.id) @@ -594,6 +792,25 @@ fn agents_section(app: &mut SolveApp, ui: &mut egui::Ui) { if let Some(id) = edit { open_edit(app, &id); } + if let Some((id, pick)) = picked_model { + if app.agent_chat.running_id == id && app.agent_chat.backend.is_some() { + match pick { + ui_kit::Picked::Listed(model) => set_model(app, &model), + ui_kit::Picked::Custom(model) => { + set_custom_model(app, &model); + } + } + } else { + let (ui_kit::Picked::Listed(model) | ui_kit::Picked::Custom(model)) = pick; + let model = model.trim(); + if model_id_valid(model) { + if let Some(c) = app.preferences.agents.iter_mut().find(|c| c.id == id) { + c.model = model.to_string(); + } + app.preferences.agent_models.insert(id, model.to_string()); + } + } + } // The running conversation uses a new timeout from its next request on. if let Some((id, secs)) = retimed && app.agent_chat.running_id == id @@ -748,10 +965,34 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { ui_kit::text_field(ui, &mut s.name, ""); }); ui_kit::row(ui, tr("ui.ai_base_url"), |ui| { - ui_kit::text_field(ui, &mut s.base_url, tr("ui.ai_url_hint")); + s.list_again |= + ui_kit::cell_editor(ui, egui::Id::new("sc_ai_add_url"), &mut s.base_url, tr("ui.ai_url_hint"), false).lost_focus(); }); ui_kit::row(ui, tr("ui.ai_model"), |ui| { - ui_kit::text_field(ui, &mut s.model, tr("ui.ai_model_hint")); + let (models, note) = listed_for(&app.agent_chat.settings.endpoint_models, s.listing.as_ref()); + let rows = super::model_rows(models); + let choices = model_choices(models, &rows); + let current = if s.model.is_empty() { tr("ui.agent_chat_choose_model") } else { s.model.as_str() }; + let picker = ui_kit::search_picker( + ui, + ui_kit::SearchPicker { + id: "sc_ai_add_model", + handles: "ai_add:model", + current, + current_value: &s.model, + hint: tr("ui.agent_chat_model_search"), + choices: &choices, + custom: true, + note: note.as_deref(), + open_group: None, + enabled: true, + }, + ); + s.list_again |= picker.response.clicked(); + if let Some(ui_kit::Picked::Listed(model) | ui_kit::Picked::Custom(model)) = picker.inner { + s.model = model; + s.error = None; + } }); ui_kit::row(ui, tr("ui.ai_request_timeout"), |ui| { timeout_field(ui, &mut s.request_timeout_s, "ai_add:request_timeout"); @@ -764,6 +1005,7 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { let hint = tr(if s.saved_key { "ui.ai_key_keep_hint" } else { "ui.ai_key_hint" }); let r = ui_kit::password_field(ui, egui::Id::new("sc_ai_add_key"), &mut s.key, hint); crate::scenario::publish_target("ai_add:key", r.rect); + s.list_again |= r.lost_focus(); }); }); ui_kit::text(ui, tr(if has_keychain { "ui.ai_key_note" } else { "ui.ai_no_keychain" }), ui_kit::Text::Note("keychain")); @@ -782,6 +1024,8 @@ pub fn dialog(app: &mut SolveApp, ctx: &egui::Context) { } add |= action == ui_kit::Action::Ok; open &= !closed && action != ui_kit::Action::Cancel; + #[cfg(not(target_arch = "wasm32"))] + list_for_dialog(app, ctx); if test { #[cfg(not(target_arch = "wasm32"))] if let Some(s) = app.agent_chat.settings.add.as_ref() { @@ -1179,4 +1423,267 @@ mod card_tests { assert_eq!(add_agent(&mut h.app), Err(tr("ui.ai_edit_gone").to_string())); assert!(h.app.preferences.agents.is_empty()); } + + /// An `agent_http` that may not be called on the window's thread: it answers `/models` as + /// OpenRouter does, or 401 for an address with `refused` in it, and records what it was asked. + fn listing_http(h: &mut Harness) -> std::sync::Arc>> { + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = seen.clone(); + let ui_thread = std::thread::current().id(); + h.app.services.agent_http = Some(std::sync::Arc::new(move |request: &super::super::backend::HttpRequest| { + assert_ne!(std::thread::current().id(), ui_thread); + // The running agent's capability check goes through here too. + if request.url.ends_with("/models") + && let Ok(mut log) = log.lock() + { + log.push((request.url.clone(), request.headers.iter().any(|(name, _)| name == "Authorization"))); + } + if request.url.contains("refused") { + return Ok((401, br#"{"error":{"message":"no such key"}}"#.to_vec())); + } + if request.url.contains("/page/") { + return Ok((200, b"Control UI".to_vec())); + } + if request.url.contains("/empty/") { + return Ok((200, br#"{"data":[]}"#.to_vec())); + } + Ok((200, json!({"data": [{"id": "vendor/big", "name": "Vendor: Big"}, {"id": "vendor/small"}]}).to_string().into_bytes())) + })); + seen + } + + /// A web page where the models should be, or a list with nothing in it, says so under the + /// picker, and is asked for again the next time. + #[test] + fn a_listing_that_is_no_list_or_lists_nothing_says_so_and_is_asked_again() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let seen = listing_http(&mut h); + let requests = || seen.lock().unwrap().len(); + open_add(&mut h.app); + h.frames(3); + h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_endpoint"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests(), 1); + let note = |h: &Harness| { + let add = h.app.agent_chat.settings.add.as_ref().unwrap(); + listed_for(&h.app.agent_chat.settings.endpoint_models, add.listing.as_ref()).1.unwrap_or_default() + }; + // What the dialog's listing holds for the fields as they are (the words are the language's). + let listing = |h: &Harness| { + let add = h.app.agent_chat.settings.add.as_ref().unwrap(); + add.listing.as_ref().and_then(|key| h.app.agent_chat.settings.endpoint_models.get(key)).cloned() + }; + let ask = |h: &mut Harness, url: &str| { + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = url.into(); + add.list_again = true; + list_settled(h); + }; + ask(&mut h, "http://localhost:18789/page/v1"); + assert_eq!(requests(), 2); + assert!(matches!(listing(&h), Some(Err(_))), "a page where the list should be is an error: {:?}", listing(&h)); + assert!(!note(&h).is_empty(), "and the picker says so"); + ask(&mut h, "http://localhost:18789/page/v1"); + assert_eq!(requests(), 3, "a page where the list should be is asked for again"); + ask(&mut h, "http://localhost:18789/empty/v1"); + assert_eq!(requests(), 4); + assert!(matches!(listing(&h), Some(Ok(models)) if models.is_empty()), "{:?}", listing(&h)); + assert!(!note(&h).is_empty(), "an empty list is said so too"); + ask(&mut h, "http://localhost:18789/empty/v1"); + assert_eq!(requests(), 5, "an empty list is asked for again"); + ask(&mut h, "http://localhost:11434/v1"); + assert_eq!(requests(), 5, "a list that had models is kept"); + assert_eq!(note(&h), ""); + } + + /// Editing an endpoint whose key is kept lists its models at once, with that key from the + /// keychain (never shown). + #[test] + fn editing_an_endpoint_lists_with_its_stored_key() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let keys = std::sync::Arc::new(MemoryKeys::default()); + h.app.services.secrets = Some(keys.clone()); + keys.set("api-1", "test-key-1").unwrap(); + let seen = listing_http(&mut h); + let requests = || seen.lock().unwrap().clone(); + h.app.preferences.agents.push(AgentConfig { + id: "api-1".into(), + name: "Endpoint".into(), + kind: Kind::Api, + base_url: "https://openrouter.ai/api/v1".into(), + model: "vendor/big".into(), + key: true, + ..Default::default() + }); + h.call("ui.prefs", json!({"open": "AI"})); + h.frames(3); + assert!(open_edit(&mut h.app, "api-1")); + list_settled(&mut h); + assert_eq!(requests(), [("https://openrouter.ai/api/v1/models".to_string(), true)], "listed on opening, with the kept key"); + assert!(h.app.agent_chat.settings.add.as_ref().unwrap().key.is_empty(), "the kept key stays out of the field"); + } + + fn list_settled(h: &mut Harness) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + h.frames(2); + while (h.app.agent_chat.settings.listing.is_some() || h.app.agent_chat.settings.card_listing.is_some()) + && std::time::Instant::now() < deadline + { + std::thread::sleep(std::time::Duration::from_millis(1)); + h.frames(1); + } + assert!(h.app.agent_chat.settings.listing.is_none()); + h.frames(2); + } + + /// The dialog lists an endpoint's models off the window's thread, once per endpoint and key, of + /// what the fields say when they are left and not while they are typed in; a key goes only + /// where it may. A row and a typed model both fill the field, and Add takes either. + #[test] + fn the_add_dialog_lists_an_endpoints_models_once_and_takes_a_row_or_a_typed_model() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let seen = listing_http(&mut h); + let requests = || seen.lock().unwrap().clone(); + open_add(&mut h.app); + h.frames(3); + assert!(requests().is_empty(), "no endpoint chosen yet"); + h.step(&json!({"click":{"handle":"ai_add:ui.ai_add_endpoint"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests(), [("http://localhost:11434/v1/models".to_string(), false)]); + h.frames(5); + assert_eq!(requests().len(), 1, "once"); + + h.step(&json!({"click":{"handle":"ai_add:preset"}})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"ai_add:preset:OpenRouter"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests().last().cloned(), Some(("https://openrouter.ai/api/v1/models".to_string(), false))); + + // Typed in: no request until the field is left, which here the flag stands for. + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "http://10.0.0.2:1234/v1".into(); + add.key = "not-a-real-key".into(); + h.frames(5); + assert_eq!(requests().len(), 2, "not while it is typed"); + h.app.agent_chat.settings.add.as_mut().unwrap().list_again = true; + list_settled(&mut h); + assert_eq!( + requests().last().cloned(), + Some(("http://10.0.0.2:1234/v1/models".to_string(), false)), + "no key over plain http to another computer" + ); + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "https://openrouter.ai/api/v1".into(); + add.list_again = true; + list_settled(&mut h); + assert_eq!(requests().last().cloned(), Some(("https://openrouter.ai/api/v1/models".to_string(), true)), "with a key is another listing"); + + // A row and a typed model. + assert!(scenario::handle_at("ai_add:model").is_some()); + h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap(); + h.frames(3); + assert!(scenario::handle_at("ai_add:model:search").is_some()); + assert!(scenario::handle_at("ai_add:model:group:Vendor").is_some(), "an endpoint's vendors are the groups"); + h.step(&json!({"click":{"handle":"ai_add:model:vendor/big"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.agent_chat.settings.add.as_ref().unwrap().model, "vendor/big"); + h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap(); + h.frames(3); + h.step(&json!({"text":"vendor/own:free"})).unwrap(); + h.frames(3); + h.step(&json!({"click":{"handle":"ai_add:model:custom"}})).unwrap(); + h.frames(3); + assert_eq!(h.app.agent_chat.settings.add.as_ref().unwrap().model, "vendor/own:free"); + assert_eq!(requests().len(), 4, "opening the picker asks nobody again"); + + // A refusal shows in the popup, and opening it again asks again. + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "https://refused.example/v1".into(); + add.key.clear(); + add.list_again = true; + list_settled(&mut h); + h.step(&json!({"click":{"handle":"ai_add:model"}})).unwrap(); + list_settled(&mut h); + assert_eq!(requests().len(), 6, "asked again on opening"); + let listing = h.app.agent_chat.settings.add.as_ref().unwrap().listing.clone(); + let (models, note) = listed_for(&h.app.agent_chat.settings.endpoint_models, listing.as_ref()); + assert!(models.is_empty()); + assert!(note.as_deref().is_some_and(|note| note.contains("no such key")), "{note:?}"); + h.step(&json!({"key":"Escape"})).unwrap(); + h.frames(3); + let add = h.app.agent_chat.settings.add.as_mut().unwrap(); + add.base_url = "https://openrouter.ai/api/v1".into(); + h.step(&json!({"click":{"handle":"ai_add:add"}})).unwrap(); + assert!(h.app.agent_chat.settings.add.is_none()); + assert_eq!(h.app.preferences.agents.last().map(|a| a.model.as_str()), Some("vendor/own:free")); + } + + /// The keychain answers on the listing's thread, not on the window's. + struct KeyOffTheWindow(std::thread::ThreadId); + impl super::super::backend::Secrets for KeyOffTheWindow { + fn get(&self, _: &str) -> Result, String> { + assert_ne!(std::thread::current().id(), self.0); + Ok(Some("not-a-real-key".into())) + } + fn set(&self, _: &str, _: &str) -> Result<(), String> { + Ok(()) + } + fn delete(&self, _: &str) -> Result<(), String> { + Ok(()) + } + } + + /// An endpoint's card has a model row. The page asks nobody; opening the picker lists, with the + /// agent's key from the keychain, and a row or a typed model becomes an idle agent's model. + #[test] + fn the_card_lists_when_its_picker_opens_and_changes_an_idle_endpoints_model() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + h.app.services.secrets = Some(std::sync::Arc::new(KeyOffTheWindow(std::thread::current().id()))); + let seen = listing_http(&mut h); + h.app.preferences.agents.push(AgentConfig { + id: "api-1".into(), + name: "Endpoint".into(), + kind: Kind::Api, + base_url: "http://localhost:1/v1".into(), + model: "local".into(), + key: true, + ..Default::default() + }); + h.step(&json!({"call":"ui.prefs","params":{"open":"AI"}})).unwrap(); + h.frames(4); + assert!(scenario::handle_at("prefs:ai_model:api-1").is_some()); + assert!(seen.lock().unwrap().is_empty(), "looking at the page asks nobody"); + + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1"}})).unwrap(); + list_settled(&mut h); + assert_eq!(*seen.lock().unwrap(), [("http://localhost:1/v1/models".to_string(), true)]); + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1:vendor/big"}})).unwrap(); + h.frames(3); + let model = |h: &Harness| h.app.preferences.agents.iter().find(|a| a.id == "api-1").map(|a| a.model.clone()); + assert_eq!(model(&h).as_deref(), Some("vendor/big")); + assert_eq!(h.app.preferences.agent_models.get("api-1").map(String::as_str), Some("vendor/big")); + + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1"}})).unwrap(); + h.frames(3); + h.step(&json!({"text":" vendor/own "})).unwrap(); + h.frames(3); + assert!(h.ctx.memory(|m| m.has_focus(egui::Id::new("sc_ai_model:api-1").with("search"))), "the box keeps the focus over Preferences"); + h.step(&json!({"click":{"handle":"prefs:ai_model:api-1:custom"}})).unwrap(); + h.frames(3); + assert_eq!(model(&h).as_deref(), Some("vendor/own")); + assert_eq!(h.app.preferences.agent_models.get("api-1").map(String::as_str), Some("vendor/own")); + assert_eq!(seen.lock().unwrap().len(), 1, "listed once"); + } } diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 927766943..9f2054c91 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -1400,6 +1400,83 @@ fn models_reply(current: &str) -> Event { Event::Models { current: current.into(), available: vec![m("fast"), m("smart")] } } +/// An endpoint's listing whose ids read `vendor/model` and whose names (the descriptions here) read +/// `Vendor: Model`, as OpenRouter's, names its providers; the rows then read the model's name with +/// the id as the tooltip. One vendor is one flat list. +#[test] +fn an_endpoints_vendor_named_listing_names_its_providers() { + let m = |id: &str, description: &str| acp::ModelInfo { id: id.into(), name: id.into(), description: description.into() }; + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra")), Some(("OpenAI".into(), "GPT-6.1 Terra".into()))); + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra\nmore")), Some(("OpenAI".into(), "GPT-6.1 Terra".into()))); + assert_eq!(model_provider(&m("gpt-6.1-terra", "OpenAI: GPT-6.1 Terra")), None, "no vendor in the id"); + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "OpenAI: ")), None, "no name"); + assert_eq!(model_provider(&m("openai/gpt-6.1-terra", "")), None); + assert_eq!( + model_provider(&m("openai/gpt-6.1-terra", "Provider: Host • current")), + Some(("Host".into(), "openai/gpt-6.1-terra".into())), + "an agent's own word first" + ); + let rows = model_rows(&[m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra"), m("qwen/qwen3.8-flash", "Qwen: Qwen3.8 Flash"), m("free-model", "")]); + assert_eq!( + rows, + [ + ("GPT-6.1 Terra".to_string(), Some("OpenAI".to_string()), "openai/gpt-6.1-terra".to_string()), + ("Qwen3.8 Flash".to_string(), Some("Qwen".to_string()), "qwen/qwen3.8-flash".to_string()), + ("free-model".to_string(), Some(tr("ui.agent_chat_provider_other").to_string()), String::new()), + ] + ); + let rows = model_rows(&[m("openai/gpt-6.1-terra", "OpenAI: GPT-6.1 Terra"), m("openai/gpt-5.6-luna", "OpenAI: GPT-5.6 Luna")]); + assert_eq!(rows[0], ("openai/gpt-6.1-terra".to_string(), None, "OpenAI: GPT-6.1 Terra".to_string()), "one vendor is one flat list"); +} + +/// Models from several providers fold under their providers inside the picker: the current model's +/// provider is open and the others folded; a header opens or folds its group; a typed search opens +/// every group with a match but one folded by hand; the provider asked for over the control channel +/// is open at the next opening. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_header_groups_models_by_provider_and_folds_them() { + use crate::scenario::handle_at; + let mut h = narrow_chat(); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.running_id = "claude".into(); + let m = |id: &str, name: &str| acp::ModelInfo { id: id.into(), name: name.into(), description: String::new() }; + script.report(Event::Models { + current: "a".into(), + available: vec![m("a", "Host · Alpha"), m("c", "Nous Portal · Gamma"), m("b", "Host · Beta"), m("d", "Nous Portal · Delta")], + }); + h.frames(4); + assert!(handle_at("agent_chat:provider").is_none(), "no provider drop-down of its own"); + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:group:Host").is_some() && handle_at("agent_chat:model:group:Nous Portal").is_some()); + assert!(handle_at("agent_chat:model:a").is_some() && handle_at("agent_chat:model:b").is_some(), "the current model's provider is open"); + assert!(handle_at("agent_chat:model:c").is_none() && handle_at("agent_chat:model:d").is_none(), "the other provider is folded"); + h.step(&json!({"click": {"handle": "agent_chat:model:group:Nous Portal"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:c").is_some(), "a header opens its group"); + h.step(&json!({"click": {"handle": "agent_chat:model:group:Host"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:a").is_none(), "and folds it"); + h.step(&json!({"text": "ta"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:b").is_none(), "a fold made by hand stays while searching, Beta or not"); + assert!(handle_at("agent_chat:model:d").is_some() && handle_at("agent_chat:model:c").is_none(), "Delta matches, Gamma does not"); + h.step(&json!({"click": {"handle": "agent_chat:model:d"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: d"]); + assert_eq!(h.app.agent_chat.model, "d"); + assert!(handle_at("agent_chat:model:search").is_none(), "a choice closes it"); + + control(&mut h.app, &h.ctx, &json!({"provider": "Host"})).unwrap(); + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:a").is_some(), "the provider asked for is open"); + assert!(handle_at("agent_chat:model:d").is_some(), "and the current model's"); +} + /// Choosing a model tells the agent, shows it as current and remembers it for this agent; a model /// the agent did not offer is ignored. #[test] @@ -1423,6 +1500,388 @@ fn choosing_a_model_sets_it_and_remembers_it() { assert_eq!(app.agent_chat.models.len(), 2, "the list stays"); } +/// A scripted endpoint: its agent is configured, and it is running with these models. +#[cfg(not(target_arch = "wasm32"))] +fn endpoint_with_script() -> (SolveApp, Script, egui::Context) { + let (mut app, script, ctx) = app_with_script(); + let endpoint = "http://localhost:11434/v1"; + app.agent_chat.running_id = "api-1".into(); + app.agent_chat.running_endpoint = endpoint.into(); + app.preferences.agents.push(agents::AgentConfig { + id: "api-1".into(), + kind: agents::Kind::Api, + base_url: endpoint.into(), + model: "fast".into(), + ..Default::default() + }); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + (app, script, ctx) +} + +/// A typed model goes straight to an endpoint, joins the list for the next connection and becomes +/// the agent's default. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_typed_model_goes_to_an_endpoint_and_is_remembered() { + let (mut app, script, _ctx) = endpoint_with_script(); + assert!(custom_models_accepted(&app)); + assert!(set_custom_model(&mut app, " openai/gpt-x ")); + assert_eq!(script.calls(), ["set_model: openai/gpt-x"]); + assert_eq!(app.agent_chat.models.first().map(|m| m.id.as_str()), Some("openai/gpt-x")); + assert_eq!(app.agent_chat.models_cache.get("http://localhost:11434/v1").and_then(|l| l.first()).map(|m| m.id.as_str()), Some("openai/gpt-x")); + assert_eq!(app.preferences.agents.iter().find(|a| a.id == "api-1").unwrap().model, "openai/gpt-x"); + assert_eq!(app.preferences.agent_models.get("api-1").map(String::as_str), Some("openai/gpt-x")); + assert_eq!(status(&app)["model"], "openai/gpt-x"); + assert_eq!(status(&app)["customModels"], true); + let listed = app.agent_chat.models.len(); + assert!(set_custom_model(&mut app, "smart")); + assert_eq!(app.agent_chat.models.len(), listed, "a listed id goes the usual way"); + assert_eq!(app.agent_chat.model, "smart"); +} + +/// A typed model is only sent when it could be a model at all, and the list stays within its cap. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_typed_model_that_cannot_be_one_is_not_sent() { + let (mut app, script, _ctx) = endpoint_with_script(); + for text in ["", " ", "x".repeat(MODEL_ID_CAP + 1).as_str(), "bell\u{7}", "two\nlines"] { + assert!(!set_custom_model(&mut app, text), "{text:?}"); + } + assert!(script.calls().is_empty()); + assert!(set_custom_model(&mut app, &"x".repeat(MODEL_ID_CAP))); + app.agent_chat.models = + (0..MODEL_LIST_CAP).map(|i| acp::ModelInfo { id: format!("m{i}"), name: String::new(), description: String::new() }).collect(); + assert!(set_custom_model(&mut app, "one-more")); + assert_eq!(app.agent_chat.models.len(), MODEL_LIST_CAP); + assert_eq!(app.agent_chat.models.first().map(|m| m.id.as_str()), Some("one-more")); +} + +/// An agent with a model option gets a typed model through it. Nothing changes until it answers, +/// and a refusal leaves the old model with the agent's reason in the chat. +#[test] +fn a_typed_model_is_sent_to_a_modern_agent_and_a_rejection_keeps_the_old_one() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "modern".into(); + script.report(Event::ConfigOptions(modern_options("fast"))); + poll(&mut app, &ctx); + assert!(custom_models_accepted(&app)); + assert!(set_custom_model(&mut app, "claude-x")); + assert_eq!(script.calls(), ["set_config_option: some.provider.model=claude-x"]); + assert!(app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "fast"); + assert!(!set_custom_model(&mut app, "claude-y"), "one request at a time"); + + script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Err("no such model".into()) }); + poll(&mut app, &ctx); + assert!(!app.agent_chat.config_pending); + assert_eq!(app.agent_chat.model, "fast"); + assert!( + app.agent_chat + .items + .iter() + .any(|i| matches!(i, Item::Notice { text, error: true } if text.contains("claude-x") && text.contains("no such model"))), + "the notice names the model and the reason" + ); + assert!(!app.preferences.agent_models.contains_key("modern")); + assert_eq!(app.agent_chat.typed_model, None); + + // An agent that takes it says so in its snapshot, and that is what is remembered. + assert!(set_custom_model(&mut app, "claude-x")); + script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("claude-x")) }); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "claude-x"); + assert_eq!(app.preferences.agent_models.get("modern").map(String::as_str), Some("claude-x")); +} + +/// A legacy agent shows a typed model at once; a refusal puts everything back and says why. +#[test] +fn a_typed_model_is_sent_to_a_legacy_agent_and_a_rejection_reverts_it() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "claude".into(); + app.preferences.agent_models.insert("claude".into(), "fast".into()); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + assert!(set_custom_model(&mut app, "zzz")); + assert_eq!(script.calls(), ["set_model: zzz"]); + assert_eq!(app.agent_chat.model, "zzz"); + assert_eq!(app.preferences.agent_models.get("claude").map(String::as_str), Some("zzz")); + + script.report(Event::ModelRejected("no such model".into())); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "fast"); + assert_eq!(app.agent_chat.models.iter().map(|m| m.id.as_str()).collect::>(), ["fast", "smart"]); + assert_eq!(app.preferences.agent_models.get("claude").map(String::as_str), Some("fast")); + assert!( + app.agent_chat + .items + .iter() + .any(|i| matches!(i, Item::Notice { text, error: true } if text.contains("zzz") && text.contains("no such model"))), + "the notice names the model and the reason" + ); + + // A listed model the agent refuses goes back too, and nothing was remembered before it here. + app.preferences.agent_models.remove("claude"); + set_model(&mut app, "smart"); + script.report(Event::ModelRejected("x".repeat(MODELS_NOTE_CAP * 2))); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "fast"); + assert_eq!(app.agent_chat.models.len(), 2); + assert!(!app.preferences.agent_models.contains_key("claude")); + let Some(Item::Notice { text, .. }) = app.agent_chat.items.last() else { panic!("no notice") }; + assert_eq!(text.chars().count(), MODELS_NOTE_CAP); + + // The agent confirming its model ends the wait: a later refusal has nothing to put back. + assert!(set_custom_model(&mut app, "zzz")); + script.report(Event::Models { current: "zzz".into(), available: vec![] }); + script.report(Event::ModelRejected("late".into())); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.model, "zzz"); +} + +/// An agent that lists no models and has no model option cannot be sent one; a stopped one neither. +#[test] +fn an_agent_without_models_takes_no_typed_model() { + let (mut app, script, ctx) = app_with_script(); + app.agent_chat.running_id = "other".into(); + script.report(Event::Ready { agent: "fake".into(), images: false }); + poll(&mut app, &ctx); + assert!(!custom_models_accepted(&app)); + assert_eq!(status(&app)["customModels"], false); + assert!(!set_custom_model(&mut app, "zzz")); + assert!(script.calls().is_empty()); + script.report(Event::ConfigOptions(vec![])); + poll(&mut app, &ctx); + assert!(!custom_models_accepted(&app), "its options name no model"); + + let (mut app, script, ctx) = app_with_script(); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + assert!(custom_models_accepted(&app)); + app.agent_chat.backend = None; + assert!(!custom_models_accepted(&app)); + assert!(!set_custom_model(&mut app, "zzz")); +} + +/// The control channel's `model`: a listed one as before, an unlisted one when the agent takes +/// typed models, otherwise ignored as before. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_control_channel_sends_an_unlisted_model_where_it_can_go() { + let (mut app, script, ctx) = endpoint_with_script(); + let reply = control(&mut app, &ctx, &json!({"model": "smart"})).unwrap(); + assert_eq!(reply["model"], "smart"); + let reply = control(&mut app, &ctx, &json!({"model": "unlisted"})).unwrap(); + assert_eq!(reply["model"], "unlisted"); + assert_eq!(reply["customModels"], true); + assert_eq!(reply["modelsNote"], Value::Null); + assert_eq!(script.calls(), ["set_model: smart", "set_model: unlisted"]); + + let (mut app, script, ctx) = app_with_script(); + let reply = control(&mut app, &ctx, &json!({"model": "unlisted"})).unwrap(); + assert_eq!(reply["model"], ""); + assert_eq!(reply["customModels"], false); + assert!(script.calls().is_empty()); +} + +/// The header's picker on an agent that lists models: it searches, a row chooses, and what was typed +/// can be chosen too. The control and the popup stay in a narrow chat's window. +#[test] +fn the_header_model_picker_searches_and_takes_a_typed_model() { + use crate::scenario::{handle_at, rect_of}; + let mut h = narrow_chat(); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.running_id = "claude".into(); + script.report(models_reply("fast")); + h.frames(4); + let panel = rect_of("agent_chat:panel").expect("the panel"); + let control = rect_of("agent_chat:model").expect("the picker"); + assert!(control.left() >= panel.left() && control.right() <= panel.right(), "{control:?} in {panel:?}"); + assert!(handle_at("agent_chat:model:search").is_none(), "closed"); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + for name in ["search", "fast", "smart"] { + assert!(handle_at(&format!("agent_chat:model:{name}")).is_some(), "{name}"); + } + assert!(handle_at("agent_chat:model:custom").is_none(), "nothing typed"); + let search = rect_of("agent_chat:model:search").expect("the search box"); + assert!(search.left() >= 0.0 && search.right() <= 1600.0, "inside the harness's window: {search:?}"); + + h.step(&json!({"text": "SMA"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:fast").is_none() && handle_at("agent_chat:model:smart").is_some()); + assert!(handle_at("agent_chat:model:custom").is_some(), "the typed text is not a listed model"); + h.step(&json!({"click": {"handle": "agent_chat:model:smart"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart"]); + assert_eq!(h.app.agent_chat.model, "smart"); + assert!(handle_at("agent_chat:model:search").is_none(), "a choice closes it"); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + h.step(&json!({"click": {"handle": "agent_chat:model:custom"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart", "set_model: zzz"]); + assert_eq!(h.app.agent_chat.model, "zzz"); + disconnect(&mut h.app); +} + +/// The picker on an agent with a model option goes by the same names. A row and a typed model both +/// go through the option, and other options stay plain dropdowns. +#[test] +fn the_header_model_option_searches_and_takes_a_typed_model() { + use crate::scenario::handle_at; + let mut h = narrow_chat(); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + script.report(Event::ConfigOptions(modern_options("fast"))); + h.frames(4); + assert_eq!(handle_at("agent_chat:model"), handle_at("agent_chat:config:some.provider.model")); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + for name in ["search", "fast", "smart"] { + assert!(handle_at(&format!("agent_chat:model:{name}")).is_some(), "{name}"); + assert_eq!(handle_at(&format!("agent_chat:model:{name}")), handle_at(&format!("agent_chat:config:some.provider.model:{name}"))); + } + h.step(&json!({"click": {"handle": "agent_chat:model:smart"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_config_option: some.provider.model=smart"]); + script.report(Event::ConfigOptionFinished { id: "some.provider.model".into(), result: Ok(modern_options("smart")) }); + h.frames(3); + assert_eq!(h.app.agent_chat.model, "smart"); + + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:custom").is_some()); + h.step(&json!({"click": {"handle": "agent_chat:model:custom"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls().last().map(String::as_str), Some("set_config_option: some.provider.model=zzz")); + assert_eq!(h.app.agent_chat.model, "smart", "not until the agent says so"); + assert!(h.app.agent_chat.config_pending); + disconnect(&mut h.app); +} + +/// Nothing typed can be chosen where it could not be sent, and the reason a listing failed shows +/// in the popup. +#[test] +fn the_header_model_picker_offers_no_typed_model_it_cannot_send_and_shows_why_listing_failed() { + use crate::scenario::handle_at; + let mut h = narrow_chat(); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.models = vec![acp::ModelInfo { id: "fast".into(), name: "fast".into(), description: String::new() }]; + h.app.agent_chat.model = "fast".into(); + h.app.agent_chat.models_note = Some("Couldn't list models: offline".into()); + h.frames(4); + assert!(!custom_models_accepted(&h.app)); + h.step(&json!({"click": {"handle": "agent_chat:model"}})).unwrap(); + h.frames(3); + assert!(h.widget("Couldn't list models: offline").is_some()); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + assert!(handle_at("agent_chat:model:search").is_some()); + assert!(handle_at("agent_chat:model:custom").is_none()); +} + +/// A running endpoint's card uses the chat's list and changes the chat's model. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_card_of_a_running_endpoint_changes_the_chats_model() { + use crate::scenario::handle_at; + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.preferences.ai_features = true; + h.app.agent_chat.detection = Some(Default::default()); + let script = Script::default(); + h.app.agent_chat.backend = Some(Box::new(script.clone())); + h.app.agent_chat.state = Some(State::Ready); + h.app.agent_chat.running_id = "api-1".into(); + h.app.agent_chat.running_endpoint = "http://localhost:1/v1".into(); + h.app.preferences.agents.push(agents::AgentConfig { + id: "api-1".into(), + name: "Endpoint".into(), + kind: agents::Kind::Api, + base_url: "http://localhost:1/v1".into(), + model: "fast".into(), + ..Default::default() + }); + script.report(models_reply("fast")); + h.step(&json!({"call": "ui.prefs", "params": {"open": "AI"}})).unwrap(); + h.frames(4); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1"}})).unwrap(); + h.frames(3); + assert!(handle_at("prefs:ai_model:api-1:smart").is_some()); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1:smart"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart"]); + assert_eq!(h.app.agent_chat.model, "smart"); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1"}})).unwrap(); + h.frames(3); + h.step(&json!({"text": "zzz"})).unwrap(); + h.frames(3); + h.step(&json!({"click": {"handle": "prefs:ai_model:api-1:custom"}})).unwrap(); + h.frames(3); + assert_eq!(script.calls(), ["set_model: smart", "set_model: zzz"]); + assert_eq!(h.app.preferences.agents.iter().find(|a| a.id == "api-1").map(|a| a.model.as_str()), Some("zzz")); + disconnect(&mut h.app); +} + +/// A listing that fails says why and leaves last time's list, with the configured model in it; the +/// next connection starts without the note. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_listing_that_fails_says_why_and_keeps_the_list_of_last_time() { + let (mut app, script, ctx) = app_with_script(); + let endpoint = "http://localhost:11434/v1"; + app.agent_chat.running_endpoint = endpoint.into(); + script.report(Event::ModelsNote(None)); + script.report(models_reply("fast")); + poll(&mut app, &ctx); + assert_eq!(app.agent_chat.models_note, None); + let ids = |app: &SolveApp| app.agent_chat.models.iter().map(|m| m.id.clone()).collect::>(); + assert_eq!(ids(&app), ["fast", "smart"]); + + let only = |id: &str| acp::ModelInfo { id: id.into(), name: id.into(), description: String::new() }; + script.report(Event::ModelsNote(Some("x".repeat(MODELS_NOTE_CAP + 10)))); + script.report(Event::Models { current: "local".into(), available: vec![only("local")] }); + poll(&mut app, &ctx); + let note = app.agent_chat.models_note.clone().unwrap(); + assert!(note.starts_with(&trf("ui.agent_chat_models_failed", &[("error", "x")])), "{note}"); + assert_eq!(note.chars().count(), MODELS_NOTE_CAP); + assert_eq!(ids(&app), ["local", "fast", "smart"]); + assert_eq!(app.agent_chat.model, "local"); + assert_eq!(app.agent_chat.models_cache.get(endpoint).map(Vec::len), Some(2), "the failed listing is not remembered"); + + script.report(Event::ModelsNote(Some("again".into()))); + script.report(Event::Models { current: "fast".into(), available: vec![only("fast")] }); + poll(&mut app, &ctx); + assert_eq!(ids(&app), ["local", "fast", "smart"], "a model already listed is not listed twice"); + + // A real listing on an endpoint that cannot be reached. + let mut app = app_with_endpoints(); + app.agent_chat.models_note = Some("from before".into()); + app.agent_chat.agent_id = Some("api-1".into()); + connect(&mut app, &ctx); + assert_eq!(app.agent_chat.models_note, None); + let start = std::time::Instant::now(); + while app.agent_chat.models.is_empty() && start.elapsed() < std::time::Duration::from_secs(10) { + poll(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert!(app.agent_chat.models_note.as_deref().is_some_and(|note| note.contains("offline")), "{:?}", app.agent_chat.models_note); + assert_eq!(ids(&app), ["m"]); + assert!(models_shown(&app)); + disconnect(&mut app); +} + /// The next session puts back the model chosen last time, when the agent offers it. #[test] fn the_remembered_model_is_set_on_the_next_session() { @@ -1944,7 +2403,8 @@ done } /// An agent that lists `models` but does not serve the unstable `session/set_model` answers -/// "method not found": the choice stays and no error shows (#9970). Other errors still show. +/// "method not found": the choice stays and no error shows (#9970). Other errors still show, as +/// the refusal of the model they were about. #[cfg(unix)] #[test] fn set_model_method_not_found_shows_no_error() { @@ -1986,12 +2446,13 @@ done set_model(&mut app, "fast"); // Replies come in order: once the second one's error shows, the first reply was handled too. let t = std::time::Instant::now(); - while !errors(&app).iter().any(|e| e == "model unavailable") { + let refused = trf("ui.agent_chat_model_rejected", &[("model", "fast"), ("error", "model unavailable")]); + while !errors(&app).contains(&refused) { poll(&mut app, &ctx); assert!(t.elapsed() < std::time::Duration::from_secs(20), "no error for the second choice: {:?}", errors(&app)); std::thread::sleep(std::time::Duration::from_millis(10)); } - assert_eq!(errors(&app), ["model unavailable"], "method not found is no error to show"); + assert_eq!(errors(&app), [refused], "method not found is no error to show"); assert!(app.agent_chat.state().running(), "the chat goes on"); assert_eq!(std::fs::read_to_string(&log).unwrap().matches("session/set_model").count(), 2); disconnect(&mut app); diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs index af1071583..b93f4e07a 100644 --- a/crates/ui-egui/src/ui_kit/fields.rs +++ b/crates/ui-egui/src/ui_kit/fields.rs @@ -256,6 +256,397 @@ fn searchable_dropdown_with( chosen } +/// Longest search text and custom value a `search_picker` takes. +const SEARCH_TEXT_CAP: usize = 256; +/// Characters of a label shown on a `search_picker` row, and of a tip or note shown with it. +const SEARCH_LABEL_CAP: usize = 64; +const SEARCH_NOTE_CAP: usize = 1024; +/// Characters of a `search_picker` note shown under its list; the rest shows on hover. +const SEARCH_NOTE_SHOWN: usize = 200; +/// Rows a `search_picker` makes room for when it opens with none. +const SEARCH_ROWS_AWAITED: usize = 6; + +/// One row of a `search_picker`. The value, label and tip are searched; `tip` also shows on hover, +/// and a change of `group` between rows draws a heading. +pub(crate) struct SearchChoice<'a> { + pub value: &'a str, + pub label: &'a str, + pub tip: &'a str, + pub group: Option<&'a str>, +} + +/// What a `search_picker` shows. +pub(crate) struct SearchPicker<'a> { + /// ComboBox id salt; it also keys the search text, so one per picker in the window. + pub id: &'a str, + /// Scenario names: the control `{handles}`, its box `{handles}:search`, its custom row + /// `{handles}:custom` and its rows `{handles}:{value}`. + pub handles: &'a str, + /// The text on the closed control, and the value of the row to highlight. + pub current: &'a str, + pub current_value: &'a str, + /// The search box's empty-text hint. + pub hint: &'a str, + pub choices: &'a [SearchChoice<'a>], + /// Offer what was typed as a value of its own when it is not a listed one. + pub custom: bool, + /// A dim line under the list: still listing, or why it could not. + pub note: Option<&'a str>, + /// With two or more groups, each folds under its header. Before anything is typed, only the + /// current value's group and this one are open (every group, when neither names one); a group + /// with a match opens once something is typed; a fold made by hand stays until the popup closes. + pub open_group: Option<&'a str>, + pub enabled: bool, +} + +/// A `search_picker` choice: a listed value, or one typed into the box. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Picked { + Listed(String), + Custom(String), +} + +/// Dropdown whose popup opens on a focused search box over a list of `choices`, filtered as the +/// box is typed in, with an optional row taking the typed text as a value of its own. Enter picks +/// the exact or first match, else the typed text. Only the rows in view are laid out, so a long +/// list stays cheap. Returns the pick and the control's response. +/// Tokens: dropdown tokens, field tokens, `space_24`, `font_small`, `text_dim`, `form_card_width`. +pub(crate) fn search_picker(ui: &mut Ui, p: SearchPicker<'_>) -> egui::InnerResponse> { + crate::prefs_search::note_current(ui, p.current); + // As in `dropdown_menu_with_close_behavior`: only a search probe skips the real control. + if crate::prefs_search::querying(ui) + && (!ui.is_visible() || (crate::prefs_search::suppress_chrome(ui) && !crate::prefs_search::texts_hit(ui, &[p.current]))) + { + return egui::InnerResponse::new(None, crate::prefs_search::hidden_response(ui)); + } + let state = egui::Id::new(p.id); + let mut picked = None; + let response = ui + .add_enabled_ui(p.enabled, |ui| { + let response = egui::ComboBox::from_id_salt(p.id) + .width(dimension(ui.available_width())) + .height(Tokens::get().space_24 * 20.0) + .selected_text(p.current) + .icon(dropdown_arrow) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show_ui(ui, |ui| picked = search_picker_popup(ui, &p, state)) + .response; + // Closed: the next opening starts with an empty box that has the focus. + if !egui::ComboBox::is_open(ui.ctx(), response.id) { + ui.data_mut(|data| { + data.remove::(state.with("filter")); + data.remove::(state.with("focused")); + data.remove::(state.with("height")); + data.remove::(state.with("folds")); + }); + } + response + }) + .inner; + publish(ui, &response, egui::WidgetType::ComboBox); + scenario::publish_target(p.handles, response.rect); + egui::InnerResponse::new(picked, response) +} + +/// What a `search_picker` shows while it is open; the pick, if one was made this frame. +fn search_picker_popup(ui: &mut Ui, p: &SearchPicker<'_>, state: egui::Id) -> Option { + let t = Tokens::get(); + let (filter_id, focused_id, folds_id) = (state.with("filter"), state.with("focused"), state.with("folds")); + // Esc closes this popup only: left in the input, it would also cancel a dialog around it. + if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + ui.close(); + } + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + // The rows' text starts where the box's and the headings' do. + ui.spacing_mut().button_padding.x = t.form_inset; + ui.set_min_width(search_popup_width(ui, p)); + let mut filter: String = ui.data(|data| data.get_temp(filter_id)).unwrap_or_default(); + let search = ui.add( + text_input(egui::TextEdit::singleline(&mut filter)) + .id(state.with("search")) + .char_limit(SEARCH_TEXT_CAP) + .hint_text(p.hint) + .background_color(t.input_fill()) + .desired_width(f32::INFINITY), + ); + t.input_bevel(ui, &search); + scenario::publish_target(&format!("{}:search", p.handles), search.rect); + // Asked until it has it: over a modal window egui drops the request of the opening's first frame. + if !ui.data(|data| data.get_temp::(focused_id)).unwrap_or(false) { + if search.has_focus() { + ui.data_mut(|data| data.insert_temp(focused_id, true)); + } else { + search.request_focus(); + ui.ctx().request_repaint(); + } + } + if search.has_focus() { + crate::prefs_search::note_key_sink(ui.ctx()); + } + if search.changed() { + ui.data_mut(|data| data.insert_temp(filter_id, filter.clone())); + } + let typed = filter.trim(); + let query: String = typed.chars().flat_map(char::to_lowercase).collect(); + // One buffer for every row: this runs each frame the popup is open, over a list of thousands. + let mut searched = String::new(); + let mut hit = |choice: &SearchChoice<'_>| { + searched.clear(); + for text in [choice.value, choice.label, choice.tip] { + searched.extend(text.chars().take(SEARCH_TEXT_CAP).flat_map(char::to_lowercase)); + searched.push('\n'); + } + searched.contains(&query) + }; + let visible: Vec<&SearchChoice<'_>> = p.choices.iter().filter(|choice| query.is_empty() || hit(choice)).collect(); + // Two or more groups fold under their headers: open by default are the current value's group, + // `open_group`, and every group once something is typed; a fold made by hand stays until the + // popup closes. + let grouped = search_groups(p.choices).iter().filter(|(group, _)| group.is_some()).count() >= 2; + let folds: SearchFolds = ui.data(|data| data.get_temp(folds_id)).unwrap_or_default(); + let current_group = p.choices.iter().find(|c| c.value == p.current_value).and_then(|c| c.group).filter(|g| !g.is_empty()); + let nothing_preferred = p.open_group.is_none() && current_group.is_none(); + let is_open = |group: &str| { + folds.get(group).copied().unwrap_or(!query.is_empty() || nothing_preferred || Some(group) == p.open_group || Some(group) == current_group) + }; + let rows = search_rows(&visible, grouped, &is_open); + let shown: Vec<&SearchChoice<'_>> = rows.iter().filter_map(|row| if let SearchRow::Choice(c) = row { Some(*c) } else { None }).collect(); + let custom = (p.custom && !typed.is_empty() && !p.choices.iter().any(|c| c.value == typed)).then_some(typed); + let mut picked = None; + let mut toggled: Option<(String, bool)> = None; + if search.lost_focus() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { + let found = visible.iter().find(|c| c.value == typed).or_else(|| shown.first()); + picked = match (typed.is_empty(), found, custom) { + // Nothing asked for: the choice stands. + (true, ..) => { + ui.close(); + None + } + (_, Some(choice), _) => Some(Picked::Listed(choice.value.to_owned())), + (_, None, Some(model)) => Some(Picked::Custom(model.to_owned())), + (_, None, None) => { + search.request_focus(); + None + } + }; + } + let width = ui.available_width(); + let note = p.note.map(|note| { + let shown = compact(note, SEARCH_NOTE_SHOWN); + ui.painter().layout(shown, egui::FontId::proportional(t.font_small), t.text_dim, width) + }); + let gap = ui.spacing().item_spacing.y; + let note_height = note.as_ref().map_or(0.0, |note| note.size().y + gap); + let row_height = row_height(); + let most = ui.ctx().content_rect().height() - t.space_24 * 4.0; + // A popup's Ui stays within its size of the last frame, so it can't grow once it is open. All + // that can change below the box shares a height fixed when it opens, the list taking the rest. + let height = ui.data_mut(|data| { + *data.get_temp_mut_or_insert_with(state.with("height"), || { + let rows = p.choices.len() + search_groups(p.choices).iter().filter(|(group, _)| group.is_some()).count(); + // No rows yet: they may still be on their way, and this can't grow to take them. + let rows = if rows == 0 { SEARCH_ROWS_AWAITED } else { rows }; + let heading = t.space_16 + gap; + let custom = if p.custom { heading + row_height + gap } else { 0.0 }; + let list = (rows as f32 * (row_height + gap)).clamp(custom + row_height + gap, t.space_24 * 10.0); + (heading + list + note_height).min(most).max(heading + custom + row_height + gap) + }) + }); + ui.allocate_ui(vec2(dimension(width), height), |ui| { + ui.set_min_height(height); + if let Some(model) = custom { + search_heading(ui, crate::i18n::tr("ui.agent_chat_custom_heading"), t.space_16); + let text = crate::i18n::format("ui.agent_chat_model_custom", &[("model", &compact(model, SEARCH_LABEL_CAP))]); + let row = search_row(ui, &text, false); + scenario::publish_target(&format!("{}:custom", p.handles), row.rect); + if row.clicked() { + picked = Some(Picked::Custom(model.to_owned())); + } + } + if !visible.is_empty() { + search_heading(ui, crate::i18n::tr("ui.agent_chat_models_heading"), t.space_16); + // Rows of one height, group headings too: only those in view are laid out. + let list = (ui.available_height() - note_height).max(row_height); + egui::ScrollArea::vertical() + .id_salt(state.with("list")) + .max_height(list) + .min_scrolled_height(list) + .auto_shrink([false, false]) + .show_rows(ui, row_height, rows.len(), |ui, range| { + for row in rows.get(range).unwrap_or_default() { + match row { + SearchRow::Heading(group) => search_heading(ui, group, row_height), + SearchRow::Group { name, count, open } => { + let response = search_group_row(ui, name, *count, *open); + scenario::publish_target(&format!("{}:group:{}", p.handles, name), response.rect); + if response.clicked() { + toggled = Some(((*name).to_owned(), !*open)); + } + } + SearchRow::Choice(choice) => { + let response = search_row(ui, &compact(choice.label, SEARCH_LABEL_CAP), choice.value == p.current_value); + scenario::publish_target(&format!("{}:{}", p.handles, choice.value), response.rect); + let response = + if choice.tip.is_empty() { response } else { response.on_hover_text(compact(choice.tip, SEARCH_NOTE_CAP)) }; + if response.clicked() { + picked = Some(Picked::Listed(choice.value.to_owned())); + } + } + } + } + }); + } + if let Some((group, open)) = toggled { + let mut folds = folds; + folds.insert(group, open); + ui.data_mut(|data| data.insert_temp(folds_id, folds)); + // The click took the focus from the box; typing goes on filtering. + search.request_focus(); + } + if let Some(note) = note { + let response = ui.add(egui::Label::new(note)); + if let Some(whole) = p.note.filter(|whole| whole.chars().count() > SEARCH_NOTE_SHOWN) { + response.on_hover_text(compact(whole, SEARCH_NOTE_CAP)); + } + } + }); + if picked.is_some() { + ui.close(); + } + picked +} + +enum SearchRow<'a> { + /// A lone group's dim heading. + Heading(&'a str), + /// One of several groups: its header, with how many of its choices are listed, folded or open. + Group { + name: &'a str, + count: usize, + open: bool, + }, + Choice(&'a SearchChoice<'a>), +} + +/// The folds made by hand in one opening of a `search_picker`: group name to open. +type SearchFolds = std::collections::HashMap; + +/// The groups among `choices` in order of first appearance, each with its choices; `None` is the +/// choices with no group. +fn search_groups<'a, 'c, I>(choices: I) -> Vec<(Option<&'a str>, Vec<&'c SearchChoice<'a>>)> +where + 'a: 'c, + I: IntoIterator>, +{ + let mut groups: Vec<(Option<&'a str>, Vec<&'c SearchChoice<'a>>)> = Vec::new(); + for choice in choices { + let group = choice.group.filter(|g| !g.is_empty()); + match groups.iter_mut().find(|(name, _)| *name == group) { + Some((_, members)) => members.push(choice), + None => groups.push((group, vec![choice])), + } + } + groups +} + +/// The list's rows: each group's choices under its header, which folds them when there are several +/// groups and is a plain heading when there is one; choices with no group as they are. +fn search_rows<'a>(visible: &[&'a SearchChoice<'a>], grouped: bool, is_open: &dyn Fn(&str) -> bool) -> Vec> { + let mut rows = Vec::with_capacity(visible.len()); + for (group, members) in search_groups(visible.iter().copied()) { + match group { + Some(name) if grouped => { + let open = is_open(name); + rows.push(SearchRow::Group { name, count: members.len(), open }); + if open { + rows.extend(members.into_iter().map(SearchRow::Choice)); + } + } + Some(name) => { + rows.push(SearchRow::Heading(name)); + rows.extend(members.into_iter().map(SearchRow::Choice)); + } + None => rows.extend(members.into_iter().map(SearchRow::Choice)), + } + } + rows +} + +/// The header of one of several groups in a `search_picker`: a chevron, the name, how many of its +/// choices are listed, and a rule. A click folds or opens the group. +fn search_group_row(ui: &mut Ui, name: &str, count: usize, open: bool) -> Response { + let t = Tokens::get(); + let (rect, response) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), row_height()), egui::Sense::click()); + if !ui.is_rect_visible(rect) { + return response; + } + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect, t.radius_sm, t.hover); + } + let y = rect.center().y; + super::disclosure(painter, egui::pos2(rect.left() + t.form_inset + t.space_8 * 0.5, y), open, t.text_dim); + let small = egui::FontId::proportional(t.font_small); + let title = painter.layout_no_wrap(compact(&name.to_uppercase(), SEARCH_LABEL_CAP), small.clone(), t.text); + let title_pos = egui::pos2(rect.left() + t.form_inset + t.space_16, y - title.size().y / 2.0); + let title_width = title.size().x; + painter.galley(title_pos, title, t.text); + let number = painter.layout_no_wrap(count.to_string(), small, t.text_dim); + let pad = t.space_8 * 0.75; + let badge_height = (number.size().y + pad).min(rect.height()); + let badge = egui::Rect::from_min_size( + egui::pos2(title_pos.x + title_width + t.space_8, y - badge_height / 2.0), + vec2(number.size().x + pad * 2.0, badge_height), + ); + painter.rect_filled(badge, t.radius_sm, t.chip); + painter.galley(egui::pos2(badge.left() + pad, y - number.size().y / 2.0), number, t.text_dim); + let (rule_from, rule_to) = (badge.right() + t.space_8, rect.right() - t.form_inset); + if rule_from < rule_to { + painter.hline(rule_from..=rule_to, y, egui::Stroke::new(1.0, t.border)); + } + response.on_hover_text(crate::i18n::format("ui.agent_chat_provider_models", &[("count", &count.to_string())])) +} + +/// A `search_picker` row: as `list_picker`, but read from the left, as a list of ids is. +fn search_row(ui: &mut Ui, text: &str, selected: bool) -> Response { + ui.add_sized(vec2(dimension(ui.available_width()), row_height()), egui::Button::selectable(selected, (text, egui::Atom::grow()))) +} + +/// A dim one-line heading in a `search_picker`'s popup. +fn search_heading(ui: &mut Ui, text: &str, height: f32) { + let t = Tokens::get(); + let (rect, response) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), height), egui::Sense::hover()); + paint_text( + ui, + rect.shrink2(vec2(t.form_inset, 0.0)), + &compact(text, SEARCH_LABEL_CAP), + egui::FontId::proportional(t.font_small), + t.text_dim, + false, + ); + if text.chars().count() > SEARCH_LABEL_CAP { + response.on_hover_text(compact(text, SEARCH_NOTE_CAP)); + } +} + +/// A `search_picker` popup's width: the control's, wide enough for the longest label and to search +/// in, and never wider than the window. +fn search_popup_width(ui: &Ui, p: &SearchPicker<'_>) -> f32 { + let t = Tokens::get(); + let longest = p.choices.iter().map(|c| c.label).max_by_key(|label| label.chars().take(SEARCH_LABEL_CAP + 1).count()).unwrap_or(""); + let text = ui.painter().layout_no_wrap(compact(longest, SEARCH_LABEL_CAP), egui::TextStyle::Button.resolve(ui.style()), t.text).size().x; + let wanted = text + ui.spacing().button_padding.x * 2.0 + ui.spacing().scroll.bar_width + t.space_8; + let most = (ui.ctx().content_rect().width() - t.space_24 * 2.0).max(0.0); + dimension(wanted.max(ui.available_width()).max(t.form_card_width).min(most)) +} + +/// `text` cut to `max_chars`, with an ellipsis if anything was left out. +fn compact(text: &str, max_chars: usize) -> String { + let mut chars = text.chars(); + let short: String = chars.by_ref().take(max_chars).collect(); + if chars.next().is_some() { format!("{short}…") } else { short } +} + /// Completion/focus implementation shared by field variants. Tokens: `same as field`. fn editor(ui: &mut Ui, value: &mut String, hint: &str, completion: bool) -> (bool, bool, Response) { editor_reserving(ui, value, hint, completion, 0.0) diff --git a/crates/ui-egui/src/ui_kit/fields_tests.rs b/crates/ui-egui/src/ui_kit/fields_tests.rs index 0a84b8a16..135c9a247 100644 --- a/crates/ui-egui/src/ui_kit/fields_tests.rs +++ b/crates/ui-egui/src/ui_kit/fields_tests.rs @@ -122,6 +122,363 @@ fn searchable_dropdown_filters_selects_and_accepts_custom_values() { } } +#[test] +fn search_picker_filters_focuses_picks_and_takes_custom_values() { + let ctx = crate::fonts::test_context(); + let picked = std::cell::RefCell::new(Vec::new()); + let custom = std::cell::Cell::new(true); + let enabled = std::cell::Cell::new(true); + let choices = [ + SearchChoice { value: "a/one", label: "One", tip: "The first model", group: None }, + SearchChoice { value: "b/two", label: "Two", tip: "The second model", group: Some("Group") }, + SearchChoice { value: "b/three", label: "Three", tip: "", group: Some("Group") }, + ]; + let draw = |ui: &mut Ui| { + row(ui, "Model", |ui| { + let shown = search_picker( + ui, + SearchPicker { + id: "search_picker_test", + handles: "test:model", + current: "One", + current_value: "a/one", + hint: "Search models…", + choices: &choices, + custom: custom.get(), + note: Some("Listing models…"), + open_group: None, + enabled: enabled.get(), + }, + ); + picked.borrow_mut().extend(shown.inner); + }); + }; + let open = || { + let at = scenario::handle_at("test:model").unwrap(); + frame(&ctx, pointer(at, true), draw); + frame(&ctx, pointer(at, false), draw); + frame(&ctx, vec![], draw); + }; + let click = |name: &str| { + let at = scenario::handle_at(name).unwrap_or_else(|| panic!("no {name}")); + frame(&ctx, pointer(at, true), draw); + frame(&ctx, pointer(at, false), draw); + frame(&ctx, vec![], draw); + }; + let typing = |text: &str| { + frame(&ctx, vec![egui::Event::Text(text.into())], draw); + frame(&ctx, vec![], draw); + }; + let is_open = || scenario::handle_at("test:model:search").is_some(); + frame(&ctx, vec![], draw); + assert!(!is_open() && scenario::handle_at("test:model:a/one").is_none(), "closed: only the control"); + + // Opening focuses the box: what is typed filters over labels, tips and values. + open(); + assert!(is_open()); + assert!(ctx.memory(|m| m.has_focus(egui::Id::new("search_picker_test").with("search"))), "the box has the focus"); + for row in ["a/one", "b/two", "b/three"] { + assert!(scenario::handle_at(&format!("test:model:{row}")).is_some(), "{row}"); + } + assert!(scenario::handle_at("test:model:custom").is_none(), "nothing typed, nothing to use"); + typing("SECOND"); + assert!(scenario::handle_at("test:model:b/two").is_some(), "a tip is searched, whatever the case"); + assert!(scenario::handle_at("test:model:a/one").is_none() && scenario::handle_at("test:model:b/three").is_none()); + assert!(scenario::handle_at("test:model:custom").is_some(), "a substring is no listed value"); + + // A click picks the row, closes the popup and forgets the text. + click("test:model:b/two"); + assert_eq!(picked.take(), [Picked::Listed("b/two".into())]); + assert!(!is_open()); + open(); + assert!(scenario::handle_at("test:model:a/one").is_some(), "the next opening starts unfiltered"); + + // A value exactly as listed needs no custom row; a text nothing matches gets one. + typing("b/three"); + assert!(scenario::handle_at("test:model:custom").is_none()); + assert!(scenario::handle_at("test:model:b/three").is_some()); + frame(&ctx, key(egui::Key::Escape), draw); + frame(&ctx, vec![], draw); + assert!(!is_open() && picked.borrow().is_empty(), "Esc closes without a pick"); + open(); + typing(" vendor/model:free "); + assert!(scenario::handle_at("test:model:a/one").is_none()); + click("test:model:custom"); + assert_eq!(picked.take(), [Picked::Custom("vendor/model:free".into())], "trimmed"); + assert!(!is_open()); + + // Enter picks the first row shown; with no match, the typed text. + open(); + typing("t"); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert_eq!(picked.take(), [Picked::Listed("a/one".into())], "the first row with a t"); + assert!(!is_open()); + open(); + typing("b/"); + typing("three"); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert_eq!(picked.take(), [Picked::Listed("b/three".into())]); + open(); + typing("nothing"); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert_eq!(picked.take(), [Picked::Custom("nothing".into())]); + + // Enter on an empty box leaves the choice as it is. + open(); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert!(picked.borrow().is_empty() && !is_open()); + + // Without custom values, a miss offers nothing and Enter keeps the box. + custom.set(false); + open(); + typing("nothing"); + assert!(scenario::handle_at("test:model:custom").is_none()); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert!(picked.borrow().is_empty() && is_open()); + typing("!"); + frame(&ctx, key(egui::Key::Escape), draw); + frame(&ctx, vec![], draw); + assert!(!is_open()); + + // A disabled control does not open. + enabled.set(false); + open(); + assert!(!is_open()); +} + +/// A long list costs only the rows in view, and a long label neither widens the popup past the +/// window nor reaches past its edge. +/// A popup can't grow once it is open, so what appears in it later must fit in the room it opened +/// with: a custom row above a short list, a list that was empty, a note, and a list again after a +/// search that matched nothing. +#[test] +fn search_picker_keeps_every_row_reachable_as_its_contents_change() { + use std::cell::{Cell, RefCell}; + let ctx = crate::fonts::test_context(); + let values = RefCell::new(vec!["a/one", "b/two"]); + let note: Cell> = Cell::new(None); + let picked = RefCell::new(Vec::new()); + let frame = |events: Vec| { + scenario::clear_handles(); + let raw = + egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 700.0))), ..Default::default() }; + let _ = ctx.run_ui(raw, |ui| { + ui.allocate_ui(egui::vec2(160.0, 40.0), |ui| { + crate::ui_kit::scope(ui, |ui| { + let values = values.borrow(); + let choices: Vec> = + values.iter().map(|value| SearchChoice { value, label: value, tip: "", group: None }).collect(); + let result = search_picker( + ui, + SearchPicker { + id: "search_picker_room", + handles: "room", + current: "b/two", + current_value: "b/two", + hint: "Search", + choices: &choices, + custom: true, + note: note.get(), + open_group: None, + enabled: true, + }, + ); + if let Some(pick) = result.inner { + picked.borrow_mut().push(pick); + } + }); + }); + }); + }; + let pointer = |at: egui::Pos2, pressed: bool| { + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }, + ] + }; + let click = |name: &str| { + let at = scenario::handle_at(name).unwrap_or_else(|| panic!("no {name}")); + frame(pointer(at, true)); + frame(pointer(at, false)); + frame(vec![]); + frame(vec![]); + }; + let typing = |text: &str| { + frame(vec![egui::Event::Text(text.into())]); + frame(vec![]); + frame(vec![]); + }; + let erase = |times: usize| { + for _ in 0..times { + frame(vec![egui::Event::Key { + key: egui::Key::Backspace, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }]); + frame(vec![]); + } + frame(vec![]); + }; + frame(vec![]); + frame(vec![]); + + // The custom row appears above the two rows: the row under it can still be clicked. + click("room"); + typing("two"); + assert!(scenario::handle_at("room:custom").is_some()); + click("room:b/two"); + assert_eq!(picked.take(), [Picked::Listed("b/two".into())]); + + // A search that matches nothing leaves no list; taking it back brings the rows, in reach. + click("room"); + typing("zzz"); + assert!(scenario::handle_at("room:a/one").is_none()); + frame(vec![]); + frame(vec![]); + erase(3); + click("room:b/two"); + assert_eq!(picked.take(), [Picked::Listed("b/two".into())]); + + // A list that arrives while it is open, with a long note, stays in reach; the custom row too. + values.borrow_mut().clear(); + note.set(Some("Listing models…")); + frame(vec![]); + click("room"); + frame(vec![]); + values.borrow_mut().extend(["a/one", "b/two", "c/three", "d/four"]); + note.set(Some("A long reason, repeated until it wraps over a few lines of the popup, repeated until it wraps over a few lines of the popup.")); + frame(vec![]); + frame(vec![]); + typing("four"); + click("room:d/four"); + assert_eq!(picked.take(), [Picked::Listed("d/four".into())]); + click("room"); + typing("nothing"); + click("room:custom"); + assert_eq!(picked.take(), [Picked::Custom("nothing".into())]); +} + +#[test] +fn search_picker_lays_out_the_rows_in_view_inside_a_narrow_window() { + let ctx = crate::fonts::test_context(); + let values: Vec = (0..2000).map(|n| format!("vendor/a-model-with-a-rather-long-name-{n:04}-and-then-some-more-of-it-and-more")).collect(); + let choices: Vec> = values.iter().map(|v| SearchChoice { value: v, label: v, tip: "", group: None }).collect(); + let draw = |ui: &mut Ui| { + ui.allocate_ui(egui::vec2(120.0, 28.0), |ui| { + search_picker( + ui, + SearchPicker { + id: "search_picker_long", + handles: "test:long", + current: "One", + current_value: "", + hint: "", + choices: &choices, + custom: false, + note: None, + open_group: None, + enabled: true, + }, + ); + }); + }; + frame(&ctx, vec![], draw); + let at = scenario::handle_at("test:long").unwrap(); + frame(&ctx, pointer(at, true), draw); + frame(&ctx, pointer(at, false), draw); + frame(&ctx, vec![], draw); + frame(&ctx, vec![], draw); + let rows = scenario::handles("test:long:vendor/"); + assert!(!rows.is_empty() && rows.len() < 30, "{} rows laid out", rows.len()); + let row = scenario::rect_of("test:long:vendor/a-model-with-a-rather-long-name-0000-and-then-some-more-of-it-and-more").unwrap(); + assert!(row.left() >= 0.0 && row.right() <= 320.0, "{row:?} reaches past the window"); + let search = scenario::rect_of("test:long:search").unwrap(); + assert!(search.left() >= 0.0 && search.right() <= 320.0, "{search:?} reaches past the window"); +} + +/// Several groups fold under their headers: at first only the current value's group and the one +/// asked for are open; a header opens or folds its group; a typed search opens the groups with a +/// match but one folded by hand; Enter takes the first row shown; a fresh opening forgets the folds. +#[test] +fn search_picker_folds_groups_under_their_headers() { + let ctx = crate::fonts::test_context(); + let picked = std::cell::RefCell::new(Vec::new()); + let open_group = std::cell::Cell::new(None::<&'static str>); + let current = std::cell::Cell::new("b1"); + let choices = [ + SearchChoice { value: "a1", label: "Alpha one", tip: "", group: Some("A") }, + SearchChoice { value: "b1", label: "Beta one", tip: "", group: Some("B") }, + SearchChoice { value: "a2", label: "Alpha two", tip: "", group: Some("A") }, + SearchChoice { value: "c1", label: "Gamma one", tip: "", group: Some("C") }, + ]; + let draw = |ui: &mut Ui| { + row(ui, "Model", |ui| { + let shown = search_picker( + ui, + SearchPicker { + id: "search_picker_groups", + handles: "grp", + current: "Beta one", + current_value: current.get(), + hint: "", + choices: &choices, + custom: false, + note: None, + open_group: open_group.get(), + enabled: true, + }, + ); + picked.borrow_mut().extend(shown.inner); + }); + }; + let click = |name: &str| { + let at = scenario::handle_at(name).unwrap_or_else(|| panic!("no {name}")); + frame(&ctx, pointer(at, true), draw); + frame(&ctx, pointer(at, false), draw); + frame(&ctx, vec![], draw); + }; + let typing = |text: &str| { + frame(&ctx, vec![egui::Event::Text(text.into())], draw); + frame(&ctx, vec![], draw); + }; + let has = |name: &str| scenario::handle_at(name).is_some(); + frame(&ctx, vec![], draw); + click("grp"); + assert!(has("grp:group:A") && has("grp:group:B") && has("grp:group:C"), "a header per group"); + assert!(has("grp:b1") && !has("grp:a1") && !has("grp:c1"), "only the current value's group is open"); + click("grp:group:A"); + assert!(has("grp:a1") && has("grp:a2"), "a header opens its group"); + click("grp:group:A"); + assert!(!has("grp:a1"), "and folds it again"); + typing("one"); + assert!(!has("grp:a1"), "a fold made by hand stays while searching"); + assert!(has("grp:b1") && has("grp:c1"), "groups with a match open"); + frame(&ctx, key(egui::Key::Enter), draw); + frame(&ctx, vec![], draw); + assert_eq!(picked.take(), [Picked::Listed("b1".into())], "Enter takes the first row shown, not one folded away"); + assert!(!has("grp:search")); + + open_group.set(Some("C")); + click("grp"); + assert!(!has("grp:a1") && has("grp:b1") && has("grp:c1"), "C opens as asked, B as the current value's, A folds"); + frame(&ctx, key(egui::Key::Escape), draw); + frame(&ctx, vec![], draw); + + open_group.set(None); + current.set(""); + click("grp"); + assert!(has("grp:a1") && has("grp:b1") && has("grp:c1"), "nothing to prefer: every group starts open"); + frame(&ctx, key(egui::Key::Escape), draw); + frame(&ctx, vec![], draw); +} + #[test] fn preference_dropdown_keeps_disabled_choices_inert_and_closes_after_selection() { let ctx = crate::fonts::test_context(); diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs index 608422d42..30c1a1ad4 100644 --- a/crates/ui-egui/src/ui_kit/gallery.rs +++ b/crates/ui-egui/src/ui_kit/gallery.rs @@ -1299,6 +1299,25 @@ const ELEMENTS: &[Element] = &[ searchable_dropdown(ui, "gallery", "One", &mut String::new(), &[SearchOption { value: "one", label: "One", handle: None }], None, None); }); }), + element!("search_picker", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, _| { + row(ui, "Gallery", |ui| { + search_picker( + ui, + SearchPicker { + id: "gallery_search_picker", + handles: "gallery:search_picker", + current: "One", + current_value: "one", + hint: "Search", + choices: &[SearchChoice { value: "one", label: "One", tip: "", group: None }], + custom: true, + note: None, + open_group: None, + enabled: true, + }, + ); + }); + }), element!("text_emphasis", "dialog:row:Gallery", Some("dialog:Bold"), |ui, s| { row(ui, "Gallery", |ui| { text_emphasis(ui, &mut s.checked, &mut false, true); diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 0dd8cbded..9a06bbd3e 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -75,10 +75,22 @@ clicks and scrolling over the panel stay in the chat. The docked layout retains the last model choice for each agent and puts it back on the next session when still available. An endpoint's agent also keeps it as its default model. An agent that reports no choices shows no drop-down. When these model lists include more than one provider (Hermes and OpenCode name - each model `Provider · model`, or say `Provider: …` in its description), a provider drop-down - comes first and the model drop-down lists only that provider's models, without the provider in - front. It opens on the provider of the model in use; picking another provider changes nothing - until one of its models is chosen. Models with no provider named are listed under *Other*. + each model `Provider · model`, or say `Provider: …` in its description), the picker groups the + models under their providers, each a header with the count of its models that a click folds or + opens: the provider of the model in use starts open and the others folded, a search opens every + provider with a match, and a provider folded by hand stays folded until the picker closes. Models + with no provider named are listed under *Other*. An endpoint whose listing names its models + `Vendor: Model` under ids `vendor/model` (OpenRouter) is grouped by vendor the same way; its rows + read the model's name, and the id stays in the tooltip and in the search. +- **Picking a model.** Every model picker opens on a search box over the list the agent or endpoint + gave at this connection: SolidCraft has no list of its own. The search covers ids, names and + descriptions, and Enter takes the exact match or the first one shown. A model that isn't listed + can be typed: **Use custom: …** takes what is in the box, for an endpoint, an ACP agent with a + model option, or an older agent that listed models. An endpoint takes it as it is and keeps it as + its default model. An agent may refuse it: its model stays as it was and the chat says why. Only + an endpoint keeps a typed model for the next session; an agent gets it back only if it then + lists it. An endpoint that can't list its models (it has no such address, or refuses the key) + still shows its configured model, and the popup says why there are no others. - **Reasoning effort is not permissions.** The agent's thinking setting does not change SolidCraft's Ask / Edits / All approval policy. Reasoning options belong to the current session; changing them here does not rewrite OpenCode's configuration or another OpenCode session. @@ -246,16 +258,27 @@ Grok Build also supports `XAI_API_KEY` for users who choose API authentication. - **Custom command:** any other program that speaks ACP on stdin and stdout, such as `my-agent --acp`. SolidCraft starts it directly, not through a shell. - **OpenAI-compatible API:** a preset (Ollama `http://localhost:11434/v1`, LM Studio - `http://localhost:1234/v1`, OpenAI, Mammouth AI `https://api.mammouth.ai/v1`, OpenCode Go `https://opencode.ai/zen/go/v1`) or a custom URL, the model name, and an optional key. + `http://localhost:1234/v1`, OpenClaw `http://localhost:18789/v1`, OpenAI, Mammouth AI + `https://api.mammouth.ai/v1`, OpenCode Go `https://opencode.ai/zen/go/v1`, OpenRouter + `https://openrouter.ai/api/v1`) or a custom URL, the model name, and an optional key. OpenCode Go models are routed to their endpoint by themselves (`/responses`, `/messages` or Gemini for those families, `/chat/completions` for the rest), each conversation request carrying the session header Go asks for, so one preset covers every model. A model the list does not know is retried on the next protocol when Go names the mismatch. + For OpenClaw, turn on its chat endpoint (`gateway.http.endpoints.chatCompletions.enabled` in its + config) and use its gateway token as the key; the models it lists are its agents, such as `openclaw/default`. - **Anthropic-compatible API:** a preset (Anthropic) or a custom URL, for an endpoint that speaks the Anthropic Messages API (`{base}/v1/messages`). This covers Anthropic itself and providers that offer an Anthropic-compatible endpoint, such as DeepSeek and Qwen. +- The **Model** picker lists the endpoint's models, without a key where the endpoint allows that + (OpenRouter does), once you leave the address and key fields; opening it asks again after a + failure. You can also type a model. +- An endpoint's card under Preferences → AI → **Agents** has the same **Model** picker. While the + agent isn't running, opening the picker lists the models (just viewing the page asks nothing), + and a pick becomes the model for its next connection. While it runs, a pick changes the chat's + model at once. - The key goes into the system keychain (Keychain on macOS, Credential Manager on Windows, the Secret Service on Linux) and is only ever sent over HTTPS or to this computer. **Test** asks an OpenAI-compatible endpoint for its models; an Anthropic-compatible one gets a short message, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 43440ed5a..7bcd5ea29 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -414,7 +414,7 @@ no box selection. | `engine.execute` → `browser.expand_all` | `path?`: occurrence ids; `component?`: id; omit both for the whole tree | Open every Browser row under that scope, including folders that start closed (Origin, Named Views, Features). Display only: not saved in the design, not an undo step. | | `engine.execute` → `browser.collapse_all` | same | Close those rows. The design row stays open when the whole tree is collapsed. | | `engine.execute` → `view.history_layout` | `width?`, `dock?`: `bottom`, `left`, `under_browser`, `collapsed?` | Resize/dock the history without opening a dialog or changing the design. Contents respond to measured width; browser-stacked history shares its width and splits the height at the remembered share (`browser_share`, half until the seam between the two cards is dragged). One folded header gives the expanded card the rest; two folded headers stay at the top. | -| `ui.agent_chat` | `features?`, `toolbar_button?`, `connect_at_start?` and `open_at_start?` (connect the agent started last, and open the panel, when SolidCraft starts; both off by default, never with `--control`), `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model` + `request_timeout_s?` (seconds one model request may take, 300 by default, rounded and clamped to 30 to 3600)}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `edit_dialog?` (the id of an agent you added: the same dialog filled with what it holds, as its **Edit** button opens it; the key is never shown), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `provider?` (which provider's models the model picker lists, when they come from several), `model?` (one of its models), `open?`, `side?` (`left`, `right`), `minimized?`, `popped?` (in its own window), `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `attach_view?`, `attach_selection?`, `pick?` (true: open the context picker), `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited, failed: the agent never got ready, and Connect reads Retry), `connectAtStart`, `openAtStart`, `lastAgent` (the agent started last), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `modelWarning` (the model capability warning text, or `null` when unknown or tool support is reported; checked asynchronously and never blocks sending), `turnWarning` (the latest completed turn's no-tool notice, otherwise `null`; cleared on the next turn or new chat), `providers` (`name` and `count` of each, empty with one provider), `provider` (the one listed), `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) | +| `ui.agent_chat` | `features?`, `toolbar_button?`, `connect_at_start?` and `open_at_start?` (connect the agent started last, and open the panel, when SolidCraft starts; both off by default, never with `--control`), `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model` + `request_timeout_s?` (seconds one model request may take, 300 by default, rounded and clamped to 30 to 3600)}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `edit_dialog?` (the id of an agent you added: the same dialog filled with what it holds, as its **Edit** button opens it; the key is never shown), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `provider?` (which provider's group the model picker opens first, when the models come from several), `model?` (one of its models, or see below), `open?`, `side?` (`left`, `right`), `minimized?`, `popped?` (in its own window), `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `attach_view?`, `attach_selection?`, `pick?` (true: open the context picker), `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited, failed: the agent never got ready, and Connect reads Retry), `connectAtStart`, `openAtStart`, `lastAgent` (the agent started last), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `modelWarning` (the model capability warning text, or `null` when unknown or tool support is reported; checked asynchronously and never blocks sending), `turnWarning` (the latest completed turn's no-tool notice, otherwise `null`; cleared on the next turn or new chat), `providers` (`name` and `count` of each, empty with one provider), `provider` (the one listed), `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) | | `ui.resize` | `width`, `height` | | | `app.quit` | `force?` (quit without asking about unsaved designs) | `quitting` (the window closes), `asking` (a "save changes?" prompt is open) | @@ -427,6 +427,12 @@ the agent's reply. Read the confirmed state after that reply; submitting a chang confirmation. The existing `model` and `mode` inputs use the corresponding configuration option when advertised, and retain their existing behavior for agents using legacy lists or API endpoints. +`model` may also name a model the agent did not list, as the picker's custom row does: it goes to an +API endpoint, to an agent with a model option, and to a legacy agent that listed models; the reply's +`customModels` says whether this agent takes one. Otherwise it is ignored. A model an agent refuses +leaves its previous model and adds a notice. `modelsNote` says why an endpoint's models could not be +listed, or is `null`. + ### `ui.prefs` settings `render_previous_geometry_budget` (Graphics, default false) restores the previous fixed Render preview geometry budget: 512 MiB on 64-bit desktop, 128 MiB elsewhere. With it off, desktop uses the device-based budget. diff --git a/docs/design/in-app-agent-chat.md b/docs/design/in-app-agent-chat.md index bc6cd06c3..8085a5f7b 100644 --- a/docs/design/in-app-agent-chat.md +++ b/docs/design/in-app-agent-chat.md @@ -126,8 +126,10 @@ requests, for a backend that runs tools in process). Two backends exist: that speaks the Messages API), and runs the tool loop itself: it starts the same `solidcraft-cli mcp --connect` server an ACP agent would get and is its MCP client (`tools/list` becomes the endpoint's tools, `crash_reports` left out), so its calls pass the - same gate, limits, questions and undo as an ACP agent's. At most 24 model requests per - message. The HTTP request is the desktop host's (`Services::agent_http`, ureq with no + same gate, limits, questions and undo as an ACP agent's. There is no cap on model requests + per message; Stop ends it. It lists the endpoint's models at each connection (`Event::Models`), + and when it can't, `Event::ModelsNote` says why and only the configured model is offered. The + HTTP request is the desktop host's (`Services::agent_http`, ureq with no redirects); the key comes from the system keychain (`Services::secrets`, the keyring crate) for the connection only and is refused over plain HTTP to another computer. The two protocols differ only in their wire shape: OpenAI sends the system note as a message, function tools @@ -264,7 +266,7 @@ returns the whole state, for tests and screenshots. | Area | Work | |---|---| | Conversation | Diffs, persisted conversation history, resume (`session/load`) | -| Session controls | Model and mode pickers from `configOptions` / `modes`, slash commands | +| Session controls | Slash commands | | Auth | An embedded terminal or "open a terminal here" for terminal logins on each OS; logout | | Discovery | Read the ACP registry; keychain-aware login check on macOS | | Packaging | Make sure every desktop package ships `solidcraft-cli` next to `solidcraft` (Flatpak, AppImage, macOS bundle, Windows zip), or serve MCP from the app binary itself | diff --git a/docs/ui-kit.md b/docs/ui-kit.md index 742314845..9e95888e0 100644 --- a/docs/ui-kit.md +++ b/docs/ui-kit.md @@ -232,6 +232,7 @@ table. Panel/Window/Confirm compositions also have dedicated geometry and intera | `text_area` | Bounded multiline JSON/data editor | field tokens | | `dropdown`, `dropdown_menu`, `compact_dropdown_menu` | Indexed choices or caller-supplied menu controls | `control_height`, `text_dim`, form tokens | | `searchable_dropdown`, `SearchOption` | Filtered choices, custom-value action and pending message | dropdown tokens | +| `search_picker`, `SearchPicker`, `SearchChoice`, `Picked` | Dropdown whose popup opens on a focused search box over rows filtered by value, label and tip, with group headings (two or more groups fold under headers with a count, the current value's open), per-row tips, an optional "use what was typed" row and a dim note; Enter picks the exact or first match, Esc closes the popup only; only the rows in view are laid out, and the popup keeps the height it opened with, the list taking what the rest leaves. Handles `{handles}`, `{handles}:search`, `{handles}:custom`, `{handles}:{value}`; returns the pick and the control's response | dropdown and field tokens, `space_16/24`, `font_small`, `text_dim`, `form_card_width` | | `selection_field`, `Selection` | Selection chip with explicit `active` and `filled` state, in three looks: the active input (where the next pick goes) has a `form_primary` border and `selected_bg` tint; a filled inactive one a quiet neutral tint, a stronger neutral border and its count in `form_ink`; an empty inactive one the plain control with a dim prompt | `selected_bg/ink`, `form_primary/ink/dim`, `control_*`, `form_inset`, `space_2/8/24` | | `value_pair` | Paired captions/expressions; optional independent field names | row/field tokens, `space_8` | | `fraction_field`, `scalar_field`, `mixed_scalar_field` | Locale-aware bounded dimensionless values; scalar fields fill their control column; the mixed variant accepts a translated placeholder | form control/font tokens | From 0478f7e4019902b5d351d31afbd4ec62ad958eca Mon Sep 17 00:00:00 2001 From: Vvynot <925823079@qq.com> Date: Sun, 1 Nov 2026 20:05:49 +0000 Subject: [PATCH 18/55] Hole: reference Distance shows the document precision (#10693) (#10777) * Hole: reference Distance shows the document precision (#10693) A measured reference distance showed the raw float (10.000000868569572 mm). The field now reads at the document's length precision while Refs keeps the measured value for the model, so OK still sends what was measured. Co-Authored-By: Claude Sonnet 5 * Hole: restored literals use the document precision (#10693) Round every literal reference distance on Edit Feature, including comma decimals and exact whole values; expressions stay as written. Co-Authored-By: Claude Sonnet 5 --------- Co-authored-by: Claude Sonnet 5 --- crates/ui-egui/src/dialogs.rs | 4 +- crates/ui-egui/src/dialogs_dense.rs | 2 +- crates/ui-egui/src/hole_refs.rs | 66 ++++++++++++++++++++---- crates/ui-egui/src/hole_refs_ui_tests.rs | 55 +++++++++++++++++++- 4 files changed, 113 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 838c26b05..d8a8678c8 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -6048,7 +6048,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option = at.iter().map(|e| e.as_str()).collect(); d.extra.insert("position_exprs".into(), json!({"at": exprs, "point": pt3(position.0)})); } - crate::hole_refs::restore(s, &mut d, references, &f.edge_names); + crate::hole_refs::restore(s, &mut d, references, &f.edge_names, app.preferences.length_decimals); } } if to.is_some() { @@ -6101,7 +6101,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option) -> Option; 2], + /// The rounded text written into `distance` for that model value. + shown: [Option; 2], seen: Option, frame: Option, focus: Option, } +/// The text that drives the model for reference `k`: the exact measured value while the field +/// still shows its rounded form, else what the user typed. +fn model_text(refs: &Refs, k: usize) -> Option<&str> { + match (refs.exact.get(k).and_then(Option::as_deref), refs.shown.get(k).and_then(Option::as_deref)) { + (Some(exact), Some(shown)) if refs.distance.get(k).is_some_and(|d| d == shown) => Some(exact), + _ => refs.distance.get(k).map(String::as_str), + } +} + /// The place, edges and distances the dialog last had in step. #[derive(Clone, Debug, PartialEq)] struct Seen { @@ -186,7 +200,7 @@ fn frame(s: &Session, d: &mut Dialog) -> Option<(ReferenceFrame, Vec)> { /// Keep the distances and the hole's place in step: a new place or a new edge is measured, a /// typed distance moves the place there (when it stays on the face). Run before the dialog's /// commands are made. -pub(crate) fn sync(s: &Session, d: &mut Dialog) { +pub(crate) fn sync(s: &Session, d: &mut Dialog, decimals: u8) { if !takes(d) { return; } @@ -207,7 +221,7 @@ pub(crate) fn sync(s: &Session, d: &mut Dialog) { // Typed: the hole goes to the distances. Some(sn) if sn.distance != refs.distance => { let values: Option> = - picked.iter().map(|k| refs.distance.get(*k).and_then(|e| s.doc.eval(e, ValueKind::Length).ok())).collect(); + picked.iter().map(|k| model_text(refs, *k).and_then(|e| s.doc.eval(e, ValueKind::Length).ok())).collect(); if let Some(c) = values.and_then(|v| f.place(at, &v).ok()).filter(|c| on_reference_face(&s.world_state(), f, *c)) { to = c; } @@ -221,7 +235,13 @@ pub(crate) fn sync(s: &Session, d: &mut Dialog) { if let Some(slot) = refs.distance.get_mut(*k) && (moved || new_edge || slot.trim().is_empty()) { - *slot = crate::canvas::format_len(&s.doc, v.max(0.0)); + // The field shows the document's length precision; the model keeps the + // measured value until the user edits that field. + let measured = v.max(0.0); + refs.exact[*k] = Some(crate::length_input::model(&s.doc, measured)); + let shown = crate::prefs::format_length(measured, &s.doc.units, decimals); + refs.shown[*k] = Some(shown.clone()); + *slot = shown; } if new_edge && edges.get(*k).is_some_and(Option::is_some) { refs.focus = Some(*k); @@ -238,7 +258,7 @@ pub(crate) fn sync(s: &Session, d: &mut Dialog) { /// The Single hole's (or the Cylinder's) selection rows, each reference edge with its distance on /// the row below it once it is picked. Whether Enter was pressed in a distance. -pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, names: crate::prefs::OriginPlaneNames) -> bool { +pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, names: crate::prefs::OriginPlaneNames, decimals: u8) -> bool { let mut enter = false; for i in 0..d.inputs.len() { crate::dialogs::input_rows_range(d, ui, s, names, i..i + 1); @@ -250,6 +270,11 @@ pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, names: && let (Some(label), Some(value)) = (DISTANCES.get(k), refs.distance.get_mut(k)) { enter |= crate::ui_kit::expr_row(ui, label, value); + // The field no longer shows the measured value: the user now owns what drives it. + if refs.shown[k].as_deref().is_some_and(|shown| shown != value.as_str()) { + refs.exact[k] = None; + refs.shown[k] = None; + } // Without value boxes in the view (#9479), a newly picked edge's distance takes the // keyboard here, as its box would. if refs.focus == Some(k) && !crate::canvas::boxes_shown(ui.ctx()) { @@ -261,19 +286,26 @@ pub(crate) fn input_rows(d: &mut Dialog, ui: &mut egui::Ui, s: &Session, names: d.give_keyboard(id); } } - sync(s, d); + sync(s, d, decimals); enter } /// The `references` OK sends: each picked edge (a point on it) with its distance. pub(crate) fn params(d: &Dialog) -> Vec { let Some(refs) = refs(d).filter(|_| takes(d)) else { return Vec::new() }; - edges(d).iter().zip(&refs.distance).filter_map(|(e, distance)| e.map(|p| json!({"edge": [p.x, p.y, p.z], "distance": distance.trim()}))).collect() + edges(d) + .iter() + .enumerate() + .filter_map(|(k, e)| { + let distance = model_text(refs, k)?; + e.map(|p| json!({"edge": [p.x, p.y, p.z], "distance": distance.trim()})) + }) + .collect() } /// Editing a hole (or a cylinder) with reference edges: the edges picked again where they are /// now, their distances, and the place where those distances put it now. -pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], names: &[String]) { +pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], names: &[String], decimals: u8) { if references.is_empty() { return; } @@ -298,7 +330,23 @@ pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], if let Some(refs) = refs_mut(d) && let Some(slot) = refs.distance.get_mut(k) { - *slot = r.distance.to_string(); + // A literal distance shows at the document's precision; its exact value stays for the + // model. An expression stays as written, since rounding it would break its parameters. + let exact = r.distance.to_string(); + let literal = if solidcraft_engine::doc::expr::is_literal(&exact) { s.doc.eval(&exact, ValueKind::Length).ok() } else { None }; + match literal { + Some(value) => { + let shown = crate::prefs::format_length(value, &s.doc.units, decimals); + refs.exact[k] = Some(exact); + refs.shown[k] = Some(shown.clone()); + *slot = shown; + } + None => { + *slot = exact; + refs.exact[k] = None; + refs.shown[k] = None; + } + } } } // The hole where its distances put it now (the part may have changed since it was placed). @@ -306,7 +354,7 @@ pub(crate) fn restore(s: &Session, d: &mut Dialog, references: &[HoleReference], if let Some(f) = &found && let Some(refs) = refs(d) { - let values: Option> = refs.distance.iter().take(f.lines.len()).map(|e| s.doc.eval(e, ValueKind::Length).ok()).collect(); + let values: Option> = (0..f.lines.len()).map(|k| model_text(refs, k).and_then(|e| s.doc.eval(e, ValueKind::Length).ok())).collect(); if let Some(c) = values.and_then(|v| f.place(at, &v).ok()).filter(|c| on_reference_face(&st, f, *c)) { to = c; } diff --git a/crates/ui-egui/src/hole_refs_ui_tests.rs b/crates/ui-egui/src/hole_refs_ui_tests.rs index 12d3d64e4..45c73043e 100644 --- a/crates/ui-egui/src/hole_refs_ui_tests.rs +++ b/crates/ui-egui/src/hole_refs_ui_tests.rs @@ -110,19 +110,70 @@ fn a_hole_is_placed_by_its_distances_from_two_edges() { h.frames(4); assert!(picked_edge(&h, "Reference 1").is_some_and(|p| p.x.abs() < 1e-6), "{:?}", picked_edge(&h, "Reference 1")); assert!(picked_edge(&h, "Reference 2").is_some_and(|p| p.y.abs() < 1e-6), "{:?}", picked_edge(&h, "Reference 2")); - assert_eq!(distances(&h), ["10 mm", "12 mm"]); + assert_eq!(distances(&h), ["10.00 mm", "12.00 mm"]); assert!(place(&h).dist(Vec3::new(10.0, 12.0, 10.0)) < 1e-6, "{:?}", place(&h)); // The hole moved on its face (a new pick, or its handle dragged): the distances follow. if let Some(Sel::Face { point, .. }) = h.app.dialog.as_mut().and_then(|d| d.inputs.first_mut()).and_then(|i| i.items.first_mut()) { *point = Vec3::new(20.0, 30.0, 10.0); } h.frames(2); - assert_eq!(distances(&h), ["20 mm", "30 mm"]); + assert_eq!(distances(&h), ["20.00 mm", "30.00 mm"]); h.step(&json!({"widget": "OK"})).unwrap(); assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().map(|d| &d.error)); assert!(!solid_at(&h, Vec3::new(20.0, 30.0, 8.0)) && solid_at(&h, Vec3::new(10.0, 12.0, 8.0)), "the edit moved the hole to (20, 30)"); } +/// #10693: a measured distance reads at the document's precision, while OK still sends the +/// measured value, not the rounded one. +#[test] +fn a_measured_distance_shows_the_document_precision_but_keeps_its_model_value() { + let mut h = plate(); + h.step(&json!({"start": "solid.hole"})).unwrap(); + let at = screen(&mut h, Vec3::new(30.0, 25.0, 10.0)); + h.step(&json!({"click": at})).unwrap(); + h.step(&json!({"click": {"handle": "dialog:Reference 1"}})).unwrap(); + let left = screen(&mut h, Vec3::new(0.0, 20.0, 10.0)); + h.step(&json!({"click": left})).unwrap(); + h.frames(2); + // A face pick lands a hair off the whole millimetre, as a real pick does. + let exact = 20.000000868569572; + if let Some(Sel::Face { point, .. }) = h.app.dialog.as_mut().and_then(|d| d.inputs.first_mut()).and_then(|i| i.items.first_mut()) { + *point = Vec3::new(exact, 30.0, 10.0); + } + h.frames(2); + assert_eq!(distances(&h)[0], "20.00 mm"); + h.step(&json!({"widget": "OK"})).unwrap(); + let f = h.app.session.doc.features.last().unwrap().clone(); + let FeatureKind::Hole { references, .. } = &f.kind else { panic!("the last feature is a hole") }; + let text = references[0].distance.to_string(); + let value = h.app.session.doc.eval(&text, solidcraft_engine::doc::expr::Kind::Length).unwrap(); + assert!((value - exact).abs() < 1e-9, "OK keeps the measured distance, not the rounded text: {text}"); +} + +/// #10693: a comma decimal literal stored on a reference reads at the document's precision. +#[test] +fn a_comma_decimal_reference_distance_shows_the_document_precision() { + let mut h = plate(); + h.app + .run( + "solid.hole", + json!({ + "position": [30.0, 25.0, 10.0], + "diameter": 5, + "depth": 6, + "references": [ + {"edge": [0.0, 20.0, 10.0], "distance": "29,99999999999999 mm"}, + {"edge": [25.0, 0.0, 10.0], "distance": "25,000001373022986 mm"}, + ], + }), + ) + .unwrap(); + let id = h.app.session.doc.features.last().unwrap().id; + h.step(&json!({"call": "ui.editFeature", "params": {"feature": id}})).unwrap(); + h.frames(4); + assert_eq!(distances(&h), ["30.00 mm", "25.00 mm"]); +} + /// Reference edges place one hole: with places on two faces, OK says to pick one. #[test] fn reference_edges_place_one_hole() { From 0515dee9cef78af3c531fc0a6f658810ced7f3e3 Mon Sep 17 00:00:00 2001 From: semmelrinde <124386289+semmelrinde@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:08:43 +0000 Subject: [PATCH 19/55] Colour popover: a held step button keeps stepping, and R, G and B have tooltips (#10201) (#10203) * Colour popover: a held step button keeps stepping, and R, G and B have tooltips (#10201) The step buttons beside each colour number sensed clicks only. egui stops counting a press as a possible click once it outlasts its longest click (0.8 s), so the held button stopped repeating after 8 steps. They now sense drags too, which keeps a long press down on the button until it is let go. R, G and B now carry tooltips (Red, Green, Blue) as H, S and V already did: a single letter doesn't name the colour in every language. Co-Authored-By: Claude Opus 5.5 * Colour popover: the R, G and B tooltips in Vietnamese too, a complete catalog (#10201) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../locales/pending/color-channel-names.json | 42 +++++++++++++++++++ crates/ui-egui/src/ui_kit/color.rs | 12 ++++-- crates/ui-egui/src/ui_kit/color_tests.rs | 40 ++++++++++++++++++ 3 files changed, 91 insertions(+), 3 deletions(-) create mode 100644 assets/locales/pending/color-channel-names.json diff --git a/assets/locales/pending/color-channel-names.json b/assets/locales/pending/color-channel-names.json new file mode 100644 index 000000000..8fa193b0e --- /dev/null +++ b/assets/locales/pending/color-channel-names.json @@ -0,0 +1,42 @@ +{ + "ar": { + "color.blue": "أزرق", + "color.green": "أخضر", + "color.red": "أحمر" + }, + "de": { + "color.blue": "Blau", + "color.green": "Grün", + "color.red": "Rot" + }, + "en": { + "color.blue": "Blue", + "color.green": "Green", + "color.red": "Red" + }, + "he": { + "color.blue": "כחול", + "color.green": "ירוק", + "color.red": "אדום" + }, + "ja": { + "color.blue": "青", + "color.green": "緑", + "color.red": "赤" + }, + "ko": { + "color.blue": "파랑", + "color.green": "초록", + "color.red": "빨강" + }, + "vi": { + "color.blue": "Xanh dương", + "color.green": "Xanh lá", + "color.red": "Đỏ" + }, + "zh": { + "color.blue": "蓝色", + "color.green": "绿色", + "color.red": "红色" + } +} diff --git a/crates/ui-egui/src/ui_kit/color.rs b/crates/ui-egui/src/ui_kit/color.rs index dfef5e72a..3f181be17 100644 --- a/crates/ui-egui/src/ui_kit/color.rs +++ b/crates/ui-egui/src/ui_kit/color.rs @@ -205,8 +205,11 @@ fn color_popover_with_opacity(ui: &mut Ui, rgb: &mut [u8; 3], mut opacity: Optio Spin { max: 255.0, step: 1.0, speed: 0.5, decimals: 0 } }; ui.columns(3, |columns| { - for ((ui, channel), name) in columns.iter_mut().zip(channels.iter_mut()).zip(["R", "G", "B"]) { - edited |= spin_channel(ui, name, None, channel, spin); + // Named like H, S and V: "R" alone doesn't say red in every language (#10201). + for ((ui, channel), (name, tip)) in + columns.iter_mut().zip(channels.iter_mut()).zip([("R", "color.red"), ("G", "color.green"), ("B", "color.blue")]) + { + edited |= spin_channel(ui, name, Some(i18n::tr(tip)), channel, spin); } }); } @@ -436,7 +439,10 @@ fn spin_buttons(ui: &mut Ui, key: &str, height: f32) -> i32 { let mut steps = 0; for (direction, half, label, end) in [(1, top, "color.step_up", "up"), (-1, bottom, "color.step_down", "down")] { let id = ui.id().with(("color_spin", key, end)); - let response = ui.interact(half, id, Sense::click()); + // Sensing drags too keeps a long press down on the button: a press that senses clicks + // only stops counting once it outlasts egui's longest click (0.8 s), and the repeat with + // it, after 8 steps (#10201). + let response = ui.interact(half, id, Sense::click_and_drag()); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), i18n::tr(label))); publish(&format!("color:spin:{key}:{end}"), &response); let held = response.is_pointer_button_down_on(); diff --git a/crates/ui-egui/src/ui_kit/color_tests.rs b/crates/ui-egui/src/ui_kit/color_tests.rs index ffc05c0f0..8e417c114 100644 --- a/crates/ui-egui/src/ui_kit/color_tests.rs +++ b/crates/ui-egui/src/ui_kit/color_tests.rs @@ -501,3 +501,43 @@ fn recent_colours_are_saved_with_the_preferences_and_hostile_entries_dropped() { assert_eq!(restored.ui.recent_colors.get(1), Some(&[1, 2, 3])); assert_eq!(restored.ui.recent_colors.len(), MAX_RECENT_COLORS); } + +/// #10201: a step button held down keeps stepping until it is let go, past egui's longest click +/// (0.8 s): two seconds of holding H's up button step it about 32 degrees, not the 8 a press +/// counted as a click managed before it stopped. +#[test] +fn a_held_step_button_keeps_stepping_until_it_is_let_go() { + let ctx = crate::fonts::test_context(); + let mut rgb = [255, 0, 0]; + let at_time = |time: f64, events: Vec, rgb: &mut [u8; 3]| { + scenario::clear_handles(); + let _ = crate::test_support::frame( + &ctx, + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 600.0))), + events, + time: Some(time), + focused: true, + ..Default::default() + }, + |ui| { + ui.set_width(280.0); + ui.push_id("picker", |ui| crate::ui_kit::scope(ui, |ui| color_popover(ui, rgb))); + }, + ); + }; + at_time(0.0, vec![], &mut rgb); + let up = scenario::handle_at("color:spin:H:up").expect("H's up button"); + at_time(0.01, pointer(up, true), &mut rgb); + for frame in 1..=120 { + at_time(0.01 + f64::from(frame) / 60.0, vec![egui::Event::PointerMoved(up)], &mut rgb); + } + let hue = |rgb: [u8; 3]| HsvaGamma::from(Color32::from_rgb(rgb[0], rgb[1], rgb[2])).h * 360.0; + let held = hue(rgb); + assert!(held > 20.0, "two seconds held stepped the hue to {held:.1} degrees"); + at_time(2.1, pointer(up, false), &mut rgb); + for frame in 1..=30 { + at_time(2.1 + f64::from(frame) / 60.0, vec![], &mut rgb); + } + assert!((hue(rgb) - held).abs() < 1.5, "let go, it stops: {} after {held}", hue(rgb)); +} From ce296a1ad5a9b3966b8f166210277936bd17b57b Mon Sep 17 00:00:00 2001 From: semmelrinde <124386289+semmelrinde@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:09:21 +0000 Subject: [PATCH 20/55] Extrude preview: a round face sweeps round walls, with lines up its corners only (#8838) The live preview of extruding a picked face built its walls from the face's display triangles and drew a line up the wall at every boundary point, each wall piece shaded flat. A round face (the Bolted Flange's flange) looked like a polygon while extruding. Lines now go up only where an edge of the face ends and the outline turns there more than its curves do, and a wall's normal turns with it between smooth pieces. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/extrude_preview.rs | 162 ++++++++++++++++++++++++-- 1 file changed, 154 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/extrude_preview.rs b/crates/ui-egui/src/extrude_preview.rs index e21182941..536213abb 100644 --- a/crates/ui-egui/src/extrude_preview.rs +++ b/crates/ui-egui/src/extrude_preview.rs @@ -31,6 +31,9 @@ struct Surface { normal: Vec3, triangles: Vec<[Vec3; 3]>, edges: Vec<[Vec3; 2]>, + /// Per edge: whether its start is a corner of the outline, where the walls meet at an edge + /// of their own (a line is drawn up it), and the wall's normal at its start and end. + sides: Vec<(bool, [Vec3; 2])>, } impl StraightPreview { @@ -138,11 +141,18 @@ impl StraightPreview { } } let edge_color = if operation == "cut" { cut_edge } else { scene.color(colors.edge) }; - for &[a, b] in &surface.edges { - let normal = (b - a).cross(surface.normal).normalized()?; - triangle(&mut scene, [a + low, b + low, b + high], normal); - triangle(&mut scene, [a + low, b + high, a + high], normal); - for (a, b) in [(a + low, b + low), (a + high, b + high), (a + low, a + high)] { + for (&[a, b], &(corner, [na, nb])) in surface.edges.iter().zip(&surface.sides) { + for (points, normals) in [([a + low, b + low, b + high], [na, nb, nb]), ([a + low, b + high, a + high], [na, nb, na])] { + for (point, normal) in points.into_iter().zip(normals) { + if matches!(operation, "cut" | "intersect") { + scene.xray_tri(point.to_f32(), normal.to_f32(), color); + } else { + scene.tri(point.to_f32(), normal.to_f32(), color); + } + } + } + let up = corner.then_some((a + low, a + high)); + for (a, b) in [(a + low, b + low), (a + high, b + high)].into_iter().chain(up) { scene.line(a.to_f32(), b.to_f32(), edge_color, 1.3, operation != "join"); } } @@ -184,7 +194,7 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { if triangles.is_empty() { return None; } - let edges = std::iter::once((®ion.outer, true)) + let edges: Vec<[Vec3; 2]> = std::iter::once((®ion.outer, true)) .chain(region.holes.iter().map(|hole| (hole, false))) .flat_map(|(loop_, outer)| { let reverse = (loop_.signed_area() > 0.) != outer; @@ -194,9 +204,12 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { }) }) .collect(); - surfaces.push(Surface { normal: sketch.plane.normal(), triangles, edges }); + // Profiles of lines only: every end is a corner. + let sides = walls(&edges, sketch.plane.normal(), &|_| true)?; + surfaces.push(Surface { normal: sketch.plane.normal(), triangles, edges, sides }); } } else if inputs.iter().all(|input| matches!(input, Sel::Face { .. })) { + let mut vertices: HashMap, f64)> = HashMap::new(); // One pass over each selected body's triangles, rather than one full scan per pick. for body in &state.bodies { let mut selected = HashMap::new(); @@ -210,7 +223,7 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { } let normal = body.body.planar_face(*index)?.normal(); selected.insert(face, (surfaces.len(), *point)); - surfaces.push(Surface { normal, triangles: Vec::new(), edges: Vec::new() }); + surfaces.push(Surface { normal, triangles: Vec::new(), edges: Vec::new(), sides: Vec::new() }); } } if selected.is_empty() { @@ -228,6 +241,19 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { surface.triangles.push(points); } } + // The ends of the face's own edges: an outline turns at a corner only there, never + // between the points a curved edge is drawn with. + for (face, (index, _)) in &selected { + let ends: Vec = mesh + .edges + .iter() + .zip(&mesh.edge_faces) + .filter(|(_, faces)| faces.contains(face)) + .flat_map(|(points, _)| [points.first().copied(), points.last().copied()]) + .flatten() + .collect(); + vertices.insert(*index, (ends, (mesh.bounds().diagonal() * 1e-9).max(1e-9))); + } // The command resolves picks by their point. A stale display face index // must fall back rather than previewing a different face. let tolerance = (mesh.bounds().diagonal() * 1e-8).max(1e-8); @@ -263,6 +289,12 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { return None; } } + for (index, surface) in surfaces.iter_mut().enumerate() { + let (ends, tolerance) = vertices.remove(&index).unwrap_or_default(); + // A face whose edges the mesh doesn't list: every point may be a corner, as before. + let vertex = |p: Vec3| ends.is_empty() || ends.iter().any(|e| e.dist(p) <= tolerance); + surface.sides = walls(&surface.edges, surface.normal, &vertex)?; + } } else { return None; } @@ -270,6 +302,61 @@ fn prepare(app: &SolveApp, inputs: &[Sel]) -> Option { Some(Cached { document: app.session.doc.clone(), revision: app.session.revision, inputs: inputs.to_vec(), surfaces, bounds }) } +/// The walls an outline sweeps: per edge (in `edges`' order), whether its start is a corner +/// and the wall's normal at its start and end. A point turns the outline at a corner only +/// where `vertex` says an edge of the face ends there, and only by more than the points of the +/// curves on either side turn it (a circle drawn in two halves meets itself smoothly). Between +/// two smooth pieces the wall's normal is their mean, so a round wall shades round. `None` +/// when an edge has no length. +fn walls(edges: &[[Vec3; 2]], normal: Vec3, vertex: &dyn Fn(Vec3) -> bool) -> Option> { + let key = |point: Vec3| [point.x, point.y, point.z].map(|coordinate| if coordinate == 0. { 0 } else { coordinate.to_bits() }); + let starts: HashMap<_, usize> = edges.iter().enumerate().map(|(i, e)| (key(e[0]), i)).collect(); + let next = |i: usize| edges.get(i).and_then(|e| starts.get(&key(e[1])).copied()); + let mut prev = vec![None; edges.len()]; + for i in 0..edges.len() { + if let Some(j) = next(i) + && let Some(slot) = prev.get_mut(j) + { + *slot = Some(i); + } + } + let dirs: Vec = edges.iter().map(|e| (e[1] - e[0]).normalized()).collect::>()?; + let outward: Vec = dirs.iter().map(|d| d.cross(normal).normalized()).collect::>()?; + // The turn at the start of edge `i`. + let turn = |i: usize| -> Option { + let p = prev.get(i).copied().flatten()?; + Some(dirs.get(p)?.dot(*dirs.get(i)?).clamp(-1.0, 1.0).acos()) + }; + let corner: Vec = (0..edges.len()) + .map(|i| { + let (Some(a), Some(t)) = (edges.get(i).map(|e| e[0]), turn(i)) else { return true }; + if !vertex(a) { + return false; + } + // How far the curves on either side turn between their own points. + let before = prev.get(i).copied().flatten().filter(|p| edges.get(*p).is_some_and(|e| !vertex(e[0]))).and_then(turn).unwrap_or(0.0); + let after = next(i).filter(|n| edges.get(*n).is_some_and(|e| !vertex(e[0]))).and_then(turn).unwrap_or(0.0); + t > 1.25 * before.max(after) + 1e-2 + }) + .collect(); + let mean = |a: Vec3, b: Option<&Vec3>| b.and_then(|b| (a + *b).normalized()).unwrap_or(a); + let smooth = |i: usize| corner.get(i).is_some_and(|c| !c); + (0..edges.len()) + .map(|i| { + let own = *outward.get(i)?; + let at_start = match prev.get(i).copied().flatten() { + Some(p) if smooth(i) => mean(own, outward.get(p)), + _ => own, + }; + let at_end = match next(i) { + Some(n) if smooth(n) => mean(own, outward.get(n)), + _ => own, + }; + Some((!smooth(i), [at_start, at_end])) + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -352,6 +439,65 @@ mod tests { commands[0].1 = json!({"distance":2,"taper":"3deg"}); assert!(preview.compute(&harness.app, &commands, colors).is_none()); } + /// Lines the feedback draws straight up the walls (along +z), under or over the model. + fn upright_lines(scene: &GpuScene) -> usize { + [&scene.lines, &scene.overlay] + .into_iter() + .flat_map(|lines| lines.as_chunks::<{ crate::gpu::LINE_SIZE }>().0) + .filter(|line| { + let v: Vec = line.as_chunks::<4>().0.iter().take(6).map(|bytes| f32::from_le_bytes(*bytes)).collect(); + (v[0] - v[3]).abs() < 1e-4 && (v[1] - v[4]).abs() < 1e-4 && (v[2] - v[5]).abs() > 1e-3 + }) + .count() + } + + /// A face with round edges is swept into round walls: no line up the wall at each point the + /// circle is drawn with, and normals that turn with the wall (the Bolted Flange's face looked + /// like a polygon while extruding, 2026-10-29). A box's face keeps a line up each corner. + #[test] + fn face_feedback_draws_lines_up_corners_only() { + for (shape, corners) in [("solid.cylinder", 0), ("solid.box", 4)] { + let mut harness = Harness::new(); + let params = if shape == "solid.cylinder" { + json!({"radius": 20, "height": 5, "body_name": "Stock"}) + } else { + json!({"length": 4, "width": 3, "height": 5, "body_name": "Stock"}) + }; + harness.app.run(shape, params).unwrap(); + let state = harness.app.session.world_state(); + let face = state + .body("Stock") + .unwrap() + .body + .faces(0.001) + .unwrap() + .into_iter() + .find(|face| face.plane_normal.is_some_and(|normal| normal.z > 0.99)) + .unwrap(); + harness.app.session.selection = vec![Sel::Face { body: "Stock".into(), index: face.index, point: face.centroid }]; + harness.app.start("solid.extrude"); + if let Kind::Extrude { distance, operation, auto_op, .. } = &mut harness.app.dialog.as_mut().unwrap().kind { + *distance = "2".into(); + *operation = 0; + *auto_op = false; + } + let commands = crate::dialogs::apply_commands(&harness.app, harness.app.dialog.as_ref().unwrap()).unwrap(); + let mut preview = StraightPreview::default(); + let built = preview.compute(&harness.app, &commands, Colors::from_tokens(&crate::theme::Tokens::get())).unwrap().unwrap(); + assert_eq!(upright_lines(&built.scene), corners, "{shape}"); + if shape == "solid.cylinder" { + // Each wall vertex's normal points away from the axis. + let surface = &preview.cached.as_ref().unwrap().surfaces[0]; + for (edge, (_, normals)) in surface.edges.iter().zip(&surface.sides) { + for (point, normal) in edge.iter().zip(normals) { + let radial = Vec3::new(point.x, point.y, 0.0).normalized().unwrap(); + assert!(normal.dot(radial) > 0.999, "{point:?}: {normal:?}"); + } + } + } + } + } + #[test] fn identity_component_feedback_skips_moved_and_repeated_placements() { let mut h = Harness::new(); From cffa6e1580a2f774e059dfa852ec336e1727f214 Mon Sep 17 00:00:00 2001 From: Jesper We Date: Sun, 1 Nov 2026 20:10:13 +0000 Subject: [PATCH 21/55] Loft and Surface Loft: two sections from one sketch (#8221) (#8222) * claim: #8221 * Loft and Surface Loft: two sections from one sketch (#8221) --- .../pending/loft-sections-one-sketch.json | 26 ++++++ crates/ui-egui/src/dialogs.rs | 30 +++---- crates/ui-egui/src/dialogs_surface.rs | 49 +++++----- crates/ui-egui/src/loft_rails_dialog_tests.rs | 90 +++++++++++++++++++ 4 files changed, 158 insertions(+), 37 deletions(-) create mode 100644 assets/locales/pending/loft-sections-one-sketch.json diff --git a/assets/locales/pending/loft-sections-one-sketch.json b/assets/locales/pending/loft-sections-one-sketch.json new file mode 100644 index 000000000..708b80eff --- /dev/null +++ b/assets/locales/pending/loft-sections-one-sketch.json @@ -0,0 +1,26 @@ +{ + "en": { + "Sections": "Sections" + }, + "ar": { + "Sections": "المقاطع" + }, + "de": { + "Sections": "Querschnitte" + }, + "he": { + "Sections": "חתכים" + }, + "ja": { + "Sections": "セクション" + }, + "ko": { + "Sections": "단면" + }, + "vi": { + "Sections": "Các mặt cắt" + }, + "zh": { + "Sections": "截面" + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d8a8678c8..0e323356d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4641,33 +4641,31 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result, S } Kind::Loft { operation, rail_fit } => { need(0, "profiles of two or more sketches")?; - // One section per sketch, in the order the sketches were first picked; a sketch point - // is a section of its own, an apex the loft closes to (#4830). - let mut sections: Vec<(u64, Vec, Option<&str>)> = Vec::new(); + // Each picked profile is a section, in pick order, two of them from one sketch + // included (#8221); a sketch point is a section of its own, an apex the loft closes + // to (#4830). + let mut sections: Vec = Vec::new(); + let (mut profile_sketches, mut apexes) = (Vec::new(), 0); for x in sels(d, 0) { match x { - Sel::Profile { sketch, index } => match sections.iter_mut().find(|(sk, _, apex)| sk == sketch && apex.is_none()) { - Some((_, v, _)) => v.push(*index), - None => sections.push((*sketch, vec![*index], None)), - }, + Sel::Profile { sketch, index } => { + sections.push(json!({"sketch": sketch, "profiles": [index]})); + profile_sketches.push(*sketch); + } Sel::SketchPoint { id } => { if let Some((sk, point)) = id.split_once(':').and_then(|(sk, point)| Some((sk.parse::().ok()?, point))) { - sections.push((sk, Vec::new(), Some(point))); + sections.push(json!({"sketch": sk, "point": point})); + apexes += 1; } } _ => {} } } - if sections.len() < 2 { + profile_sketches.sort_unstable(); + profile_sketches.dedup(); + if profile_sketches.len() + apexes < 2 { return Err("pick profiles in two or more sketches, or a profile and a sketch point".into()); } - let sections: Vec = sections - .into_iter() - .map(|(sk, v, apex)| match apex { - Some(point) => json!({"sketch": sk, "point": point}), - None => json!({"sketch": sk, "profiles": v}), - }) - .collect(); let mut p = json!({"sections": sections, "operation": OPS.get(*operation).copied().unwrap_or("new")}); crate::dialogs_sweep::rail_params(app, *rail_fit, [sels(d, 1), sels(d, 2)], &mut p)?; ("solid.loft", p) diff --git a/crates/ui-egui/src/dialogs_surface.rs b/crates/ui-egui/src/dialogs_surface.rs index fa2fbadaf..fc26a53b5 100644 --- a/crates/ui-egui/src/dialogs_surface.rs +++ b/crates/ui-egui/src/dialogs_surface.rs @@ -173,7 +173,7 @@ fn inputs(k: &Surf) -> Vec { } Surf::Loft { .. } => { let [rail, rail2] = crate::dialogs_sweep::rail_inputs(); - vec![SelInput::new("Sections (one sketch each)", PROFILES | CURVES, true), rail, rail2] + vec![SelInput::new("Sections", PROFILES | CURVES, true), rail, rail2] } Surf::Blend { .. } => vec![SelInput::new("From edges", EDGES, true), SelInput::new("To edges", EDGES, true)], Surf::Boundary { .. } => vec![SelInput::new("Curves", CURVES | EDGES, true), SelInput::new("Cross curves", CURVES | EDGES, true)], @@ -517,30 +517,37 @@ pub fn commands(app: &SolveApp, k: &Surf, inputs: &[SelInput], extra: &Map { - need(0, "the sections, one sketch each")?; - // One section per sketch, in the order the sketches were first picked. - let sketch_of = |x: &Sel| match x { - Sel::Profile { sketch, .. } => Some(*sketch), - Sel::SketchCurve { .. } => crate::dialogs::picks_sketch(app, std::slice::from_ref(x), None), - _ => None, - }; - let mut order: Vec = Vec::new(); - for x in items(inputs, 0) { - let sk = sketch_of(x).ok_or("a picked curve is no longer in a sketch")?; - if !order.contains(&sk) { - order.push(sk); + need(0, "the sections")?; + // Each picked profile is a section, and so is each chain of picked curves (those of + // one sketch that meet end to end), in the order of their first pick: two sections + // can come from one sketch (#8221). + let picks = items(inputs, 0); + let curves: Vec = picks.iter().filter(|x| matches!(x, Sel::SketchCurve { .. })).cloned().collect(); + let mut chained: Vec> = chains(app, &curves)?.into_iter().map(Some).collect(); + let mut sections: Vec = Vec::new(); + let mut sketches: Vec = Vec::new(); + for x in picks { + match x { + Sel::Profile { sketch, index } => { + sections.push(json!({"sketch": sketch, "profiles": [index]})); + sketches.push(*sketch); + } + Sel::SketchCurve { id, .. } => { + let sk = crate::dialogs::picks_sketch(app, std::slice::from_ref(x), None).ok_or("a picked curve is no longer in a sketch")?; + let holds = |c: &Option| matches!(c, Some(Chain::Sketch { sketch, ids }) if *sketch == sk && ids.contains(id)); + if let Some(Some(Chain::Sketch { sketch, ids })) = chained.iter_mut().find(|c| holds(c)).map(Option::take) { + sections.push(json!({"sketch": sketch, "curves": ids})); + sketches.push(sketch); + } + } + _ => {} } } - if order.len() < 2 { + sketches.sort_unstable(); + sketches.dedup(); + if sketches.len() < 2 { return Err("pick sections in two or more sketches".into()); } - let sections: Vec = order - .iter() - .map(|sk| { - let picks: Vec = items(inputs, 0).iter().filter(|x| sketch_of(x) == Some(*sk)).cloned().collect(); - sheet_picks(app, &picks) - }) - .collect::>()?; let mut p = json!({ "sections": sections }); crate::dialogs_sweep::rail_params(app, *rail_fit, [items(inputs, 1), items(inputs, 2)], &mut p)?; ("surface.loft", p) diff --git a/crates/ui-egui/src/loft_rails_dialog_tests.rs b/crates/ui-egui/src/loft_rails_dialog_tests.rs index 6a3a74aa6..5a5a74aa2 100644 --- a/crates/ui-egui/src/loft_rails_dialog_tests.rs +++ b/crates/ui-egui/src/loft_rails_dialog_tests.rs @@ -1,5 +1,6 @@ //! The Loft and Surface Loft dialogs' guide rails (#201): rails picked in the dialog reach the //! commands with their sketches and the fit, and editing the loft brings them back and keeps them. +//! Their sections follow the picks, two of them from one sketch included (#8221). use crate::dialogs::Kind; use crate::dialogs_surface::Surf; use crate::scenario::Harness; @@ -127,3 +128,92 @@ fn curves_that_share_an_id_are_picked_from_their_own_sketches() { let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); assert_eq!(commands[0].1["sections"], json!([{"sketch": low, "curves": ["l"]}, {"sketch": high, "curves": ["l"]}])); } + +/// A sketch at height `z` named `name`, made by `draw`; its id. +fn sketch_at(h: &mut Harness, name: &str, z: i32, draw: &[(&str, serde_json::Value)]) -> u64 { + h.app.run("sketch.create", json!({"name": name, "plane": {"origin": [0, 0, z], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})).unwrap(); + for (command, params) in draw { + h.app.run(command, params.clone()).unwrap(); + } + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.session.doc.find_feature(name).unwrap().id +} + +/// Two sections can come from one sketch (#8221): Surface Loft from one line of `A`, over `B`'s, +/// back to `A`'s other line makes three sections in pick order, and an edit keeps them. +#[test] +fn surface_loft_sections_from_one_sketch_stay_apart() { + let mut h = Harness::new(); + let a = sketch_at( + &mut h, + "A", + 0, + &[ + ("sketch.line", json!({"points": [[-10, 0], [10, 0]], "ids": ["front"]})), + ("sketch.line", json!({"points": [[-10, 40], [10, 40]], "ids": ["back"]})), + ], + ); + let b = sketch_at(&mut h, "B", 30, &[("sketch.line", json!({"points": [[-10, 20], [10, 20]], "ids": ["top"]}))]); + h.step(&json!({"call":"ui.start","params":{"command":"surface.loft"}})).unwrap(); + h.frames(3); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![ + Sel::SketchCurve { id: "front".into(), sketch: Some(a) }, + Sel::SketchCurve { id: "top".into(), sketch: Some(b) }, + Sel::SketchCurve { id: "back".into(), sketch: Some(a) }, + ]; + let expected = json!([{"sketch": a, "curves": ["front"]}, {"sketch": b, "curves": ["top"]}, {"sketch": a, "curves": ["back"]}]); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["sections"], expected); + ok(&mut h); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap(); + h.frames(8); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["params"]["sections"], expected); + ok(&mut h); +} + +/// Curves of one sketch that meet end to end are still one Surface Loft section, whatever order +/// they were picked in. +#[test] +fn surface_loft_curves_that_meet_are_one_section() { + let mut h = Harness::new(); + let a = sketch_at(&mut h, "A", 0, &[("sketch.line", json!({"points": [[-10, 0], [0, 0], [10, 5]], "ids": ["left", "right"]}))]); + let b = sketch_at(&mut h, "B", 30, &[("sketch.line", json!({"points": [[-10, 0], [10, 0]], "ids": ["top"]}))]); + h.step(&json!({"call":"ui.start","params":{"command":"surface.loft"}})).unwrap(); + h.frames(3); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![ + Sel::SketchCurve { id: "right".into(), sketch: Some(a) }, + Sel::SketchCurve { id: "top".into(), sketch: Some(b) }, + Sel::SketchCurve { id: "left".into(), sketch: Some(a) }, + ]; + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["sections"], json!([{"sketch": a, "curves": ["right", "left"]}, {"sketch": b, "curves": ["top"]}])); +} + +/// Loft from one circle of `C`, over `D`'s, back to `C`'s other circle (#8221): each picked +/// profile is a section, in pick order, and an edit keeps them. +#[test] +fn loft_profiles_from_one_sketch_stay_apart() { + let mut h = Harness::new(); + let circle = |x: i32, y: i32| ("sketch.circle.center", json!({"center": [x, y], "diameter": 12})); + let c = sketch_at(&mut h, "C", 0, &[circle(0, 0), circle(0, 40)]); + let d_sketch = sketch_at(&mut h, "D", 30, &[circle(0, 20)]); + h.step(&json!({"call":"ui.start","params":{"command":"solid.loft"}})).unwrap(); + h.frames(3); + let d = h.app.dialog.as_mut().unwrap(); + d.inputs[0].items = vec![Sel::Profile { sketch: c, index: 0 }, Sel::Profile { sketch: d_sketch, index: 0 }, Sel::Profile { sketch: c, index: 1 }]; + let expected = json!([{"sketch": c, "profiles": [0]}, {"sketch": d_sketch, "profiles": [0]}, {"sketch": c, "profiles": [1]}]); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["sections"], expected); + ok(&mut h); + assert_eq!(h.app.session.world_state().bodies.len(), 1, "{:?}", h.app.session.log); + let name = h.app.session.doc.features.last().unwrap().name.clone(); + h.step(&json!({"call":"ui.editFeature","params":{"feature":name}})).unwrap(); + h.frames(8); + let commands = crate::dialogs::apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + assert_eq!(commands[0].1["params"]["sections"], expected); + ok(&mut h); +} From 958ab867cd5d3a74712638f681912e48c619cb98 Mon Sep 17 00:00:00 2001 From: Daniel Date: Sun, 1 Nov 2026 20:11:00 +0000 Subject: [PATCH 22/55] Press Pull on a chamfer or fillet face edits it where you clicked (#4986) (#9771) * claim: #4986 Co-Authored-By: Claude Opus 5.5 * Press Pull on a chamfer's face changes the chamfer's distance (#4986) A chamfer's face is flat, so solid.press_pull and the Press Pull start path in the UI took it for a planar face and extruded it. Both now look for a fillet's or chamfer's face before asking whether the face is planar, so a chamfer's face reopens the chamfer and its distance grows by the distance pulled, as a fillet's radius already does. A first pick with Press Pull already open is routed the same way. Co-Authored-By: Claude Opus 5.5 * Press Pull on a blend face puts the arrow on the edge clicked A fillet or chamfer reopened by Press Pull from one of its faces drew its radius or distance arrow on the feature's first stored edge, which can be a corner the user did not click and cannot see (the Sample Plate's fillet, from the far corner). The click's point now goes with the reopened dialog as a hint that is never saved, and the arrow sits on the feature's edge nearest it, at the point on that edge nearest the click. Opened any other way (the history, Edit Feature) the arrow stays on the first edge as before. A click point that is not finite is not kept, and a point on a flat face next to a chamfer still extrudes that face (tested). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/features.rs | 17 ++--- crates/engine/src/tests.rs | 54 +++++++++++++++ crates/ui-egui/src/canvas.rs | 49 ++++++++++++- crates/ui-egui/src/dialogs.rs | 4 ++ crates/ui-egui/src/documents.rs | 2 + crates/ui-egui/src/lib.rs | 41 +++++++---- crates/ui-egui/src/preselect_tests.rs | 99 +++++++++++++++++++++++++++ crates/ui-egui/src/viewport.rs | 8 ++- 8 files changed, 250 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 9a38d94a2..18be03cd0 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -1591,8 +1591,8 @@ pub(crate) fn edge_ref_form(e: &Value) -> std::result::Result, & Ok(EdgeRefForm::Index { body, index }) } -/// Press Pull: a face moves along its normal (an extrude that joins outward or cuts inward); an -/// edge is rounded (a fillet). +/// Press Pull: a face moves along its normal (an extrude that joins outward or cuts inward); a +/// fillet's or chamfer's face changes that feature's size; an edge is rounded (a fillet). fn press_pull(s: &mut Session, p: &Value) -> Result { let cmd = "solid.press_pull"; let distance = req_expr(cmd, p, "distance")?; @@ -1604,10 +1604,9 @@ fn press_pull(s: &mut Session, p: &Value) -> Result { if d.abs() < 1e-9 { return Err(bad(cmd, "the distance must not be zero")); } - // A fillet's or chamfer's face: its size changes by the distance (the feature is edited). - if let Some(fp) = vec3(face) - && super::face::face_is_planar(s, fp) == Some(false) - { + // A fillet's or chamfer's face: its size changes by the distance (the feature is edited). A + // chamfer's face is flat, so this is asked before whether the face is planar (#4986). + if let Some(fp) = vec3(face) { let name = solidcraft_doc::naming::face_names_at(&s.model.state(), &[fp]).into_iter().next().unwrap_or_default(); let fid = solidcraft_doc::persistent_name::made_by(&name); if solidcraft_doc::persistent_name::is_blend(&name) { @@ -1625,8 +1624,10 @@ fn press_pull(s: &mut Session, p: &Value) -> Result { return Ok(json!({"feature": f.id, "edited": f.name, key: new, "recomputed": out.get("recomputed"), "restored": out.get("restored")})); } // Another curved face moves along its normal. - let r = super::find_command("solid.offset_face").ok_or_else(|| bad(cmd, "solid.offset_face"))?; - return (r.run)(s, &json!({"faces": [face], "distance": distance})); + if super::face::face_is_planar(s, fp) == Some(false) { + let r = super::find_command("solid.offset_face").ok_or_else(|| bad(cmd, "solid.offset_face"))?; + return (r.run)(s, &json!({"faces": [face], "distance": distance})); + } } // Pushed in: the extrude cuts the other way by as much (a bare number stays one, so it keeps // being read as a bare number typed into the extrude). diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e2dfd5e39..a4cbe1bd9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2878,6 +2878,60 @@ fn press_pull_on_curved_faces() { assert!(err.contains("offset"), "{err}"); } +/// #4986: Press Pull on a chamfer's flat face changes the chamfer's distance, as on a fillet's +/// face it changes the radius, rather than extruding the face. +#[test] +fn press_pull_on_a_chamfer_face_edits_the_chamfer() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + run(&mut s, "solid.chamfer", json!({"edges": [[40, 0, 10]], "distance": 3, "name": "Bevel"})); + let cut = |d: f64| d * d / 2.0 * 20.0; + assert!(rel(volume(&mut s), 24000.0 - cut(3.0)) < 1e-6); + // The chamfer's face runs from (37, 0) to (40, 3); its middle. + let out = run(&mut s, "solid.press_pull", json!({"face": [38.5, 1.5, 10], "distance": 2})); + assert_eq!(out["edited"], "Bevel", "{out}"); + assert_eq!(s.doc.features.len(), 2, "no extrude added"); + assert!(rel(volume(&mut s), 24000.0 - cut(5.0)) < 1e-6, "{}", volume(&mut s)); + // A point on the flat front face 0.02 mm from its edge with the chamfer (which now runs from + // (35, 0) to (40, 5)) is the front face's: it is extruded, the chamfer is left alone. + let mut t = Session::default(); + run(&mut t, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + run(&mut t, "solid.chamfer", json!({"edges": [[40, 0, 10]], "distance": 3, "name": "Bevel"})); + let out = run(&mut t, "solid.press_pull", json!({"face": [36.98, 0, 10], "distance": 1})); + assert!(out.get("edited").is_none(), "{out}"); + assert!(matches!(t.doc.features.last().map(|f| &f.kind), Some(solidcraft_doc::FeatureKind::Extrude { .. })), "an extrude added: {out}"); + assert!( + matches!(&t.doc.features[1].kind, solidcraft_doc::FeatureKind::Chamfer { distance, .. } if distance == "3"), + "{:?}", + t.doc.features[1].kind + ); + // Too far in (past zero) or too far out: an error, the chamfer as it was. + let on = [39.0, 1.0, 10.0]; + for d in [-10.0, 1e9] { + assert!(s.execute("solid.press_pull", &json!({"face": on, "distance": d})).is_err(), "{d}"); + assert!(rel(volume(&mut s), 24000.0 - cut(5.0)) < 1e-6, "{d}: {}", volume(&mut s)); + } + // An unequal chamfer's first distance changes and its second stays; an angle chamfer keeps + // its angle. + // Each chamfer's face crosses the corner's bisector at legs a, b: (40 - u, u), u = ab / (a + b). + let tan30 = (PI / 6.0).tan(); + for (extra, u) in [(json!({"distance2": 4}), 8.0 / 6.0), (json!({"angle": "30 deg"}), 2.0 * tan30 / (1.0 + tan30))] { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + let mut p = json!({"edges": [[40, 0, 10]], "distance": 2, "name": "Bevel"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + run(&mut s, "solid.chamfer", p); + let v0 = volume(&mut s); + let out = run(&mut s, "solid.press_pull", json!({"face": [40.0 - u, u, 10.0], "distance": 1})); + assert_eq!(out["edited"], "Bevel", "{extra}: {out}"); + assert_eq!(s.doc.features.len(), 2, "{extra}"); + let Some(solidcraft_doc::FeatureKind::Chamfer { distance2, angle, .. }) = s.doc.features.last().map(|f| &f.kind) else { panic!("{extra}") }; + assert_eq!(distance2.as_ref().map(|e| e.to_string()), extra.get("distance2").map(|v| v.to_string()), "{extra}"); + assert_eq!(angle.as_ref().map(|e| e.to_string()), extra.get("angle").and_then(|v| v.as_str()).map(str::to_string), "{extra}"); + assert!(volume(&mut s) < v0 - 1.0, "{extra}: a bigger chamfer cuts more"); + } +} + /// A cut in one component leaves other components' bodies alone unless they are named as /// participants; auto join/cut looks at the active component only. #[test] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 760a23dce..8e284097e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -20,7 +20,7 @@ use crate::viewport::{Proj, projected_polygon}; /// direction a growing value points. pub fn anchor(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Option)> { let st = app.session.world_state(); - let first = d.inputs.first()?.items.first()?; + let first = &anchor_item(app, d)?; let (at, normal) = match first { Sel::Profile { sketch, index } => { let ss = st.sketch(*sketch)?; @@ -250,12 +250,44 @@ pub(crate) fn blend_grow_dir(m: &Mesh, index: usize, p: Vec3) -> Option { Some(if edge_concave(m, index, p).unwrap_or(false) { n } else { -n }) } +/// The pick the dialog's arrow sits on: the first, or for a fillet or chamfer reopened from a +/// click on one of its faces (Press Pull), its edge nearest the click, at the point on it nearest +/// the click (#4986). +fn anchor_item(app: &SolveApp, d: &Dialog) -> Option { + let items = &d.inputs.first()?.items; + let first = items.first()?.clone(); + let (Some(hint), Kind::Fillet { .. }) = (d.anchor_hint, &d.kind) else { return Some(first) }; + let st = app.session.world_state(); + let nearest = items + .iter() + .filter_map(|s| { + let Sel::Edge { body, index, .. } = s else { return None }; + let at = nearest_on_polyline(st.body(body)?.mesh().edges.get(*index)?, hint)?; + Some((at.dist(hint), Sel::Edge { body: body.clone(), index: *index, point: at })) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)); + Some(nearest.map_or(first, |(_, s)| s)) +} + +/// The point of the polyline `pts` nearest `p`. +fn nearest_on_polyline(pts: &[Vec3], p: Vec3) -> Option { + let on = |a: Vec3, b: Vec3| { + let ab = b - a; + let len2 = ab.dot(ab); + a + ab * if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 } + }; + pts.windows(2) + .filter_map(|w| if let [a, b] = w { Some(on(*a, *b)) } else { None }) + .min_by(|x, y| x.dist(p).total_cmp(&y.dist(p))) + .or_else(|| pts.first().copied()) +} + /// The directions Distance 1 and Distance 2 of a chamfer of two distances run from its edge at /// `at`: along the face that faces up most, or the other one with Flip, and along the remaining /// face (the kernel's `chamfer_tool_sides` picks them the same way). None for any other dialog. pub(crate) fn chamfer_face_dirs(app: &SolveApp, d: &Dialog, at: Vec3) -> Option<(Vec3, Vec3)> { let Kind::Fillet { chamfer: true, ctype: 1, flip, .. } = &d.kind else { return None }; - let Some(Sel::Edge { body, index, .. }) = d.inputs.first()?.items.first() else { return None }; + let Some(Sel::Edge { body, index, .. }) = &anchor_item(app, d) else { return None }; let st = app.session.world_state(); let mesh = st.body(body)?.mesh(); let sides = edge_sides(&mesh, *index, at)?; @@ -1963,6 +1995,19 @@ fn arrow(painter: &egui::Painter, a: Pos2, b: Pos2, col: Color32) { mod tests { use super::*; + /// The arrow's point on a picked edge: one point, a zero-length piece, a click past the end. + #[test] + fn nearest_on_polyline_handles_short_edges_and_clicks_past_the_end() { + let p = |x: f64, y: f64| Vec3::new(x, y, 0.0); + assert_eq!(nearest_on_polyline(&[], p(1.0, 1.0)), None); + assert_eq!(nearest_on_polyline(&[p(2.0, 3.0)], p(9.0, 9.0)), Some(p(2.0, 3.0))); + assert_eq!(nearest_on_polyline(&[p(2.0, 3.0), p(2.0, 3.0)], p(9.0, 9.0)), Some(p(2.0, 3.0))); + let edge = [p(0.0, 0.0), p(0.0, 0.0), p(10.0, 0.0)]; + assert_eq!(nearest_on_polyline(&edge, p(4.0, 2.0)), Some(p(4.0, 0.0))); + assert_eq!(nearest_on_polyline(&edge, p(15.0, 1.0)), Some(p(10.0, 0.0))); + assert_eq!(nearest_on_polyline(&edge, p(-3.0, -1.0)), Some(p(0.0, 0.0))); + } + #[test] fn offset_plane_preview_stays_within_its_square() { let rect = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 0e323356d..98ef7c920 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -508,6 +508,9 @@ pub struct Dialog { pub press_pull: bool, /// The operation the window chooses by itself (#6901). pub op_auto: crate::op_auto::OpAuto, + /// Where the face that reopened this fillet or chamfer was clicked (Press Pull): its arrow + /// sits on the edge nearest it. UI state only, never saved. + pub(crate) anchor_hint: Option, } #[derive(Clone, Debug)] @@ -764,6 +767,7 @@ impl Dialog { shell_chain: Default::default(), press_pull: false, op_auto: Default::default(), + anchor_hint: None, } } diff --git a/crates/ui-egui/src/documents.rs b/crates/ui-egui/src/documents.rs index a17a7efda..af6cc8be7 100644 --- a/crates/ui-egui/src/documents.rs +++ b/crates/ui-egui/src/documents.rs @@ -234,6 +234,8 @@ fn swap_in(app: &mut SolveApp, mut slot: DocSlot) -> DocSlot { crate::agent_chat::leave_document(app); app.agent_chat.swap_document(&mut slot.agent_chat); let out_rev = app.session.revision; + // A click's point means nothing in the other design. + app.edit_anchor_hint = None; let mut out = DocSlot { session: std::mem::replace(&mut app.session, slot.session), autosave: app.autosave.as_mut().and_then(|a| std::mem::replace(&mut a.active, slot.autosave)), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 58674104c..95f8f95ef 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -594,6 +594,8 @@ pub struct SolveApp { /// A linked component's design edited in place, with its assembly around it. pub edit_in_place: edit_in_place::EditInPlace, pub(crate) pending_feature_edit: Option, + /// The feature being reopened from a click and where, until its dialog opens (UI state only). + edit_anchor_hint: Option<(u64, solidcraft_engine::geom::Vec3)>, /// The open feature window's check of what its material does (#6901). pub op_check: op_auto::OpCheck, /// A command recomputing the history (the marker moved, undo) computing off the window @@ -828,6 +830,7 @@ impl SolveApp { editing_state: None, edit_in_place: Default::default(), pending_feature_edit: None, + edit_anchor_hint: None, op_check: op_auto::OpCheck::default(), deferred: None, deferred_queue: Vec::new(), @@ -1851,9 +1854,9 @@ impl SolveApp { self.cancel_sketch(); return; } - // Press Pull: edges get a fillet, a fillet's round face reopens its fillet (its size - // changes, as `solid.press_pull` does: #1932), other curved faces an offset, planar faces - // and profiles an extrude. + // Press Pull: edges get a fillet, a fillet's round face or a chamfer's flat one reopens + // its feature (its size changes, as `solid.press_pull` does: #1932, #4986), other curved + // faces an offset, planar faces and profiles an extrude. if id == "solid.press_pull" { if let Some(pending) = &mut self.pending_feature_edit { pending.then_start(id); @@ -1863,16 +1866,18 @@ impl SolveApp { return self.start("solid.fillet"); } let sel = &self.session.selection; - let curved = sel.iter().find_map(|s| match s { - solidcraft_engine::Sel::Face { body, index, .. } if dialogs::planar_face(&self.session, body, *index).is_none() => { - Some((body, *index)) - } + let blend = sel.iter().find_map(|s| match s { + solidcraft_engine::Sel::Face { body, index, point } => dialogs::blend_feature(&self.session, body, *index).map(|id| (id, *point)), _ => None, }); - if let Some((body, index)) = curved { - if let Some(blend) = dialogs::blend_feature(&self.session, body, index) { - return self.edit_feature(blend); - } + // Its arrow sits on the edge of the face clicked. + if let Some((blend, point)) = blend { + return self.edit_feature_at(blend, Some(point)); + } + let curved = sel.iter().any( + |s| matches!(s, solidcraft_engine::Sel::Face { body, index, .. } if dialogs::planar_face(&self.session, body, *index).is_none()), + ); + if curved { return self.start("solid.offset_face"); } let empty = sel.is_empty(); @@ -2052,7 +2057,15 @@ impl SolveApp { /// Edit a feature: sketches open in sketch mode; other features roll the /// timeline back to just before themselves and reopen their dialog, filled in. pub fn edit_feature(&mut self, id: u64) { + self.edit_feature_at(id, None); + } + + /// [`Self::edit_feature`] opened from a click at `at` on what the feature made: the dialog's + /// arrow sits by that point (a fillet's or chamfer's edge nearest it). + pub(crate) fn edit_feature_at(&mut self, id: u64, at: Option) { use solidcraft_engine::doc::FeatureKind; + // A non-finite point (over the control channel) keeps the first edge. + self.edit_anchor_hint = at.filter(|p| p.is_finite()).map(|p| (id, p)); dialogs::cancel(self); let Some(f) = self.session.doc.feature(id) else { return }; if matches!(f.kind, FeatureKind::Sketch { .. }) { @@ -2075,8 +2088,12 @@ impl SolveApp { fn open_feature_edit(&mut self, id: u64, marker: Option, original: Session) { self.editing_state = Some(dialogs::EditingState { source: self.session.scratch(), original }); + // The id check matters while another feature's reopening is still pending: a later call + // for a feature id that is gone returns before it drops that pending edit. + let hint = self.edit_anchor_hint.take().filter(|(f, _)| *f == id).map(|(_, p)| p); match dialogs::for_feature(self, id, marker) { - Some(d) => { + Some(mut d) => { + d.anchor_hint = hint; if !d.previews() { self.editing_state = None; } diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index 846838ed5..713e311f9 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -942,6 +942,105 @@ fn fillet_face_then_press_pull_edits_its_fillet() { assert_eq!(d.editing.map(|e| e.0), Some(fillet)); } +/// Press Pull on a chamfer's flat face reopens the chamfer to change its distance, as on a +/// fillet's face, rather than extruding it (#4986): picked first, or picked with Press Pull +/// already open. +#[test] +fn chamfer_face_then_press_pull_edits_its_chamfer() { + let script = json!([ + {"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20}}, + {"command": "solid.chamfer", "params": {"edges": [[40, 0, 10]], "distance": 3}} + ]); + // The middle of the chamfer's face, from (37, 0) to (40, 3). + let p = Vec3::new(38.5, 1.5, 10.0); + let bevel = |app: &SolveApp| { + let names = solidcraft_engine::doc::naming::face_names_at(&app.session.model.state(), &[p]); + assert!(names[0].contains("blend"), "{names:?}"); + let st = app.session.model.state(); + let b = st.body("Body1").unwrap(); + let index = solidcraft_engine::doc::naming::face_names(b).iter().position(|n| *n == names[0]).unwrap(); + Sel::Face { body: "Body1".into(), index, point: p } + }; + let mut app = app_with(script.clone()); + let chamfer = app.session.doc.features.last().unwrap().id; + let sel = bevel(&app); + let d = start(&mut app, vec![sel], "solid.press_pull"); + assert!(matches!(&d.kind, Kind::Fillet { radius, chamfer: true, .. } if radius.starts_with('3')), "{:?}", d.kind); + assert_eq!(d.editing.map(|e| e.0), Some(chamfer)); + + let mut app = app_with(script); + app.start("solid.press_pull"); + let sel = bevel(&app); + let index = if let Sel::Face { index, .. } = &sel { *index } else { 0 }; + crate::viewport::dialog_pick(&mut app, &crate::viewport::Hit::Face { body: "Body1".into(), index, point: p }, sel); + let d = app.dialog.clone().unwrap(); + assert!(matches!(d.kind, Kind::Fillet { chamfer: true, .. }), "{:?}", d.kind); + assert_eq!(d.editing.map(|e| e.0), Some(chamfer)); +} + +/// Press Pull reopens a fillet or chamfer of several edges with its arrow on the edge of the face +/// clicked, not on the feature's first edge (the Sample Plate's far corner): picked first, or +/// picked with Press Pull open. Opened from the history, the arrow stays on the first edge. +#[test] +fn press_pull_on_a_blend_face_puts_the_arrow_on_the_clicked_edge() { + let r = 6.0 * std::f64::consts::FRAC_1_SQRT_2; + let chamfered = json!([ + {"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20}}, + {"command": "solid.chamfer", "params": {"edges": [[20, 0, 20], [40, 15, 20], [20, 30, 20], [0, 15, 20]], "distance": 2}} + ]); + // The script, the body, a point on the clicked blend face, its edge, the feature's first edge. + let cases = [ + (solidcraft_engine::sample::script(), "Plate", Vec3::new(74.0 + r, 44.0 + r, 4.0), Vec3::new(80.0, 50.0, 4.0), Vec3::new(0.0, 0.0, 4.0)), + (chamfered, "Body1", Vec3::new(20.0, 29.0, 19.0), Vec3::new(20.0, 30.0, 20.0), Vec3::new(20.0, 0.0, 20.0)), + ]; + for (script, body, p, clicked, first) in cases { + let setup = |h: &mut crate::scenario::Harness| -> Sel { + h.app.session.run_script(&script).unwrap(); + h.frames(2); + h.step(&json!({"call": "ui.view", "params": {"view": "fit"}})).unwrap(); + let names = solidcraft_engine::doc::naming::face_names_at(&h.app.session.model.state(), &[p]); + assert!(names[0].contains("blend"), "{names:?}"); + let st = h.app.session.model.state(); + let index = solidcraft_engine::doc::naming::face_names(st.body(body).unwrap()).iter().position(|n| *n == names[0]).unwrap(); + Sel::Face { body: body.into(), index, point: p } + }; + // The arrow is nearer `want` than `other` on screen. + let arrow_near = |h: &mut crate::scenario::Harness, want: Vec3, other: Vec3, how: &str| { + h.frames(5); + assert!( + matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(Kind::Fillet { .. })), + "{body} {how}: {:?}", + h.app.dialog.as_ref().map(|d| &d.kind) + ); + let tip = crate::scenario::handle_at("arrow").unwrap_or_else(|| panic!("{body} {how}: no arrow")); + let mut dist = |w: Vec3| { + let [x, y] = h.at(&json!({"world": [w.x, w.y, w.z]})).unwrap(); + tip.distance(egui::pos2(x as f32, y as f32)) + }; + let (a, b) = (dist(want), dist(other)); + assert!(a < b, "{body} {how}: the arrow is {a} px from the edge it should be on, {b} px from the other"); + }; + let mut h = crate::scenario::Harness::new(); + let face = setup(&mut h); + h.app.session.selection = vec![face]; + h.step(&json!({"start": "solid.press_pull"})).unwrap(); + arrow_near(&mut h, clicked, first, "picked first"); + // No click to go by: the feature's first edge, as before. + let id = h.app.dialog.as_ref().and_then(|d| d.editing).map(|e| e.0).unwrap(); + crate::dialogs::cancel(&mut h.app); + h.step(&json!({"call": "ui.editFeature", "params": {"feature": id}})).unwrap(); + arrow_near(&mut h, first, clicked, "from the history"); + + let mut h = crate::scenario::Harness::new(); + let face = setup(&mut h); + h.step(&json!({"start": "solid.press_pull"})).unwrap(); + let index = if let Sel::Face { index, .. } = &face { *index } else { 0 }; + let hit = crate::viewport::Hit::Face { body: body.into(), index, point: p }; + crate::viewport::dialog_pick(&mut h.app, &hit, face); + arrow_near(&mut h, clicked, first, "picked with Press Pull open"); + } +} + #[test] fn faces_then_shell_and_face_then_hole() { let mut app = boxed(); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index b33f196da..074e2c05b 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -3201,13 +3201,17 @@ pub(crate) fn dialog_pick(app: &mut SolveApp, hit: &Hit, sel: Sel) { if app.applying.is_some() { return; } - // Press Pull's first pick of a curved face or an edge reopens it as an offset or a fillet. + // Press Pull's first pick of a curved face, a chamfer's face or an edge reopens it as an + // offset, the chamfer or a fillet. if let Some(d) = &app.dialog && d.press_pull && d.inputs.first().is_some_and(|i| i.items.is_empty()) && match &sel { Sel::Edge { .. } => true, - Sel::Face { body, index, .. } => crate::dialogs::planar_face(&app.session, body, *index).is_none(), + Sel::Face { body, index, .. } => { + crate::dialogs::planar_face(&app.session, body, *index).is_none() + || crate::dialogs::blend_feature(&app.session, body, *index).is_some() + } _ => false, } { From 9efcb461f859155f0ea4226e34d119627237c150 Mon Sep 17 00:00:00 2001 From: Kai Evans Date: Sun, 1 Nov 2026 20:11:05 +0000 Subject: [PATCH 23/55] Feature edits: OK computes off the window thread in a dialog without a live preview too (#7388) Offset Plane and a cosmetic Thread have no live preview, so their edits' OK ran on the window thread and recomputed every later feature there. Any edit now goes through the off-thread transaction. The editor's pinned original is used only while the dialog previews, as open_feature_edit keeps it: a Thread switched from Modeled to cosmetic edits the design as it is, so a body hidden meanwhile doesn't refuse it as a changed design. --- crates/ui-egui/src/apply_off_thread_tests.rs | 36 ++++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 10 ++++-- crates/ui-egui/src/preselect_tests.rs | 33 ++++++++++++++++++ 3 files changed, 76 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/apply_off_thread_tests.rs b/crates/ui-egui/src/apply_off_thread_tests.rs index b177fef68..ec98b1203 100644 --- a/crates/ui-egui/src/apply_off_thread_tests.rs +++ b/crates/ui-egui/src/apply_off_thread_tests.rs @@ -336,6 +336,42 @@ fn changed_first_cut_adopts_its_entire_suffix_without_window_evaluation() { assert!((redone - after_volume).abs() < 0.001); } +/// An edit in a dialog without a live preview (Offset Plane) is computed off the window thread +/// too: OK evaluates nothing here, the features after the plane included. +#[test] +fn an_edit_without_a_preview_adopts_its_suffix_without_window_evaluation() { + let mut h = Harness::new(); + h.app.home.open = false; + h.app.apply_off_thread = Some(Duration::ZERO); + h.app.run("construct.plane.offset", json!({"base":"XY","offset":10,"name":"Shelf"})).unwrap(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.app.run("solid.box", json!({"corner":[5,5,20],"length":10,"width":10,"height":5,"operation":"join"})).unwrap(); + let plane = h.app.session.doc.find_feature("Shelf").unwrap().id; + let undo = h.app.session.undo.len(); + h.call("ui.editFeature", json!({"feature":plane})); + h.frames(2); + assert!(h.app.dialog.as_ref().is_some_and(|d| !d.previews()), "Offset Plane has no live preview"); + if let Some(crate::dialogs::Kind::OffsetPlane { offset }) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + *offset = "15".into(); + } + let window = std::sync::Arc::new(solidcraft_engine::doc::progress::Progress::default()); + solidcraft_engine::doc::progress::watch(window.clone(), || { + h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap(); + assert!(h.app.applying.is_some(), "computing beside the window"); + until_applied(&mut h); + }); + assert_eq!(window.features(), (0, 0), "nothing evaluated on the window thread"); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + assert_eq!(h.app.session.doc.marker, None); + assert_eq!(h.app.session.undo.len(), undo + 1); + let shelf = &h.app.session.doc.feature(plane).unwrap().kind; + assert!( + matches!(shelf, solidcraft_engine::doc::FeatureKind::ConstructionPlane { plane: solidcraft_engine::doc::PlaneRef::Offset { distance, .. } } if *distance == "15"), + "{shelf:?}" + ); + h.step(&json!({"expect":{"bodies":1,"volume":24500}})).unwrap(); +} + #[test] fn cancelling_an_edit_restores_pinned_geometry_without_evaluating_an_evicted_suffix() { let (mut h, target) = cut_chain(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 98ef7c920..3f827d9e3 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -548,8 +548,11 @@ impl DialogComputation { session, cmds, marker: d.editing.map(|(_, marker)| marker), + // The editor's pinned original is for a dialog that previews (as `open_feature_edit` + // keeps it); one that no longer does (Modeled unticked) edits the design as it is. editing: d .editing + .filter(|_| d.previews()) .and(app.editing_state.as_ref()) .map(|state| EditingState { source: state.source.scratch(), original: state.original.scratch() }), }) @@ -619,12 +622,13 @@ fn display_quality(app: &SolveApp) -> solidcraft_engine::doc::display_quality::D solidcraft_engine::doc::display_quality::DisplayQuality::parse(&app.preferences.display_quality).unwrap_or_default() } -/// Desktop feature dialogs evaluate the entire command and its dependent suffix once. -/// Results wait until a later frame before adoption, keeping the computing state visible. +/// Desktop feature dialogs evaluate the entire command and its dependent suffix once; so does +/// any feature edit, with a live preview or without. Results wait until a later frame before +/// adoption, keeping the computing state visible. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn begin_applying(app: &SolveApp, d: &Dialog) -> Option { let wait = app.apply_off_thread?; - if !d.previews() { + if !d.previews() && d.editing.is_none() { return None; } let computation = DialogComputation::new(app, d).ok()?; diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rs index 713e311f9..8c633f0a9 100644 --- a/crates/ui-egui/src/preselect_tests.rs +++ b/crates/ui-egui/src/preselect_tests.rs @@ -1699,6 +1699,39 @@ fn modeled_thread_survives_timeline_double_click_and_ok() { } } +/// A modeled thread's editor previews; unticking Modeled makes it a plain edit, so its OK +/// computes off the window thread from the design as it is: a body hidden meanwhile doesn't +/// refuse it as a changed design. +#[test] +fn a_thread_edit_switched_to_cosmetic_applies_after_a_body_is_hidden() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.apply_off_thread = Some(std::time::Duration::ZERO); + h.app.run("solid.cylinder", json!({"radius":4,"height":4})).unwrap(); + h.app.run("solid.box", json!({"corner":[20,0,0],"length":4,"width":4,"height":4})).unwrap(); + let Sel::Face { point, .. } = thread_face(&h.app, "Body1") else { panic!("face") }; + let id = h.app.run("solid.thread", json!({"face":point,"designation":"M8x1","modeled":true})).unwrap()["feature"].as_u64().unwrap(); + h.frames(4); + h.step(&json!({"click":{"handle":"timeline:Thread1"},"double":true})).unwrap(); + h.frames(4); + assert!(h.app.dialog.as_ref().unwrap().previews(), "a modeled thread previews"); + h.app.dialog.as_mut().unwrap().extra["modeled"] = json!(false); + assert!(!h.app.dialog.as_ref().unwrap().previews()); + h.app.run("browser.visibility", json!({"items":["Body2"],"visible":false})).unwrap(); + h.step(&json!({"widget":"OK"})).unwrap(); + for _ in 0..500 { + if h.app.applying.is_none() { + break; + } + h.frames(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + h.frames(4); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|d| d.error.clone())); + assert_eq!(h.app.session.doc.marker, None); + assert!(matches!(h.app.session.doc.feature(id).unwrap().kind, solidcraft_engine::doc::FeatureKind::Thread { modeled: false, .. })); +} + #[test] fn planar_face_reopen_keeps_the_tight_pick_tolerance() { for (command, mut params, point) in [ From 89cb651084fa9d1bd780a6a64108d3fbd052cb34 Mon Sep 17 00:00:00 2001 From: semmelrinde <124386289+semmelrinde@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:12:42 +0000 Subject: [PATCH 24/55] Warnings: quote a long generated name by its start and end (#8673) A chamfer's warning quoted the full generated names of fourteen split edges, 122,701 characters (#8541). Names over about 80 characters are now quoted by their first 48 and last 24 characters. Co-authored-by: Claude Opus 5.5 --- crates/doc/src/eval.rs | 9 +++++---- crates/doc/src/eval_more.rs | 5 ++++- crates/doc/src/name_lookup.rs | 24 ++++++++++++++++++++---- crates/doc/src/project.rs | 2 +- crates/doc/src/tests.rs | 15 +++++++++++++++ 5 files changed, 45 insertions(+), 10 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 5101f1efa..caffae2f9 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -4310,7 +4310,8 @@ fn blend_edges_on(mb: &ModelBody, f: &Feature, edges: &[crate::Position], idx: & Some((_, Err(_))) | None => { let mut w = None; let refs: Vec = f.edge_refs.get(i).cloned().into_iter().collect(); - let skipped = format!("edge `{}` no longer exists and was skipped", stored.map(String::as_str).unwrap_or("?")); + let skipped = + format!("edge `{}` no longer exists and was skipped", stored.map_or_else(|| "?".into(), |n| crate::name_lookup::quoted(n))); // The name is gone. A pick on the axis of a round must not fall through to the // tangency seam (#775). A sharp edge that moved still resolves from the point, // which an edit relies on. @@ -4319,7 +4320,7 @@ fn blend_edges_on(mb: &ModelBody, f: &Feature, edges: &[crate::Position], idx: & } else if let Ok(q) = resolve_edges(&mb.body, &[p], &refs, &mut w) { out.extend(q); notes.push(match stored { - Some(n) => format!("edge `{n}` no longer exists; using the edge at the picked point"), + Some(n) => format!("edge `{}` no longer exists; using the edge at the picked point", crate::name_lookup::quoted(n)), None => "an edge reference without a name was found by its point".into(), }); } else { @@ -7215,10 +7216,10 @@ fn face_plane(st: &ModelState, picked: &Plane, at: Vec3, name: Option<&str>) -> let note = if crate::naming::legacy_name(name).is_some() { None } else if !crate::naming::face_has_name(b, f.index, name) { - Some(format!("face `{name}` was split; using the piece nearest the picked point")) + Some(format!("face `{}` was split; using the piece nearest the picked point", crate::name_lookup::quoted(name))) } else if !crate::naming::face_name_exact(b, f.index) && (f.centroid - at).dot(n).abs() > tol { // Named from geometry and moved off the picked plane: geometry alone decided. - Some(format!("face `{name}` was found by geometry, not exact history; check it")) + Some(format!("face `{}` was found by geometry, not exact history; check it", crate::name_lookup::quoted(name))) } else { None }; diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rs index 7a5b7c0f7..9cc895242 100644 --- a/crates/doc/src/eval_more.rs +++ b/crates/doc/src/eval_more.rs @@ -802,7 +802,10 @@ pub(super) fn sheet_eval( hit.point } Some((n, Err(_))) => { - append_warning(warning, format!("edge `{n}` no longer exists; using the edge at the picked point")); + append_warning( + warning, + format!("edge `{}` no longer exists; using the edge at the picked point", crate::name_lookup::quoted(n)), + ); p.0 } None => p.0, diff --git a/crates/doc/src/name_lookup.rs b/crates/doc/src/name_lookup.rs index 003f17d7b..44f941c22 100644 --- a/crates/doc/src/name_lookup.rs +++ b/crates/doc/src/name_lookup.rs @@ -203,11 +203,11 @@ impl FaceHit { /// What a feature says about how it found a face by its stored name `name` (`None`: exactly). pub fn note(&self, name: &str) -> Option { if self.split { - Some(format!("face `{name}` was split; using the piece nearest the picked point")) + Some(format!("face `{}` was split; using the piece nearest the picked point", quoted(name))) } else if self.merged { Some(format!("face `{name}` was merged into another face; using that face")) } else if !self.verified && !self.on_point && !self.legacy { - Some(format!("face `{name}` was found by geometry, not exact history; check it")) + Some(format!("face `{}` was found by geometry, not exact history; check it", quoted(name))) } else { None } @@ -243,13 +243,29 @@ impl FaceHit { } } +/// A stored name as a message quotes it: whole up to about 80 characters, else its start and +/// end around an ellipsis. Generated names grow with the history (a split edge's name holds both +/// its faces' names), and a chamfer's warning that quoted fourteen of them in full ran to 122,701 +/// characters (#8541). +pub(crate) fn quoted(name: &str) -> String { + const HEAD: usize = 48; + const TAIL: usize = 24; + let n = name.chars().count(); + if n <= HEAD + TAIL + 8 { + return name.to_string(); + } + let head: String = name.chars().take(HEAD).collect(); + let tail: String = name.chars().skip(n - TAIL).collect(); + format!("{head}…{tail}") +} + impl EdgeHit { /// What a feature says about how it found an edge by its stored name `name` (`None`: exactly). pub fn note(&self, name: &str) -> Option { if self.split { - Some(format!("edge `{name}` was split; using the piece nearest the picked point")) + Some(format!("edge `{}` was split; using the piece nearest the picked point", quoted(name))) } else if !self.verified && !self.on_point && !self.legacy { - Some(format!("edge `{name}` was found by geometry, not exact history; check it")) + Some(format!("edge `{}` was found by geometry, not exact history; check it", quoted(name))) } else { None } diff --git a/crates/doc/src/project.rs b/crates/doc/src/project.rs index b705ea326..3887765b7 100644 --- a/crates/doc/src/project.rs +++ b/crates/doc/src/project.rs @@ -738,7 +738,7 @@ fn refresh_links_in( *at = p; named_face = Some((body.clone(), index, p)); if split { - warn.push(format!("projected face `{name}` was split; using the nearest piece")); + warn.push(format!("projected face `{}` was split; using the nearest piece", crate::name_lookup::quoted(name))); } } else { sk.set_link_lost(&l.id, true); diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index e3051078a..0d21d014e 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -159,6 +159,21 @@ fn results_kept_ahead_outlive_the_cache() { assert!(rel(measure(&m.state().bodies[0].body).unwrap().volume, 30000.0) < 1e-9); } +/// A warning quotes a long generated name by its start and end (#8541: fourteen split edges' +/// full names made one chamfer warning 122,701 characters long); a short name stays whole. +#[test] +fn warnings_quote_long_names_by_their_ends() { + let face = |i: usize| format!("Extrude{i}.side(Sketch{i}.l{i})·Fillet{i}.blend(Chamfer{i}.cap)"); + let long = (0..40).map(face).collect::>().join("|"); + let q = crate::name_lookup::quoted(&long); + assert!(q.chars().count() <= 80, "{q}"); + assert!(q.starts_with("Extrude0.side") && q.ends_with(&long[long.len() - 10..]) && q.contains('…'), "{q}"); + assert_eq!(crate::name_lookup::quoted("Extrude1.side|Box1.top"), "Extrude1.side|Box1.top"); + // Characters, not bytes: a name of non-ASCII characters is cut between characters. + let wide = "Ü".repeat(200); + assert_eq!(crate::name_lookup::quoted(&wide).chars().count(), 73); +} + /// A saved model whose feature warning is longer than 65,536 characters is still taken on open /// (#8541): Save writes it, so Open reads it. #[test] From d730a273dc806fce76bc3c9c440bfbada75bb99c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:33:02 +0000 Subject: [PATCH 25/55] Regenerate generated files and fold pending files [skip ci] --- assets/locales/ar.json | 9 ++ assets/locales/de.json | 9 ++ assets/locales/en.json | 9 ++ assets/locales/he.json | 9 ++ assets/locales/ja.json | 9 ++ assets/locales/ko.json | 9 ++ .../pending/agent-chat-model-picker.json | 90 ------------------- assets/locales/vi.json | 9 ++ assets/locales/zh.json | 9 ++ 9 files changed, 72 insertions(+), 90 deletions(-) delete mode 100644 assets/locales/pending/agent-chat-model-picker.json diff --git a/assets/locales/ar.json b/assets/locales/ar.json index 22a35f53d..b77cbf2d8 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -4128,6 +4128,7 @@ "ui.agent_chat_ctx_features": "الميزات", "ui.agent_chat_ctx_more": "+{n} أخرى", "ui.agent_chat_ctx_other": "أخرى", + "ui.agent_chat_custom_heading": "نموذج مخصص", "ui.agent_chat_custom_hint": "أي برنامج يتحدث بروتوكول Agent Client Protocol عبر stdin وstdout. لا تشغّله أي صدفة أوامر.", "ui.agent_chat_denied": "مرفوض", "ui.agent_chat_deny": "رفض", @@ -4171,8 +4172,16 @@ "ui.agent_chat_mode_all": "الكل", "ui.agent_chat_mode_ask": "السؤال", "ui.agent_chat_mode_edits": "التعديلات", + "ui.agent_chat_model_custom": "استخدام المخصص: {model}", "ui.agent_chat_model_no_tools": "لا يستطيع {model} استخدام أدوات SolidCraft، لذا يمكنه المحادثة فقط. اختر نموذجًا يدعم الأدوات.", + "ui.agent_chat_model_rejected": "لم يقبل الوكيل {model}: {error}", + "ui.agent_chat_model_search": "البحث عن النماذج…", "ui.agent_chat_model_tip": "النموذج الذي يستخدمه الوكيل. يُحفظ اختيارك لهذا الوكيل.", + "ui.agent_chat_models_failed": "تعذّر جلب قائمة النماذج: {error}", + "ui.agent_chat_models_heading": "النماذج المتاحة", + "ui.agent_chat_models_listing": "جارٍ جلب قائمة النماذج…", + "ui.agent_chat_models_none": "لا تسرد نقطة النهاية أي نماذج", + "ui.agent_chat_models_not_a_list": "لم يكن الرد قائمة نماذج", "ui.agent_chat_new": "محادثة جديدة", "ui.agent_chat_new_confirm": "بدء محادثة جديدة؟ ستُمسح المحادثة الحالية.", "ui.agent_chat_next_picture": "الصورة التالية", diff --git a/assets/locales/de.json b/assets/locales/de.json index e50bc40dd..69a0d4050 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -4123,6 +4123,7 @@ "ui.agent_chat_ctx_features": "Funktionen", "ui.agent_chat_ctx_more": "+{n} weitere", "ui.agent_chat_ctx_other": "Sonstiges", + "ui.agent_chat_custom_heading": "Eigenes Modell", "ui.agent_chat_custom_hint": "Jedes Programm, das das Agent Client Protocol über stdin und stdout spricht. Es läuft ohne Shell.", "ui.agent_chat_denied": "Abgelehnt", "ui.agent_chat_deny": "Ablehnen", @@ -4166,8 +4167,16 @@ "ui.agent_chat_mode_all": "Alles", "ui.agent_chat_mode_ask": "Fragen", "ui.agent_chat_mode_edits": "Ändern", + "ui.agent_chat_model_custom": "Eigenes verwenden: {model}", "ui.agent_chat_model_no_tools": "{model} kann die Werkzeuge von SolidCraft nicht verwenden und daher nur chatten. Wählen Sie ein Modell mit Werkzeugunterstützung.", + "ui.agent_chat_model_rejected": "Der Agent hat {model} nicht akzeptiert: {error}", + "ui.agent_chat_model_search": "Modelle suchen…", "ui.agent_chat_model_tip": "Das vom Agenten verwendete Modell. Ihre Auswahl wird für diesen Agenten gespeichert.", + "ui.agent_chat_models_failed": "Modelle konnten nicht abgerufen werden: {error}", + "ui.agent_chat_models_heading": "Verfügbare Modelle", + "ui.agent_chat_models_listing": "Modelle werden abgerufen…", + "ui.agent_chat_models_none": "Der Endpunkt listet keine Modelle", + "ui.agent_chat_models_not_a_list": "Die Antwort war keine Modellliste", "ui.agent_chat_new": "Neuer Chat", "ui.agent_chat_new_confirm": "Neuen Chat starten? Der aktuelle wird geleert.", "ui.agent_chat_next_picture": "Nächstes Bild", diff --git a/assets/locales/en.json b/assets/locales/en.json index 9824d4a5c..3854bd08f 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -4128,6 +4128,7 @@ "ui.agent_chat_ctx_features": "Features", "ui.agent_chat_ctx_more": "+{n} more", "ui.agent_chat_ctx_other": "Other", + "ui.agent_chat_custom_heading": "Custom model", "ui.agent_chat_custom_hint": "Any program that speaks the Agent Client Protocol on stdin and stdout. No shell runs it.", "ui.agent_chat_denied": "Denied", "ui.agent_chat_deny": "Deny", @@ -4171,8 +4172,16 @@ "ui.agent_chat_mode_all": "All", "ui.agent_chat_mode_ask": "Ask", "ui.agent_chat_mode_edits": "Edits", + "ui.agent_chat_model_custom": "Use custom: {model}", "ui.agent_chat_model_no_tools": "{model} can't use SolidCraft's tools, so it can only chat. Pick a model with tool support.", + "ui.agent_chat_model_rejected": "The agent did not accept {model}: {error}", + "ui.agent_chat_model_search": "Search models…", "ui.agent_chat_model_tip": "The model the agent uses. Your choice is remembered for this agent.", + "ui.agent_chat_models_failed": "Couldn't list models: {error}", + "ui.agent_chat_models_heading": "Available models", + "ui.agent_chat_models_listing": "Listing models…", + "ui.agent_chat_models_none": "The endpoint lists no models", + "ui.agent_chat_models_not_a_list": "The answer was no model list", "ui.agent_chat_new": "New chat", "ui.agent_chat_new_confirm": "Start a new chat? The current one is cleared.", "ui.agent_chat_next_picture": "Next picture", diff --git a/assets/locales/he.json b/assets/locales/he.json index 1a63962bd..101aa8bef 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -4128,6 +4128,7 @@ "ui.agent_chat_ctx_features": "פיצ'רים", "ui.agent_chat_ctx_more": "+{n} נוספים", "ui.agent_chat_ctx_other": "אחר", + "ui.agent_chat_custom_heading": "מודל מותאם אישית", "ui.agent_chat_custom_hint": "כל תוכנה שמדברת Agent Client Protocol דרך stdin ו־stdout. היא לא מורצת דרך מעטפת (shell).", "ui.agent_chat_denied": "נדחה", "ui.agent_chat_deny": "דחייה", @@ -4171,8 +4172,16 @@ "ui.agent_chat_mode_all": "הכול", "ui.agent_chat_mode_ask": "שאלה", "ui.agent_chat_mode_edits": "עריכות", + "ui.agent_chat_model_custom": "שימוש במותאם אישית: {model}", "ui.agent_chat_model_no_tools": "{model} לא יכול להשתמש בכלים של SolidCraft, ולכן הוא יכול רק לשוחח. יש לבחור מודל שתומך בכלים.", + "ui.agent_chat_model_rejected": "הסוכן לא קיבל את {model}: {error}", + "ui.agent_chat_model_search": "חיפוש מודלים…", "ui.agent_chat_model_tip": "המודל שבו הסוכן משתמש. הבחירה נשמרת עבור הסוכן הזה.", + "ui.agent_chat_models_failed": "לא ניתן היה לטעון את רשימת המודלים: {error}", + "ui.agent_chat_models_heading": "מודלים זמינים", + "ui.agent_chat_models_listing": "טוען רשימת מודלים…", + "ui.agent_chat_models_none": "נקודת הקצה אינה מציגה מודלים", + "ui.agent_chat_models_not_a_list": "התשובה לא הייתה רשימת מודלים", "ui.agent_chat_new": "צ'אט חדש", "ui.agent_chat_new_confirm": "להתחיל צ'אט חדש? הצ'אט הנוכחי יימחק.", "ui.agent_chat_next_picture": "התמונה הבאה", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 17424db1a..53303ab8a 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -4128,6 +4128,7 @@ "ui.agent_chat_ctx_features": "フィーチャ", "ui.agent_chat_ctx_more": "ほか{n}件", "ui.agent_chat_ctx_other": "その他", + "ui.agent_chat_custom_heading": "カスタムモデル", "ui.agent_chat_custom_hint": "標準入出力で Agent Client Protocol を話す任意のプログラム。シェルは使いません。", "ui.agent_chat_denied": "拒否しました", "ui.agent_chat_deny": "拒否", @@ -4171,8 +4172,16 @@ "ui.agent_chat_mode_all": "すべて", "ui.agent_chat_mode_ask": "確認", "ui.agent_chat_mode_edits": "編集", + "ui.agent_chat_model_custom": "カスタムを使用: {model}", "ui.agent_chat_model_no_tools": "{model} は SolidCraft のツールを使えず、チャットのみ可能です。ツール対応のモデルを選んでください。", + "ui.agent_chat_model_rejected": "エージェントは {model} を受け付けませんでした: {error}", + "ui.agent_chat_model_search": "モデルを検索…", "ui.agent_chat_model_tip": "エージェントが使うモデル。選択はこのエージェントに対して記憶されます。", + "ui.agent_chat_models_failed": "モデルを一覧表示できませんでした: {error}", + "ui.agent_chat_models_heading": "利用可能なモデル", + "ui.agent_chat_models_listing": "モデルを一覧表示中…", + "ui.agent_chat_models_none": "エンドポイントにモデルがありません", + "ui.agent_chat_models_not_a_list": "応答はモデル一覧ではありませんでした", "ui.agent_chat_new": "新しいチャット", "ui.agent_chat_new_confirm": "新しいチャットを始めますか? 現在のチャットは消去されます。", "ui.agent_chat_next_picture": "次の画像", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index a8b8a68a8..2304b0375 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -2957,6 +2957,7 @@ "ui.agent_chat_command": "에이전트 명령", "ui.agent_chat_connect": "연결", "ui.agent_chat_copy": "복사", + "ui.agent_chat_custom_heading": "사용자 지정 모델", "ui.agent_chat_custom_hint": "표준 입출력으로 Agent Client Protocol을 사용하는 모든 프로그램. 셸 없이 실행됩니다.", "ui.agent_chat_denied": "거부함", "ui.agent_chat_deny": "거부", @@ -2998,7 +2999,15 @@ "ui.agent_chat_mode_all": "모두", "ui.agent_chat_mode_ask": "확인", "ui.agent_chat_mode_edits": "편집", + "ui.agent_chat_model_custom": "직접 입력 사용: {model}", + "ui.agent_chat_model_rejected": "에이전트가 {model}을(를) 받아들이지 않았습니다: {error}", + "ui.agent_chat_model_search": "모델 검색…", "ui.agent_chat_model_tip": "에이전트가 사용하는 모델입니다. 선택은 이 에이전트에 기억됩니다.", + "ui.agent_chat_models_failed": "모델 목록을 가져올 수 없습니다: {error}", + "ui.agent_chat_models_heading": "사용 가능한 모델", + "ui.agent_chat_models_listing": "모델 목록을 가져오는 중…", + "ui.agent_chat_models_none": "엔드포인트에 나열된 모델이 없습니다", + "ui.agent_chat_models_not_a_list": "응답이 모델 목록이 아닙니다", "ui.agent_chat_new": "새 채팅", "ui.agent_chat_new_confirm": "새 채팅을 시작할까요? 현재 채팅은 지워집니다.", "ui.agent_chat_next_picture": "다음 이미지", diff --git a/assets/locales/pending/agent-chat-model-picker.json b/assets/locales/pending/agent-chat-model-picker.json deleted file mode 100644 index c97b17710..000000000 --- a/assets/locales/pending/agent-chat-model-picker.json +++ /dev/null @@ -1,90 +0,0 @@ -{ - "en": { - "ui.agent_chat_custom_heading": "Custom model", - "ui.agent_chat_model_custom": "Use custom: {model}", - "ui.agent_chat_model_rejected": "The agent did not accept {model}: {error}", - "ui.agent_chat_model_search": "Search models…", - "ui.agent_chat_models_failed": "Couldn't list models: {error}", - "ui.agent_chat_models_heading": "Available models", - "ui.agent_chat_models_listing": "Listing models…", - "ui.agent_chat_models_none": "The endpoint lists no models", - "ui.agent_chat_models_not_a_list": "The answer was no model list" - }, - "de": { - "ui.agent_chat_custom_heading": "Eigenes Modell", - "ui.agent_chat_model_custom": "Eigenes verwenden: {model}", - "ui.agent_chat_model_rejected": "Der Agent hat {model} nicht akzeptiert: {error}", - "ui.agent_chat_model_search": "Modelle suchen…", - "ui.agent_chat_models_failed": "Modelle konnten nicht abgerufen werden: {error}", - "ui.agent_chat_models_heading": "Verfügbare Modelle", - "ui.agent_chat_models_listing": "Modelle werden abgerufen…", - "ui.agent_chat_models_none": "Der Endpunkt listet keine Modelle", - "ui.agent_chat_models_not_a_list": "Die Antwort war keine Modellliste" - }, - "ko": { - "ui.agent_chat_custom_heading": "사용자 지정 모델", - "ui.agent_chat_model_custom": "직접 입력 사용: {model}", - "ui.agent_chat_model_rejected": "에이전트가 {model}을(를) 받아들이지 않았습니다: {error}", - "ui.agent_chat_model_search": "모델 검색…", - "ui.agent_chat_models_failed": "모델 목록을 가져올 수 없습니다: {error}", - "ui.agent_chat_models_heading": "사용 가능한 모델", - "ui.agent_chat_models_listing": "모델 목록을 가져오는 중…", - "ui.agent_chat_models_none": "엔드포인트에 나열된 모델이 없습니다", - "ui.agent_chat_models_not_a_list": "응답이 모델 목록이 아닙니다" - }, - "ar": { - "ui.agent_chat_custom_heading": "نموذج مخصص", - "ui.agent_chat_model_custom": "استخدام المخصص: {model}", - "ui.agent_chat_model_rejected": "لم يقبل الوكيل {model}: {error}", - "ui.agent_chat_model_search": "البحث عن النماذج…", - "ui.agent_chat_models_failed": "تعذّر جلب قائمة النماذج: {error}", - "ui.agent_chat_models_heading": "النماذج المتاحة", - "ui.agent_chat_models_listing": "جارٍ جلب قائمة النماذج…", - "ui.agent_chat_models_none": "لا تسرد نقطة النهاية أي نماذج", - "ui.agent_chat_models_not_a_list": "لم يكن الرد قائمة نماذج" - }, - "he": { - "ui.agent_chat_custom_heading": "מודל מותאם אישית", - "ui.agent_chat_model_custom": "שימוש במותאם אישית: {model}", - "ui.agent_chat_model_rejected": "הסוכן לא קיבל את {model}: {error}", - "ui.agent_chat_model_search": "חיפוש מודלים…", - "ui.agent_chat_models_failed": "לא ניתן היה לטעון את רשימת המודלים: {error}", - "ui.agent_chat_models_heading": "מודלים זמינים", - "ui.agent_chat_models_listing": "טוען רשימת מודלים…", - "ui.agent_chat_models_none": "נקודת הקצה אינה מציגה מודלים", - "ui.agent_chat_models_not_a_list": "התשובה לא הייתה רשימת מודלים" - }, - "ja": { - "ui.agent_chat_custom_heading": "カスタムモデル", - "ui.agent_chat_model_custom": "カスタムを使用: {model}", - "ui.agent_chat_model_rejected": "エージェントは {model} を受け付けませんでした: {error}", - "ui.agent_chat_model_search": "モデルを検索…", - "ui.agent_chat_models_failed": "モデルを一覧表示できませんでした: {error}", - "ui.agent_chat_models_heading": "利用可能なモデル", - "ui.agent_chat_models_listing": "モデルを一覧表示中…", - "ui.agent_chat_models_none": "エンドポイントにモデルがありません", - "ui.agent_chat_models_not_a_list": "応答はモデル一覧ではありませんでした" - }, - "vi": { - "ui.agent_chat_custom_heading": "Mô hình tùy chỉnh", - "ui.agent_chat_model_custom": "Dùng tùy chỉnh: {model}", - "ui.agent_chat_model_rejected": "Tác tử không chấp nhận {model}: {error}", - "ui.agent_chat_model_search": "Tìm mô hình…", - "ui.agent_chat_models_failed": "Không thể lấy danh sách mô hình: {error}", - "ui.agent_chat_models_heading": "Các mô hình có sẵn", - "ui.agent_chat_models_listing": "Đang lấy danh sách mô hình…", - "ui.agent_chat_models_none": "Điểm cuối không liệt kê mô hình nào", - "ui.agent_chat_models_not_a_list": "Phản hồi không phải là danh sách mô hình" - }, - "zh": { - "ui.agent_chat_custom_heading": "自定义模型", - "ui.agent_chat_model_custom": "使用自定义:{model}", - "ui.agent_chat_model_rejected": "智能体未接受 {model}:{error}", - "ui.agent_chat_model_search": "搜索模型…", - "ui.agent_chat_models_failed": "无法列出模型:{error}", - "ui.agent_chat_models_heading": "可用模型", - "ui.agent_chat_models_listing": "正在列出模型…", - "ui.agent_chat_models_none": "该端点未列出任何模型", - "ui.agent_chat_models_not_a_list": "响应不是模型列表" - } -} diff --git a/assets/locales/vi.json b/assets/locales/vi.json index a57861425..902780f69 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -4128,6 +4128,7 @@ "ui.agent_chat_ctx_features": "Tính năng", "ui.agent_chat_ctx_more": "+{n} mục khác", "ui.agent_chat_ctx_other": "Khác", + "ui.agent_chat_custom_heading": "Mô hình tùy chỉnh", "ui.agent_chat_custom_hint": "Bất kỳ chương trình nào hỗ trợ giao thức Agent Client Protocol qua stdin và stdout. Không chạy qua shell hệ thống.", "ui.agent_chat_denied": "Đã từ chối", "ui.agent_chat_deny": "Từ chối", @@ -4171,8 +4172,16 @@ "ui.agent_chat_mode_all": "Tất cả", "ui.agent_chat_mode_ask": "Hỏi", "ui.agent_chat_mode_edits": "Chỉnh sửa", + "ui.agent_chat_model_custom": "Dùng tùy chỉnh: {model}", "ui.agent_chat_model_no_tools": "{model} không thể sử dụng các công cụ của SolidCraft nên chỉ có thể trò chuyện. Hãy chọn mô hình có hỗ trợ công cụ.", + "ui.agent_chat_model_rejected": "Tác tử không chấp nhận {model}: {error}", + "ui.agent_chat_model_search": "Tìm mô hình…", "ui.agent_chat_model_tip": "Mô hình AI đang sử dụng. Lựa chọn của bạn sẽ được ghi nhớ cho Agent này.", + "ui.agent_chat_models_failed": "Không thể lấy danh sách mô hình: {error}", + "ui.agent_chat_models_heading": "Các mô hình có sẵn", + "ui.agent_chat_models_listing": "Đang lấy danh sách mô hình…", + "ui.agent_chat_models_none": "Điểm cuối không liệt kê mô hình nào", + "ui.agent_chat_models_not_a_list": "Phản hồi không phải là danh sách mô hình", "ui.agent_chat_new": "Cuộc trò chuyện mới", "ui.agent_chat_new_confirm": "Bắt đầu cuộc trò chuyện mới? Cuộc trò chuyện hiện tại sẽ bị xóa.", "ui.agent_chat_next_picture": "Ảnh kế tiếp", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index f4522dc84..7a046bcc9 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -4128,6 +4128,7 @@ "ui.agent_chat_ctx_features": "特征", "ui.agent_chat_ctx_more": "另有 {n} 项", "ui.agent_chat_ctx_other": "其他", + "ui.agent_chat_custom_heading": "自定义模型", "ui.agent_chat_custom_hint": "任何通过标准输入输出使用 Agent Client Protocol 的程序。不经过 shell 运行。", "ui.agent_chat_denied": "已拒绝", "ui.agent_chat_deny": "拒绝", @@ -4171,8 +4172,16 @@ "ui.agent_chat_mode_all": "全部", "ui.agent_chat_mode_ask": "询问", "ui.agent_chat_mode_edits": "编辑", + "ui.agent_chat_model_custom": "使用自定义:{model}", "ui.agent_chat_model_no_tools": "{model} 无法使用 SolidCraft 的工具,只能聊天。请选择支持工具的模型。", + "ui.agent_chat_model_rejected": "智能体未接受 {model}:{error}", + "ui.agent_chat_model_search": "搜索模型…", "ui.agent_chat_model_tip": "智能体使用的模型。你的选择会为此智能体记住。", + "ui.agent_chat_models_failed": "无法列出模型:{error}", + "ui.agent_chat_models_heading": "可用模型", + "ui.agent_chat_models_listing": "正在列出模型…", + "ui.agent_chat_models_none": "该端点未列出任何模型", + "ui.agent_chat_models_not_a_list": "响应不是模型列表", "ui.agent_chat_new": "新对话", "ui.agent_chat_new_confirm": "开始新对话?当前对话将被清除。", "ui.agent_chat_next_picture": "下一张图片", From 84c3b6356c334c1bbc3ca2b04bb1058710ca9a53 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:42:12 +0000 Subject: [PATCH 26/55] Regenerate generated files and fold pending files [skip ci] --- assets/locales/ar.json | 4 ++ assets/locales/de.json | 4 ++ assets/locales/en.json | 4 ++ assets/locales/he.json | 4 ++ assets/locales/ja.json | 4 ++ assets/locales/ko.json | 4 ++ .../locales/pending/color-channel-names.json | 42 ------------------- .../pending/loft-sections-one-sketch.json | 26 ------------ assets/locales/vi.json | 4 ++ assets/locales/zh.json | 4 ++ 10 files changed, 32 insertions(+), 68 deletions(-) delete mode 100644 assets/locales/pending/color-channel-names.json delete mode 100644 assets/locales/pending/loft-sections-one-sketch.json diff --git a/assets/locales/ar.json b/assets/locales/ar.json index b77cbf2d8..41668bdbd 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -556,6 +556,7 @@ "Section": "مقطع", "Section (optional)": "المقطع (اختياري)", "Section position": "موضع المقطع", + "Sections": "المقاطع", "Sections (one sketch each)": "المقاطع (رسم واحد لكل منها)", "Select Other": "تحديد آخر", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "تحديد آخر: أبقِ الزر الأيسر ثابتًا على النموذج (أو انقر بالزر الأيمن › تحديد آخر…) لعرض كل ما تحت المؤشر؛ وانقر مرة أخرى في الموضع نفسه لتحديد العنصر التالي هناك. انقر نقرًا مزدوجًا بالزر الأوسط للانتقال إلى العرض الرئيسي (التفضيلات › التنقل).", @@ -1299,9 +1300,11 @@ "cmd.view_tool": "أداة التنقل", "cmd.view_top": "العرض العلوي", "cmd.view_visual_style": "نمط العرض", + "color.blue": "أزرق", "color.copy": "انقر لنسخ قيم اللون", "color.edit": "انقر لتعديل اللون", "color.gamma": "عرض قيم اللون في نطاق جاما 0-255", + "color.green": "أخضر", "color.hex": "Hex", "color.hex_help": "أدخل #rrggbb أو #rrggbbaa؛ مع الخانات الست تبقى العتامة كما هي", "color.hex_hint": "#rrggbb", @@ -1309,6 +1312,7 @@ "color.linear": "عرض قيم اللون في النطاق الخطي 0-1", "color.recent": "الألوان الأخيرة", "color.recent_help": "تظهر هنا الألوان التي تختارها في أي حقل لون", + "color.red": "أحمر", "color.saturation": "التشبع (بالمئة)", "color.saturation_value": "التشبع والقيمة", "color.selected": "اللون المحدد", diff --git a/assets/locales/de.json b/assets/locales/de.json index 69a0d4050..27446fe97 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -556,6 +556,7 @@ "Section": "Schnitt", "Section (optional)": "Abschnitt (optional)", "Section position": "Lage des Querschnitts", + "Sections": "Querschnitte", "Sections (one sketch each)": "Querschnitte (je eine Skizze)", "Select Other": "Andere auswählen", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Anderes auswählen: Halten Sie die linke Taste ruhig auf dem Modell gedrückt (oder Rechtsklick › Anderes auswählen…), um alles unter dem Cursor aufzulisten; klicken Sie erneut an dieselbe Stelle, um das nächste Element dort auszuwählen. Doppelklick mit der mittleren Taste wechselt zur Startansicht (Einstellungen › Navigation).", @@ -1296,9 +1297,11 @@ "cmd.view_tool": "Navigationswerkzeug", "cmd.view_top": "Draufsicht", "cmd.view_visual_style": "Darstellungsstil", + "color.blue": "Blau", "color.copy": "Klicken, um Farbwerte zu kopieren", "color.edit": "Klicken, um Farbe zu bearbeiten", "color.gamma": "Farbwerte im Gammaraum 0-255 anzeigen", + "color.green": "Grün", "color.hex": "Hex", "color.hex_help": "#rrggbb oder #rrggbbaa eingeben; sechs Ziffern behalten die Deckkraft bei", "color.hex_hint": "#rrggbb", @@ -1306,6 +1309,7 @@ "color.linear": "Farbwerte im linearen Raum 0-1 anzeigen", "color.recent": "Zuletzt verwendete Farben", "color.recent_help": "Farben, die Sie in einem beliebigen Farbfeld wählen, erscheinen hier", + "color.red": "Rot", "color.saturation": "Sättigung (Prozent)", "color.saturation_value": "Sättigung und Wert", "color.selected": "Ausgewählte Farbe", diff --git a/assets/locales/en.json b/assets/locales/en.json index 3854bd08f..afefba8c4 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -556,6 +556,7 @@ "Section": "Section", "Section (optional)": "Section (optional)", "Section position": "Section position", + "Sections": "Sections", "Sections (one sketch each)": "Sections (one sketch each)", "Select Other": "Select Other", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).", @@ -1299,9 +1300,11 @@ "cmd.view_tool": "Navigation tool", "cmd.view_top": "Top View", "cmd.view_visual_style": "Visual style", + "color.blue": "Blue", "color.copy": "Click to copy color values", "color.edit": "Click to edit color", "color.gamma": "Showing color values in 0-255 gamma space", + "color.green": "Green", "color.hex": "Hex", "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity", "color.hex_hint": "#rrggbb", @@ -1309,6 +1312,7 @@ "color.linear": "Showing color values in 0-1 linear space", "color.recent": "Recent colors", "color.recent_help": "Colors you pick in any color field appear here", + "color.red": "Red", "color.saturation": "Saturation (percent)", "color.saturation_value": "Saturation and value", "color.selected": "Selected color", diff --git a/assets/locales/he.json b/assets/locales/he.json index 101aa8bef..f3adc473b 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -556,6 +556,7 @@ "Section": "חתך", "Section (optional)": "חתך (אופציונלי)", "Section position": "מיקום החתך", + "Sections": "חתכים", "Sections (one sketch each)": "חתכים (סקיצה אחת לכל אחד)", "Select Other": "בחירת אחר", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "בחירת אחר: החזקת הכפתור השמאלי ללא תזוזה על המודל (או לחיצה ימנית › בחירת אחר…) מציגה את כל מה שמתחת לסמן; לחיצה נוספת באותה נקודה בוחרת את הפריט הבא שם. לחיצה כפולה על הכפתור האמצעי חוזרת לתצוגת הבית (העדפות › ניווט).", @@ -1299,9 +1300,11 @@ "cmd.view_tool": "כלי ניווט", "cmd.view_top": "תצוגה עליונה", "cmd.view_visual_style": "סגנון תצוגה", + "color.blue": "כחול", "color.copy": "לחיצה מעתיקה את ערכי הצבע", "color.edit": "לחיצה לעריכת הצבע", "color.gamma": "ערכי הצבע מוצגים במרחב גמא 0-255", + "color.green": "ירוק", "color.hex": "Hex", "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity", "color.hex_hint": "#rrggbb", @@ -1309,6 +1312,7 @@ "color.linear": "ערכי הצבע מוצגים במרחב לינארי 0-1", "color.recent": "צבעים אחרונים", "color.recent_help": "צבעים שבוחרים בכל שדה צבע מופיעים כאן", + "color.red": "אדום", "color.saturation": "רוויה (אחוזים)", "color.saturation_value": "רוויה ובהירות", "color.selected": "הצבע שנבחר", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 53303ab8a..81485c32f 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -556,6 +556,7 @@ "Section": "断面", "Section (optional)": "断面(任意)", "Section position": "断面の位置", + "Sections": "セクション", "Sections (one sketch each)": "セクション (各1スケッチ)", "Select Other": "その他を選択", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。中ボタンをダブルクリックするとホームビューに戻ります(環境設定 › ナビゲーション)。", @@ -1299,9 +1300,11 @@ "cmd.view_tool": "ナビゲーションツール", "cmd.view_top": "上面ビュー", "cmd.view_visual_style": "表示スタイル", + "color.blue": "青", "color.copy": "クリックして色の値をコピー", "color.edit": "クリックして色を編集", "color.gamma": "0〜255のガンマ空間で色の値を表示", + "color.green": "緑", "color.hex": "Hex", "color.hex_help": "#rrggbb または #rrggbbaa を入力。6 桁の場合は不透明度を維持", "color.hex_hint": "#rrggbb", @@ -1309,6 +1312,7 @@ "color.linear": "0〜1の線形空間で色の値を表示", "color.recent": "最近使った色", "color.recent_help": "どの色フィールドで選んだ色もここに表示されます", + "color.red": "赤", "color.saturation": "彩度(パーセント)", "color.saturation_value": "彩度と明度", "color.selected": "選択した色", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 2304b0375..cb833cc6e 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -476,6 +476,7 @@ "Second point": "두 번째 점", "Section": "단면", "Section position": "단면 위치", + "Sections": "단면", "Sections (one sketch each)": "단면 (각각 스케치 하나)", "Select Other": "다른 항목 선택", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "다른 항목 선택: 모델 위에서 왼쪽 버튼을 가만히 누르고 있거나(또는 오른쪽 클릭 › 다른 항목 선택…) 커서 아래의 모든 항목을 나열합니다. 같은 위치를 다시 클릭하면 다음 항목이 선택됩니다. 가운데 버튼을 더블 클릭하면 홈으로 이동합니다(환경설정 › 탐색).", @@ -1113,14 +1114,17 @@ "cmd.view_render_frame": "렌더 프레임 가이드", "cmd.view_save": "새 이름 있는 보기", "cmd.view_shots_strip": "샷 스트립", + "color.blue": "파랑", "color.copy": "클릭하여 색상 값 복사", "color.edit": "클릭하여 색상 편집", "color.gamma": "색상 값을 0-255 감마 공간으로 표시 중", + "color.green": "초록", "color.hex": "Hex", "color.hex_help": "#rrggbb 또는 #rrggbbaa 입력. 6자리 값은 불투명도 유지", "color.hex_hint": "#rrggbb", "color.hue": "색조", "color.linear": "색상 값을 0-1 선형 공간으로 표시 중", + "color.red": "빨강", "color.saturation_value": "채도 및 명도", "color.selected": "선택한 색상", "config.column_filter_empty": "일치하는 열이 없습니다", diff --git a/assets/locales/pending/color-channel-names.json b/assets/locales/pending/color-channel-names.json deleted file mode 100644 index 8fa193b0e..000000000 --- a/assets/locales/pending/color-channel-names.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "ar": { - "color.blue": "أزرق", - "color.green": "أخضر", - "color.red": "أحمر" - }, - "de": { - "color.blue": "Blau", - "color.green": "Grün", - "color.red": "Rot" - }, - "en": { - "color.blue": "Blue", - "color.green": "Green", - "color.red": "Red" - }, - "he": { - "color.blue": "כחול", - "color.green": "ירוק", - "color.red": "אדום" - }, - "ja": { - "color.blue": "青", - "color.green": "緑", - "color.red": "赤" - }, - "ko": { - "color.blue": "파랑", - "color.green": "초록", - "color.red": "빨강" - }, - "vi": { - "color.blue": "Xanh dương", - "color.green": "Xanh lá", - "color.red": "Đỏ" - }, - "zh": { - "color.blue": "蓝色", - "color.green": "绿色", - "color.red": "红色" - } -} diff --git a/assets/locales/pending/loft-sections-one-sketch.json b/assets/locales/pending/loft-sections-one-sketch.json deleted file mode 100644 index 708b80eff..000000000 --- a/assets/locales/pending/loft-sections-one-sketch.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "en": { - "Sections": "Sections" - }, - "ar": { - "Sections": "المقاطع" - }, - "de": { - "Sections": "Querschnitte" - }, - "he": { - "Sections": "חתכים" - }, - "ja": { - "Sections": "セクション" - }, - "ko": { - "Sections": "단면" - }, - "vi": { - "Sections": "Các mặt cắt" - }, - "zh": { - "Sections": "截面" - } -} diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 902780f69..e62b851b4 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -556,6 +556,7 @@ "Section": "Mặt cắt", "Section (optional)": "Mặt cắt (tùy chọn)", "Section position": "Vị trí mặt cắt", + "Sections": "Các mặt cắt", "Sections (one sketch each)": "Các mặt cắt (mỗi mặt cắt một phác thảo)", "Select Other": "Chọn đối tượng khác", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Chọn đối tượng khác: giữ nút chuột trái đứng yên trên mô hình (hoặc nhấp chuột phải › Chọn đối tượng khác…) để liệt kê mọi đối tượng dưới con trỏ; nhấp lại vào cùng vị trí đó để chọn đối tượng kế tiếp. Nhấp đúp chuột giữa để về Góc nhìn chuẩn (Tùy chọn cài đặt › Điều hướng).", @@ -1299,9 +1300,11 @@ "cmd.view_tool": "Công cụ điều hướng", "cmd.view_top": "Góc nhìn từ trên", "cmd.view_visual_style": "Kiểu hiển thị trực quan", + "color.blue": "Xanh dương", "color.copy": "Nhấp để sao chép giá trị màu", "color.edit": "Nhấp để sửa màu", "color.gamma": "Đang hiển thị giá trị màu trong không gian gamma 0-255", + "color.green": "Xanh lá", "color.hex": "Hex", "color.hex_help": "Enter #rrggbb or #rrggbbaa; six digits preserve opacity", "color.hex_hint": "#rrggbb", @@ -1309,6 +1312,7 @@ "color.linear": "Đang hiển thị giá trị màu trong không gian tuyến tính 0-1", "color.recent": "Màu gần đây", "color.recent_help": "Các màu bạn chọn ở bất kỳ ô màu nào sẽ hiện ở đây", + "color.red": "Đỏ", "color.saturation": "Độ bão hòa (phần trăm)", "color.saturation_value": "Độ bão hòa và giá trị", "color.selected": "Màu đã chọn", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 7a046bcc9..ac532b0c4 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -556,6 +556,7 @@ "Section": "剖面", "Section (optional)": "截面(可选)", "Section position": "截面位置", + "Sections": "截面", "Sections (one sketch each)": "截面(每个一个草图)", "Select Other": "选择其他", "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。双击中键转到主视图(首选项 › 导航)。", @@ -1299,9 +1300,11 @@ "cmd.view_tool": "导航工具", "cmd.view_top": "俯视图", "cmd.view_visual_style": "视觉样式", + "color.blue": "蓝色", "color.copy": "单击复制颜色值", "color.edit": "单击编辑颜色", "color.gamma": "以 0–255 伽马空间显示颜色值", + "color.green": "绿色", "color.hex": "Hex", "color.hex_help": "输入 #rrggbb 或 #rrggbbaa;六位数保留不透明度", "color.hex_hint": "#rrggbb", @@ -1309,6 +1312,7 @@ "color.linear": "以 0–1 线性空间显示颜色值", "color.recent": "最近使用的颜色", "color.recent_help": "在任意颜色字段中选择的颜色会显示在这里", + "color.red": "红色", "color.saturation": "饱和度(百分比)", "color.saturation_value": "饱和度和明度", "color.selected": "所选颜色", From 835e2615930f5e5db6a7114e9987c84a9c6fef45 Mon Sep 17 00:00:00 2001 From: semmelrinde <124386289+semmelrinde@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:12:56 +0000 Subject: [PATCH 27/55] Coil: up and down arrows on the Revolutions field (#7481) (#7766) * claim: #7481 Co-Authored-By: Claude Opus 5.5 * Coil: step arrows on the Revolutions field (#7481) The Coil dialog drew Revolutions as a plain expression row, the one count without the step arrows the pattern quantities have. It is now a count row from 1 to 200 turns (the helix's limit); a fraction still types in, and an arrow steps it to the next whole turn. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/dialogs_all_tests.rs | 45 +++++++++++++++++++++++++ crates/ui-egui/src/dialogs_dense.rs | 19 +++++++++-- 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs index 82ca574f8..5a59b364e 100644 --- a/crates/ui-egui/src/dialogs_all_tests.rs +++ b/crates/ui-egui/src/dialogs_all_tests.rs @@ -963,6 +963,51 @@ fn coil_from_a_profile_hides_the_primitive_section() { assert!(p.get("operation").is_some(), "{p}"); } +/// The Revolutions field steps by whole turns like the other counts (#7481). +#[test] +fn coil_revolutions_arrows_step_whole_turns() { + let mut h = fixture(); + h.app.run("parameters.add", json!({"name":"turns","expression":"3","unit":""})).unwrap(); + h.app.dialog = Some(Dialog::for_command(&h.app, "solid.coil").unwrap()); + h.settle(); + let sent = |h: &Harness| { + let cmds = crate::dialogs::preview_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap(); + cmds.iter().find(|(id, _)| id == "solid.coil").map(|(_, p)| p["revolutions"].clone()).unwrap_or_else(|| panic!("{cmds:?}")) + }; + let set = |h: &mut Harness, text: &str| { + if let Some(Kind::Primitive { fields, .. }) = h.app.dialog.as_mut().map(|d| &mut d.kind) + && let Some((_, value)) = fields.iter_mut().find(|(k, _)| *k == "revolutions") + { + *value = text.into(); + } + h.frames(2); + }; + let click = |h: &mut Harness, arrow: &str| h.step(&json!({"click":{"handle":format!("dialog:ui.revolutions {arrow}")}})).unwrap(); + assert_eq!(sent(&h), json!("4")); + click(&mut h, "up"); + assert_eq!(sent(&h), json!("5")); + click(&mut h, "down"); + click(&mut h, "down"); + assert_eq!(sent(&h), json!("3")); + // A fraction steps to the next whole turn either way. + set(&mut h, "2.5"); + click(&mut h, "up"); + assert_eq!(sent(&h), json!("3")); + set(&mut h, "2.5"); + click(&mut h, "down"); + assert_eq!(sent(&h), json!("2")); + // From 1 to the helix's 200 turns. + set(&mut h, "1"); + click(&mut h, "down"); + assert_eq!(sent(&h), json!("1")); + set(&mut h, "200"); + click(&mut h, "up"); + assert_eq!(sent(&h), json!("200")); + set(&mut h, "turns"); + click(&mut h, "up"); + assert_eq!(sent(&h), json!("turns + 1")); +} + fn extrude_focus_fixture() -> Harness { let mut h = Harness::new(); h.app.home.open = false; diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 1ae0c525e..da8f7b572 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -115,8 +115,18 @@ const MAX_PATTERN_INSTANCES: i64 = 1000; /// A solid pattern's quantity row, with step arrows from 1 to `MAX_PATTERN_INSTANCES`. The /// count goes to the command as typed, so it is evaluated as the document evaluates it. fn quantity_row(ui: &mut egui::Ui, doc: &solidcraft_engine::doc::Document, label: &str, value: &mut String) -> bool { + count_row_to(ui, doc, label, value, MAX_PATTERN_INSTANCES) +} + +/// The most revolutions a coil makes (the helix's own limit). +const MAX_COIL_REVOLUTIONS: i64 = 200; + +/// A count row with step arrows by whole numbers from 1 to `max`, evaluated as the document +/// evaluates it. A fraction still types in (a coil's revolutions); an arrow steps it to the next +/// whole number. +fn count_row_to(ui: &mut egui::Ui, doc: &solidcraft_engine::doc::Document, label: &str, value: &mut String, max: i64) -> bool { let eval = |text: &str| doc.eval(text.trim(), solidcraft_engine::doc::expr::Kind::Unitless).ok(); - ui_kit::count_row(ui, label, value, &ui_kit::Count { min: 1, max: MAX_PATTERN_INSTANCES, eval: &eval }) + ui_kit::count_row(ui, label, value, &ui_kit::Count { min: 1, max, eval: &eval }) } fn fillet_type(extra: &serde_json::Map) -> usize { @@ -860,7 +870,12 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo if from_sketch && (*k == "diameter" || *k == "section_size") { continue; } - enter |= expr_row(ui, primitive_label(k), v); + // Revolutions steps by whole turns like the other counts (#7481). + enter |= if *k == "revolutions" { + count_row_to(ui, &app.session.doc, primitive_label(k), v, MAX_COIL_REVOLUTIONS) + } else { + expr_row(ui, primitive_label(k), v) + }; } if *cmd == "solid.coil" { enter |= coil_rows(ui, &mut d.extra); From 0ad74f2577a5f4f0d2be61f0ba9dcb53b5d7006f Mon Sep 17 00:00:00 2001 From: Thodoris Tsagkogeorgas Date: Sun, 1 Nov 2026 20:18:27 +0000 Subject: [PATCH 28/55] Revolve: keep the angle grab point when the sweep is zero (#9601) (#9602) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A revolve of 0° still builds no solid. The handle stays on the profile so the angle can be dragged back into range. --- crates/doc/src/eval.rs | 25 +++++++++++- crates/doc/src/lib.rs | 6 +-- crates/ui-egui/src/canvas.rs | 4 +- .../ui-egui/src/revolve_manipulator_tests.rs | 38 +++++++++++++++++++ 4 files changed, 68 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index caffae2f9..6f3b328e9 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -5014,6 +5014,29 @@ pub fn revolve_extent_with_convention( symmetric: bool, to: Option, convention: crate::RevolveConvention, +) -> Result { + let extent = revolve_extent_for_handle(st, plane, regions, (origin, axis), (angle, angle2), symmetric, to, convention)?; + // A solid needs an open sweep inside one full turn. Zero and a turn past 360° keep a + // handle frame (`revolve_extent_for_handle`) and still fail here, with the same message. + if !(extent.sweep.abs() > 1e-9 && extent.sweep.abs() <= std::f64::consts::TAU + 1e-9) { + return Err(DocError::Invalid("the revolve angle must be more than 0 and at most 360°".into())); + } + Ok(extent) +} + +/// Where the angle handle sits. A sweep of zero, or past a full turn, builds no solid and +/// [`revolve_extent_with_convention`] refuses it. The boundary is still a point on the circle, +/// and the grab point stays there so the angle can be dragged back into range. +#[allow(clippy::too_many_arguments)] +pub fn revolve_extent_for_handle( + st: &ModelState, + plane: &Plane, + regions: &[Region2], + (origin, axis): (Vec3, Vec3), + (angle, angle2): (f64, Option), + symmetric: bool, + to: Option, + convention: crate::RevolveConvention, ) -> Result { let (start, sweep) = match (to, angle2, symmetric) { (Some(point), _, _) => { @@ -5053,7 +5076,7 @@ pub fn revolve_extent_with_convention( (None, None, true) => (-angle / 2.0, angle), (None, None, false) => (0.0, angle), }; - if !(sweep.is_finite() && start.is_finite() && sweep.abs() > 1e-9 && sweep.abs() <= std::f64::consts::TAU + 1e-9) { + if !(sweep.is_finite() && start.is_finite()) { return Err(DocError::Invalid("the revolve angle must be more than 0 and at most 360°".into())); } let points: Vec = regions.iter().flat_map(|r| r.outer.polyline(1e-2)).collect(); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index fbd94b407..bd89b493b 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -87,9 +87,9 @@ pub use document::*; pub use eval::{ EdgeRef, FeatureResult, Model, ModelBody, ModelState, PlacedBodies, RevolveExtent, SavedModel, SolvedSketch, ThreadInfo, curve_pick_error, edge_names_for, edge_refs, face_point_names, face_point_state, hole_direction_at, import_body_names, join_pieces_added, map_wire, - metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_with_convention, select_profiles, - sketch_hole_direction, sketch_line_plane, state_in_frame, state_in_frame_at, suggested_thread, tangent_face_chain, through_all_distance, - world_state, world_state_reusing, + metric_thread_sizes, object_height, parse_metric_thread, pattern_matrices, revolve_extent, revolve_extent_for_handle, + revolve_extent_with_convention, select_profiles, sketch_hole_direction, sketch_line_plane, state_in_frame, state_in_frame_at, suggested_thread, + tangent_face_chain, through_all_distance, world_state, world_state_reusing, }; pub use eval::{EvalCache, KeptResults}; pub use expr::Expr; diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8e284097e..15cde8dc4 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1862,7 +1862,9 @@ fn revolve_display_extent(app: &SolveApp, d: &Dialog, axis: (Vec3, Vec3)) -> Opt .ok()?; (angle, other) }; - solidcraft_engine::doc::revolve_extent_with_convention( + // The solid refuses 0° and a sweep past a full turn, and the dialog says so. The handle + // still uses that boundary, so the grab point stays and the angle can be dragged back. + solidcraft_engine::doc::revolve_extent_for_handle( &state, &plane, ®ions, diff --git a/crates/ui-egui/src/revolve_manipulator_tests.rs b/crates/ui-egui/src/revolve_manipulator_tests.rs index a9d493af2..324cbbf7c 100644 --- a/crates/ui-egui/src/revolve_manipulator_tests.rs +++ b/crates/ui-egui/src/revolve_manipulator_tests.rs @@ -225,6 +225,44 @@ fn free_drag_and_invalid_expression_stay_editable_before_commit() { assert!((volume(&h) - expected_volume(60.0)).abs() < 0.03); } +/// Typing 0° builds no solid, and the dialog keeps the range error. The grab point stays on +/// the profile, and dragging it brings the angle back. +#[test] +fn zero_angle_keeps_the_grab_point_and_a_drag_brings_the_angle_back() { + for (params, handle, drag_to, entered_angle, committed) in + [(json!({}), "revolve", 45.0, "45 deg", 45.0), (json!({"direction": "symmetric"}), "revolve2", -45.0, "90 deg", 90.0)] + { + let mut h = fixture(Harness::new(), params.clone()); + open(&mut h); + h.step(&json!({"click":{"handle":"dialog:Angle"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"0 deg"})).unwrap(); + h.frames(4); + handle_at(&mut h, "revolve", at_angle(0.0)); + // A preview refusal stays on the preview while the angle field is still being typed in. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while h.app.preview.busy { + assert!(std::time::Instant::now() < deadline, "the preview did not finish"); + h.frames(1); + } + let error = h.app.dialog.as_ref().and_then(|dialog| dialog.error.clone()).or_else(|| h.app.preview.error.clone()).unwrap_or_default(); + assert!(error.contains("more than 0"), "{error}"); + h.step(&json!({"widget":"OK"})).unwrap(); + assert!(h.app.dialog.is_some(), "a zero angle still builds no solid"); + h.step(&json!({"drag":[{"handle":handle},{"world":at_angle(drag_to)}]})).unwrap(); + let crate::dialogs::Kind::Revolve { angle: entered, .. } = &h.app.dialog.as_ref().unwrap().kind else { panic!("revolve") }; + assert_eq!(entered, entered_angle); + h.step(&json!({"widget":"OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().map(|dialog| &dialog.error)); + assert_eq!(angle(&h), entered_angle); + let got = volume(&h); + let want = expected_volume(committed); + // A symmetric drag that starts with both handles stacked at 0° lands within a tenth of a + // cubic millimetre of the analytic quarter turn. + assert!((got - want).abs() < 0.1, "params={params} got={got} want={want}"); + } +} + #[test] fn second_side_can_be_dragged_to_zero_without_becoming_full_turn() { let mut h = fixture(Harness::new(), json!({"angle":"60 deg","angle2":"30 deg"})); From e1d4cb433c63a4dbbf95e247c8f28b8f97be983b Mon Sep 17 00:00:00 2001 From: cronos Date: Sun, 1 Nov 2026 20:19:16 +0000 Subject: [PATCH 29/55] Cover sketch line-arc fillets in both selection orders (#10242) --- crates/engine/src/cmd/sketch_modify_tests.rs | 34 +++++++++++++++++- crates/ui-egui/src/sketch_corner_ui_tests.rs | 38 ++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 7d5b1b8da..4a5c66894 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -1875,7 +1875,7 @@ fn fillet_a_line_and_an_arc() { fn fillet_a_line_and_an_arc_drawn_to_meet_at_a_point() { // #1208: the arc starts at the line's end by coordinates, so the corner is two points held // together by a Coincident constraint. By point and by naming the two curves. - for how in [json!({"point": "l1.end"}), json!({"a": "l1", "b": "a1"})] { + for how in [json!({"point": "l1.end"}), json!({"a": "l1", "b": "a1"}), json!({"a": "a1", "b": "l1"})] { let mut s = new_sketch(); run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]], "ids": ["l1"]})); run(&mut s, "sketch.arc.center_point", json!({"center": [50, 0], "start": [60, 0], "end": [40, 0], "id": "a1"})); @@ -1941,6 +1941,38 @@ fn fillet_a_coincident_corner_that_a_dimension_measures_to() { } } +#[test] +fn fillet_coincident_line_and_arc_selection_order() { + for held in ["l1.end", "a1.end"] { + for (a, b) in [("l1", "a1"), ("a1", "l1")] { + let mut s = new_sketch(); + run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]], "ids": ["l1"]})); + run(&mut s, "sketch.arc.center_point", json!({"center": [50, 0], "start": [60, 0], "end": [40, 0], "id": "a1"})); + // Keep the fixed sharp corner in place, whichever endpoint is fixed or picked + // first when rounding the same corner. + run(&mut s, "sketch.constraint.fix", json!({"entity": held})); + let before = serde_json::to_value(sketch(&s)).unwrap(); + let f = run(&mut s, "sketch.fillet", json!({"a": a, "b": b, "radius": 3})); + let sk = sketch(&s); + let ai = sk.curve_index(&ids(&f["curves"])[0]).unwrap(); + let want = Vec2::new(50.0 - 160f64.sqrt(), 3.0); + assert!((sk.radius(ai).unwrap() - 3.0).abs() < 1e-7, "{held}: {a}, {b}"); + assert!(sk.center(ai).unwrap().dist(want) < 1e-6, "{held}: {a}, {b}"); + let fixed = sk + .constraints + .iter() + .find_map(|c| match c.kind { + ConstraintKind::Fix { p } => Some(p), + _ => None, + }) + .unwrap(); + assert!(sk.point(fixed).unwrap().dist(Vec2::new(40.0, 0.0)) < 1e-6); + assert_eq!(run(&mut s, "sketch.inspect", json!({}))["status"], "solved"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(serde_json::to_value(sketch(&s)).unwrap(), before); + } + } +} #[test] fn chamfer_two_lines_drawn_to_meet_at_a_point() { let mut s = new_sketch(); diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rs index b556232d1..b51f486ed 100644 --- a/crates/ui-egui/src/sketch_corner_ui_tests.rs +++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs @@ -958,3 +958,41 @@ fn corner_candidates_agree_with_engine_spatial_curve_filter() { h.app.dialog = None; } } + +#[test] +fn line_arc_fillet_preview_and_apply_work_in_both_pick_orders() { + for reverse in [false, true] { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[0,0],[40,0]],"ids":["l1"]})).unwrap(); + h.app.run("sketch.arc.center_point", json!({"center":[50,0],"start":[60,0],"end":[40,0],"id":"a1"})).unwrap(); + h.app.run("sketch.constraint.fix", json!({"entity":"l1.end"})).unwrap(); + h.app.run("view.fit", json!({})).unwrap(); + h.settle(); + let undo = h.app.session.undo.len(); + h.step(&json!({"start":"sketch.fillet"})).unwrap(); + h.frames(2); + let mut picks = [[32, 0, 0], [50, 10, 0]]; + if reverse { + picks.reverse(); + } + for point in picks { + h.step(&json!({"click":{"world":point}})).unwrap(); + h.frames(2); + } + assert_eq!(h.app.dialog.as_ref().unwrap().inputs[0].items.len(), 2); + set_size(&mut h.app, "3 mm"); + h.step(&json!({"until":{"count":{"name":"sketch_preview_curves","value":3}}})).unwrap(); + apply(&mut h); + assert!(h.app.dialog.is_none(), "reverse {reverse}: {:?}", h.app.status); + assert_eq!(h.app.session.undo.len(), undo + 1); + let st = h.app.session.world_state(); + let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); + assert!(ss.report.ok()); + assert_eq!(ss.sketch.curves.len(), 3); + let want = Vec2::new(50.0 - 160f64.sqrt(), 3.0); + assert!(ss.sketch.curves.iter().enumerate().any(|(i, _)| { + ss.sketch.radius(i).is_some_and(|r| (r - 3.0).abs() < 1e-7) && ss.sketch.center(i).is_some_and(|c| c.dist(want) < 1e-6) + })); + } +} From 97336ccfe7a57c241c2b8fe18c72291702bbf7db Mon Sep 17 00:00:00 2001 From: bherbruck Date: Sun, 1 Nov 2026 20:19:41 +0000 Subject: [PATCH 30/55] Kernel pause: pull requests are judged by the kernel directories they change (#10807) A pull request outside crates/kernel, crates/geom and vendor/truck* is no longer labelled for a kernel word in its title. Issues and discussions keep the title check. Co-authored-by: Claude Opus 5.5 --- .github/workflows/kernel-paused.yml | 7 ++++--- CONTRIBUTING.md | 13 +++++++------ scripts/kernel-paused/kernel-paused.js | 20 +++++++++++--------- scripts/kernel-paused/kernel-paused.test.js | 14 ++++++++++++++ 4 files changed, 36 insertions(+), 18 deletions(-) diff --git a/.github/workflows/kernel-paused.yml b/.github/workflows/kernel-paused.yml index cfa6d659b..be5de83cd 100644 --- a/.github/workflows/kernel-paused.yml +++ b/.github/workflows/kernel-paused.yml @@ -1,6 +1,7 @@ -# While a new geometry kernel is evaluated, new issues, pull requests and discussions about kernel -# work are labelled `kernel-paused` for a maintainer to answer (CONTRIBUTING.md, "Kernel work is -# paused"). The logic is in scripts/kernel-paused/ (tested in ci.yml). +# While a new geometry kernel is evaluated, new issues and discussions about kernel work, and new +# pull requests that change the kernel directories, are labelled `kernel-paused` for a maintainer to +# answer (CONTRIBUTING.md, "Kernel work is paused"). The logic is in scripts/kernel-paused/ (tested +# in ci.yml). name: Kernel paused on: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7d444429d..54fed4165 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,12 +19,13 @@ Questions, ideas or want to say what you're working on? Join the [Discord](https ## Kernel work is paused -We're evaluating a new geometry kernel. Until that's decided, please don't open issues, pull -requests or discussions about kernel work: booleans, fillets, chamfers, shell, offsets, sweeps and -lofts, threads and holes, STEP/IGES import and export, tessellation, or anything else that changes -`crates/kernel/`. The pinned issue on the tracker explains it. New ones get the `kernel-paused` -label (`.github/workflows/kernel-paused.yml`) and a maintainer answers them. Crashes and data loss -are still taken as issues, and everything outside the kernel carries on as normal. +We're moving to a new geometry kernel. Until that's done, please don't open pull requests that +change `crates/kernel/`, `crates/geom/` or `vendor/truck*`, or issues and discussions about kernel +work: booleans, fillets, chamfers, shell, offsets, sweeps and lofts, threads and holes, STEP/IGES +import and export, or tessellation. The pinned issue on the tracker explains it. New ones get the +`kernel-paused` label (`.github/workflows/kernel-paused.yml`) and a maintainer answers them. Crashes +and data loss are still taken as issues. Pull requests outside those directories carry on as normal, +including the dialogs and tools for these features. ## Get it running (about 10 minutes on a fast machine) diff --git a/scripts/kernel-paused/kernel-paused.js b/scripts/kernel-paused/kernel-paused.js index 480a94378..2311aa0d2 100644 --- a/scripts/kernel-paused/kernel-paused.js +++ b/scripts/kernel-paused/kernel-paused.js @@ -1,21 +1,21 @@ 'use strict'; -// While a new geometry kernel is evaluated, new issues, pull requests and discussions about -// kernel work get the `kernel-paused` label, so a maintainer finds them and answers in person -// (CONTRIBUTING.md, "Kernel work is paused"). Reports of crashes and data loss are left alone, -// and so is anyone who can push to the repository. +// While a new geometry kernel is evaluated, new issues and discussions about kernel work, and new +// pull requests that change the kernel directories, get the `kernel-paused` label, so a maintainer +// finds them and answers in person (CONTRIBUTING.md, "Kernel work is paused"). Reports of crashes +// and data loss are left alone, and so is anyone who can push to the repository. const LABEL = 'kernel-paused'; const LABEL_COLOR = 'b60205'; const LABEL_DESCRIPTION = 'Kernel work is paused while a new geometry kernel is evaluated'; -// Kernel operations named in a title. "Hole" and "shell" are left out on purpose: they name UI -// work too, and a pull request that changes the kernel is caught by its files. +// Kernel operations named in the title of an issue or discussion. "Hole" and "shell" are left out +// on purpose: they name UI work too. A pull request is judged by its files, never by its title. const TOPIC = /\b(booleans?|fillets?|chamfers?|offsets?|sweeps?|lofts?|threads?|step|stp|iges|igs|tessellat\w*|kernel|truck|b-?rep)\b/i; // Crashes and lost work come first whatever the kernel is. const URGENT = /\b(crash\w*|panic\w*|data loss|lost (my )?work|corrupt\w*)\b/i; // What a pull request changes that makes it kernel work. -const KERNEL_PATHS = ['crates/kernel/', 'vendor/truck']; +const KERNEL_PATHS = ['crates/kernel/', 'crates/geom/', 'vendor/truck']; function isTopic(title) { return TOPIC.test(title || ''); @@ -55,10 +55,12 @@ async function handleOpened({ github, context }) { const pull = Boolean(context.payload.pull_request); if (isUrgent(item.title, item.body)) return `#${item.number}: a crash or data-loss report, left alone`; if (await canPush({ github, context }, item.user.login)) return `#${item.number}: by a maintainer, left alone`; - let kernel = isTopic(item.title); - if (pull && !kernel) { + let kernel; + if (pull) { const files = await github.paginate(github.rest.pulls.listFiles, { ...context.repo, pull_number: item.number, per_page: 100 }); kernel = touchesKernel(files.map((f) => f.filename)); + } else { + kernel = isTopic(item.title); } if (!kernel) return `#${item.number}: not kernel work`; await ensureLabel({ github, context }); diff --git a/scripts/kernel-paused/kernel-paused.test.js b/scripts/kernel-paused/kernel-paused.test.js index 910ad2b15..627cd45f4 100644 --- a/scripts/kernel-paused/kernel-paused.test.js +++ b/scripts/kernel-paused/kernel-paused.test.js @@ -80,6 +80,20 @@ test('a pull request outside the kernel is left alone', async () => { assert.deepEqual(calls, []); }); +test('a pull request with a kernel topic in its title but no kernel files is left alone', async () => { + const { github, calls } = fake({ files: ['crates/ui-egui/src/dialogs.rs'] }); + const pr = { number: 10, title: 'Fillet dialog: a clearer radius field', body: '', draft: false, node_id: 'PR_3', user: { login: 'someone' } }; + await paused.handleOpened({ github, context: { repo, payload: { pull_request: pr } } }); + assert.deepEqual(calls, []); +}); + +test('a pull request that changes crates/geom is labelled', async () => { + const { github, calls } = fake({ files: ['crates/geom/src/lib.rs'] }); + const pr = { number: 11, title: 'Tidy a helper', body: '', draft: false, node_id: 'PR_4', user: { login: 'someone' } }; + await paused.handleOpened({ github, context: { repo, payload: { pull_request: pr } } }); + assert.deepEqual(names(calls), ['addLabels']); +}); + test('a kernel discussion is labelled', async () => { const { github, calls } = fake(); const d = { number: 3, title: 'Ideas for better booleans', body: '', node_id: 'D_1', user: { login: 'someone' } }; From 303236e52475c942bb54171496f44628243a00bf Mon Sep 17 00:00:00 2001 From: CamWight <91156642+CamWight@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:28:58 +0000 Subject: [PATCH 31/55] Tests: io's byte mutator moves to a testkit crate, a dev-dependency only (#5184) (#7682) * Tests: io's byte mutator moves to a testkit crate, a dev-dependency only (no behaviour change) `solidcraft-testkit` (the Testkit class xtask/src/layers.rs reserves) holds the mutator and the no-panic check unchanged: the same seeds, mutations, budget and doc comment. io's reader fuzz tests use it as a dev-dependency and give the same case counts; the mutator's own test moves with it. The co-editing wire's decoders will fuzz with it too (#5184, CE6). Co-Authored-By: Claude Opus 5.5 * Cargo.lock: testkit at the workspace version Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: bherbruck --- Cargo.lock | 5 + Cargo.toml | 2 + crates/io/Cargo.toml | 3 + crates/io/src/mutate.rs | 824 +++++++++++++------------------------- crates/testkit/Cargo.toml | 9 + crates/testkit/src/lib.rs | 294 ++++++++++++++ 6 files changed, 583 insertions(+), 554 deletions(-) create mode 100644 crates/testkit/Cargo.toml create mode 100644 crates/testkit/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 2d6fe07de..9a63ec35d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4355,6 +4355,7 @@ dependencies = [ "solidcraft-doc", "solidcraft-geom", "solidcraft-kernel", + "solidcraft-testkit", "thiserror 2.0.21", "zip", ] @@ -4424,6 +4425,10 @@ dependencies = [ "serde", ] +[[package]] +name = "solidcraft-testkit" +version = "0.29.0" + [[package]] name = "solidcraft-ui-egui" version = "0.29.0" diff --git a/Cargo.toml b/Cargo.toml index 13a3f3778..a37b2b65e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,8 @@ solidcraft-space-mouse = { path = "crates/space-mouse" } solidcraft-mcp = { path = "crates/mcp" } solidcraft-derive = { path = "crates/derive" } solidcraft-3dx-client = { path = "crates/threedx-client" } +# test tooling: a dev-dependency only (xtask/src/layers.rs) +solidcraft-testkit = { path = "crates/testkit" } # foundation thiserror = "2" diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index e5f7c4dee..8b75ac98f 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -43,3 +43,6 @@ rustix = { version = "1", default-features = false, features = ["std", "fs"] } # The computer's name for a design's lock file (src/design_lock.rs; the browser keeps no lock files). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] gethostname = { workspace = true } + +[dev-dependencies] +solidcraft-testkit = { workspace = true } diff --git a/crates/io/src/mutate.rs b/crates/io/src/mutate.rs index 10e27a12b..c5dcd68b1 100644 --- a/crates/io/src/mutate.rs +++ b/crates/io/src/mutate.rs @@ -1,323 +1,40 @@ -//! Deterministic mutations of valid files, and the readers run over them (#469). Every reader of -//! bytes the user didn't write gets the same treatment: truncation, flipped and overwritten -//! bytes, dropped and repeated runs, appended garbage and, for text formats, dropped and -//! repeated lines and numbers that lie (`nan`, `inf`, `1e400`, …). Each mutated file must give an -//! error or a result, never a panic, within a time budget and the reader's own caps. A panic a -//! reader catches itself (`solidcraft_kernel::guard`) counts too: the browser build aborts on any -//! panic, so a caught one on the desktop is a crash there. -//! -//! The mutations come from a fixed seed (xorshift), so a failure names a case that reproduces. -//! No fuzzing dependency, nothing nightly, nothing native: it runs in the normal test suite and -//! builds for wasm. The readers' own hand-written cases stay; they cover particular lies (a -//! length in a container header) that random changes rarely hit. STEP, IGES and FreeCAD/Rhino -//! files are read by the kernel, which is moving to solidcore (#1597), and keep their own tests. +//! Every reader of bytes the user didn't write, run over mutations of a valid file (#469): each +//! case gives an error or a result, never a panic, within the time budget and the reader's own +//! caps. The mutations and the check are `solidcraft_testkit`'s. -use std::panic::{AssertUnwindSafe, catch_unwind}; -use std::time::{Duration, Instant}; +use solidcraft_geom::{Mesh, Vec2, Vec3}; +use solidcraft_testkit::{mutations, survives}; -/// A deterministic xorshift64 stream. -pub(crate) struct Rng(u64); - -impl Rng { - pub(crate) fn new(seed: u64) -> Rng { - Rng(seed | 1) - } - - pub(crate) fn next(&mut self) -> u64 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - self.0 - } - - /// A value in `0..n` (0 when `n` is 0). - pub(crate) fn below(&mut self, n: usize) -> usize { - if n == 0 { 0 } else { (self.next() % n as u64) as usize } - } +fn cube() -> Mesh { + let positions = (0..8).map(|i| Vec3::new(f64::from(i & 1) * 10.0, f64::from((i >> 1) & 1) * 10.0, f64::from((i >> 2) & 1) * 10.0)).collect(); + let t = [[0, 2, 1], [1, 2, 3], [4, 5, 6], [5, 7, 6], [0, 1, 4], [1, 5, 4], [2, 6, 3], [3, 6, 7], [0, 4, 2], [2, 4, 6], [1, 3, 5], [3, 7, 5]]; + Mesh { positions, triangles: t.to_vec(), ..Default::default() } } -/// Numbers a hostile file might hold in place of a real one. -const LIARS: [&str; 10] = ["nan", "inf", "-inf", "1e400", "-1e400", "-0", "4294967296", "-1", "99999999999999999999", "0x7fffffff"]; - -/// Most truncations of one file (every length up to this, evenly spaced beyond). -const MAX_TRUNCATIONS: usize = 1024; - -/// Mutations of `good`, the same for the same `good` and `seed`. `text`: also line and number -/// mutations (the file is UTF-8 text). -pub(crate) fn mutations(good: &[u8], text: bool, seed: u64) -> Vec> { - let mut out: Vec> = Vec::new(); - let n = good.len(); - let mut rng = Rng::new(seed); - // Truncations: every length of a short file; of a long one, its first and last 64 lengths - // (headers, final records) and evenly spaced ones between. - if n <= MAX_TRUNCATIONS { - out.extend((0..n).map(|k| good[..k].to_vec())); - } else { - let mut cuts: Vec = (0..64).chain(n - 64..n).collect(); - cuts.extend((0..MAX_TRUNCATIONS - 128).map(|i| 64 + i * (n - 128) / (MAX_TRUNCATIONS - 128))); - cuts.sort_unstable(); - cuts.dedup(); - out.extend(cuts.into_iter().map(|k| good[..k].to_vec())); - } - if n == 0 { - return out; - } - // Bytes flipped, zeroed and saturated at seeded places. - for i in 0..384 { - let at = rng.below(n); - let mut b = good.to_vec(); - b[at] = match i % 3 { - 0 => b[at] ^ ((rng.next() >> 32) as u8 | 1), - 1 => 0x00, - _ => 0xff, - }; - out.push(b); - } - // Runs of bytes dropped, repeated and swapped with their neighbour. - for _ in 0..96 { - let at = rng.below(n); - let len = 1 + rng.below(64.min(n - at)); - let end = at + len; - let mut dropped = good[..at].to_vec(); - dropped.extend_from_slice(&good[end..]); - out.push(dropped); - let mut repeated = good[..end].to_vec(); - repeated.extend_from_slice(&good[at..]); - out.push(repeated); - if end + len <= n { - let mut swapped = good[..at].to_vec(); - swapped.extend_from_slice(&good[end..end + len]); - swapped.extend_from_slice(&good[at..end]); - swapped.extend_from_slice(&good[end + len..]); - out.push(swapped); - } - } - // The whole file: with garbage after it, twice over, reversed. - let mut tail = good.to_vec(); - tail.extend((0..4096).map(|_| (rng.next() >> 40) as u8)); - out.push(tail); - out.push([good, good].concat()); - out.push(good.iter().rev().copied().collect()); - if text && let Ok(s) = std::str::from_utf8(good) { - out.extend(text_mutations(s, &mut rng)); - } - out +#[test] +fn stl_survives_mutation() { + let mesh = cube(); + let binary = crate::stl_binary(std::slice::from_ref(&mesh), "fuzz"); + let ascii = crate::stl_ascii(std::slice::from_ref(&mesh), "fuzz").into_bytes(); + assert_eq!(crate::read_stl(&binary).map(|t| t.len()).ok(), Some(12)); + assert_eq!(crate::read_stl(&ascii).map(|t| t.len()).ok(), Some(12)); + let read = |b: &[u8]| crate::read_stl(b).ok().map(|t| t.len()); + survives("binary STL", &mutations(&binary, false, 0x5717), crate::MAX_STL_TRIANGLES, read); + survives("ASCII STL", &mutations(&ascii, true, 0x5718), crate::MAX_STL_TRIANGLES, read); } -/// A text file's lines dropped, repeated and swapped, and its numbers replaced by lies. -fn text_mutations(s: &str, rng: &mut Rng) -> Vec> { - let mut out = Vec::new(); - let lines: Vec<&str> = s.split_inclusive('\n').collect(); - let join = |v: &[&str]| v.concat().into_bytes(); - let picked: Vec = if lines.len() <= 200 { (0..lines.len()).collect() } else { (0..200).map(|_| rng.below(lines.len())).collect() }; - for &i in &picked { - let mut v = lines.clone(); - v.remove(i); - out.push(join(&v)); - let mut v = lines.clone(); - v.insert(i, lines[i]); - out.push(join(&v)); - if i + 1 < lines.len() { - let mut v = lines.clone(); - v.swap(i, i + 1); - out.push(join(&v)); - } - } - // A line in place of another (a block that inserts itself, a count where a coordinate was). - for _ in 0..200.min(lines.len() * lines.len()) { - let (i, j) = (rng.below(lines.len()), rng.below(lines.len())); - let mut v = lines.clone(); - v[i] = lines[j]; - out.push(join(&v)); - } - // A word in place of another of the file's own words: a renamed block, a swapped keyword, a - // block that now inserts itself. Every pair in a small file, a sample in a large one. - let words = word_spans(s); - let mut vocab: Vec<&str> = words.iter().map(|&(a, b)| &s[a..b]).collect(); - vocab.sort_unstable(); - vocab.dedup(); - let pairs = words.len().saturating_mul(vocab.len()); - let swap = |(a, b): (usize, usize), w: &str| format!("{}{w}{}", &s[..a], &s[b..]).into_bytes(); - if pairs <= 3000 { - for &span in &words { - for &w in vocab.iter().filter(|w| **w != &s[span.0..span.1]) { - out.push(swap(span, w)); - } - } - } else { - for _ in 0..400 { - out.push(swap(words[rng.below(words.len())], vocab[rng.below(vocab.len())])); - } - } - // Numbers: each of up to 200 of them, in turn, becomes one of the liars. - let numbers = number_spans(s); - let chosen: Vec<(usize, usize)> = if numbers.len() <= 200 { numbers } else { (0..200).map(|_| numbers[rng.below(numbers.len())]).collect() }; - for (k, (a, b)) in chosen.into_iter().enumerate() { - let liar = LIARS[k % LIARS.len()]; - out.push(format!("{}{liar}{}", &s[..a], &s[b..]).into_bytes()); - } - // Every number lying at once (two counts that are only harmless one at a time). - let all = number_spans(s); - for liar in LIARS { - let mut t = String::with_capacity(s.len()); - let mut at = 0; - for &(a, b) in &all { - t.push_str(&s[at..a]); - t.push_str(liar); - at = b; - } - t.push_str(&s[at..]); - out.push(t.into_bytes()); - } - out -} - -/// Byte spans of the words in `s` (runs of ASCII letters, digits and `_` that start with a -/// letter). -fn word_spans(s: &str) -> Vec<(usize, usize)> { - let b = s.as_bytes(); - let mut out = Vec::new(); - let mut i = 0; - while i < b.len() { - if !b[i].is_ascii_alphabetic() || (i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')) { - i += 1; - continue; - } - let a = i; - while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { - i += 1; - } - out.push((a, i)); - } - out -} - -/// Byte spans of the decimal numbers in `s` (a sign, digits, a point, an exponent). -fn number_spans(s: &str) -> Vec<(usize, usize)> { - let b = s.as_bytes(); - let mut out = Vec::new(); - let mut i = 0; - while i < b.len() { - let starts = b[i].is_ascii_digit() || ((b[i] == b'-' || b[i] == b'.') && b.get(i + 1).is_some_and(u8::is_ascii_digit)); - let after_word = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_'); - if !starts || after_word { - i += 1; - continue; - } - let a = i; - i += 1; - while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.' || ((b[i] == b'e' || b[i] == b'E') && i + 1 < b.len())) { - if (b[i] == b'e' || b[i] == b'E') && (b[i + 1] == b'-' || b[i + 1] == b'+') { - i += 1; - } - i += 1; - } - out.push((a, i)); - } - out -} - -thread_local! { - /// Panics on this thread so far, caught or not ([`count_panics`]). - static PANICS: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -/// Count every panic per thread (tests run on several), then run the hook that was there. -fn count_panics() { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - let previous = std::panic::take_hook(); - std::panic::set_hook(Box::new(move |info| { - PANICS.with(|p| p.set(p.get() + 1)); - previous(info); - })); +#[test] +fn obj_survives_mutation() { + let good = crate::obj(&[("Cube".into(), cube())]).into_bytes(); + assert!(crate::read_obj(&good, "fuzz").is_ok()); + survives("OBJ", &mutations(&good, true, 0x0b1), usize::MAX, |b| { + crate::read_obj(b, "fuzz").ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) }); } -/// The time any one reader call may take on a mutated file (a debug build on a loaded machine: -/// generous, but far below what unbounded work on a lying count would take). -pub(crate) const BUDGET: Duration = Duration::from_secs(2); - -/// Run `read` over `inputs`: no panic, within [`BUDGET`], and `read`'s count (triangles, -/// entities, …) at most `cap`. `read` returns `None` for an error. Panics (the test fails) naming -/// the first case that breaks a rule. -pub(crate) fn survives(what: &str, inputs: &[Vec], cap: usize, mut read: impl FnMut(&[u8]) -> Option) { - count_panics(); - let mut slowest = (Duration::ZERO, 0); - let mut read_ok = 0; - for (i, input) in inputs.iter().enumerate() { - let before = PANICS.with(std::cell::Cell::get); - let t = Instant::now(); - let r = catch_unwind(AssertUnwindSafe(|| read(input))); - let took = t.elapsed(); - let head = String::from_utf8_lossy(&input[..input.len().min(120)]).into_owned(); - let Ok(r) = r else { panic!("{what}: case {i} ({} bytes) panicked; it starts {head:?}", input.len()) }; - let caught = PANICS.with(std::cell::Cell::get) - before; - assert!( - caught == 0, - "{what}: case {i} ({} bytes) panicked inside the reader (caught there, but the browser aborts); it starts {head:?}", - input.len() - ); - assert!(took <= BUDGET, "{what}: case {i} ({} bytes) took {took:?} (budget {BUDGET:?}); it starts {head:?}", input.len()); - if let Some(count) = r { - assert!(count <= cap, "{what}: case {i} gave {count} (cap {cap})"); - read_ok += 1; - } - slowest = slowest.max((took, i)); - } - eprintln!("{what}: {} mutations, {read_ok} read, slowest case {} in {:?}", inputs.len(), slowest.1, slowest.0); -} - -#[cfg(test)] -mod tests { - use super::*; - use solidcraft_geom::{Mesh, Vec2, Vec3}; - - fn cube() -> Mesh { - let positions = (0..8).map(|i| Vec3::new(f64::from(i & 1) * 10.0, f64::from((i >> 1) & 1) * 10.0, f64::from((i >> 2) & 1) * 10.0)).collect(); - let t = [[0, 2, 1], [1, 2, 3], [4, 5, 6], [5, 7, 6], [0, 1, 4], [1, 5, 4], [2, 6, 3], [3, 6, 7], [0, 4, 2], [2, 4, 6], [1, 3, 5], [3, 7, 5]]; - Mesh { positions, triangles: t.to_vec(), ..Default::default() } - } - - #[test] - fn mutations_are_deterministic_and_cover_the_file() { - let good = b"solid x\n facet normal 0 0 1\n vertex 1.5 -2 3e2\n endfacet\nendsolid x\n"; - let a = mutations(good, true, 7); - assert_eq!(a, mutations(good, true, 7), "the same seed gives the same cases"); - assert_ne!(a, mutations(good, true, 8)); - assert!(a.iter().any(Vec::is_empty) && a.iter().any(|m| m.len() == good.len() - 1), "truncations down to nothing"); - assert!(a.iter().any(|m| m.windows(3).any(|w| w == b"nan")), "a number replaced by a liar"); - assert_eq!(number_spans("v 1.5 -2 3e2 x1 .5e-3"), vec![(2, 5), (6, 8), (9, 12), (16, 21)]); - // A long file: bounded truncations, kept to the first and last bytes and spaced between. - let long = vec![b'a'; 100_000]; - let m = mutations(&long, false, 1); - assert!(m.len() < 3000, "{} cases", m.len()); - } - - #[test] - fn stl_survives_mutation() { - let mesh = cube(); - let binary = crate::stl_binary(std::slice::from_ref(&mesh), "fuzz"); - let ascii = crate::stl_ascii(std::slice::from_ref(&mesh), "fuzz").into_bytes(); - assert_eq!(crate::read_stl(&binary).map(|t| t.len()).ok(), Some(12)); - assert_eq!(crate::read_stl(&ascii).map(|t| t.len()).ok(), Some(12)); - let read = |b: &[u8]| crate::read_stl(b).ok().map(|t| t.len()); - survives("binary STL", &mutations(&binary, false, 0x5717), crate::MAX_STL_TRIANGLES, read); - survives("ASCII STL", &mutations(&ascii, true, 0x5718), crate::MAX_STL_TRIANGLES, read); - } - - #[test] - fn obj_survives_mutation() { - let good = crate::obj(&[("Cube".into(), cube())]).into_bytes(); - assert!(crate::read_obj(&good, "fuzz").is_ok()); - survives("OBJ", &mutations(&good, true, 0x0b1), usize::MAX, |b| { - crate::read_obj(b, "fuzz").ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) - }); - } - - #[test] - fn svg_survives_mutation() { - let good = br##" +#[test] +fn svg_survives_mutation() { + let good = br##" @@ -328,266 +45,265 @@ mod tests { "##; - assert!(crate::read_svg(std::str::from_utf8(good).unwrap()).is_ok()); - survives("SVG", &mutations(good, true, 0x5f6), usize::MAX, |b| crate::read_svg(&String::from_utf8_lossy(b)).ok().map(|g| g.len())); - } + assert!(crate::read_svg(std::str::from_utf8(good).unwrap()).is_ok()); + survives("SVG", &mutations(good, true, 0x5f6), usize::MAX, |b| crate::read_svg(&String::from_utf8_lossy(b)).ok().map(|g| g.len())); +} - #[test] - fn dxf_survives_mutation() { - let geom = [ - crate::Geom2::Line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), - crate::Geom2::Circle(Vec2::new(5.0, 5.0), 2.5), - crate::Geom2::Arc { c: Vec2::new(0.0, 0.0), a: Vec2::new(3.0, 0.0), b: Vec2::new(0.0, 3.0) }, - crate::Geom2::Point(Vec2::new(1.0, 1.0)), - ]; - let written = crate::write_dxf(&geom).into_bytes(); - assert!(crate::read_dxf(std::str::from_utf8(&written).unwrap()).is_ok_and(|g| g.len() >= 3)); - survives("DXF (written)", &mutations(&written, true, 0xdf), usize::MAX, |b| { - crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) - }); - // Blocks inside blocks, an array insert and a bulged polyline: what the block recursion, - // the array cells and the work budget guard. - let pairs: &[(&str, &str)] = &[ - ("0", "SECTION"), - ("2", "BLOCKS"), - ("0", "BLOCK"), - ("2", "inner"), - ("10", "0"), - ("20", "0"), - ("0", "LINE"), - ("10", "0"), - ("20", "0"), - ("11", "1"), - ("21", "1"), - ("0", "ENDBLK"), - ("0", "BLOCK"), - ("2", "outer"), - ("10", "0"), - ("20", "0"), - ("0", "INSERT"), - ("2", "inner"), - ("10", "2"), - ("20", "2"), - ("0", "CIRCLE"), - ("10", "0"), - ("20", "0"), - ("40", "1"), - ("0", "ENDBLK"), - ("0", "ENDSEC"), - ("0", "SECTION"), - ("2", "ENTITIES"), - ("0", "INSERT"), - ("2", "outer"), - ("10", "5"), - ("20", "5"), - ("41", "2"), - ("42", "2"), - ("50", "30"), - ("70", "3"), - ("71", "2"), - ("44", "10"), - ("45", "10"), - ("0", "LWPOLYLINE"), - ("90", "3"), - ("70", "1"), - ("10", "0"), - ("20", "0"), - ("42", "0.5"), - ("10", "5"), - ("20", "0"), - ("10", "5"), - ("20", "5"), - ("0", "ENDSEC"), - ("0", "EOF"), - ]; - let blocks: String = pairs - .iter() - .map(|(c, v)| { - format!( - "{c} +#[test] +fn dxf_survives_mutation() { + let geom = [ + crate::Geom2::Line(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)), + crate::Geom2::Circle(Vec2::new(5.0, 5.0), 2.5), + crate::Geom2::Arc { c: Vec2::new(0.0, 0.0), a: Vec2::new(3.0, 0.0), b: Vec2::new(0.0, 3.0) }, + crate::Geom2::Point(Vec2::new(1.0, 1.0)), + ]; + let written = crate::write_dxf(&geom).into_bytes(); + assert!(crate::read_dxf(std::str::from_utf8(&written).unwrap()).is_ok_and(|g| g.len() >= 3)); + survives("DXF (written)", &mutations(&written, true, 0xdf), usize::MAX, |b| crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len())); + // Blocks inside blocks, an array insert and a bulged polyline: what the block recursion, + // the array cells and the work budget guard. + let pairs: &[(&str, &str)] = &[ + ("0", "SECTION"), + ("2", "BLOCKS"), + ("0", "BLOCK"), + ("2", "inner"), + ("10", "0"), + ("20", "0"), + ("0", "LINE"), + ("10", "0"), + ("20", "0"), + ("11", "1"), + ("21", "1"), + ("0", "ENDBLK"), + ("0", "BLOCK"), + ("2", "outer"), + ("10", "0"), + ("20", "0"), + ("0", "INSERT"), + ("2", "inner"), + ("10", "2"), + ("20", "2"), + ("0", "CIRCLE"), + ("10", "0"), + ("20", "0"), + ("40", "1"), + ("0", "ENDBLK"), + ("0", "ENDSEC"), + ("0", "SECTION"), + ("2", "ENTITIES"), + ("0", "INSERT"), + ("2", "outer"), + ("10", "5"), + ("20", "5"), + ("41", "2"), + ("42", "2"), + ("50", "30"), + ("70", "3"), + ("71", "2"), + ("44", "10"), + ("45", "10"), + ("0", "LWPOLYLINE"), + ("90", "3"), + ("70", "1"), + ("10", "0"), + ("20", "0"), + ("42", "0.5"), + ("10", "5"), + ("20", "0"), + ("10", "5"), + ("20", "5"), + ("0", "ENDSEC"), + ("0", "EOF"), + ]; + let blocks: String = pairs + .iter() + .map(|(c, v)| { + format!( + "{c} {v} " - ) - }) - .collect(); - let n = crate::read_dxf(&blocks).map(|g| g.len()).unwrap_or(0); - assert!(n >= 12, "the array insert expands its nested blocks: {n} entities"); - survives("DXF (blocks)", &mutations(blocks.as_bytes(), true, 0xdb), usize::MAX, |b| { - crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) - }); - // The two lies that need each other, written out: a block that inserts itself (the - // depth limit), and an array of 10,000 by 10,000 copies (the cell and work budgets). - let looped = blocks.replacen( - "2 + ) + }) + .collect(); + let n = crate::read_dxf(&blocks).map(|g| g.len()).unwrap_or(0); + assert!(n >= 12, "the array insert expands its nested blocks: {n} entities"); + survives("DXF (blocks)", &mutations(blocks.as_bytes(), true, 0xdb), usize::MAX, |b| { + crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) + }); + // The two lies that need each other, written out: a block that inserts itself (the + // depth limit), and an array of 10,000 by 10,000 copies (the cell and work budgets). + let looped = blocks.replacen( + "2 inner 10 2", - "2 + "2 outer 10 2", - 1, - ); - assert_ne!(looped, blocks, "the outer block now inserts itself"); - let huge = blocks.replacen( - "70 + 1, + ); + assert_ne!(looped, blocks, "the outer block now inserts itself"); + let huge = blocks.replacen( + "70 3 71 2", - "70 + "70 10000 71 10000", - 1, - ); - assert_ne!(huge, blocks); - survives("DXF (self-insert, huge array)", &[looped.into_bytes(), huge.into_bytes()], usize::MAX, |b| { - crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) - }); - } + 1, + ); + assert_ne!(huge, blocks); + survives("DXF (self-insert, huge array)", &[looped.into_bytes(), huge.into_bytes()], usize::MAX, |b| { + crate::read_dxf(&String::from_utf8_lossy(b)).ok().map(|g| g.len()) + }); +} - #[test] - fn threemf_survives_mutation() { - let mesh = cube(); - let object = crate::MeshObject { - name: "Cube".into(), - positions: mesh.positions, - triangles: mesh.triangles, - color: Some([0.8, 0.2, 0.1]), - ..Default::default() - }; - let good = crate::write_3mf(&[object]).unwrap(); - assert!(crate::read_3mf(&good).is_ok()); - survives("3MF", &mutations(&good, false, 0x3f), usize::MAX, |b| { +#[test] +fn threemf_survives_mutation() { + let mesh = cube(); + let object = crate::MeshObject { + name: "Cube".into(), + positions: mesh.positions, + triangles: mesh.triangles, + color: Some([0.8, 0.2, 0.1]), + ..Default::default() + }; + let good = crate::write_3mf(&[object]).unwrap(); + assert!(crate::read_3mf(&good).is_ok()); + survives("3MF", &mutations(&good, false, 0x3f), usize::MAX, |b| { + crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) + }); + // Objects in another model part (production extension), as slicers save projects. + let production = crate::threemf::tests::production_package(); + assert!(crate::read_3mf(&production).is_ok()); + survives("3MF (production extension)", &mutations(&production, false, 0x2089), usize::MAX, |b| { + crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) + }); + // Its model parts' XML mutated and zipped again: mutations of the zip mostly stop at its + // checksums, these reach the `p:path` and `objectid` handling. + let parts = crate::threemf::tests::production_parts(); + for (k, (name, xml)) in parts.iter().enumerate() { + let rezipped: Vec> = mutations(xml.as_bytes(), true, 0x2089 + k as u64) + .iter() + .map(|m| { + let entries: Vec<(&str, &[u8])> = parts.iter().map(|(n, x)| (*n, if n == name { m.as_slice() } else { x.as_bytes() })).collect(); + crate::threemf::tests::package_bytes(&entries) + }) + .collect(); + survives(&format!("3MF (production extension, {name} mutated)"), &rezipped, usize::MAX, |b| { crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) }); - // Objects in another model part (production extension), as slicers save projects. - let production = crate::threemf::tests::production_package(); - assert!(crate::read_3mf(&production).is_ok()); - survives("3MF (production extension)", &mutations(&production, false, 0x2089), usize::MAX, |b| { - crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) - }); - // Its model parts' XML mutated and zipped again: mutations of the zip mostly stop at its - // checksums, these reach the `p:path` and `objectid` handling. - let parts = crate::threemf::tests::production_parts(); - for (k, (name, xml)) in parts.iter().enumerate() { - let rezipped: Vec> = mutations(xml.as_bytes(), true, 0x2089 + k as u64) - .iter() - .map(|m| { - let entries: Vec<(&str, &[u8])> = parts.iter().map(|(n, x)| (*n, if n == name { m.as_slice() } else { x.as_bytes() })).collect(); - crate::threemf::tests::package_bytes(&entries) - }) - .collect(); - survives(&format!("3MF (production extension, {name} mutated)"), &rezipped, usize::MAX, |b| { - crate::read_3mf(b).ok().map(|(objects, _)| objects.iter().map(|o| o.triangles.len()).sum()) - }); - } - } - - #[test] - fn gltf_survives_mutation() { - let mut f = crate::gltf_in::tests::Fixture::default(); - let m = f.cube_mesh("Cube", 0.01); - let child = f.node(serde_json::json!({"name": "C", "mesh": m, "translation": [0.0, 0.1, 0.0]})); - let n = f.node(serde_json::json!({"mesh": m, "children": [child], "rotation": [0.0, 0.0, std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2]})); - f.roots = vec![n]; - let mut no_files = |name: &str| -> std::result::Result, String> { Err(format!("no file `{name}`")) }; - let glb = f.glb(); - assert!(crate::read_gltf(&glb, "fuzz.glb", &mut no_files).is_ok()); - survives("glTF (.glb)", &mutations(&glb, false, 0x91b), usize::MAX, |b| crate::read_gltf(b, "fuzz.glb", &mut no_files).ok().map(|_| 1)); - // The JSON form, its buffer embedded as a data URI. - let uri = format!("data:application/octet-stream;base64,{}", base64(&f.bin)); - let gltf = f.json(Some(&uri)).to_string().into_bytes(); - assert!(crate::read_gltf(&gltf, "fuzz.gltf", &mut no_files).is_ok()); - survives("glTF (.gltf)", &mutations(&gltf, true, 0x917), usize::MAX, |b| crate::read_gltf(b, "fuzz.gltf", &mut no_files).ok().map(|_| 1)); - } - - #[test] - fn designs_survive_mutation() { - let mut doc = solidcraft_doc::Document::new("Fuzz"); - doc.set_param("width", "40", Some("mm"), None).unwrap(); - let mesh = solidcraft_doc::MeshData { - name: "Preview".into(), - positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0].into(), - triangles: vec![0, 1, 2].into(), - color: None, - }; - let preview = crate::DesignPreview { meshes: vec![mesh] }; - let container = crate::write_design_container_with_preview(&doc, crate::DesignCompression::Fast, Some(&preview)).unwrap(); - assert!(crate::read_design(&container).is_ok() && crate::read_design_preview(&container).is_some()); - survives("design container", &mutations(&container, false, 0xde5), usize::MAX, |b| { - let _ = crate::read_design_preview(b); - let _ = crate::read_design_thumbnail(b); - crate::read_design(b).ok().map(|d| d.features.len()) - }); - let json = crate::write_design(&doc); - assert!(crate::read_design(&json).is_ok()); - survives("design JSON", &mutations(&json, true, 0xde6), usize::MAX, |b| crate::read_design(b).ok().map(|d| d.features.len())); - } - - /// A drawing, as a container and as plain JSON: every mutation gives an error or a drawing, - /// never a panic, and `file_kind` always answers. - #[test] - fn drawings_survive_mutation() { - use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet}; - let mut ids = solidcraft_doc::ids::IdSource::seeded(0xd4a); - let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); - let mut drawing = solidcraft_doc::drawing::Drawing::new("Fuzz", "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &mut ids).unwrap(); - let id = drawing.allocate_id(&mut ids).unwrap(); - drawing.sources.push(solidcraft_doc::drawing::Source { id, path: "plate.sc".into() }); - let container = crate::write_drawing_container(&drawing).unwrap(); - assert!(crate::read_drawing(&container).is_ok()); - survives("drawing container", &mutations(&container, false, 0xd4b), usize::MAX, |b| { - let _ = crate::file_kind(b); - let _ = crate::read_design(b); - crate::read_drawing(b).ok().map(|d| d.sheets.len()) - }); - let json = drawing.to_json().unwrap().into_bytes(); - assert!(crate::read_drawing(&json).is_ok()); - survives("drawing JSON", &mutations(&json, true, 0xd4c), usize::MAX, |b| { - let _ = crate::file_kind(b); - crate::read_drawing(b).ok().map(|d| d.sheets.len()) - }); - } - - /// A paper scene's JSON, mutated, read, prepared and written as SVG: an error or a document, - /// never a panic. - #[test] - fn paper_scenes_survive_mutation_into_svg() { - use solidcraft_geom::paper::{Group, Item, ObjectKind, Scene}; - use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; - let p = Vec2::new; - let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]); - let items = vec![ - Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7 }, - Item::Stroke { path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], closed: false, width_mm: 0.35 }, - Item::Fill { region: Region2 { outer: border, holes: vec![] } }, - ]; - let scene = Scene { size_mm: p(420.0, 297.0), groups: vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }] }; - let json = serde_json::to_vec(&scene).unwrap(); - let write = |b: &[u8]| -> Option { - let scene: Scene = serde_json::from_slice(b).ok()?; - let prepared = scene.prepare().ok()?; - crate::paper::paper_svg(&prepared).ok().map(|(bytes, _)| bytes.len()) - }; - assert!(write(&json).is_some()); - survives("paper scene to SVG", &mutations(&json, true, 0x5a3), usize::MAX, write); - } - - /// Standard base64 (RFC 4648) of `bytes`, for a data URI. - fn base64(bytes: &[u8]) -> String { - const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - let mut s = String::new(); - for c in bytes.chunks(3) { - let v = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); - for k in 0..4 { - if k <= c.len() { - s.push(char::from(A[(v >> (18 - 6 * k)) as usize & 63])); - } else { - s.push('='); - } - } - } - s } } + +#[test] +fn gltf_survives_mutation() { + let mut f = crate::gltf_in::tests::Fixture::default(); + let m = f.cube_mesh("Cube", 0.01); + let child = f.node(serde_json::json!({"name": "C", "mesh": m, "translation": [0.0, 0.1, 0.0]})); + let n = f.node( + serde_json::json!({"mesh": m, "children": [child], "rotation": [0.0, 0.0, std::f64::consts::FRAC_1_SQRT_2, std::f64::consts::FRAC_1_SQRT_2]}), + ); + f.roots = vec![n]; + let mut no_files = |name: &str| -> std::result::Result, String> { Err(format!("no file `{name}`")) }; + let glb = f.glb(); + assert!(crate::read_gltf(&glb, "fuzz.glb", &mut no_files).is_ok()); + survives("glTF (.glb)", &mutations(&glb, false, 0x91b), usize::MAX, |b| crate::read_gltf(b, "fuzz.glb", &mut no_files).ok().map(|_| 1)); + // The JSON form, its buffer embedded as a data URI. + let uri = format!("data:application/octet-stream;base64,{}", base64(&f.bin)); + let gltf = f.json(Some(&uri)).to_string().into_bytes(); + assert!(crate::read_gltf(&gltf, "fuzz.gltf", &mut no_files).is_ok()); + survives("glTF (.gltf)", &mutations(&gltf, true, 0x917), usize::MAX, |b| crate::read_gltf(b, "fuzz.gltf", &mut no_files).ok().map(|_| 1)); +} + +#[test] +fn designs_survive_mutation() { + let mut doc = solidcraft_doc::Document::new("Fuzz"); + doc.set_param("width", "40", Some("mm"), None).unwrap(); + let mesh = solidcraft_doc::MeshData { + name: "Preview".into(), + positions: vec![0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0].into(), + triangles: vec![0, 1, 2].into(), + color: None, + }; + let preview = crate::DesignPreview { meshes: vec![mesh] }; + let container = crate::write_design_container_with_preview(&doc, crate::DesignCompression::Fast, Some(&preview)).unwrap(); + assert!(crate::read_design(&container).is_ok() && crate::read_design_preview(&container).is_some()); + survives("design container", &mutations(&container, false, 0xde5), usize::MAX, |b| { + let _ = crate::read_design_preview(b); + let _ = crate::read_design_thumbnail(b); + crate::read_design(b).ok().map(|d| d.features.len()) + }); + let json = crate::write_design(&doc); + assert!(crate::read_design(&json).is_ok()); + survives("design JSON", &mutations(&json, true, 0xde6), usize::MAX, |b| crate::read_design(b).ok().map(|d| d.features.len())); +} + +/// A drawing, as a container and as plain JSON: every mutation gives an error or a drawing, +/// never a panic, and `file_kind` always answers. +#[test] +fn drawings_survive_mutation() { + use solidcraft_geom::drawing_sheet::{DrawingBorderProfile, Orientation, PaperSize, Sheet}; + let mut ids = solidcraft_doc::ids::IdSource::seeded(0xd4a); + let a3 = Sheet::standard(PaperSize::A3, Orientation::Landscape); + let mut drawing = solidcraft_doc::drawing::Drawing::new("Fuzz", "en", "Sheet 1", a3, Some(DrawingBorderProfile::iso()), &mut ids).unwrap(); + let id = drawing.allocate_id(&mut ids).unwrap(); + drawing.sources.push(solidcraft_doc::drawing::Source { id, path: "plate.sc".into() }); + let container = crate::write_drawing_container(&drawing).unwrap(); + assert!(crate::read_drawing(&container).is_ok()); + survives("drawing container", &mutations(&container, false, 0xd4b), usize::MAX, |b| { + let _ = crate::file_kind(b); + let _ = crate::read_design(b); + crate::read_drawing(b).ok().map(|d| d.sheets.len()) + }); + let json = drawing.to_json().unwrap().into_bytes(); + assert!(crate::read_drawing(&json).is_ok()); + survives("drawing JSON", &mutations(&json, true, 0xd4c), usize::MAX, |b| { + let _ = crate::file_kind(b); + crate::read_drawing(b).ok().map(|d| d.sheets.len()) + }); +} + +/// A paper scene's JSON, mutated, read, prepared and written as SVG: an error or a document, +/// never a panic. +#[test] +fn paper_scenes_survive_mutation_into_svg() { + use solidcraft_geom::paper::{Group, Item, ObjectKind, Scene}; + use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; + let p = Vec2::new; + let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]); + let items = vec![ + Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7 }, + Item::Stroke { path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], closed: false, width_mm: 0.35 }, + Item::Fill { region: Region2 { outer: border, holes: vec![] } }, + ]; + let scene = Scene { size_mm: p(420.0, 297.0), groups: vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }] }; + let json = serde_json::to_vec(&scene).unwrap(); + let write = |b: &[u8]| -> Option { + let scene: Scene = serde_json::from_slice(b).ok()?; + let prepared = scene.prepare().ok()?; + crate::paper::paper_svg(&prepared).ok().map(|(bytes, _)| bytes.len()) + }; + assert!(write(&json).is_some()); + survives("paper scene to SVG", &mutations(&json, true, 0x5a3), usize::MAX, write); +} + +/// Standard base64 (RFC 4648) of `bytes`, for a data URI. +fn base64(bytes: &[u8]) -> String { + const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut s = String::new(); + for c in bytes.chunks(3) { + let v = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0)); + for k in 0..4 { + if k <= c.len() { + s.push(char::from(A[(v >> (18 - 6 * k)) as usize & 63])); + } else { + s.push('='); + } + } + } + s +} diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml new file mode 100644 index 000000000..118c436d2 --- /dev/null +++ b/crates/testkit/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "solidcraft-testkit" +description = "SolidCraft test tooling: deterministic mutations of valid files and the no-panic check run over them (a dev-dependency only)" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs new file mode 100644 index 000000000..60ba9eccc --- /dev/null +++ b/crates/testkit/src/lib.rs @@ -0,0 +1,294 @@ +//! Deterministic mutations of valid files, and the readers run over them (#469). Every reader of +//! bytes the user didn't write gets the same treatment: truncation, flipped and overwritten +//! bytes, dropped and repeated runs, appended garbage and, for text formats, dropped and +//! repeated lines and numbers that lie (`nan`, `inf`, `1e400`, …). Each mutated file must give an +//! error or a result, never a panic, within a time budget and the reader's own caps. A panic a +//! reader catches itself (`solidcraft_kernel::guard`) counts too: the browser build aborts on any +//! panic, so a caught one on the desktop is a crash there. +//! +//! The mutations come from a fixed seed (xorshift), so a failure names a case that reproduces. +//! No fuzzing dependency, nothing nightly, nothing native: it runs in the normal test suite and +//! builds for wasm. The readers' own hand-written cases stay; they cover particular lies (a +//! length in a container header) that random changes rarely hit. STEP, IGES and FreeCAD/Rhino +//! files are read by the kernel, which is moving to solidcore (#1597), and keep their own tests. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::time::{Duration, Instant}; + +/// A deterministic xorshift64 stream. +struct Rng(u64); + +impl Rng { + fn new(seed: u64) -> Rng { + Rng(seed | 1) + } + + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + /// A value in `0..n` (0 when `n` is 0). + fn below(&mut self, n: usize) -> usize { + if n == 0 { 0 } else { (self.next() % n as u64) as usize } + } +} + +/// Numbers a hostile file might hold in place of a real one. +const LIARS: [&str; 10] = ["nan", "inf", "-inf", "1e400", "-1e400", "-0", "4294967296", "-1", "99999999999999999999", "0x7fffffff"]; + +/// Most truncations of one file (every length up to this, evenly spaced beyond). +const MAX_TRUNCATIONS: usize = 1024; + +/// Mutations of `good`, the same for the same `good` and `seed`. `text`: also line and number +/// mutations (the file is UTF-8 text). +pub fn mutations(good: &[u8], text: bool, seed: u64) -> Vec> { + let mut out: Vec> = Vec::new(); + let n = good.len(); + let mut rng = Rng::new(seed); + // Truncations: every length of a short file; of a long one, its first and last 64 lengths + // (headers, final records) and evenly spaced ones between. + if n <= MAX_TRUNCATIONS { + out.extend((0..n).map(|k| good[..k].to_vec())); + } else { + let mut cuts: Vec = (0..64).chain(n - 64..n).collect(); + cuts.extend((0..MAX_TRUNCATIONS - 128).map(|i| 64 + i * (n - 128) / (MAX_TRUNCATIONS - 128))); + cuts.sort_unstable(); + cuts.dedup(); + out.extend(cuts.into_iter().map(|k| good[..k].to_vec())); + } + if n == 0 { + return out; + } + // Bytes flipped, zeroed and saturated at seeded places. + for i in 0..384 { + let at = rng.below(n); + let mut b = good.to_vec(); + b[at] = match i % 3 { + 0 => b[at] ^ ((rng.next() >> 32) as u8 | 1), + 1 => 0x00, + _ => 0xff, + }; + out.push(b); + } + // Runs of bytes dropped, repeated and swapped with their neighbour. + for _ in 0..96 { + let at = rng.below(n); + let len = 1 + rng.below(64.min(n - at)); + let end = at + len; + let mut dropped = good[..at].to_vec(); + dropped.extend_from_slice(&good[end..]); + out.push(dropped); + let mut repeated = good[..end].to_vec(); + repeated.extend_from_slice(&good[at..]); + out.push(repeated); + if end + len <= n { + let mut swapped = good[..at].to_vec(); + swapped.extend_from_slice(&good[end..end + len]); + swapped.extend_from_slice(&good[at..end]); + swapped.extend_from_slice(&good[end + len..]); + out.push(swapped); + } + } + // The whole file: with garbage after it, twice over, reversed. + let mut tail = good.to_vec(); + tail.extend((0..4096).map(|_| (rng.next() >> 40) as u8)); + out.push(tail); + out.push([good, good].concat()); + out.push(good.iter().rev().copied().collect()); + if text && let Ok(s) = std::str::from_utf8(good) { + out.extend(text_mutations(s, &mut rng)); + } + out +} + +/// A text file's lines dropped, repeated and swapped, and its numbers replaced by lies. +fn text_mutations(s: &str, rng: &mut Rng) -> Vec> { + let mut out = Vec::new(); + let lines: Vec<&str> = s.split_inclusive('\n').collect(); + let join = |v: &[&str]| v.concat().into_bytes(); + let picked: Vec = if lines.len() <= 200 { (0..lines.len()).collect() } else { (0..200).map(|_| rng.below(lines.len())).collect() }; + for &i in &picked { + let mut v = lines.clone(); + v.remove(i); + out.push(join(&v)); + let mut v = lines.clone(); + v.insert(i, lines[i]); + out.push(join(&v)); + if i + 1 < lines.len() { + let mut v = lines.clone(); + v.swap(i, i + 1); + out.push(join(&v)); + } + } + // A line in place of another (a block that inserts itself, a count where a coordinate was). + for _ in 0..200.min(lines.len() * lines.len()) { + let (i, j) = (rng.below(lines.len()), rng.below(lines.len())); + let mut v = lines.clone(); + v[i] = lines[j]; + out.push(join(&v)); + } + // A word in place of another of the file's own words: a renamed block, a swapped keyword, a + // block that now inserts itself. Every pair in a small file, a sample in a large one. + let words = word_spans(s); + let mut vocab: Vec<&str> = words.iter().map(|&(a, b)| &s[a..b]).collect(); + vocab.sort_unstable(); + vocab.dedup(); + let pairs = words.len().saturating_mul(vocab.len()); + let swap = |(a, b): (usize, usize), w: &str| format!("{}{w}{}", &s[..a], &s[b..]).into_bytes(); + if pairs <= 3000 { + for &span in &words { + for &w in vocab.iter().filter(|w| **w != &s[span.0..span.1]) { + out.push(swap(span, w)); + } + } + } else { + for _ in 0..400 { + out.push(swap(words[rng.below(words.len())], vocab[rng.below(vocab.len())])); + } + } + // Numbers: each of up to 200 of them, in turn, becomes one of the liars. + let numbers = number_spans(s); + let chosen: Vec<(usize, usize)> = if numbers.len() <= 200 { numbers } else { (0..200).map(|_| numbers[rng.below(numbers.len())]).collect() }; + for (k, (a, b)) in chosen.into_iter().enumerate() { + let liar = LIARS[k % LIARS.len()]; + out.push(format!("{}{liar}{}", &s[..a], &s[b..]).into_bytes()); + } + // Every number lying at once (two counts that are only harmless one at a time). + let all = number_spans(s); + for liar in LIARS { + let mut t = String::with_capacity(s.len()); + let mut at = 0; + for &(a, b) in &all { + t.push_str(&s[at..a]); + t.push_str(liar); + at = b; + } + t.push_str(&s[at..]); + out.push(t.into_bytes()); + } + out +} + +/// Byte spans of the words in `s` (runs of ASCII letters, digits and `_` that start with a +/// letter). +fn word_spans(s: &str) -> Vec<(usize, usize)> { + let b = s.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + if !b[i].is_ascii_alphabetic() || (i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')) { + i += 1; + continue; + } + let a = i; + while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { + i += 1; + } + out.push((a, i)); + } + out +} + +/// Byte spans of the decimal numbers in `s` (a sign, digits, a point, an exponent). +fn number_spans(s: &str) -> Vec<(usize, usize)> { + let b = s.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + let starts = b[i].is_ascii_digit() || ((b[i] == b'-' || b[i] == b'.') && b.get(i + 1).is_some_and(u8::is_ascii_digit)); + let after_word = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_'); + if !starts || after_word { + i += 1; + continue; + } + let a = i; + i += 1; + while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.' || ((b[i] == b'e' || b[i] == b'E') && i + 1 < b.len())) { + if (b[i] == b'e' || b[i] == b'E') && (b[i + 1] == b'-' || b[i + 1] == b'+') { + i += 1; + } + i += 1; + } + out.push((a, i)); + } + out +} + +thread_local! { + /// Panics on this thread so far, caught or not ([`count_panics`]). + static PANICS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Count every panic per thread (tests run on several), then run the hook that was there. +fn count_panics() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + PANICS.with(|p| p.set(p.get() + 1)); + previous(info); + })); + }); +} + +/// The time any one reader call may take on a mutated file (a debug build on a loaded machine: +/// generous, but far below what unbounded work on a lying count would take). +pub const BUDGET: Duration = Duration::from_secs(2); + +/// Run `read` over `inputs`: no panic, within [`BUDGET`], and `read`'s count (triangles, +/// entities, …) at most `cap`. `read` returns `None` for an error. Panics (the test fails) naming +/// the first case that breaks a rule. +// Failing the calling test is this function's job; it only ever runs inside tests. +#[allow(clippy::panic)] +pub fn survives(what: &str, inputs: &[Vec], cap: usize, mut read: impl FnMut(&[u8]) -> Option) { + count_panics(); + let mut slowest = (Duration::ZERO, 0); + let mut read_ok = 0; + for (i, input) in inputs.iter().enumerate() { + let before = PANICS.with(std::cell::Cell::get); + let t = Instant::now(); + let r = catch_unwind(AssertUnwindSafe(|| read(input))); + let took = t.elapsed(); + let head = String::from_utf8_lossy(&input[..input.len().min(120)]).into_owned(); + let Ok(r) = r else { panic!("{what}: case {i} ({} bytes) panicked; it starts {head:?}", input.len()) }; + let caught = PANICS.with(std::cell::Cell::get) - before; + assert!( + caught == 0, + "{what}: case {i} ({} bytes) panicked inside the reader (caught there, but the browser aborts); it starts {head:?}", + input.len() + ); + assert!(took <= BUDGET, "{what}: case {i} ({} bytes) took {took:?} (budget {BUDGET:?}); it starts {head:?}", input.len()); + if let Some(count) = r { + assert!(count <= cap, "{what}: case {i} gave {count} (cap {cap})"); + read_ok += 1; + } + slowest = slowest.max((took, i)); + } + eprintln!("{what}: {} mutations, {read_ok} read, slowest case {} in {:?}", inputs.len(), slowest.1, slowest.0); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mutations_are_deterministic_and_cover_the_file() { + let good = b"solid x\n facet normal 0 0 1\n vertex 1.5 -2 3e2\n endfacet\nendsolid x\n"; + let a = mutations(good, true, 7); + assert_eq!(a, mutations(good, true, 7), "the same seed gives the same cases"); + assert_ne!(a, mutations(good, true, 8)); + assert!(a.iter().any(Vec::is_empty) && a.iter().any(|m| m.len() == good.len() - 1), "truncations down to nothing"); + assert!(a.iter().any(|m| m.windows(3).any(|w| w == b"nan")), "a number replaced by a liar"); + assert_eq!(number_spans("v 1.5 -2 3e2 x1 .5e-3"), vec![(2, 5), (6, 8), (9, 12), (16, 21)]); + // A long file: bounded truncations, kept to the first and last bytes and spaced between. + let long = vec![b'a'; 100_000]; + let m = mutations(&long, false, 1); + assert!(m.len() < 3000, "{} cases", m.len()); + } +} From 446590dca133cbcff8d70c113c2df4e11e37a0b9 Mon Sep 17 00:00:00 2001 From: Kushagra Kumar <38453569+kk376@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:00:44 +0000 Subject: [PATCH 32/55] fix(engine): report design variant in timeline.inspect and accept in timeline.add (#10748) (#10792) * fix(engine): report design variant in timeline.inspect and accept in timeline.add (#10748) * ci: refresh checks to clear cancelled workflow run --- crates/doc/src/document.rs | 161 ++++++++++++++++++++++++++ crates/doc/src/tests.rs | 16 +++ crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/script.rs | 13 +++ crates/engine/src/cmd/script_tests.rs | 28 +++++ crates/engine/src/tests.rs | 3 +- docs/book/src/guide/features.md | 2 +- docs/book/src/reference/glossary.md | 4 +- 8 files changed, 224 insertions(+), 5 deletions(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index bd4711568..51c2fb760 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2433,6 +2433,167 @@ impl FeatureKind { FeatureKind::MeshConvert { .. } => "MeshConvertFeature", } } + + /// Design-file variant key (e.g. `"extrude"`, `"box"`, `"sheet_flange"`). + pub fn kind_key(&self) -> &'static str { + match self { + FeatureKind::BodyTransfer { .. } => "body_transfer", + FeatureKind::Sketch { .. } => "sketch", + FeatureKind::Extrude { .. } => "extrude", + FeatureKind::Revolve { .. } => "revolve", + FeatureKind::Fillet { .. } => "fillet", + FeatureKind::Chamfer { .. } => "chamfer", + FeatureKind::Box { .. } => "box", + FeatureKind::Cylinder { .. } => "cylinder", + FeatureKind::Sphere { .. } => "sphere", + FeatureKind::Torus { .. } => "torus", + FeatureKind::Cone { .. } => "cone", + FeatureKind::Combine { .. } => "combine", + FeatureKind::Pattern { .. } => "pattern", + FeatureKind::Mirror { .. } => "mirror", + FeatureKind::Hole { .. } => "hole", + FeatureKind::Thread { .. } => "thread", + FeatureKind::Loft { .. } => "loft", + FeatureKind::Sweep { .. } => "sweep", + FeatureKind::Shell { .. } => "shell", + FeatureKind::Draft { .. } => "draft", + FeatureKind::ConstructionPlane { .. } => "construction_plane", + FeatureKind::Split { .. } => "split", + FeatureKind::ConstructionAxis { .. } => "construction_axis", + FeatureKind::ConstructionPoint { .. } => "construction_point", + FeatureKind::SplitFace { .. } => "split_face", + FeatureKind::Scale { .. } => "scale", + FeatureKind::OffsetFace { .. } => "offset_face", + FeatureKind::DeleteFace { .. } => "delete_face", + FeatureKind::BoundingSolid { .. } => "bounding_solid", + FeatureKind::Pipe { .. } => "pipe", + FeatureKind::FrameMember { .. } => "frame_member", + FeatureKind::Emboss { .. } => "emboss", + FeatureKind::Rib { .. } => "rib", + FeatureKind::ReplaceFace { .. } => "replace_face", + FeatureKind::Align { .. } => "align", + FeatureKind::Coil { .. } => "coil", + FeatureKind::SheetBase { .. } => "sheet_base", + FeatureKind::SheetContour { .. } => "sheet_contour", + FeatureKind::SheetFlange { .. } => "sheet_flange", + FeatureKind::SheetHem { .. } => "sheet_hem", + FeatureKind::SheetPerforate { .. } => "sheet_perforate", + FeatureKind::SheetFold { .. } => "sheet_fold", + FeatureKind::SheetPath { .. } => "sheet_path", + FeatureKind::SheetUnfold { .. } => "sheet_unfold", + FeatureKind::SheetConvert { .. } => "sheet_convert", + FeatureKind::Boss { .. } => "boss", + FeatureKind::Lip { .. } => "lip", + FeatureKind::SnapFit { .. } => "snap_fit", + FeatureKind::Rest { .. } => "rest", + FeatureKind::BoundaryFill { .. } => "boundary_fill", + FeatureKind::Remove { .. } => "remove", + FeatureKind::Patch { .. } => "patch", + FeatureKind::Stitch { .. } => "stitch", + FeatureKind::Thicken { .. } => "thicken", + FeatureKind::SurfaceExtrude { .. } => "surface_extrude", + FeatureKind::Unstitch { .. } => "unstitch", + FeatureKind::ReverseNormal { .. } => "reverse_normal", + FeatureKind::SurfaceUntrim { .. } => "surface_untrim", + FeatureKind::SurfaceRevolve { .. } => "surface_revolve", + FeatureKind::SurfaceSweep { .. } => "surface_sweep", + FeatureKind::SurfaceLoft { .. } => "surface_loft", + FeatureKind::SurfaceOffset { .. } => "surface_offset", + FeatureKind::SurfaceRuled { .. } => "surface_ruled", + FeatureKind::SurfaceExtend { .. } => "surface_extend", + FeatureKind::SurfaceBlend { .. } => "surface_blend", + FeatureKind::SurfaceBoundary { .. } => "surface_boundary", + FeatureKind::SurfaceNetwork { .. } => "surface_network", + FeatureKind::SurfaceMatch { .. } => "surface_match", + FeatureKind::SurfaceFair { .. } => "surface_fair", + FeatureKind::SurfaceTrim { .. } => "surface_trim", + FeatureKind::Move { .. } => "move", + FeatureKind::Import { .. } => "import", + FeatureKind::MeshConvert { .. } => "mesh_convert", + FeatureKind::MeshImport { .. } => "mesh_import", + } + } + + /// Map a display or Rust type name (e.g. `"HoleFeature"`, `"EdgeFlangeFeature"`) + /// to the canonical design-file variant key (`"hole"`, `"sheet_flange"`). + pub fn type_name_to_kind_key(name: &str) -> Option<&'static str> { + Some(match name { + "BodyTransferFeature" => "body_transfer", + "Sketch" => "sketch", + "ExtrudeFeature" => "extrude", + "RevolveFeature" => "revolve", + "FilletFeature" => "fillet", + "ChamferFeature" => "chamfer", + "BoxFeature" => "box", + "CylinderFeature" => "cylinder", + "SphereFeature" => "sphere", + "TorusFeature" => "torus", + "ConeFeature" => "cone", + "CombineFeature" => "combine", + "RectangularPatternFeature" | "PathPatternFeature" | "CircularPatternFeature" => "pattern", + "MirrorFeature" => "mirror", + "ConstructionPlane" => "construction_plane", + "HoleFeature" => "hole", + "ThreadFeature" => "thread", + "LoftFeature" => "loft", + "SweepFeature" => "sweep", + "ShellFeature" => "shell", + "DraftFeature" => "draft", + "SplitBodyFeature" => "split", + "SplitFaceFeature" => "split_face", + "ConstructionAxis" => "construction_axis", + "ConstructionPoint" => "construction_point", + "MoveFeature" => "move", + "ScaleFeature" => "scale", + "OffsetFacesFeature" => "offset_face", + "DeleteFaceFeature" => "delete_face", + "OffsetSurfaceFeature" => "surface_offset", + "BoundingSolidFeature" => "bounding_solid", + "PipeFeature" => "pipe", + "FrameMemberFeature" => "frame_member", + "EmbossFeature" => "emboss", + "BossFeature" => "boss", + "LipFeature" | "GrooveFeature" => "lip", + "SnapFitFeature" => "snap_fit", + "RestFeature" => "rest", + "BoundaryFillFeature" => "boundary_fill", + "BaseFlangeFeature" => "sheet_base", + "ContourFlangeFeature" => "sheet_contour", + "EdgeFlangeFeature" => "sheet_flange", + "HemFeature" => "sheet_hem", + "PerforateFeature" => "sheet_perforate", + "FoldFeature" => "sheet_fold", + "PathFlangeFeature" => "sheet_path", + "UnfoldFeature" | "RefoldFeature" => "sheet_unfold", + "ConvertToSheetMetalFeature" => "sheet_convert", + "CoilFeature" => "coil", + "RibFeature" | "WebFeature" => "rib", + "ReplaceFaceFeature" => "replace_face", + "AlignFeature" => "align", + "RemoveFeature" => "remove", + "PatchFeature" => "patch", + "SurfaceExtrudeFeature" => "surface_extrude", + "SurfaceRevolveFeature" => "surface_revolve", + "SurfaceSweepFeature" => "surface_sweep", + "SurfaceLoftFeature" => "surface_loft", + "BlendFeature" => "surface_blend", + "BoundaryFeature" => "surface_boundary", + "MatchFeature" => "surface_match", + "FairFeature" => "surface_fair", + "StitchFeature" => "stitch", + "ThickenFeature" => "thicken", + "TrimFeature" => "surface_trim", + "ExtendFeature" => "surface_extend", + "RuledSurfaceFeature" => "surface_ruled", + "UnstitchFeature" => "unstitch", + "ReverseNormalFeature" => "reverse_normal", + "UntrimFeature" => "surface_untrim", + "BaseFeature" => "import", + "MeshFeature" => "mesh_import", + "MeshConvertFeature" => "mesh_convert", + _ => return None, + }) + } /// Default name prefix (`Extrude` → `Extrude1`). pub fn base_name(&self) -> &'static str { match self { diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 0d21d014e..263889763 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -885,3 +885,19 @@ fn browser_data_survives_a_save_and_old_designs_read_unchanged() { assert_eq!(resaved["browser_groups"], groups, "{order}"); } } + +/// #10748: verify that type names map to their canonical design-file kind keys. +#[test] +fn feature_kind_key_and_type_name_mappings() { + assert_eq!(FeatureKind::type_name_to_kind_key("HoleFeature"), Some("hole")); + assert_eq!(FeatureKind::type_name_to_kind_key("BoxFeature"), Some("box")); + assert_eq!(FeatureKind::type_name_to_kind_key("EdgeFlangeFeature"), Some("sheet_flange")); + assert_eq!(FeatureKind::type_name_to_kind_key("RectangularPatternFeature"), Some("pattern")); + assert_eq!(FeatureKind::type_name_to_kind_key("PathPatternFeature"), Some("pattern")); + assert_eq!(FeatureKind::type_name_to_kind_key("CircularPatternFeature"), Some("pattern")); + assert_eq!(FeatureKind::type_name_to_kind_key("ExtrudeFeature"), Some("extrude")); + assert_eq!(FeatureKind::type_name_to_kind_key("SplitBodyFeature"), Some("split")); + assert_eq!(FeatureKind::type_name_to_kind_key("BaseFeature"), Some("import")); + assert_eq!(FeatureKind::type_name_to_kind_key("MeshFeature"), Some("mesh_import")); + assert_eq!(FeatureKind::type_name_to_kind_key("NonExistent"), None); +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f17b911e6..bc4ef7d23 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1123,7 +1123,7 @@ fn inspect_feature(s: &mut Session, p: &Value) -> Result { let rolled_back = s.doc.features.iter().position(|x| x.id == id).is_some_and(|i| i >= marker); let r = s.model.result(id); Ok(json!({ - "id": f.id, "name": f.name, "type": f.kind.type_name(), "suppressed": f.suppressed, "rolled_back": rolled_back, + "id": f.id, "name": f.name, "type": f.kind.kind_key(), "type_name": f.kind.type_name(), "suppressed": f.suppressed, "rolled_back": rolled_back, "definition": def, "omitted": omitted, "inputs": inputs, "error": r.and_then(|r| r.error.clone()), "warning": r.and_then(|r| r.warning.clone()), "boolean_diagnostics": r.map(|r| &r.boolean_diagnostics), diff --git a/crates/engine/src/cmd/script.rs b/crates/engine/src/cmd/script.rs index d2bd90779..24a4a13dc 100644 --- a/crates/engine/src/cmd/script.rs +++ b/crates/engine/src/cmd/script.rs @@ -36,6 +36,19 @@ fn add(s: &mut Session, p: &Value) -> Result { .and_then(Value::as_object) .ok_or_else(|| bad(cmd, "`feature` must be a feature object, as a design file or timeline.inspect has it"))?; let mut raw = raw.clone(); + if let Some(Value::Object(def)) = raw.remove("definition") { + for (k, v) in def { + raw.entry(k).or_insert(v); + } + } + for meta in ["omitted", "inputs", "error", "warning", "boolean_diagnostics", "rolled_back", "type_name"] { + raw.remove(meta); + } + if let Some(kind_str) = raw.get("type").and_then(Value::as_str) + && let Some(canonical) = FeatureKind::type_name_to_kind_key(kind_str) + { + raw.insert("type".into(), json!(canonical)); + } resolve_legacy_names(&mut raw, &s.doc); let feature = recorded_feature(cmd, &raw)?; let params = step_params(cmd, p.get("params"))?; diff --git a/crates/engine/src/cmd/script_tests.rs b/crates/engine/src/cmd/script_tests.rs index 75ff02d33..5050985f9 100644 --- a/crates/engine/src/cmd/script_tests.rs +++ b/crates/engine/src/cmd/script_tests.rs @@ -243,6 +243,34 @@ fn a_recorded_feature_that_does_not_fit_is_refused_and_changes_nothing() { assert!(s.doc.feature(r["feature"].as_u64().unwrap()).is_some_and(|f| !f.param_names.is_empty()), "its inputs get parameter names"); } +/// #10748: `timeline.inspect` reports a feature's design variant name in `type` and display name +/// in `type_name`; `timeline.add` accepts `timeline.inspect` results and inspect type names. +#[test] +fn timeline_add_accepts_inspect_result_and_type_names() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 20, "width": 10, "height": 5, "name": "Block"})); + let mut inspected = run(&mut s, "timeline.inspect", json!({"feature": "Block"})); + assert_eq!(inspected["type"], "box", "inspect type is the design file variant name"); + assert_eq!(inspected["type_name"], "BoxFeature", "inspect type_name is the display type"); + + // 1. timeline.add accepts the full inspected object directly in a new session + let mut s2 = Session::default(); + let added = run(&mut s2, "timeline.add", json!({"feature": inspected.clone()})); + assert!(added["error"].is_null(), "{added}"); + assert_eq!(s2.doc.features.len(), 1); + + // 2. timeline.add with id 0 allocates a new id in the current session + inspected["id"] = json!(0); + let added2 = run(&mut s, "timeline.add", json!({"feature": inspected})); + assert!(added2["error"].is_null(), "{added2}"); + assert_eq!(s.doc.features.len(), 2); + + // 3. timeline.add accepts the inspect type name (e.g. BoxFeature, HoleFeature) + let added_by_type_name = + run(&mut s, "timeline.add", json!({"feature": {"type": "BoxFeature", "length": "5", "width": "5", "height": "5", "corner": [50, 0, 0]}})); + assert!(added_by_type_name["error"].is_null(), "{added_by_type_name}"); +} + #[test] fn the_script_is_written_to_a_file_that_replays() { let mut s = Session::default(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a4cbe1bd9..788faa656 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1131,7 +1131,8 @@ fn timeline_inspect_shows_what_timeline_edit_changes() { run(&mut s, "solid.extrude", json!({"distance": 10, "name": "Slab"})); run(&mut s, "solid.fillet", json!({"edges": [[20, 0, 10]], "radius": 2, "name": "Round"})); let i = run(&mut s, "timeline.inspect", json!({"feature": "Slab"})); - assert_eq!(i["type"], "ExtrudeFeature", "{i}"); + assert_eq!(i["type"], "extrude", "{i}"); + assert_eq!(i["type_name"], "ExtrudeFeature", "{i}"); assert_eq!(i["definition"]["extent"]["distance"], "10", "{i}"); assert_eq!(i["definition"]["operation"], "new_body", "{i}"); assert!(i["definition"].get("type").is_none() && i["definition"].get("param_names").is_none(), "{i}"); diff --git a/docs/book/src/guide/features.md b/docs/book/src/guide/features.md index a7815aa5e..6d991b211 100644 --- a/docs/book/src/guide/features.md +++ b/docs/book/src/guide/features.md @@ -282,7 +282,7 @@ edited with the sketch commands. Expressions are text (`"30"`, `"30 mm"`, `"widt ```json {"command": "timeline.inspect", "params": {"feature": "Slab"}} -→ {"type": "ExtrudeFeature", +→ {"type": "extrude", "type_name": "ExtrudeFeature", "definition": {"sketch": 1, "profiles": {"type": "all"}, "operation": "new_body", "extent": {"distance": "10", "direction": "positive"}}, "inputs": [{"label": "Distance", "param": "d1", "expression": "10", "unit": "mm"}], …} diff --git a/docs/book/src/reference/glossary.md b/docs/book/src/reference/glossary.md index 7cb85b277..83581c790 100644 --- a/docs/book/src/reference/glossary.md +++ b/docs/book/src/reference/glossary.md @@ -519,8 +519,8 @@ Search lists both under the same name, and the label lookup gives both the same ## A feature's type A feature type has one name: its design-file key, such as `sheet_flange`. The label (Flange) is -its display name. Replies and scripts should use the design-file key; today `timeline.inspect` -reports a different name (`EdgeFlangeFeature`), so a script can't match one against the other. +its display name. Replies and scripts use the design-file key (`timeline.inspect` reports both +`type: "sheet_flange"` and `type_name: "EdgeFlangeFeature"`). ## Open questions for the maintainer From a1dc849e8db28ee9718cb2ce089cf4bc8bf18588 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:25:21 +0000 Subject: [PATCH 33/55] Sketch Fillet and Chamfer: a refused size's error goes once the size fits (#9316) (#9469) A corner dialog copied the preview's error into its own, where nothing cleared it when the preview recovered. The dialog already shows the preview's error, so the copy is gone. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 5 ----- crates/ui-egui/src/sketch_corner_ui_tests.rs | 21 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 3f827d9e3..c935ad23c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2861,11 +2861,6 @@ fn error_rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut { d.refuse(app, error); } - // For Corner dialogs (fillet/chamfer), propagate preview errors to `d.error` - // so impossible sizes still show a refusal message and tests can check it. - if matches!(d.kind, Kind::SketchModify(crate::sketch_modify_ui::Mod::Corner { .. })) && app.preview.error.is_some() && d.error.is_none() { - d.error = app.preview.error.clone(); - } let shown_id = egui::Id::new("sc_dialog_refusal_shown"); if d.error.is_none() && app.preview.error.is_none() { ui.data_mut(|m| m.remove::(shown_id)); diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rs index b51f486ed..cdc3cf680 100644 --- a/crates/ui-egui/src/sketch_corner_ui_tests.rs +++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs @@ -545,6 +545,27 @@ fn escape_leaves_the_sketch_and_the_history_untouched() { assert_eq!((h.app.session.doc.to_json(), h.app.session.undo.len()), before); } +/// #9316: the refusal of a size being typed (`4 m` on the way to `4 mm`) goes once the size fits. +#[test] +fn a_refused_size_gives_way_to_one_that_fits() { + let mut h = crate::scenario::Harness::new(); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[20,30]})).unwrap(); + h.frames(2); + h.step(&json!({"start":"sketch.fillet"})).unwrap(); + h.frames(2); + h.step(&json!({"click":{"world":[0,0,0]}})).unwrap(); + h.frames(2); + let shown = |h: &mut crate::scenario::Harness, size: &str| { + set_size(&mut h.app, size); + h.settle(); + h.frames(2); + h.app.dialog.as_ref().and_then(|d| d.error.clone()).or_else(|| h.app.preview.error.clone()) + }; + assert!(shown(&mut h, "4 m").is_some_and(|e| e.contains("too large"))); + assert_eq!(shown(&mut h, "4 mm"), None); +} + /// A size the corner cannot take is refused with a reason, and the window stays open on it. #[test] fn an_impossible_size_keeps_the_window_open_with_its_reason() { From b6aabb88ff91924ec964a72a872ada28af0cd610 Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Sun, 1 Nov 2026 21:47:53 +0000 Subject: [PATCH 34/55] Insert Design: place reused links from their parent origin (#10813) (#10825) * claim: #10813 * fix: place reused linked designs from parent origin (#10813) --- crates/engine/src/cmd/component_link.rs | 12 ++- .../engine/src/cmd/component_relink_tests.rs | 84 +++++++++++++++++++ docs/book/src/guide/assemblies.md | 5 ++ 3 files changed, 98 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/component_link.rs b/crates/engine/src/cmd/component_link.rs index ce7c78157..4523c6bf9 100644 --- a/crates/engine/src/cmd/component_link.rs +++ b/crates/engine/src/cmd/component_link.rs @@ -31,7 +31,8 @@ mod relink_tests; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("component.insert_design", "Insert Design", insert_design).at("SOLID", "ASSEMBLE").icon("component").params( "path: a .sc design → a new component linked to it, holding its solid bodies as placed in that design and a copy of its design properties; \ - name? (default: the design's name); parent?: component id or name (default: the active one); translate?: [x,y,z]; \ + name? (default: the design's name); parent?: component id or name (default: the active one); \ + translate?: [x,y,z] in mm from the destination parent's origin (default [0,0,0], also with reuse); \ reuse?: bool (default false): insert a free occurrence, reusing an existing link to the same file when available", ), CommandSpec::new("component.update_links", "Update Links", update_links).icon("update").params( @@ -506,8 +507,13 @@ fn insert_design(s: &mut Session, p: &Value) -> Result { if p.get("reuse").and_then(Value::as_bool).unwrap_or(false) { let existing = s.doc.links.iter().find(|(_, link)| absolute(&resolve(s.path.as_deref(), &link.path)) == file).map(|(id, _)| *id); if let Some(component) = existing { - let parent = p.get("parent").cloned().unwrap_or_else(|| json!(s.active_component)); - return super::component::copy_occurrence(s, &json!({"component": component, "parent": parent, "translate": translate})); + let parent = if p.get("parent").is_some() { component_key(s, p, "parent", cmd)? } else { s.active_component }; + // Reuse the definition, not another placement's captured or pending move. + // Insert Design places from the parent origin whether the link is new or reused. + let mut transform = solidcraft_doc::IDENTITY; + transform[3] = [translate.x, translate.y, translate.z, 1.0]; + let occurrence = s.doc_mut().add_occurrence(component, parent, transform)?; + return Ok(json!({"occurrence": occurrence, "component": component})); } } let ((design_name, sf, faces, metadata, properties), read) = linked_bodies_read(&file, s.path.as_deref())?; diff --git a/crates/engine/src/cmd/component_relink_tests.rs b/crates/engine/src/cmd/component_relink_tests.rs index 4044b5b76..f214f20ab 100644 --- a/crates/engine/src/cmd/component_relink_tests.rs +++ b/crates/engine/src/cmd/component_relink_tests.rs @@ -161,6 +161,90 @@ fn reused_design_insertion_is_free_even_before_a_link_exists() { let _ = std::fs::remove_dir_all(dir); } +#[test] +fn reused_design_insertion_uses_the_requested_position_and_survives_undo_and_reopen() { + let dir = folder("reuse-position"); + let file = dir.join("part.sc"); + part(&file, 30); + for first_reuses in [false, true] { + let mut s = Session::default(); + let first = run(&mut s, "component.insert_design", json!({"path": file, "translate": [20, 0, 0], "reuse": first_reuses})); + let before = s.doc.to_json(); + let undo = s.undo.len(); + let second = run(&mut s, "component.insert_design", json!({"path": file, "translate": [40, 5, 7], "reuse": true})); + assert_eq!(first["component"], second["component"]); + assert_eq!(s.doc.links.len(), 1); + assert_eq!(s.doc.features.len(), 1); + assert_eq!(s.undo.len(), undo + 1); + let occurrence = second["occurrence"].as_u64().unwrap(); + assert_linked_bounds(&mut s, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]); + assert_linked_bounds(&mut s, first["occurrence"].as_u64().unwrap(), [20.0, 0.0, 0.0], [30.0, 20.0, 30.0]); + assert!(!s.doc.occurrences.iter().find(|o| o.id == occurrence).unwrap().grounded); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.doc.to_json(), before); + run(&mut s, "edit.redo", json!({})); + assert_linked_bounds(&mut s, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]); + let assembly = dir.join("assembly.sc"); + run(&mut s, "file.save", json!({"path": assembly})); + let mut cold = Session::default(); + run(&mut cold, "doc.open", json!({"path": assembly})); + assert_linked_bounds(&mut cold, occurrence, [40.0, 5.0, 7.0], [50.0, 25.0, 37.0]); + let at_origin = run(&mut cold, "component.insert_design", json!({"path": file, "reuse": true}))["occurrence"].as_u64().unwrap(); + assert_linked_bounds(&mut cold, at_origin, [0.0, 0.0, 0.0], [10.0, 20.0, 30.0]); + } + let _ = std::fs::remove_dir_all(dir); +} + +fn assert_linked_bounds(s: &mut Session, occurrence: u64, min: [f64; 3], max: [f64; 3]) { + let p = run(s, "occurrence.properties", json!({"occurrence": occurrence})); + assert_eq!(p["body_count"], 1); + assert!((p["total"]["volume_mm3"].as_f64().unwrap() - 6000.0).abs() < 1e-6, "{p}"); + for (key, expected) in [("min", min), ("max", max)] { + for (axis, expected) in expected.into_iter().enumerate() { + assert!((p["total"]["bbox"][key][axis].as_f64().unwrap() - expected).abs() < 1e-6, "{key}[{axis}] != {expected}: {p}"); + } + } +} + +#[test] +fn reused_design_insertion_ignores_existing_moves_and_uses_the_destination_parent() { + let dir = folder("reuse-parent"); + let file = dir.join("part.sc"); + part(&file, 30); + for capture in [false, true] { + let mut s = Session::default(); + let first = run(&mut s, "component.insert_design", json!({"path": file, "translate": [20, 0, 0]})); + run( + &mut s, + "occurrence.move", + json!({"occurrence": first["occurrence"], "translate": [0, 10, 0], "axis": [0, 0, 1], "angle": "90 deg", "capture": capture, "move_grounded": true}), + ); + let original = s.doc.occurrences.clone(); + let pending = s.pending_moves.clone(); + let parent = run(&mut s, "component.create", json!({"name": "Parent", "activate": false})); + run(&mut s, "occurrence.move", json!({"occurrence": parent["occurrence"], "translate": [100, 0, 0], "axis": [0, 0, 1], "angle": "90 deg"})); + for explicit_parent in [true, false] { + let mut params = json!({"path": file, "translate": [40, 5, 7], "reuse": true}); + if explicit_parent { + params["parent"] = json!("Parent"); + } else { + run(&mut s, "component.activate", json!({"component": parent["component"]})); + } + let inserted = run(&mut s, "component.insert_design", params); + assert_eq!(inserted["component"], first["component"]); + assert_linked_bounds(&mut s, inserted["occurrence"].as_u64().unwrap(), [75.0, 40.0, 7.0], [95.0, 50.0, 37.0]); + assert_eq!(s.doc.occurrences.first(), original.first()); + assert_eq!(s.pending_moves, pending); + } + let before = s.doc.to_json(); + for parent in [json!("missing"), first["component"].clone()] { + assert!(s.execute("component.insert_design", &json!({"path": file, "parent": parent, "reuse": true})).is_err()); + assert_eq!(s.doc.to_json(), before); + } + } + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn linked_design_properties_update_density_without_geometry_and_keep_edited_cards() { let dir = folder("properties-density"); diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index ad046e7d5..512d56bd6 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -394,6 +394,11 @@ off. A STEP or mesh file picked there is inserted as **Insert STEP** or **Insert Mesh** would. The part's solid bodies come in as they sit in that design, and they are kept in the assembly, so it opens even without the part file. The link is stored relative to the assembly's folder once the assembly is saved. +For scripts, `translate: [x,y,z]` places the design's origin in millimetres from the destination +parent's origin (the active component unless `parent` is supplied). It defaults to `[0,0,0]`. +With `reuse: true`, insertion reuses the existing linked component but uses the same coordinates; +it does not inherit another occurrence's position or rotation. For example, inserts at +`[20,0,0]` and `[40,0,0]` place the two origins at 20 and 40 mm, even when the second reuses the link. After the part file changes, **Update Links** (`component.update_links`) reads it again. An assembly that opens, or whose tab comes back to the front, does that by itself for the parts whose files changed since it last read them, whether the part was saved in another tab, another window or by From 5c7e50cb678a6b180bbfea94f40046ee9fc1e9f4 Mon Sep 17 00:00:00 2001 From: Nathan Dane Date: Sun, 1 Nov 2026 21:58:35 +0000 Subject: [PATCH 35/55] Preferences redesign 2/11: shared widgets and painters in ui_kit (#9874) (#9890) * claim: #9874 * Add shared Preferences cards, figure painters and gallery entries to ui_kit * Preferences: Arabic, Hebrew and Vietnamese carousel labels Co-Authored-By: Claude Opus 5.5 * Use the app's selection colours in the Preferences cards * Measure Preferences figure inks and use shared palette metrics --------- Co-authored-by: bherbruck Co-authored-by: Claude Opus 5.5 --- assets/locales/pending/preferences-v2.json | 10 + assets/styles/ui/palettes.rs | 42 + crates/ui-egui/src/colour_tokens_tests.rs | 2 + crates/ui-egui/src/colour_vision_tests.rs | 35 + crates/ui-egui/src/theme.rs | 44 + crates/ui-egui/src/theme_files.rs | 1 + crates/ui-egui/src/ui_kit/gallery.rs | 347 ++ crates/ui-egui/src/ui_kit/mod.rs | 8 + crates/ui-egui/src/ui_kit/preferences.rs | 2 +- .../ui-egui/src/ui_kit/preferences_cards.rs | 319 ++ .../src/ui_kit/preferences_figure_data.rs | 4580 +++++++++++++++++ .../src/ui_kit/preferences_figure_ops.rs | 583 +++ .../ui-egui/src/ui_kit/preferences_figures.rs | 117 + docs/ui-kit.md | 49 + tools/preferences-figures/generate.py | 588 +++ 15 files changed, 6726 insertions(+), 1 deletion(-) create mode 100644 assets/locales/pending/preferences-v2.json create mode 100644 crates/ui-egui/src/ui_kit/preferences_cards.rs create mode 100644 crates/ui-egui/src/ui_kit/preferences_figure_data.rs create mode 100644 crates/ui-egui/src/ui_kit/preferences_figure_ops.rs create mode 100644 tools/preferences-figures/generate.py diff --git a/assets/locales/pending/preferences-v2.json b/assets/locales/pending/preferences-v2.json new file mode 100644 index 000000000..60ba54424 --- /dev/null +++ b/assets/locales/pending/preferences-v2.json @@ -0,0 +1,10 @@ +{ + "ar": { "prefs.carousel_next": "التالي", "prefs.carousel_previous": "السابق" }, + "de": { "prefs.carousel_next": "Weiter", "prefs.carousel_previous": "Zurück" }, + "en": { "prefs.carousel_next": "Next", "prefs.carousel_previous": "Previous" }, + "he": { "prefs.carousel_next": "הבא", "prefs.carousel_previous": "הקודם" }, + "ja": { "prefs.carousel_next": "次へ", "prefs.carousel_previous": "前へ" }, + "ko": { "prefs.carousel_next": "다음", "prefs.carousel_previous": "이전" }, + "vi": { "prefs.carousel_next": "Tiếp", "prefs.carousel_previous": "Trước" }, + "zh": { "prefs.carousel_next": "下一个", "prefs.carousel_previous": "上一个" } +} diff --git a/assets/styles/ui/palettes.rs b/assets/styles/ui/palettes.rs index 201c45da7..442dde543 100644 --- a/assets/styles/ui/palettes.rs +++ b/assets/styles/ui/palettes.rs @@ -226,6 +226,28 @@ impl Tokens { dialog_label: Color32::from_rgb(58, 70, 86), selected_ink: Color32::from_rgb(26, 80, 127), selected_bg: Color32::from_rgb(232, 241, 250), + figure_ground: Color32::from_rgb(247, 248, 250), + figure_line: Color32::from_rgb(111, 124, 143), + figure_face_top: Color32::from_rgb(255, 255, 255), + figure_face_left: Color32::from_rgb(228, 233, 240), + figure_face_right: Color32::from_rgb(201, 210, 222), + figure_card: Color32::from_rgb(255, 255, 255), + figure_white: Color32::WHITE, + figure_black: Color32::BLACK, + figure_accent: Color32::from_rgb(35, 110, 173), + figure_reference: Color32::from_rgb(138, 83, 0), + figure_axis_x: Color32::from_rgb(214, 69, 69), + figure_axis_y: Color32::from_rgb(46, 158, 91), + figure_axis_z: Color32::from_rgb(47, 111, 208), + figure_ok: Color32::from_rgb(47, 125, 91), + figure_warn: Color32::from_rgb(201, 138, 0), + pref_well: Color32::from_rgb(238, 241, 245), + pref_note: Color32::from_rgb(184, 74, 0), + pref_note_fill: Color32::from_rgb(251, 235, 221), + pref_on_accent: Color32::from_rgb(255, 255, 255), + pref_ok: Color32::from_rgb(39, 107, 44), + pref_ok_fill: Color32::from_rgb(229, 242, 230), + pref_disabled: Color32::from_rgb(138, 148, 163), timeline_item: Color32::WHITE, timeline_item_error: Color32::from_rgb(250, 220, 220), timeline_marker: Color32::from_rgb(70, 76, 88), @@ -345,6 +367,26 @@ impl Tokens { t.dialog_label = t.text; t.selected_ink = Color32::from_rgb(156, 199, 245); t.selected_bg = Color32::from_rgb(42, 70, 110); + t.figure_ground = Color32::from_rgb(28, 31, 38); + t.figure_line = Color32::from_rgb(163, 174, 194); + t.figure_face_top = Color32::from_rgb(107, 119, 144); + t.figure_face_left = Color32::from_rgb(81, 91, 114); + t.figure_face_right = Color32::from_rgb(57, 66, 86); + t.figure_card = Color32::from_rgb(47, 52, 62); + t.figure_accent = Color32::from_rgb(140, 190, 245); + t.figure_reference = Color32::from_rgb(232, 194, 74); + t.figure_axis_x = Color32::from_rgb(242, 122, 122); + t.figure_axis_y = Color32::from_rgb(98, 212, 142); + t.figure_axis_z = Color32::from_rgb(108, 168, 247); + t.figure_ok = Color32::from_rgb(127, 209, 174); + t.figure_warn = Color32::from_rgb(232, 194, 74); + t.pref_well = Color32::from_rgb(47, 52, 62); + t.pref_note = Color32::from_rgb(240, 162, 122); + t.pref_note_fill = Color32::from_rgb(74, 51, 38); + t.pref_on_accent = Color32::from_rgb(15, 22, 32); + t.pref_ok = Color32::from_rgb(127, 209, 174); + t.pref_ok_fill = Color32::from_rgb(31, 58, 49); + t.pref_disabled = Color32::from_rgb(138, 148, 163); t.construction_geom = icon_primary(crate::icon_svg::CONSTRUCTION_PRIMARY[1]); t.error = Color32::from_rgb(240, 100, 96); t.sketch_conflict = t.error; diff --git a/crates/ui-egui/src/colour_tokens_tests.rs b/crates/ui-egui/src/colour_tokens_tests.rs index 8be8a444c..28188e185 100644 --- a/crates/ui-egui/src/colour_tokens_tests.rs +++ b/crates/ui-egui/src/colour_tokens_tests.rs @@ -31,6 +31,8 @@ fn moved_colours_keep_the_values_they_were_drawn_with() { assert_eq!(t.logo, [Color32::from_rgb(96, 158, 236), Color32::from_rgb(58, 136, 238), Color32::from_rgb(55, 108, 197)]); assert_eq!(t.icons.marker_halo, Color32::from_black_alpha(150)); assert_eq!(t.icons.agent, Color32::from_rgb(168, 85, 247)); + assert_eq!(t.figure_white, Color32::WHITE); + assert_eq!(t.figure_black, Color32::BLACK); } let (l, d) = (Tokens::light(), Tokens::dark()); assert_eq!((l.bend_up, l.bend_down), (Color32::from_rgb(30, 140, 50), Color32::from_rgb(200, 90, 20))); diff --git a/crates/ui-egui/src/colour_vision_tests.rs b/crates/ui-egui/src/colour_vision_tests.rs index 5e9fdbe78..4c046de44 100644 --- a/crates/ui-egui/src/colour_vision_tests.rs +++ b/crates/ui-egui/src/colour_vision_tests.rs @@ -396,6 +396,35 @@ fn groups(t: &Tokens) -> Vec { out.push(group(name, &[(key, fill)], &[("panel", t.panel)])); } out.push(group("dark pill text", &[("tab_on_fill_dark", t.tab_on_fill_dark)], &[("mesh_fill", t.mesh_fill)])); + // Miniature figures identify axes by labels and direction, reference points by + // position. Each ink must remain visible on its surfaces; + // the hues are not the only way to distinguish these marks from one another. + for (key, ink) in [ + ("figure_line", t.figure_line), + ("figure_accent", t.figure_accent), + ("figure_reference", t.figure_reference), + ("figure_axis_x", t.figure_axis_x), + ("figure_axis_y", t.figure_axis_y), + ("figure_axis_z", t.figure_axis_z), + ("figure_ok", t.figure_ok), + ("figure_warn", t.figure_warn), + ] { + out.push(group(key, &[(key, ink)], &[("figure_ground", t.figure_ground), ("figure_card", t.figure_card)])); + } + // The static sketch-state illustration uses success and warm alert inks on + // the top face. Keep success apart from each alert; the two warm warning + // shades are not a colour-only legend for live solver states. + out.push(group( + "preferences sketch states", + &[("figure_ok", t.figure_ok), ("figure_warn", t.figure_warn)], + &[("figure_face_top", t.figure_face_top)], + )); + out.push(group("preferences sketch note", &[("figure_ok", t.figure_ok), ("pref_note", t.pref_note)], &[("figure_face_top", t.figure_face_top)])); + // Badge words identify the status; check the ink against its own fill, as for + // tab text above, rather than treating an ink and its tint as competing states. + out.push(group("preferences note", &[("pref_note", t.pref_note)], &[("pref_note_fill", t.pref_note_fill)])); + out.push(group("preferences success", &[("pref_ok", t.pref_ok)], &[("pref_ok_fill", t.pref_ok_fill)])); + out.push(group("preferences accent ink", &[("pref_on_accent", t.pref_on_accent)], &[("form_primary", t.form_primary)])); // The removed part of a cut preview is translucent over the body. if let Some(sel) = out.iter_mut().find(|g| g.name == "selection") { sel.members.push(("preview_cut", over(t.preview_cut, t.body))); @@ -409,6 +438,12 @@ const SHADED: [&str; 2] = ["analysis.draft", "analysis.access"]; /// Tokens no colour vision mode needs to keep apart, and why. A new token fails /// `every_token_is_measured_or_carries_no_meaning` until it is in a group above or here. const NO_MEANING: &[(&str, &str)] = &[ + ("figure_face_left", "neutral cube shading; face geometry identifies the orientation"), + ("figure_face_right", "neutral cube shading; face geometry identifies the orientation"), + ("figure_white", "neutral axis label and highlight ink; letters identify the axes"), + ("figure_black", "neutral hatching and shadows; pattern and geometry carry the meaning"), + ("pref_well", "neutral well behind a labelled control or illustration"), + ("pref_disabled", "dimmed control ink; label and disabled interaction identify availability"), ("nav_hover", "neutral hover surface; placement and pointer feedback identify the control"), ("nav_press", "neutral pressed/open surface; interaction and menu presence identify the state"), ("nav_dim", "neutral secondary ink; the Later label identifies the unavailable option"), diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index e6616aaa0..da0952af4 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -1187,6 +1187,50 @@ pub struct Tokens { pub dialog_label: Color32, pub selected_ink: Color32, pub selected_bg: Color32, + /// Ground under every Preferences figure. + pub figure_ground: Color32, + /// Outlines and reference lines of Preferences figures. + pub figure_line: Color32, + /// Top face of the Preferences figure cube. + pub figure_face_top: Color32, + /// Left face of the Preferences figure cube. + pub figure_face_left: Color32, + /// Right face of the Preferences figure cube. + pub figure_face_right: Color32, + /// Paper, panels and pads drawn inside Preferences figures. + pub figure_card: Color32, + /// Fixed white label and highlight ink inside Preferences illustrations. + pub figure_white: Color32, + /// Fixed black hatch and shadow ink inside Preferences illustrations. + pub figure_black: Color32, + /// What a Preferences figure or selected card acts on. + pub figure_accent: Color32, + /// Reference point in a Preferences figure: pivot, origin, pointer. + pub figure_reference: Color32, + /// X axis in a Preferences figure. + pub figure_axis_x: Color32, + /// Y axis in a Preferences figure. + pub figure_axis_y: Color32, + /// Z axis in a Preferences figure. + pub figure_axis_z: Color32, + /// Done or fully constrained mark in a Preferences figure. + pub figure_ok: Color32, + /// Warning mark in a Preferences figure. + pub figure_warn: Color32, + /// Segmented control well and tint behind figures in Preferences. + pub pref_well: Color32, + /// Warning badge text and stroke in Preferences. + pub pref_note: Color32, + /// Warning badge fill in Preferences. + pub pref_note_fill: Color32, + /// Ink on a Preferences accent fill. + pub pref_on_accent: Color32, + /// Success badge text in Preferences. + pub pref_ok: Color32, + /// Success badge fill in Preferences. + pub pref_ok_fill: Color32, + /// Ink of a dimmed Preferences control. + pub pref_disabled: Color32, /// Timeline items: normal and failed. pub timeline_item: Color32, pub timeline_item_error: Color32, diff --git a/crates/ui-egui/src/theme_files.rs b/crates/ui-egui/src/theme_files.rs index fda8da471..ecd761a62 100644 --- a/crates/ui-egui/src/theme_files.rs +++ b/crates/ui-egui/src/theme_files.rs @@ -470,6 +470,7 @@ macro_rules! theme_keys { form_card_width: _, form_icon_size: _, form_close_size: _, form_inset: _, form_icon_inset: _, form_section_icon_size: _, form_checkbox_height: _, form_button_height: _, sketch_palette_width: _, sketch_mode_size: _, sketch_mode_radius: _, sketch_mode_border: _, sketch_palette_alpha: _, sketch_mode_tint: _, sketch_footer_icon_size: _, font_section_tracking: _, + figure_ground: _, figure_line: _, figure_face_top: _, figure_face_left: _, figure_face_right: _, figure_card: _, figure_white: _, figure_black: _, figure_accent: _, figure_reference: _, figure_axis_x: _, figure_axis_y: _, figure_axis_z: _, figure_ok: _, figure_warn: _, pref_well: _, pref_note: _, pref_note_fill: _, pref_on_accent: _, pref_ok: _, pref_ok_fill: _, pref_disabled: _, } = t; let IconColors { $($ione: _,)* } = &t.icons; } diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs index 30c1a1ad4..1897f4177 100644 --- a/crates/ui-egui/src/ui_kit/gallery.rs +++ b/crates/ui-egui/src/ui_kit/gallery.rs @@ -1,4 +1,5 @@ //! Table-driven layout/paint references in both themes. No window or GPU required. +use super::preferences_figures::{ThemeSample, paint_theme_system, paint_theme_thumbnail}; use super::*; use crate::ui_kit::{Container, Surface}; use crate::{scenario, theme::Tokens}; @@ -530,6 +531,177 @@ const ELEMENTS: &[Element] = &[ }, ); }), + element!("picture_card", |ui, _| { + use super::preferences_figure_data as figures; + let gap = ui.spacing().item_spacing.x; + let width = card_width(ui.available_width(), 4, gap); + ui.horizontal(|ui| { + picture_card( + ui, + &Card { + label: "Coarse", + sub: Some("fastest"), + selected: false, + enabled: true, + options: None, + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_tess_coarse, + }, + width, + ); + picture_card( + ui, + &Card { + label: "Normal", + sub: Some("default"), + selected: true, + enabled: true, + options: None, + check: true, + aspect: 120.0 / 64.0, + figure: &figures::paint_tess_normal, + }, + width, + ); + picture_card( + ui, + &Card { + label: "Fine", + sub: Some("smoother"), + selected: false, + enabled: true, + options: Some("Has options"), + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_tess_fine, + }, + width, + ); + picture_card( + ui, + &Card { + label: "8×", + sub: Some("not on this GPU"), + selected: false, + enabled: false, + options: None, + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_aa_8x, + }, + width, + ); + }); + }), + element!("toggle_tile", |ui, _| { + use super::preferences_figure_data as figures; + let gap = ui.spacing().item_spacing.x; + let width = card_width(ui.available_width(), 3, gap); + ui.horizontal(|ui| { + toggle_tile( + ui, + &Card { + label: "Grid", + sub: None, + selected: true, + enabled: true, + options: None, + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_view_grid, + }, + width, + ); + toggle_tile( + ui, + &Card { + label: "Ground shadow", + sub: None, + selected: false, + enabled: true, + options: None, + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_view_shadow, + }, + width, + ); + toggle_tile( + ui, + &Card { + label: "Perspective", + sub: None, + selected: false, + enabled: false, + options: None, + check: false, + aspect: 120.0 / 64.0, + figure: &figures::paint_view_perspective, + }, + width, + ); + }); + }), + element!("preset_card", |ui, _| { + let icon = |p: &egui::Painter, r: egui::Rect, ink: egui::Color32| crate::icons::paint_ink(p, r, "settings", ink); + let width = ui.available_width(); + for (name, word, selected, enabled) in + [("Performance", "Fastest", false, true), ("Quality", "Sharpest", true, true), ("Custom", "Your own mix", false, false)] + { + preset_card(ui, name, word, selected, enabled, &icon, width); + } + }), + element!("help_icon", |ui, _| { + ui.horizontal(|ui| { + text(ui, "Anti-aliasing", Text::Hint("gallery_help")); + help_icon(ui, "Applies when SolidCraft restarts."); + }); + }), + element!("carousel", |ui, _| { + let sample = ThemeSample::from_tokens(&Tokens::get()); + let width = Tokens::get().space_24 * 2.0 + Tokens::get().space_24; + carousel(ui, "gallery_carousel", 6, width, width * 0.8, |ui, index| { + let label = ["Light", "Dark", "System", "Gruvbox", "Studio", "Mono"][index % 6]; + picture_card( + ui, + &Card { + label, + sub: Some("Built in"), + selected: index == 1, + enabled: true, + options: None, + check: false, + aspect: 124.0 / 76.0, + figure: &|p, r| paint_theme_thumbnail(p, r, &sample), + }, + width, + ); + }); + }), + element!("preference_theme_thumbnails", |ui, _| { + let (light, dark) = (ThemeSample::from_tokens(&Tokens::light()), ThemeSample::from_tokens(&Tokens::dark())); + ui.horizontal(|ui| { + for kind in 0..3 { + let (rect, _) = ui.allocate_exact_size(vec2(88.0, 88.0 * 76.0 / 124.0), egui::Sense::hover()); + match kind { + 0 => paint_theme_thumbnail(ui.painter(), rect, &light), + 1 => paint_theme_thumbnail(ui.painter(), rect, &dark), + _ => paint_theme_system(ui.painter(), rect, &light, &dark), + } + } + }); + }), + element!("preference_figures", |ui, _| { + ui.horizontal_wrapped(|ui| { + for (name, size, paint) in super::preferences_figure_data::FIGURES { + let width = 96.0; + let (rect, response) = ui.allocate_exact_size(vec2(width, width * size[1] / size[0]), egui::Sense::hover()); + paint(ui.painter(), rect); + response.on_hover_text(*name); + } + }); + }), element!("preference_option_cards", |ui, _| { ui.horizontal_wrapped(|ui| { for figure in [ @@ -1956,6 +2128,7 @@ fn gallery_covers_every_inline_element() { "look_chain.rs", "menu.rs", "metrics.rs", + "preferences_cards.rs", "radial.rs", "reports.rs", "sphere.rs", @@ -2567,3 +2740,177 @@ fn tree_icon_actions_keep_repeated_light_rows_independent() { }); assert_eq!(ids.len(), 3); } + +#[test] +fn card_looks_follow_selected_hover_disabled_and_focus() { + use super::preferences_cards::{CardFill, CardInk, card_look}; + let rest = card_look(false, true, false, false); + assert_eq!((rest.border, rest.fill, rest.ink, rest.bold, rest.alpha, rest.focus_ring), (1.0, CardFill::Face, CardInk::Text, false, 1.0, false)); + let hover = card_look(false, true, true, false); + assert_eq!(hover.fill, CardFill::Hover); + let selected = card_look(true, true, true, false); + assert_eq!((selected.border, selected.fill, selected.ink, selected.bold), (2.0, CardFill::Selected, CardInk::Accent, true)); + let disabled = card_look(false, false, true, true); + assert_eq!((disabled.fill, disabled.alpha, disabled.focus_ring), (CardFill::Face, 0.5, false), "a disabled card neither hovers nor shows focus"); + assert!(card_look(false, true, false, true).focus_ring); + assert!(card_look(true, false, false, false).alpha < 1.0, "a selected card can be disabled too"); +} + +#[test] +fn cards_size_to_their_container_and_survive_hostile_sizes() { + use super::preferences_cards::{card_width, carousel_window}; + assert_eq!(card_width(320.0, 4, 10.0), 72.5); + assert_eq!(card_width(320.0, 0, 10.0), 320.0); + for bad in [0.0, -5.0, f32::NAN, f32::INFINITY, f32::MAX] { + let w = card_width(bad, 3, 10.0); + assert!(w.is_finite() && w >= 0.0, "{bad}: {w}"); + let (first, visible) = carousel_window(5, 9, bad, 88.0, 8.0, 26.0); + assert!(first + visible <= 5 && visible >= 1, "{bad}: {first} {visible}"); + } + assert_eq!(carousel_window(0, 3, 400.0, 88.0, 8.0, 26.0), (0, 0)); + // 400 wide: two arrows and their gaps leave 332, which fits three 88-wide items with gaps. + assert_eq!(carousel_window(6, 0, 400.0, 88.0, 8.0, 26.0), (0, 3)); + assert_eq!(carousel_window(6, 5, 400.0, 88.0, 8.0, 26.0), (3, 3), "the offset stops at the last full window"); +} + +fn sample_card<'a>(label: &'a str, selected: bool, enabled: bool) -> super::preferences_cards::Card<'a> { + super::preferences_cards::Card { + label, + sub: Some("sub"), + selected, + enabled, + options: None, + check: selected, + aspect: 120.0 / 64.0, + figure: &super::preferences_figure_data::paint_tess_normal, + } +} + +#[test] +fn picture_cards_and_tiles_click_only_when_enabled_and_never_panic() { + use super::preferences_cards::{picture_card, toggle_tile}; + let ctx = crate::fonts::test_context(); + for tile in [false, true] { + for enabled in [true, false] { + let mut clicked = false; + let mut at = None; + for pass in 0..3 { + let events = match (pass, at) { + (1, Some(p)) => super::test_support::pointer(p, true), + (2, Some(p)) => super::test_support::pointer(p, false), + _ => vec![], + }; + super::test_support::frame(&ctx, events, |ui| { + let card = sample_card("Normal", false, enabled); + let response = if tile { toggle_tile(ui, &card, 120.0) } else { picture_card(ui, &card, 120.0) }; + at = Some(response.rect.center()); + assert!(response.rect.width() == 120.0 && response.rect.height() > 40.0); + clicked |= response.clicked(); + }); + } + assert_eq!(clicked, enabled, "tile {tile}, enabled {enabled}"); + // Zero, negative and non-finite widths must not panic and must stay finite. + super::test_support::frame(&ctx, vec![], |ui| { + for width in [0.0, -3.0, f32::NAN, f32::INFINITY, 1.0e6] { + let response = if tile { + toggle_tile(ui, &sample_card("x", true, enabled), width) + } else { + picture_card(ui, &sample_card("x", true, enabled), width) + }; + assert!(response.rect.is_finite()); + } + }); + } + } +} + +#[test] +fn preset_card_help_icon_and_carousel_behave() { + use super::preferences_cards::{carousel, help_icon, preset_card}; + let ctx = crate::fonts::test_context(); + let icon = |p: &egui::Painter, r: egui::Rect, ink: egui::Color32| crate::icons::paint_ink(p, r, "settings", ink); + super::test_support::frame(&ctx, vec![], |ui| { + for width in [0.0, 10.0, 204.0, f32::NAN] { + let response = preset_card(ui, "Performance", "Fastest", true, true, &icon, width); + assert!(response.rect.is_finite()); + } + let help = help_icon(ui, "Help text"); + assert!(help.rect.width() > 8.0 && help.rect.width() < 20.0); + }); + // The next arrow moves the window by one and stays inert at the end. + let mut first = vec![]; + let mut at = None; + for pass in 0..6 { + let events = match (pass, at) { + (2, Some(p)) => super::test_support::pointer(p, true), + (3, Some(p)) => super::test_support::pointer(p, false), + _ => vec![], + }; + super::test_support::frame(&ctx, events, |ui| { + let (f, visible) = carousel(ui, "carousel_test", 5, 60.0, 40.0, |ui, _| { + ui.allocate_exact_size(egui::vec2(60.0, 40.0), egui::Sense::hover()); + }); + first.push((f, visible)); + if let Some(rect) = scenario::rect_of("prefs:carousel:Next") { + at = Some(rect.center()); + } + }); + } + let (f0, visible) = first[0]; + assert_eq!(f0, 0); + assert!((1..5).contains(&visible), "{visible}"); + assert!(first.last().unwrap().0 >= 1, "the next arrow advanced the window: {first:?}"); +} + +/// Light and dark boards of the shared Preferences widgets and of every figure, rendered on the CPU. +/// Set `SOLIDCRAFT_PREFERENCE_WIDGET_EVIDENCE` to a directory to keep the PNGs. +#[test] +fn preference_widgets_and_figures_board_in_both_themes() { + use super::checks::tests::{raster, textures_update}; + use std::collections::HashMap; + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + for (board, names) in [ + ("widgets", &["picture_card", "toggle_tile", "preset_card", "help_icon", "carousel", "preference_theme_thumbnails"][..]), + ("figures", &["preference_figures"][..]), + ] { + for scale in [1.0_f32, 2.0] { + let ctx = crate::fonts::test_context(); + ctx.set_pixels_per_point(scale); + let bounds = egui::Rect::from_min_size( + egui::Pos2::ZERO, + vec2(if board == "figures" { 700.0 } else { 360.0 }, if board == "figures" { 920.0 } else { 800.0 }), + ); + let mut textures = HashMap::new(); + let mut image = None; + for _ in 0..3 { + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(bounds), ..Default::default() }, |ui| { + ui.set_width(bounds.width() - 40.0); + ui.painter().rect_filled(bounds, 0.0, Tokens::get().dialog_body); + ui.add_space(12.0); + scope(ui, |ui| { + for name in names { + example(ui, ELEMENTS.iter().find(|e| e.name == *name).unwrap()); + ui.add_space(Tokens::get().space_12); + } + }); + }); + textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + image = Some(raster(&ctx, output.shapes, output.pixels_per_point, bounds, &textures)); + } + let image = image.unwrap(); + assert!(image.pixels().any(|p| p.0[3] != 0)); + if let Some(dir) = std::env::var_os("SOLIDCRAFT_PREFERENCE_WIDGET_EVIDENCE") { + std::fs::create_dir_all(&dir).unwrap(); + let suffix = if scale > 1.0 { "@2x" } else { "" }; + image + .save(std::path::Path::new(&dir).join(format!("preferences-{board}-{}{suffix}.png", if dark { "dark" } else { "light" }))) + .unwrap(); + } + } + } + } + crate::theme::set_dark(previous); +} diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rs index c280159ca..06ea66cde 100644 --- a/crates/ui-egui/src/ui_kit/mod.rs +++ b/crates/ui-egui/src/ui_kit/mod.rs @@ -28,6 +28,12 @@ mod navigation_settings; pub(crate) mod panel; mod preferences; mod preferences_assistant; +#[allow(dead_code, reason = "composed by the Preferences pages of #9875 to #9883")] +mod preferences_cards; +#[allow(dead_code, reason = "painted by the Preferences pages of #9875 to #9883")] +mod preferences_figure_data; +#[allow(dead_code, reason = "painted by the Preferences pages of #9875 to #9883")] +mod preferences_figure_ops; mod preferences_figures; mod preferences_layout; mod preferences_navigation; @@ -85,6 +91,8 @@ pub use panel::{DialogButtons, Window}; pub(crate) use panel::{collapsible_header, header}; pub(crate) use preferences::*; pub(crate) use preferences_assistant::*; +#[allow(unused_imports, reason = "composed by the Preferences pages of #9875 to #9883")] +pub(crate) use preferences_cards::*; pub(crate) use preferences_navigation::*; pub(crate) use preferences_small::*; pub(crate) use radial::{RADIAL_RADIUS, radial_menu}; diff --git a/crates/ui-egui/src/ui_kit/preferences.rs b/crates/ui-egui/src/ui_kit/preferences.rs index 0275e5ee7..470345cf0 100644 --- a/crates/ui-egui/src/ui_kit/preferences.rs +++ b/crates/ui-egui/src/ui_kit/preferences.rs @@ -729,7 +729,7 @@ pub(crate) fn option_card(ui: &mut Ui, label: &str, note: Option<&str>, selected if enabled { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response } } -fn centred_text(p: &egui::Painter, rect: Rect, label: &str, font: FontId, ink: Color32) { +pub(super) fn centred_text(p: &egui::Painter, rect: Rect, label: &str, font: FontId, ink: Color32) { centred_text_rows(p, rect, label, font, ink, 1); } diff --git a/crates/ui-egui/src/ui_kit/preferences_cards.rs b/crates/ui-egui/src/ui_kit/preferences_cards.rs new file mode 100644 index 000000000..7b227d209 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/preferences_cards.rs @@ -0,0 +1,319 @@ +//! The controls the redesigned Preferences pages share: picture cards, toggle tiles, preset cards, +//! the hover-help icon and the carousel. Sizes follow `docs/design/preferences/measurements.md`; +//! every colour comes from `Tokens`. A card sizes to the width its container gives it and its +//! figure keeps the figure's aspect ratio. +use super::{metrics::dimension, preferences::centred_text}; +use crate::{scenario, theme::Tokens}; +use egui::{Color32, FontId, Painter, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; + +/// How a card or tile looks in a state. Kept separate from painting so the state rules can be tested. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct CardLook { + /// Border width in points: 2 when selected, else 1. + pub border: f32, + pub fill: CardFill, + pub ink: CardInk, + pub bold: bool, + /// Multiplier on every colour; a disabled card is dimmed. + pub alpha: f32, + /// A keyboard focus ring outside the border. + pub focus_ring: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CardFill { + Face, + Hover, + Selected, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CardInk { + Text, + Accent, +} + +pub(super) fn card_look(selected: bool, enabled: bool, hovered: bool, focused: bool) -> CardLook { + CardLook { + border: if selected { 2.0 } else { 1.0 }, + fill: if selected { + CardFill::Selected + } else if enabled && hovered { + CardFill::Hover + } else { + CardFill::Face + }, + ink: if selected { CardInk::Accent } else { CardInk::Text }, + bold: selected, + alpha: if enabled { 1.0 } else { 0.5 }, + focus_ring: enabled && focused, + } +} + +/// What a picture card or toggle tile shows. +pub(crate) struct Card<'a> { + pub label: &'a str, + /// One short line under the label ("default", "Built in"). + pub sub: Option<&'a str>, + /// Selected (radio) or on (tile). + pub selected: bool, + pub enabled: bool, + /// The small "has options" disc at the top right. + pub options: Option<&'a str>, + /// An accent check at the top right (picture cards only). + pub check: bool, + /// Width over height of the figure. + pub aspect: f32, + pub figure: &'a dyn Fn(&Painter, Rect), +} + +/// The width of one of `columns` cards in `available` points with `gap` between them. +pub(super) fn card_width(available: f32, columns: usize, gap: f32) -> f32 { + let columns = columns.max(1) as f32; + let available = dimension(available); + ((available - gap.max(0.0) * (columns - 1.0)) / columns).max(0.0) +} + +fn card_height(t: &Tokens, width: f32, card: &Card) -> f32 { + let pad = t.space_6; + let aspect = if card.aspect.is_finite() && card.aspect > 0.01 { card.aspect } else { 1.0 }; + let figure = ((width - 2.0 * pad).max(0.0) / aspect).min(dimension(f32::MAX)); + let sub = if card.sub.is_some() { t.space_14 } else { 0.0 }; + pad + figure + gap(t) + t.space_16 + sub + pad + 1.0 +} + +fn gap(t: &Tokens) -> f32 { + (t.space_4 + t.space_6) * 0.5 +} + +fn paint_card(ui: &mut Ui, card: &Card, width: f32, tile: bool) -> Response { + let t = Tokens::get(); + let width = dimension(width); + let enabled = card.enabled && ui.is_enabled(); + let (rect, response) = ui.allocate_exact_size(vec2(width, card_height(&t, width, card)), if enabled { Sense::click() } else { Sense::hover() }); + let look = card_look(card.selected, enabled, response.hovered(), response.has_focus()); + let p = ui.painter(); + let dim = |c: Color32| c.gamma_multiply(look.alpha); + let fill = match look.fill { + CardFill::Selected => t.selected_bg, + CardFill::Hover => t.hover, + CardFill::Face => t.control_fill, + }; + let border = if card.selected { t.form_primary } else { t.dialog_border }; + let radius = f32::from(t.radius_lg); + p.rect(rect, radius, dim(fill), Stroke::new(look.border, dim(border)), StrokeKind::Inside); + if look.focus_ring { + p.rect_stroke(rect.expand(t.space_2), radius + t.space_2, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside); + } + let inset = t.space_6; + let figure = Rect::from_min_size( + rect.min + vec2(inset, inset), + vec2((rect.width() - 2.0 * inset).max(0.0), ((rect.width() - 2.0 * inset).max(0.0) / card.aspect.max(0.01)).min(rect.height())), + ); + if figure.is_positive() { + let figure_painter = p.with_clip_rect(figure.intersect(p.clip_rect())); + (card.figure)(&figure_painter, figure); + if !enabled { + p.rect_filled(figure, 0.0, t.control_fill.gamma_multiply(0.5)); + } + } + let ink = match look.ink { + CardInk::Accent => t.selected_ink, + CardInk::Text => t.form_ink, + }; + let font = if look.bold { crate::fonts::semibold(t.font_label) } else { FontId::proportional(t.font_label) }; + let label_rect = + Rect::from_min_size(pos2(rect.left() + t.space_2, figure.bottom() + gap(&t)), vec2((rect.width() - 2.0 * t.space_2).max(0.0), t.space_16)); + centred_text(p, label_rect, card.label, font, dim(ink)); + if let Some(sub) = card.sub { + let sub_rect = Rect::from_min_size(pos2(label_rect.left(), label_rect.bottom()), vec2(label_rect.width(), t.space_14)); + centred_text(p, sub_rect, sub, FontId::proportional(t.font_small), dim(t.form_dim)); + } + let corner = pos2(rect.right() - t.space_6, rect.top() + t.space_6); + if tile { + // The checkbox in the corner: 15 points, radius 4, accent with a tick when on. + let size = t.space_14 + 1.0; + let box_rect = Rect::from_min_size(corner - vec2(size, 0.0), vec2(size, size)); + if card.selected { + p.rect_filled(box_rect, t.space_4, dim(t.form_primary)); + tick(p, box_rect, dim(t.on_accent)); + } else { + p.rect(box_rect, t.space_4, dim(t.control_fill), Stroke::new(1.0, dim(t.control_border)), StrokeKind::Inside); + } + } else if card.options.is_some() || card.check { + let size = t.space_16; + let centre = pos2(rect.right() - t.space_6 + 1.0 - size * 0.5, rect.top() + t.space_6 - 1.0 + size * 0.5); + p.circle_filled(centre, size * 0.5, dim(t.form_primary)); + if card.check { + tick(p, Rect::from_center_size(centre, vec2(size, size) * 0.75), dim(t.on_accent)); + } else { + let dot = Rect::from_center_size(centre, vec2(size, size) * 0.6); + crate::icons::paint_ink(p, dot, "settings", dim(t.on_accent)); + } + } + let kind = if tile { egui::WidgetType::Checkbox } else { egui::WidgetType::RadioButton }; + response.widget_info(|| egui::WidgetInfo::selected(kind, enabled, card.selected, card.label)); + scenario::publish_target(&format!("prefs:card:{}", card.label), rect); + let response = if let Some(options) = card.options { response.on_hover_text(options) } else { response }; + if enabled { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response } +} + +fn tick(p: &Painter, r: Rect, ink: Color32) { + let w = (r.width() * 0.16).max(1.0); + let a = pos2(r.left() + r.width() * 0.24, r.top() + r.height() * 0.52); + let b = pos2(r.left() + r.width() * 0.42, r.top() + r.height() * 0.70); + let c = pos2(r.left() + r.width() * 0.78, r.top() + r.height() * 0.32); + p.line_segment([a, b], Stroke::new(w, ink)); + p.line_segment([b, c], Stroke::new(w, ink)); +} + +/// A radio card: a figure, a label and an optional sub-label. Click it to choose it. +pub(crate) fn picture_card(ui: &mut Ui, card: &Card, width: f32) -> Response { + paint_card(ui, card, width, false) +} + +/// A toggle tile: the same picture with a checkbox in the corner. Click it to flip `card.selected`. +pub(crate) fn toggle_tile(ui: &mut Ui, card: &Card, width: f32) -> Response { + paint_card(ui, card, width, true) +} + +/// A preset card: an icon, a name, one word and a check. `icon` paints into the 38-point box in +/// the colour it is given. +pub(crate) fn preset_card( + ui: &mut Ui, + name: &str, + word: &str, + selected: bool, + enabled: bool, + icon: &dyn Fn(&Painter, Rect, Color32), + width: f32, +) -> Response { + let t = Tokens::get(); + let enabled = enabled && ui.is_enabled(); + let width = dimension(width); + let height = t.space_24 * 3.0 - t.space_2; + let (rect, response) = ui.allocate_exact_size(vec2(width, height), if enabled { Sense::click() } else { Sense::hover() }); + let look = card_look(selected, enabled, response.hovered(), response.has_focus()); + let dim = |c: Color32| c.gamma_multiply(look.alpha); + let p = ui.painter(); + let fill = match look.fill { + CardFill::Selected => t.selected_bg, + CardFill::Hover => t.hover, + CardFill::Face => t.control_fill, + }; + let radius = f32::from(t.radius_lg) + t.space_2; + p.rect(rect, radius, dim(fill), Stroke::new(look.border, dim(if selected { t.form_primary } else { t.dialog_border })), StrokeKind::Inside); + if look.focus_ring { + p.rect_stroke(rect.expand(t.space_2), radius + t.space_2, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside); + } + let box_size = t.space_24 + t.space_14; + let box_rect = Rect::from_min_size(pos2(rect.left() + t.space_14, rect.center().y - box_size * 0.5), vec2(box_size, box_size)); + let box_fill = if selected { t.form_primary } else { t.pref_well }; + let box_ink = if selected { t.on_accent } else { t.form_dim }; + p.rect_filled(box_rect, f32::from(t.radius_lg) + t.space_2, dim(box_fill)); + icon(p, Rect::from_center_size(box_rect.center(), box_rect.size() * 0.55), dim(box_ink)); + let text_left = box_rect.right() + t.space_12; + let text_width = (rect.right() - t.space_14 - t.space_24 - text_left).max(0.0); + let name_font = crate::fonts::semibold(t.font_heading.min(t.font_subtitle)); + let name_ink = if selected { t.selected_ink } else { t.form_ink }; + let name_rect = Rect::from_min_size(pos2(text_left, rect.center().y - t.space_16), vec2(text_width, t.space_16)); + super::text::paint_text(ui, name_rect, name, name_font, dim(name_ink), false); + let word_rect = Rect::from_min_size(pos2(text_left, name_rect.bottom()), vec2(text_width, t.space_16)); + super::text::paint_text(ui, word_rect, word, FontId::proportional(t.font_small), dim(t.form_dim), false); + let p = ui.painter(); + if selected { + let centre = pos2(rect.right() - t.space_14 - t.space_8 + 1.0, rect.center().y); + p.circle_filled(centre, t.space_8 + 1.0, dim(t.form_primary)); + tick(p, Rect::from_center_size(centre, vec2(t.space_12, t.space_12)), dim(t.on_accent)); + } + response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::RadioButton, enabled, selected, name)); + scenario::publish_target(&format!("prefs:preset:{name}"), rect); + if enabled { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response } +} + +/// The (i) icon after a label: shows `text` as a tooltip and tells assistive technology the same. +pub(crate) fn help_icon(ui: &mut Ui, text: &str) -> Response { + let t = Tokens::get(); + let size = t.space_12 + 1.0; + let (rect, response) = ui.allocate_exact_size(vec2(size, size), Sense::hover()); + let ink = if response.hovered() { t.form_ink } else { t.form_dim }; + let p = ui.painter(); + p.circle_stroke(rect.center(), size * 0.5 - 0.5, Stroke::new(1.0, ink)); + p.circle_filled(pos2(rect.center().x, rect.top() + size * 0.3), 0.9, ink); + p.line_segment([pos2(rect.center().x, rect.top() + size * 0.46), pos2(rect.center().x, rect.bottom() - size * 0.24)], Stroke::new(1.2, ink)); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), text)); + scenario::publish_target("prefs:help_icon", rect); + response.on_hover_text(text) +} + +/// Which items of a carousel are shown: the first one and how many fit between the two arrows. +pub(super) fn carousel_window(count: usize, offset: usize, available: f32, item_width: f32, gap: f32, arrow: f32) -> (usize, usize) { + if count == 0 { + return (0, 0); + } + let room = dimension(available) - 2.0 * (arrow + gap); + let unit = dimension(item_width).max(1.0) + gap.max(0.0); + let visible = (((room + gap) / unit).floor() as usize).clamp(1, count); + (offset.min(count - visible), visible) +} + +/// A row of items with a previous and a next arrow; an arrow is dimmed and inert at its end. +/// `item` paints the item at an index into a column `item_width` wide and `item_height` high. +pub(crate) fn carousel( + ui: &mut Ui, + id: impl std::hash::Hash + std::fmt::Debug, + count: usize, + item_width: f32, + item_height: f32, + mut item: impl FnMut(&mut Ui, usize), +) -> (usize, usize) { + let t = Tokens::get(); + let key = ui.make_persistent_id(id); + let gap = t.space_8; + let arrow = t.space_24 + 2.0; + let offset = ui.data(|d| d.get_temp::(key)).unwrap_or(0); + let (first, visible) = carousel_window(count, offset, ui.available_width(), item_width, gap, arrow); + let height = dimension(item_height); + let mut next_offset = first; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = gap; + let can_back = first > 0; + if carousel_arrow(ui, vec2(arrow, height), -1.0, can_back, crate::i18n::tr("prefs.carousel_previous")).clicked() { + next_offset = first.saturating_sub(1); + } + for index in first..first + visible { + ui.allocate_ui_with_layout(vec2(dimension(item_width), height), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_width(dimension(item_width)); + item(ui, index); + }); + } + let can_forward = first + visible < count; + if carousel_arrow(ui, vec2(arrow, height), 1.0, can_forward, crate::i18n::tr("prefs.carousel_next")).clicked() { + next_offset = (first + 1).min(count.saturating_sub(visible)); + } + }); + ui.data_mut(|d| d.insert_temp(key, next_offset)); + (first, visible) +} + +fn carousel_arrow(ui: &mut Ui, size: egui::Vec2, direction: f32, enabled: bool, label: &str) -> Response { + let t = Tokens::get(); + let (rect, response) = ui.allocate_exact_size(size, if enabled { Sense::click() } else { Sense::hover() }); + let alpha = if enabled { 1.0 } else { 0.35 }; + let p = ui.painter(); + let fill = if enabled && response.hovered() { t.hover } else { t.control_fill }; + p.rect(rect, f32::from(t.radius_lg), fill.gamma_multiply(alpha), Stroke::new(1.0, t.dialog_border.gamma_multiply(alpha)), StrokeKind::Inside); + let icon = Rect::from_center_size(rect.center(), vec2(t.space_16, t.space_16)); + let ink = t.form_ink.gamma_multiply(alpha); + if direction < 0.0 { + crate::icons::paint_ink_mirrored(p, icon, "chevron_right", ink); + } else { + crate::icons::paint_ink(p, icon, "chevron_right", ink); + } + if enabled && response.has_focus() { + p.rect_stroke(rect.expand(t.space_2), f32::from(t.radius_lg) + t.space_2, Stroke::new(t.space_2, t.form_primary), StrokeKind::Outside); + } + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, enabled, label)); + scenario::publish_target(&format!("prefs:carousel:{label}"), rect); + if enabled { response.on_hover_cursor(egui::CursorIcon::PointingHand) } else { response } +} diff --git a/crates/ui-egui/src/ui_kit/preferences_figure_data.rs b/crates/ui-egui/src/ui_kit/preferences_figure_data.rs new file mode 100644 index 000000000..313496bb7 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/preferences_figure_data.rs @@ -0,0 +1,4580 @@ +//! Generated by `tools/preferences-figures/generate.py` from `docs/design/preferences/figures/*.svg`. +//! Do not edit by hand: change the SVG and run the script again. +#![allow(clippy::approx_constant, clippy::excessive_precision)] +use super::preferences_figure_ops::{Figure, G, Ink, L, Op, P}; + +pub(super) const AA_2X: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [108.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [84.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.25 }), line: None }, + Op::Rect { r: [90.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [96.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.25 }), line: None }, + Op::Rect { r: [78.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [84.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [66.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.25 }), line: None }, + Op::Rect { r: [48.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [54.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [36.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [42.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [24.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [6.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [12.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[6.0, 8.0], [6.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[12.0, 8.0], [12.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[18.0, 8.0], [18.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[24.0, 8.0], [24.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 8.0], [30.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[36.0, 8.0], [36.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 8.0], [42.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[48.0, 8.0], [48.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[54.0, 8.0], [54.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 8.0], [60.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.0, 8.0], [66.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 8.0], [72.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[78.0, 8.0], [78.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[84.0, 8.0], [84.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 8.0], [90.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[96.0, 8.0], [96.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[102.0, 8.0], [102.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[108.0, 8.0], [108.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[114.0, 8.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 8.0], [114.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 14.0], [114.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 20.0], [114.0, 20.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 26.0], [114.0, 26.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 32.0], [114.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 38.0], [114.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 44.0], [114.0, 44.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 50.0], [114.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 56.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const AA_4X: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.06 }), line: None }, + Op::Rect { r: [102.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.44 }), line: None }, + Op::Rect { r: [108.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.88 }), line: None }, + Op::Rect { r: [84.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.12 }), line: None }, + Op::Rect { r: [90.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.62 }), line: None }, + Op::Rect { r: [96.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.94 }), line: None }, + Op::Rect { r: [102.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.38 }), line: None }, + Op::Rect { r: [78.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [84.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.06 }), line: None }, + Op::Rect { r: [60.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.5 }), line: None }, + Op::Rect { r: [66.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.88 }), line: None }, + Op::Rect { r: [72.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.25 }), line: None }, + Op::Rect { r: [48.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.62 }), line: None }, + Op::Rect { r: [54.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.06 }), line: None }, + Op::Rect { r: [30.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.38 }), line: None }, + Op::Rect { r: [36.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.81 }), line: None }, + Op::Rect { r: [42.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.12 }), line: None }, + Op::Rect { r: [18.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.56 }), line: None }, + Op::Rect { r: [24.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.94 }), line: None }, + Op::Rect { r: [30.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [6.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.69 }), line: None }, + Op::Rect { r: [12.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[6.0, 8.0], [6.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[12.0, 8.0], [12.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[18.0, 8.0], [18.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[24.0, 8.0], [24.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 8.0], [30.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[36.0, 8.0], [36.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 8.0], [42.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[48.0, 8.0], [48.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[54.0, 8.0], [54.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 8.0], [60.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.0, 8.0], [66.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 8.0], [72.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[78.0, 8.0], [78.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[84.0, 8.0], [84.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 8.0], [90.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[96.0, 8.0], [96.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[102.0, 8.0], [102.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[108.0, 8.0], [108.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[114.0, 8.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 8.0], [114.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 14.0], [114.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 20.0], [114.0, 20.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 26.0], [114.0, 26.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 32.0], [114.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 38.0], [114.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 44.0], [114.0, 44.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 50.0], [114.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 56.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const AA_8X: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.06 }), line: None }, + Op::Rect { r: [102.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.42 }), line: None }, + Op::Rect { r: [108.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.84 }), line: None }, + Op::Rect { r: [84.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.17 }), line: None }, + Op::Rect { r: [90.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.59 }), line: None }, + Op::Rect { r: [96.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.95 }), line: None }, + Op::Rect { r: [102.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.02 }), line: None }, + Op::Rect { r: [72.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.33 }), line: None }, + Op::Rect { r: [78.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.75 }), line: None }, + Op::Rect { r: [84.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.09 }), line: None }, + Op::Rect { r: [60.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.48 }), line: None }, + Op::Rect { r: [66.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.89 }), line: None }, + Op::Rect { r: [72.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.22 }), line: None }, + Op::Rect { r: [48.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.66 }), line: None }, + Op::Rect { r: [54.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.98 }), line: None }, + Op::Rect { r: [60.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.03 }), line: None }, + Op::Rect { r: [30.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.39 }), line: None }, + Op::Rect { r: [36.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.81 }), line: None }, + Op::Rect { r: [42.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.14 }), line: None }, + Op::Rect { r: [18.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.55 }), line: None }, + Op::Rect { r: [24.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.94 }), line: None }, + Op::Rect { r: [30.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [6.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 0.7 }), line: None }, + Op::Rect { r: [12.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[6.0, 8.0], [6.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[12.0, 8.0], [12.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[18.0, 8.0], [18.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[24.0, 8.0], [24.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 8.0], [30.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[36.0, 8.0], [36.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 8.0], [42.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[48.0, 8.0], [48.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[54.0, 8.0], [54.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 8.0], [60.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.0, 8.0], [66.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 8.0], [72.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[78.0, 8.0], [78.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[84.0, 8.0], [84.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 8.0], [90.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[96.0, 8.0], [96.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[102.0, 8.0], [102.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[108.0, 8.0], [108.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[114.0, 8.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 8.0], [114.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 14.0], [114.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 20.0], [114.0, 20.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 26.0], [114.0, 26.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 32.0], [114.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 38.0], [114.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 44.0], [114.0, 44.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 50.0], [114.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 56.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 0.55 }), line: None }, + ], +}; + +pub(super) const AA_OFF: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 8.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 14.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 20.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 26.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 32.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 38.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 44.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [6.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [18.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [36.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [48.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [54.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [60.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [66.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [72.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [78.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [84.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [90.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [96.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [102.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [108.0, 50.0, 6.0, 6.0], radius: 0.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[6.0, 8.0], [6.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[12.0, 8.0], [12.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[18.0, 8.0], [18.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[24.0, 8.0], [24.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 8.0], [30.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[36.0, 8.0], [36.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 8.0], [42.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[48.0, 8.0], [48.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[54.0, 8.0], [54.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 8.0], [60.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.0, 8.0], [66.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 8.0], [72.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[78.0, 8.0], [78.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[84.0, 8.0], [84.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 8.0], [90.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[96.0, 8.0], [96.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[102.0, 8.0], [102.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[108.0, 8.0], [108.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[114.0, 8.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 8.0], [114.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 14.0], [114.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 20.0], [114.0, 20.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 26.0], [114.0, 26.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 32.0], [114.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 38.0], [114.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 44.0], [114.0, 44.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 50.0], [114.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 56.0], [114.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.14, w: 0.5, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const AGENT_POINTER_SPEED: Figure = Figure { + size: [230.0, 84.0], + ops: &[ + Op::Poly { + pts: &[[24.0, 48.0], [115.0, 42.0], [186.0, 36.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [3.0, 4.0], round: false }), + }, + Op::Circle { c: [24.0, 48.0, 3.0], fill: Some(P { ink: Ink::ControlBorder, a: 1.0 }), line: None }, + Op::Circle { c: [115.0, 42.0, 3.0], fill: Some(P { ink: Ink::ControlBorder, a: 1.0 }), line: None }, + Op::Circle { c: [186.0, 36.0, 3.0], fill: Some(P { ink: Ink::ControlBorder, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[115.0, 42.0], [118.0, 60.0], [123.0, 53.0], [130.0, 56.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Card, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const AO_ON: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[32.742, 27.5], [44.0, 34.0], [44.0, 47.0], [32.742, 40.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[55.258, 27.5], [44.0, 34.0], [44.0, 47.0], [55.258, 40.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 21.0], [55.258, 27.5], [44.0, 34.0], [32.742, 27.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[64.742, 27.5], [76.0, 34.0], [76.0, 47.0], [64.742, 40.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[87.258, 27.5], [76.0, 34.0], [76.0, 47.0], [87.258, 40.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[76.0, 21.0], [87.258, 27.5], [76.0, 34.0], [64.742, 27.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Glow { c: [60.0, 42.0, 22.0, 7.0], a: 0.55 }, + Op::Glow { c: [60.0, 31.0, 5.0, 10.0], a: 0.44 }, + ], +}; + +pub(super) const ASSEMBLY_MOVE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 32.0, 20.0], fill: None, line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }) }, + Op::Circle { c: [60.0, 32.0, 27.0], fill: None, line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }) }, + Op::Poly { + pts: &[[77.0, 32.0], [83.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[74.7, 40.5], [79.9, 43.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[68.5, 46.7], [71.5, 51.9]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 49.0], [60.0, 55.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[51.5, 46.7], [48.5, 51.9]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[45.3, 40.5], [40.1, 43.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[43.0, 32.0], [37.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[45.3, 23.5], [40.1, 20.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[51.5, 17.3], [48.5, 12.1]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 15.0], [60.0, 9.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[68.5, 17.3], [71.5, 12.1]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[74.7, 23.5], [79.9, 20.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [54.0, 26.0, 12.0, 12.0], + radius: 2.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [80.0, 32.0, 3.6], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Reference, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [80.0, 32.0, 1.4], fill: Some(P { ink: Ink::Reference, a: 1.0 }), line: None }, + ], +}; + +pub(super) const BROWSER_CARD: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 214.0, 92.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[100.01, 66.5], [113.0, 74.0], [113.0, 89.0], [100.01, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[125.99, 66.5], [113.0, 74.0], [113.0, 89.0], [125.99, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[113.0, 59.0], [125.99, 66.5], [113.0, 74.0], [100.01, 66.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [12.0, 32.0, 48.0, 62.0], + radius: 4.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 122.0, 214.0, 20.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [42.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [72.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [102.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [132.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [162.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + ], +}; + +pub(super) const BROWSER_COLUMN: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { + r: [64.0, 26.0, 156.0, 92.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[129.01, 66.5], [142.0, 74.0], [142.0, 89.0], [129.01, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[154.99, 66.5], [142.0, 74.0], [142.0, 89.0], [154.99, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.0, 59.0], [154.99, 66.5], [142.0, 74.0], [129.01, 66.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 122.0, 214.0, 20.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [42.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [72.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [102.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [132.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [162.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + ], +}; + +pub(super) const COLOUR_VISION_AXES: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[14.0, 34.0], [66.0, 34.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv2, a: 1.0, w: 3.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[14.0, 34.0], [14.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv0, a: 1.0, w: 3.0, dash: [0.0, 0.0], round: true }), + }, + ], +}; + +pub(super) const COLOUR_VISION_BENDS: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[10.0, 14.0], [74.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv1, a: 1.0, w: 2.4, dash: [6.0, 4.0], round: false }), + }, + Op::Poly { + pts: &[[10.0, 30.0], [74.0, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv3, a: 1.0, w: 2.4, dash: [6.0, 4.0], round: false }), + }, + ], +}; + +pub(super) const COLOUR_VISION_DRAFT: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { r: [8.0, 8.0, 22.0, 28.0], radius: 0.0, fill: Some(P { ink: Ink::Cv3, a: 1.0 }), line: None }, + Op::Rect { r: [30.0, 8.0, 22.0, 28.0], radius: 0.0, fill: Some(P { ink: Ink::Cv1, a: 1.0 }), line: None }, + Op::Clip(&[[52.0, 8.0], [76.0, 8.0], [76.0, 36.0], [52.0, 36.0]]), + Op::Rect { r: [52.0, 8.0, 24.0, 28.0], radius: 0.0, fill: Some(P { ink: Ink::Cv4, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[38.0, 36.0], [52.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 36.0], [58.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[50.0, 36.0], [64.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[56.0, 36.0], [70.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[62.0, 36.0], [76.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[68.0, 36.0], [82.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[74.0, 36.0], [88.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Black, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + ], +}; + +pub(super) const COLOUR_VISION_FAILED: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [14.0, 12.0, 56.0, 20.0], + radius: 4.0, + fill: Some(P { ink: Ink::NoteFill, a: 1.0 }), + line: Some(L { ink: Ink::Cv2, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[36.0, 17.0], [48.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv2, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[48.0, 17.0], [36.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv2, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + ], +}; + +pub(super) const COLOUR_VISION_FIXED: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[12.0, 22.0], [72.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv0, a: 1.0, w: 3.0, dash: [0.0, 0.0], round: true }), + }, + ], +}; + +pub(super) const COLOUR_VISION_PROJECTED: Figure = Figure { + size: [84.0, 44.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 84.0, 44.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[12.0, 22.0], [72.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Cv1, a: 1.0, w: 3.0, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { c: [12.0, 22.0, 2.2], fill: Some(P { ink: Ink::Cv1, a: 1.0 }), line: None }, + Op::Circle { c: [72.0, 22.0, 2.2], fill: Some(P { ink: Ink::Cv1, a: 1.0 }), line: None }, + ], +}; + +pub(super) const DIRECT_INTERACTION: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[31.0, 20.0], [44.0, 27.5], [44.0, 57.5], [31.0, 50.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[57.0, 20.0], [44.0, 27.5], [44.0, 57.5], [57.0, 50.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 12.5], [57.0, 20.0], [44.0, 27.5], [31.0, 20.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 12.5], [57.0, 20.0], [44.0, 27.5], [31.0, 20.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.4 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 30.5], [57.0, 38.0], [44.0, 45.5], [31.0, 38.0]], + closed: true, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.0, dash: [2.5, 2.5], round: false }), + }, + Op::Poly { + pts: &[[44.0, 34.0], [44.0, 13.1]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[44.0, 8.5], [46.8, 13.1], [41.2, 13.1]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: None, + }, + Op::Poly { + pts: &[[46.0, 18.0], [46.0, 31.5], [49.6, 28.26], [52.12, 34.2], [54.46, 33.12], [51.94, 27.36], [56.62, 27.18]], + closed: true, + fill: Some(P { ink: Ink::Text, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Ground, a: 1.0, w: 0.99, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [76.0, 14.0, 30.0, 14.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [91.0, 24.0], size: 6.5, anchor: 1, ink: Ink::Accent, a: 1.0, s: "+18 mm", bold: true }, + ], +}; + +pub(super) const FRAME_RATE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [26.0, 12.0, 68.0, 40.0], + radius: 6.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [60.0, 31.0], size: 10.0, anchor: 1, ink: Ink::Text, a: 1.0, s: "60 fps", bold: true }, + Op::Poly { + pts: &[ + [34.0, 39.0], + [39.0, 42.0], + [43.0, 42.0], + [48.0, 39.0], + [52.0, 42.0], + [57.0, 42.0], + [62.0, 39.0], + [66.0, 42.0], + [71.0, 42.0], + [75.0, 39.0], + [80.0, 42.0], + [85.0, 42.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.3, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const HISTORY_BOTTOM: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { + r: [64.0, 26.0, 156.0, 92.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[129.01, 66.5], [142.0, 74.0], [142.0, 89.0], [129.01, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[154.99, 66.5], [142.0, 74.0], [142.0, 89.0], [154.99, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.0, 59.0], [154.99, 66.5], [142.0, 74.0], [129.01, 66.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 122.0, 214.0, 20.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [42.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [72.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [102.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [132.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [162.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + ], +}; + +pub(super) const HISTORY_IN_BROWSER: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 118.0, 40.0, 16.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 0.25 }), line: None }, + Op::Rect { + r: [64.0, 26.0, 156.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[129.01, 78.5], [142.0, 86.0], [142.0, 101.0], [129.01, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[154.99, 78.5], [142.0, 86.0], [142.0, 101.0], [154.99, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.0, 71.0], [154.99, 78.5], [142.0, 86.0], [129.01, 78.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const HISTORY_LEFT: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { + r: [64.0, 26.0, 20.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [90.0, 26.0, 130.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.01, 78.5], [155.0, 86.0], [155.0, 101.0], [142.01, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[167.99, 78.5], [155.0, 86.0], [155.0, 101.0], [167.99, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[155.0, 71.0], [167.99, 78.5], [155.0, 86.0], [142.01, 78.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const HISTORY_UNDER_BROWSER: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 86.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { + r: [6.0, 116.0, 52.0, 26.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [64.0, 26.0, 156.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[129.01, 78.5], [142.0, 86.0], [142.0, 101.0], [129.01, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[154.99, 78.5], [142.0, 86.0], [142.0, 101.0], [154.99, 93.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.0, 71.0], [154.99, 78.5], [142.0, 86.0], [129.01, 78.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const LAYOUT_SCHEMATIC: Figure = Figure { + size: [226.0, 148.0], + ops: &[ + Op::Rect { + r: [0.5, 0.5, 225.0, 147.0], + radius: 7.0, + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Border, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 6.0, 214.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [11.0, 11.0, 26.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { r: [43.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { r: [71.0, 11.0, 22.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.5 }), line: None }, + Op::Rect { + r: [6.0, 26.0, 52.0, 116.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 34.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 43.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 52.0, 34.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { r: [12.0, 61.0, 26.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Dim, a: 0.45 }), line: None }, + Op::Rect { + r: [64.0, 26.0, 156.0, 92.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::ControlBorder, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[129.01, 66.5], [142.0, 74.0], [142.0, 89.0], [129.01, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[154.99, 66.5], [142.0, 74.0], [142.0, 89.0], [154.99, 81.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[142.0, 59.0], [154.99, 66.5], [142.0, 74.0], [129.01, 66.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [6.0, 122.0, 214.0, 20.0], + radius: 3.0, + fill: Some(P { ink: Ink::Card, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [12.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [42.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [72.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [102.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [132.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + Op::Rect { r: [162.0, 129.0, 22.0, 7.0], radius: 2.0, fill: Some(P { ink: Ink::Dim, a: 0.4 }), line: None }, + ], +}; + +pub(super) const MEASURE_AXIS_DISTANCES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [20.0, 22.0, 46.0, 28.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[20.0, 14.0], [66.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[20.0, 10.0], [20.0, 18.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.0, 10.0], [66.0, 18.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [43.0, 9.0], size: 7.0, anchor: 1, ink: Ink::Accent, a: 1.0, s: "X 46", bold: true }, + Op::Poly { + pts: &[[76.0, 22.0], [76.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 22.0], [80.0, 22.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.0, 50.0], [80.0, 50.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [98.0, 39.0], size: 7.0, anchor: 1, ink: Ink::Accent, a: 1.0, s: "Y 28", bold: true }, + ], +}; + +pub(super) const MOUSE_MAPPING: Figure = Figure { + size: [96.0, 120.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 96.0, 120.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [26.0, 14.0, 44.0, 86.0], + radius: 22.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[26.0, 56.0], [70.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[48.0, 14.0], [48.0, 56.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { r: [43.0, 24.0, 10.0, 20.0], radius: 5.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Poly { + pts: &[ + [26.0, 56.0], + [25.538, 54.028], + [25.259, 52.023], + [25.166, 50.0], + [25.259, 47.977], + [25.538, 45.972], + [26.0, 44.0], + [26.0, 36.0], + [26.423, 31.708], + [27.675, 27.581], + [29.708, 23.777], + [32.444, 20.444], + [35.777, 17.708], + [39.581, 15.675], + [43.708, 14.423], + [48.0, 14.0], + [48.0, 56.0], + ], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.0 }), + grad: None, + line: None, + }, + Op::Text { at: [36.0, 44.0], size: 8.0, anchor: 1, ink: Ink::Dim, a: 1.0, s: "L", bold: true }, + Op::Text { at: [60.0, 44.0], size: 8.0, anchor: 1, ink: Ink::Dim, a: 1.0, s: "R", bold: true }, + Op::Text { at: [48.0, 20.0], size: 7.0, anchor: 1, ink: Ink::Accent, a: 1.0, s: "M", bold: true }, + ], +}; + +pub(super) const NAVIGATOR_AXES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Circle { + c: [60.0, 32.0, 30.0], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 32.0, 26.0], fill: None, line: Some(L { ink: Ink::Line, a: 0.6, w: 0.6, dash: [1.5, 3.0], round: false }) }, + Op::Poly { + pts: &[[60.0, 32.0], [76.0, 22.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisY, a: 0.55, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[60.0, 32.0], [44.0, 22.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisX, a: 0.55, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[60.0, 32.0], [60.0, 50.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisZ, a: 0.55, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[60.0, 32.0], [44.0, 41.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisY, a: 1.0, w: 3.4, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[60.0, 32.0], [76.0, 41.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisX, a: 1.0, w: 3.4, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[60.0, 32.0], [60.0, 13.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisZ, a: 1.0, w: 3.4, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { c: [60.0, 32.0, 3.2], fill: Some(P { ink: Ink::Dim, a: 1.0 }), line: None }, + Op::Circle { + c: [60.0, 13.5, 8.2], + fill: Some(P { ink: Ink::AxisZ, a: 1.0 }), + line: Some(L { ink: Ink::AxisZ, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [60.0, 17.0], size: 10.0, anchor: 1, ink: Ink::White, a: 1.0, s: "Z", bold: true }, + Op::Circle { + c: [76.0, 41.2, 8.2], + fill: Some(P { ink: Ink::AxisX, a: 1.0 }), + line: Some(L { ink: Ink::AxisX, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [76.0, 44.8], size: 10.0, anchor: 1, ink: Ink::White, a: 1.0, s: "X", bold: true }, + Op::Circle { + c: [44.0, 41.2, 8.2], + fill: Some(P { ink: Ink::AxisY, a: 1.0 }), + line: Some(L { ink: Ink::AxisY, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [44.0, 44.8], size: 10.0, anchor: 1, ink: Ink::White, a: 1.0, s: "Y", bold: true }, + Op::Circle { + c: [60.0, 50.5, 5.6], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::AxisZ, a: 1.0, w: 2.2, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [44.0, 22.8, 5.6], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::AxisX, a: 1.0, w: 2.2, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [76.0, 22.8, 5.6], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::AxisY, a: 1.0, w: 2.2, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const NAVIGATOR_CUBE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Poly { + pts: &[ + [82.2, 60.0], + [81.773, 60.624], + [80.51, 61.225], + [78.459, 61.778], + [75.698, 62.263], + [72.334, 62.661], + [68.496, 62.956], + [64.331, 63.139], + [60.0, 63.2], + [55.669, 63.139], + [51.504, 62.956], + [47.666, 62.661], + [44.302, 62.263], + [41.541, 61.778], + [39.49, 61.225], + [38.227, 60.624], + [37.8, 60.0], + [38.227, 59.376], + [39.49, 58.775], + [41.541, 58.222], + [44.302, 57.737], + [47.666, 57.339], + [51.504, 57.044], + [55.669, 56.861], + [60.0, 56.8], + [64.331, 56.861], + [68.496, 57.044], + [72.334, 57.339], + [75.698, 57.737], + [78.459, 58.222], + [80.51, 58.775], + [81.773, 59.376], + ], + closed: true, + fill: Some(P { ink: Ink::Black, a: 0.12 }), + grad: None, + line: None, + }, + Op::Poly { + pts: &[[36.618, 18.5], [60.0, 32.0], [60.0, 59.0], [36.618, 45.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[83.382, 18.5], [60.0, 32.0], [60.0, 59.0], [83.382, 45.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 5.0], [83.382, 18.5], [60.0, 32.0], [36.618, 18.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 5.0], [83.382, 18.5], [60.0, 32.0], [36.618, 18.5]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 10.0], [75.4, 29.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::White, a: 0.5, w: 1.0, dash: [0.0, 0.0], round: true }), + }, + Op::Text { at: [57.402, 20.0], size: 8.375, anchor: 1, ink: Ink::Text, a: 1.0, s: "TOP", bold: true }, + Op::Text { at: [48.309, 41.15], size: 6.8, anchor: 1, ink: Ink::Text, a: 1.0, s: "FRONT", bold: true }, + Op::Text { at: [71.691, 41.15], size: 6.8, anchor: 1, ink: Ink::Text, a: 1.0, s: "RIGHT", bold: true }, + ], +}; + +pub(super) const ORBIT_CENTRE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [8.0, 5.0, 104.0, 54.0], + radius: 5.0, + fill: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 5.0], [60.0, 11.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 53.0], [60.0, 59.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[8.0, 32.0], [14.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[106.0, 32.0], [112.0, 32.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [28.0, 32.0], + [28.615, 30.244], + [30.436, 28.556], + [33.393, 27.0], + [37.373, 25.636], + [42.222, 24.517], + [47.754, 23.685], + [53.757, 23.173], + [60.0, 23.0], + [66.243, 23.173], + [72.246, 23.685], + [77.778, 24.517], + [82.627, 25.636], + [86.607, 27.0], + [89.564, 28.556], + [91.385, 30.244], + [92.0, 32.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.6, w: 1.2, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[28.144, 25.0], [42.0, 33.0], [42.0, 49.0], [28.144, 41.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[55.856, 25.0], [42.0, 33.0], [42.0, 49.0], [55.856, 41.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 17.0], [55.856, 25.0], [42.0, 33.0], [28.144, 25.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [28.0, 32.0], + [28.615, 33.756], + [30.436, 35.444], + [33.393, 37.0], + [37.373, 38.364], + [42.222, 39.483], + [47.754, 40.315], + [53.757, 40.827], + [60.0, 41.0], + [66.243, 40.827], + [72.246, 40.315], + [77.778, 39.483], + [82.627, 38.364], + [86.607, 37.0], + [89.564, 35.444], + [91.385, 33.756], + [92.0, 32.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[92.0, 26.5], [88.6, 32.8], [95.4, 32.8]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: None, + }, + Op::Circle { + c: [60.0, 32.0, 3.8], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Reference, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 32.0, 1.4], fill: Some(P { ink: Ink::Reference, a: 1.0 }), line: None }, + ], +}; + +pub(super) const ORBIT_CURSOR: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[ + [37.0, 29.0], + [37.615, 27.244], + [39.436, 25.556], + [42.393, 24.0], + [46.373, 22.636], + [51.222, 21.517], + [56.754, 20.685], + [62.757, 20.173], + [69.0, 20.0], + [75.243, 20.173], + [81.246, 20.685], + [86.778, 21.517], + [91.627, 22.636], + [95.607, 24.0], + [98.564, 25.556], + [100.385, 27.244], + [101.0, 29.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.6, w: 1.2, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[38.144, 24.0], [52.0, 32.0], [52.0, 48.0], [38.144, 40.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[65.856, 24.0], [52.0, 32.0], [52.0, 48.0], [65.856, 40.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[52.0, 16.0], [65.856, 24.0], [52.0, 32.0], [38.144, 24.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [37.0, 29.0], + [37.615, 30.756], + [39.436, 32.444], + [42.393, 34.0], + [46.373, 35.364], + [51.222, 36.483], + [56.754, 37.315], + [62.757, 37.827], + [69.0, 38.0], + [75.243, 37.827], + [81.246, 37.315], + [86.778, 36.483], + [91.627, 35.364], + [95.607, 34.0], + [98.564, 32.444], + [100.385, 30.756], + [101.0, 29.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[101.0, 23.5], [97.6, 29.8], [104.4, 29.8]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: None, + }, + Op::Circle { + c: [69.0, 29.0, 3.8], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Reference, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [69.0, 29.0, 1.4], fill: Some(P { ink: Ink::Reference, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[70.5, 30.5], [70.5, 45.5], [74.5, 41.9], [77.3, 48.5], [79.9, 47.3], [77.1, 40.9], [82.3, 40.7]], + closed: true, + fill: Some(P { ink: Ink::Text, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const ORBIT_ORIGIN: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[60.0, 21.0], [94.0, 38.0], [60.0, 55.0], [26.0, 38.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 0.35 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[ + [28.0, 38.0], + [28.615, 36.244], + [30.436, 34.556], + [33.393, 33.0], + [37.373, 31.636], + [42.222, 30.517], + [47.754, 29.685], + [53.757, 29.173], + [60.0, 29.0], + [66.243, 29.173], + [72.246, 29.685], + [77.778, 30.517], + [82.627, 31.636], + [86.607, 33.0], + [89.564, 34.556], + [91.385, 36.244], + [92.0, 38.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.6, w: 1.2, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[46.144, 22.0], [60.0, 30.0], [60.0, 46.0], [46.144, 38.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[73.856, 22.0], [60.0, 30.0], [60.0, 46.0], [73.856, 38.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 14.0], [73.856, 22.0], [60.0, 30.0], [46.144, 22.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [28.0, 38.0], + [28.615, 39.756], + [30.436, 41.444], + [33.393, 43.0], + [37.373, 44.364], + [42.222, 45.483], + [47.754, 46.315], + [53.757, 46.827], + [60.0, 47.0], + [66.243, 46.827], + [72.246, 46.315], + [77.778, 45.483], + [82.627, 44.364], + [86.607, 43.0], + [89.564, 41.444], + [91.385, 39.756], + [92.0, 38.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[92.0, 32.5], [88.6, 38.8], [95.4, 38.8]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: None, + }, + Op::Circle { + c: [60.0, 38.0, 3.8], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Reference, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 38.0, 1.4], fill: Some(P { ink: Ink::Reference, a: 1.0 }), line: None }, + ], +}; + +pub(super) const QUICK_MEASURE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[34.742, 29.5], [46.0, 36.0], [46.0, 49.0], [34.742, 42.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[57.258, 29.5], [46.0, 36.0], [46.0, 49.0], [57.258, 42.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[46.0, 23.0], [57.258, 29.5], [46.0, 36.0], [34.742, 29.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 22.0], [75.0, 13.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 22.0, 1.8], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [75.0, 13.5, 1.8], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Rect { + r: [78.0, 22.0, 34.0, 15.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [95.0, 32.5], size: 7.5, anchor: 1, ink: Ink::Accent, a: 1.0, s: "12.5 mm", bold: true }, + ], +}; + +pub(super) const SELECT_BODIES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[44.412, 25.0], [60.0, 34.0], [60.0, 52.0], [44.412, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.412, 25.0], [60.0, 34.0], [60.0, 52.0], [44.412, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[75.588, 25.0], [60.0, 34.0], [60.0, 52.0], [75.588, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[75.588, 25.0], [60.0, 34.0], [60.0, 52.0], [75.588, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [75.588, 25.0], [60.0, 34.0], [44.412, 25.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [75.588, 25.0], [60.0, 34.0], [44.412, 25.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const SELECT_FACES_EDGES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[44.412, 25.0], [60.0, 34.0], [60.0, 52.0], [44.412, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[75.588, 25.0], [60.0, 34.0], [60.0, 52.0], [75.588, 43.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [75.588, 25.0], [60.0, 34.0], [44.412, 25.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [75.588, 25.0], [60.0, 34.0], [44.412, 25.0]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const SKETCH_CONFLICT: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[ + [14.0, 46.0], + [18.637, 39.672], + [23.531, 34.188], + [28.66, 29.547], + [34.0, 25.75], + [39.527, 22.797], + [45.219, 20.688], + [51.051, 19.422], + [57.0, 19.0], + [63.043, 19.422], + [69.156, 20.688], + [75.316, 22.797], + [81.5, 25.75], + [87.684, 29.547], + [93.844, 34.188], + [99.957, 39.672], + [106.0, 46.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Note, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[14.0, 16.0], [106.0, 46.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Note, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [60.0, 31.0, 4.0], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Note, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[14.0, 54.0], [106.0, 54.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [3.0, 3.0], round: false }), + }, + ], +}; + +pub(super) const SKETCH_EXIT_KEEP: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [7.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[7.0, 12.0], [37.0, 12.0], [37.0, 42.0], [7.0, 42.0]]), + Op::Poly { + pts: &[[15.505, 24.25], [22.0, 28.0], [22.0, 35.5], [15.505, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[28.495, 24.25], [22.0, 28.0], [22.0, 35.5], [28.495, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[22.0, 20.5], [28.495, 24.25], [22.0, 28.0], [15.505, 24.25]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + Op::Rect { + r: [45.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[45.0, 12.0], [75.0, 12.0], [75.0, 42.0], [45.0, 42.0]]), + Op::Rect { + r: [53.0, 20.0, 14.0, 14.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[49.0, 27.0], [71.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [60.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Unclip, + Op::Poly { + pts: &[[37.5, 24.0], [41.5, 27.0], [37.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[75.5, 24.0], [79.5, 27.0], [75.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Rect { + r: [83.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[83.0, 12.0], [113.0, 12.0], [113.0, 42.0], [83.0, 42.0]]), + Op::Rect { + r: [91.0, 20.0, 14.0, 14.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[87.0, 27.0], [109.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Poly { + pts: &[[98.0, 16.0], [98.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Unclip, + Op::Text { at: [22.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "before", bold: false }, + Op::Text { at: [60.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "sketch", bold: false }, + Op::Text { at: [98.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Accent, a: 1.0, s: "after", bold: true }, + ], +}; + +pub(super) const SKETCH_EXIT_PREVIOUS: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [7.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[7.0, 12.0], [37.0, 12.0], [37.0, 42.0], [7.0, 42.0]]), + Op::Poly { + pts: &[[15.505, 24.25], [22.0, 28.0], [22.0, 35.5], [15.505, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[28.495, 24.25], [22.0, 28.0], [22.0, 35.5], [28.495, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[22.0, 20.5], [28.495, 24.25], [22.0, 28.0], [15.505, 24.25]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + Op::Rect { + r: [45.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[45.0, 12.0], [75.0, 12.0], [75.0, 42.0], [45.0, 42.0]]), + Op::Rect { + r: [53.0, 20.0, 14.0, 14.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[49.0, 27.0], [71.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [60.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Unclip, + Op::Poly { + pts: &[[37.5, 24.0], [41.5, 27.0], [37.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[75.5, 24.0], [79.5, 27.0], [75.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Rect { + r: [83.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[83.0, 12.0], [113.0, 12.0], [113.0, 42.0], [83.0, 42.0]]), + Op::Poly { + pts: &[[91.505, 24.25], [98.0, 28.0], [98.0, 35.5], [91.505, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[104.495, 24.25], [98.0, 28.0], [98.0, 35.5], [104.495, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[98.0, 20.5], [104.495, 24.25], [98.0, 28.0], [91.505, 24.25]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + Op::Text { at: [22.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "before", bold: false }, + Op::Text { at: [60.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "sketch", bold: false }, + Op::Text { at: [98.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Accent, a: 1.0, s: "after", bold: true }, + ], +}; + +pub(super) const SKETCH_EXIT_UNLESS_TURNED: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [7.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[7.0, 12.0], [37.0, 12.0], [37.0, 42.0], [7.0, 42.0]]), + Op::Poly { + pts: &[[15.505, 24.25], [22.0, 28.0], [22.0, 35.5], [15.505, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[28.495, 24.25], [22.0, 28.0], [22.0, 35.5], [28.495, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[22.0, 20.5], [28.495, 24.25], [22.0, 28.0], [15.505, 24.25]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + Op::Rect { + r: [45.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: Some(P { ink: Ink::Top, a: 0.45 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Clip(&[[45.0, 12.0], [75.0, 12.0], [75.0, 42.0], [45.0, 42.0]]), + Op::Rect { + r: [53.0, 20.0, 14.0, 14.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[49.0, 27.0], [71.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Poly { + pts: &[[60.0, 16.0], [60.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Unclip, + Op::Poly { + pts: &[[37.5, 24.0], [41.5, 27.0], [37.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[75.5, 24.0], [79.5, 27.0], [75.5, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: true }), + }, + Op::Rect { r: [83.0, 12.0, 30.0, 30.0], radius: 4.0, fill: Some(P { ink: Ink::Top, a: 0.45 }), line: None }, + Op::Clip(&[[83.0, 12.0], [113.0, 12.0], [113.0, 42.0], [83.0, 42.0]]), + Op::Clip(&[[83.0, 12.0], [113.0, 12.0], [83.0, 42.0]]), + Op::Poly { + pts: &[[91.505, 24.25], [98.0, 28.0], [98.0, 35.5], [91.505, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[104.495, 24.25], [98.0, 28.0], [98.0, 35.5], [104.495, 31.75]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[98.0, 20.5], [104.495, 24.25], [98.0, 28.0], [91.505, 24.25]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Unclip, + Op::Clip(&[[113.0, 12.0], [113.0, 42.0], [83.0, 42.0]]), + Op::Rect { + r: [91.0, 20.0, 14.0, 14.0], + radius: 0.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[87.0, 27.0], [109.0, 27.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Poly { + pts: &[[98.0, 16.0], [98.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.6, dash: [1.5, 1.5], round: false }), + }, + Op::Unclip, + Op::Poly { + pts: &[[113.0, 12.0], [83.0, 42.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [2.0, 2.0], round: false }), + }, + Op::Unclip, + Op::Rect { + r: [83.0, 12.0, 30.0, 30.0], + radius: 4.0, + fill: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [22.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "before", bold: false }, + Op::Text { at: [60.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Dim, a: 1.0, s: "sketch", bold: false }, + Op::Text { at: [98.0, 55.0], size: 6.5, anchor: 1, ink: Ink::Accent, a: 1.0, s: "after", bold: true }, + ], +}; + +pub(super) const SKETCH_GUIDES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [20.0, 16.0, 44.0, 30.0], + radius: 0.0, + fill: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.2, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 6.0], [42.0, 58.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[6.0, 31.0], [114.0, 31.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Circle { c: [42.0, 31.0, 3.0], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { + c: [90.0, 31.0, 3.4], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 24.0], [90.0, 38.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[83.0, 31.0], [97.0, 31.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const SKETCH_HIDE_GLYPHS: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[12.0, 44.0], [108.0, 44.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [18.0, 20.0, 14.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [42.0, 12.0, 14.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 0.8 }), + line: Some(L { ink: Ink::Line, a: 0.8, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [66.0, 20.0, 14.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 0.6 }), + line: Some(L { ink: Ink::Line, a: 0.6, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Rect { + r: [90.0, 12.0, 14.0, 14.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 0.4 }), + line: Some(L { ink: Ink::Line, a: 0.4, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const SKETCH_STATE_ICONS: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [13.0, 21.0, 22.0, 22.0], + radius: 5.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Ok, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [18.0, 38.0], + [19.0, 35.5], + [20.0, 33.333], + [21.0, 31.5], + [22.0, 30.0], + [23.0, 28.833], + [24.0, 28.0], + [25.0, 27.5], + [26.0, 27.333], + [27.0, 27.5], + [28.0, 28.0], + [29.0, 28.833], + [30.0, 30.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Ok, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { c: [30.0, 30.0, 1.8], fill: Some(P { ink: Ink::Ok, a: 1.0 }), line: None }, + Op::Rect { + r: [49.0, 21.0, 22.0, 22.0], + radius: 5.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Warn, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [54.0, 38.0], + [55.0, 35.5], + [56.0, 33.333], + [57.0, 31.5], + [58.0, 30.0], + [59.0, 28.833], + [60.0, 28.0], + [61.0, 27.5], + [62.0, 27.333], + [63.0, 27.5], + [64.0, 28.0], + [65.0, 28.833], + [66.0, 30.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Warn, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { c: [66.0, 30.0, 1.8], fill: Some(P { ink: Ink::Warn, a: 1.0 }), line: None }, + Op::Rect { + r: [85.0, 21.0, 22.0, 22.0], + radius: 5.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Note, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[ + [90.0, 38.0], + [91.0, 35.5], + [92.0, 33.333], + [93.0, 31.5], + [94.0, 30.0], + [95.0, 28.833], + [96.0, 28.0], + [97.0, 27.5], + [98.0, 27.333], + [99.0, 27.5], + [100.0, 28.0], + [101.0, 28.833], + [102.0, 30.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Note, a: 1.0, w: 1.8, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { c: [102.0, 30.0, 1.8], fill: Some(P { ink: Ink::Note, a: 1.0 }), line: None }, + ], +}; + +pub(super) const TESS_COARSE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 32.0, 21.0], fill: None, line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.9, dash: [2.0, 2.5], round: false }) }, + Op::Poly { + pts: &[[60.0, 11.0], [74.8, 17.2], [81.0, 32.0], [74.8, 46.8], [60.0, 53.0], [45.2, 46.8], [39.0, 32.0], [45.2, 17.2]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 11.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [74.8, 17.2, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [81.0, 32.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [74.8, 46.8, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 53.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [45.2, 46.8, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [39.0, 32.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [45.2, 17.2, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Text { at: [112.0, 60.0], size: 7.0, anchor: 2, ink: Ink::Dim, a: 1.0, s: "8", bold: false }, + ], +}; + +pub(super) const TESS_FINE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 32.0, 21.0], fill: None, line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.9, dash: [2.0, 2.5], round: false }) }, + Op::Poly { + pts: &[ + [60.0, 11.0], + [64.1, 11.4], + [68.0, 12.6], + [71.7, 14.5], + [74.8, 17.2], + [77.5, 20.3], + [79.4, 24.0], + [80.6, 27.9], + [81.0, 32.0], + [80.6, 36.1], + [79.4, 40.0], + [77.5, 43.7], + [74.8, 46.8], + [71.7, 49.5], + [68.0, 51.4], + [64.1, 52.6], + [60.0, 53.0], + [55.9, 52.6], + [52.0, 51.4], + [48.3, 49.5], + [45.2, 46.8], + [42.5, 43.7], + [40.6, 40.0], + [39.4, 36.1], + [39.0, 32.0], + [39.4, 27.9], + [40.6, 24.0], + [42.5, 20.3], + [45.2, 17.2], + [48.3, 14.5], + [52.0, 12.6], + [55.9, 11.4], + ], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [112.0, 60.0], size: 7.0, anchor: 2, ink: Ink::Dim, a: 1.0, s: "32", bold: false }, + ], +}; + +pub(super) const TESS_NORMAL: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 32.0, 21.0], fill: None, line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.9, dash: [2.0, 2.5], round: false }) }, + Op::Poly { + pts: &[ + [60.0, 11.0], + [68.0, 12.6], + [74.8, 17.2], + [79.4, 24.0], + [81.0, 32.0], + [79.4, 40.0], + [74.8, 46.8], + [68.0, 51.4], + [60.0, 53.0], + [52.0, 51.4], + [45.2, 46.8], + [40.6, 40.0], + [39.0, 32.0], + [40.6, 24.0], + [45.2, 17.2], + [52.0, 12.6], + ], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 11.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [68.0, 12.6, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [74.8, 17.2, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [79.4, 24.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [81.0, 32.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [79.4, 40.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [74.8, 46.8, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [68.0, 51.4, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 53.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [52.0, 51.4, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [45.2, 46.8, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [40.6, 40.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [39.0, 32.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [40.6, 24.0, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [45.2, 17.2, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [52.0, 12.6, 1.7], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Text { at: [112.0, 60.0], size: 7.0, anchor: 2, ink: Ink::Dim, a: 1.0, s: "16", bold: false }, + ], +}; + +pub(super) const TESS_ULTRA: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 32.0, 21.0], fill: None, line: Some(L { ink: Ink::Dim, a: 1.0, w: 0.9, dash: [2.0, 2.5], round: false }) }, + Op::Poly { + pts: &[ + [60.0, 11.0], + [62.1, 11.1], + [64.1, 11.4], + [66.1, 11.9], + [68.0, 12.6], + [69.9, 13.5], + [71.7, 14.5], + [73.3, 15.8], + [74.8, 17.2], + [76.2, 18.7], + [77.5, 20.3], + [78.5, 22.1], + [79.4, 24.0], + [80.1, 25.9], + [80.6, 27.9], + [80.9, 29.9], + [81.0, 32.0], + [80.9, 34.1], + [80.6, 36.1], + [80.1, 38.1], + [79.4, 40.0], + [78.5, 41.9], + [77.5, 43.7], + [76.2, 45.3], + [74.8, 46.8], + [73.3, 48.2], + [71.7, 49.5], + [69.9, 50.5], + [68.0, 51.4], + [66.1, 52.1], + [64.1, 52.6], + [62.1, 52.9], + [60.0, 53.0], + [57.9, 52.9], + [55.9, 52.6], + [53.9, 52.1], + [52.0, 51.4], + [50.1, 50.5], + [48.3, 49.5], + [46.7, 48.2], + [45.2, 46.8], + [43.8, 45.3], + [42.5, 43.7], + [41.5, 41.9], + [40.6, 40.0], + [39.9, 38.1], + [39.4, 36.1], + [39.1, 34.1], + [39.0, 32.0], + [39.1, 29.9], + [39.4, 27.9], + [39.9, 25.9], + [40.6, 24.0], + [41.5, 22.1], + [42.5, 20.3], + [43.8, 18.7], + [45.2, 17.2], + [46.7, 15.8], + [48.3, 14.5], + [50.1, 13.5], + [52.0, 12.6], + [53.9, 11.9], + [55.9, 11.4], + [57.9, 11.1], + ], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Text { at: [112.0, 60.0], size: 7.0, anchor: 2, ink: Ink::Dim, a: 1.0, s: "64", bold: false }, + ], +}; + +pub(super) const TOOL_CURSOR: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[10.0, 46.0], [13.4, 42.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.028, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[13.4, 42.8], [16.8, 39.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.083, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[16.8, 39.6], [20.2, 36.4]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.138, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[20.2, 36.4], [23.6, 33.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.193, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[23.6, 33.2], [27.0, 30.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.248, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[27.0, 30.0], [30.4, 26.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.303, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[30.4, 26.8], [33.8, 23.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.357, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[33.8, 23.6], [37.2, 20.4]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.413, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[37.2, 20.4], [40.6, 17.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.468, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[40.6, 17.2], [44.0, 14.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.522, w: 2.2, dash: [0.0, 0.0], round: true }), + }, + Op::Rect { + r: [55.5, 28.0, 22.0, 22.0], + radius: 6.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[61.0, 44.5], [72.0, 33.5]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Circle { + c: [61.0, 44.5, 2.0], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [72.0, 33.5, 2.0], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[43.5, 13.5], [43.5, 33.0], [48.7, 28.32], [52.34, 36.9], [55.72, 35.34], [52.08, 27.02], [58.84, 26.76]], + closed: true, + fill: Some(P { ink: Ink::Text, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.43, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const TOOL_EXTRUDE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [20.0, 40.0, 40.0, 14.0], + radius: 2.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[40.0, 38.0], [40.0, 18.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[40.0, 14.0], [42.5, 18.2], [37.5, 18.2]], + closed: true, + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + grad: None, + line: None, + }, + Op::Poly { + pts: &[[12.0, 10.0], [108.0, 10.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Rect { + r: [76.0, 6.0, 28.0, 8.0], + radius: 0.0, + fill: Some(P { ink: Ink::Accent, a: 0.38 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const TOOL_HOLE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [26.0, 8.0, 68.0, 48.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [60.0, 32.0, 10.0], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.6, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 32.0, 2.3], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [26.0, 32.0, 2.3], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [94.0, 32.0, 2.3], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 8.0, 2.3], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + Op::Circle { c: [60.0, 56.0, 2.3], fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + ], +}; + +pub(super) const TOOL_PLACEMENT: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Rect { + r: [22.0, 10.0, 76.0, 44.0], + radius: 3.0, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 32.0, 13.0], fill: None, line: Some(L { ink: Ink::Accent, a: 1.0, w: 1.0, dash: [3.0, 3.0], round: false }) }, + Op::Poly { + pts: &[ + [60.0, 19.0], + [62.536, 19.25], + [64.975, 19.99], + [67.222, 21.191], + [69.192, 22.808], + [70.809, 24.778], + [72.01, 27.025], + [72.75, 29.464], + [73.0, 32.0], + ], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 1.0, w: 2.4, dash: [0.0, 0.0], round: true }), + }, + Op::Rect { r: [55.0, 27.0, 10.0, 10.0], radius: 2.0, fill: Some(P { ink: Ink::Accent, a: 1.0 }), line: None }, + ], +}; + +pub(super) const VERTEX_MARKERS: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[46.144, 26.0], [60.0, 34.0], [60.0, 50.0], [46.144, 42.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[73.856, 26.0], [60.0, 34.0], [60.0, 50.0], [73.856, 42.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 18.0], [73.856, 26.0], [60.0, 34.0], [46.144, 26.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [60.0, 18.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [73.9, 26.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [73.9, 42.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [60.0, 50.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [46.1, 42.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [46.1, 26.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { + c: [60.0, 34.0, 2.4], + fill: Some(P { ink: Ink::Accent, a: 1.0 }), + line: Some(L { ink: Ink::Ground, a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const VIEW_ANGLES: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[38.0, 44.0], [38.0, 28.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisZ, a: 1.0, w: 2.0, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[38.0, 24.0], [40.8, 28.6], [35.2, 28.6]], + closed: true, + fill: Some(P { ink: Ink::AxisZ, a: 1.0 }), + grad: None, + line: None, + }, + Op::Text { at: [38.0, 20.5], size: 7.5, anchor: 1, ink: Ink::AxisZ, a: 1.0, s: "Z", bold: true }, + Op::Poly { + pts: &[[38.0, 44.0], [52.2, 52.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisX, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[55.3, 54.0], [51.1, 54.1], [53.3, 50.3]], + closed: true, + fill: Some(P { ink: Ink::AxisX, a: 1.0 }), + grad: None, + line: None, + }, + Op::Text { at: [60.516, 59.5], size: 7.5, anchor: 1, ink: Ink::AxisX, a: 1.0, s: "X", bold: true }, + Op::Poly { + pts: &[[38.0, 44.0], [23.8, 52.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::AxisY, a: 1.0, w: 1.4, dash: [0.0, 0.0], round: true }), + }, + Op::Poly { + pts: &[[20.7, 54.0], [22.7, 50.3], [24.9, 54.1]], + closed: true, + fill: Some(P { ink: Ink::AxisY, a: 1.0 }), + grad: None, + line: None, + }, + Op::Text { at: [15.484, 59.5], size: 7.5, anchor: 1, ink: Ink::AxisY, a: 1.0, s: "Y", bold: true }, + Op::Text { at: [94.0, 30.0], size: 7.5, anchor: 0, ink: Ink::Text, a: 1.0, s: "45°", bold: false }, + Op::Text { at: [94.0, 41.0], size: 7.5, anchor: 0, ink: Ink::Text, a: 1.0, s: "35°", bold: false }, + Op::Text { at: [94.0, 52.0], size: 7.5, anchor: 0, ink: Ink::Text, a: 1.0, s: "0°", bold: false }, + ], +}; + +pub(super) const VIEW_GRID: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[60.0, 13.4], [22.6, 35.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.7, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 13.4], [97.4, 35.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.7, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.2, 17.0], [28.8, 38.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[53.8, 17.0], [91.2, 38.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[72.5, 20.6], [35.1, 42.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[47.5, 20.6], [84.9, 42.2]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[78.7, 24.2], [41.3, 45.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[41.3, 24.2], [78.7, 45.8]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[84.9, 27.8], [47.5, 49.4]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[35.1, 27.8], [72.5, 49.4]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[91.2, 31.4], [53.8, 53.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[28.8, 31.4], [66.2, 53.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.4, w: 0.6, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[97.4, 35.0], [60.0, 56.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.7, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[22.6, 35.0], [60.0, 56.6]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Dim, a: 0.7, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[49.608, 23.0], [60.0, 29.0], [60.0, 41.0], [49.608, 35.0]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[70.392, 23.0], [60.0, 29.0], [60.0, 41.0], [70.392, 35.0]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 17.0], [70.392, 23.0], [60.0, 29.0], [49.608, 23.0]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const VIEW_PERSPECTIVE: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Poly { + pts: &[[30.0, 52.0], [42.0, 24.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 52.0], [78.0, 24.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 52.0], [90.0, 52.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[42.0, 24.0], [78.0, 24.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 1.1, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[30.0, 52.0], [60.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.8, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Poly { + pts: &[[90.0, 52.0], [60.0, 8.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Accent, a: 0.8, w: 1.0, dash: [3.0, 3.0], round: false }), + }, + Op::Circle { + c: [60.0, 8.0, 3.2], + fill: Some(P { ink: Ink::Ground, a: 1.0 }), + line: Some(L { ink: Ink::Reference, a: 1.0, w: 1.5, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [60.0, 8.0, 1.4], fill: Some(P { ink: Ink::Reference, a: 1.0 }), line: None }, + ], +}; + +pub(super) const VIEW_SHADOW: Figure = Figure { + size: [120.0, 64.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 120.0, 64.0], radius: 0.0, fill: Some(P { ink: Ink::Ground, a: 1.0 }), line: None }, + Op::Glow { c: [62.0, 44.0, 26.0, 8.0], a: 0.5 }, + Op::Poly { + pts: &[[48.742, 23.5], [60.0, 30.0], [60.0, 43.0], [48.742, 36.5]], + closed: true, + fill: Some(P { ink: Ink::Left, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[71.258, 23.5], [60.0, 30.0], [60.0, 43.0], [71.258, 36.5]], + closed: true, + fill: Some(P { ink: Ink::Right, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[60.0, 17.0], [71.258, 23.5], [60.0, 30.0], [48.742, 23.5]], + closed: true, + fill: Some(P { ink: Ink::Top, a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Line, a: 1.0, w: 0.9, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +pub(super) const THEME_THUMBNAIL: Figure = Figure { + size: [124.0, 76.0], + ops: &[ + Op::Rect { r: [0.0, 0.0, 124.0, 76.0], radius: 0.0, fill: Some(P { ink: Ink::Slot(0), a: 1.0 }), line: None }, + Op::Rect { r: [0.0, 0.0, 124.0, 14.0], radius: 0.0, fill: Some(P { ink: Ink::Slot(1), a: 1.0 }), line: None }, + Op::Circle { c: [6.0, 7.0, 1.8], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Circle { c: [12.0, 7.0, 1.8], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { r: [24.0, 4.0, 14.0, 6.0], radius: 3.0, fill: Some(P { ink: Ink::Slot(3), a: 1.0 }), line: None }, + Op::Rect { r: [42.0, 5.0, 12.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Slot(2), a: 0.7 }), line: None }, + Op::Rect { r: [58.0, 5.0, 12.0, 4.0], radius: 2.0, fill: Some(P { ink: Ink::Slot(2), a: 0.7 }), line: None }, + Op::Rect { r: [102.0, 3.5, 16.0, 7.0], radius: 3.5, fill: Some(P { ink: Ink::Slot(3), a: 1.0 }), line: None }, + Op::Rect { r: [0.0, 14.0, 35.0, 62.0], radius: 0.0, fill: Some(P { ink: Ink::Slot(1), a: 1.0 }), line: None }, + Op::Rect { r: [3.0, 30.0, 30.0, 8.0], radius: 2.0, fill: Some(P { ink: Ink::Slot(3), a: 0.25 }), line: None }, + Op::Circle { c: [8.0, 26.0, 1.6], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 24.5, 16.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Slot(2), a: 0.8 }), line: None }, + Op::Circle { c: [8.0, 34.0, 1.6], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 32.5, 12.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Slot(2), a: 0.8 }), line: None }, + Op::Circle { c: [8.0, 42.0, 1.6], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 40.5, 17.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Slot(2), a: 0.8 }), line: None }, + Op::Circle { c: [8.0, 50.0, 1.6], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { r: [12.0, 48.5, 11.0, 3.0], radius: 1.5, fill: Some(P { ink: Ink::Slot(2), a: 0.8 }), line: None }, + Op::Poly { + pts: &[ + [117.0, 17.0], + [118.035, 17.136], + [119.0, 17.536], + [119.828, 18.172], + [120.464, 19.0], + [120.864, 19.965], + [121.0, 21.0], + [121.0, 69.0], + [120.864, 70.035], + [120.464, 71.0], + [119.828, 71.828], + [119.0, 72.464], + [118.035, 72.864], + [117.0, 73.0], + [42.0, 73.0], + [40.965, 72.864], + [40.0, 72.464], + [39.172, 71.828], + [38.536, 71.0], + [38.136, 70.035], + [38.0, 69.0], + [38.0, 21.0], + [38.136, 19.965], + [38.536, 19.0], + [39.172, 18.172], + [40.0, 17.536], + [40.965, 17.136], + [42.0, 17.0], + ], + closed: true, + fill: None, + grad: Some(G { top: Ink::Slot(4), bottom: Ink::Slot(5), y: [17.0, 73.0] }), + line: None, + }, + Op::Poly { + pts: &[[44.0, 67.0], [115.0, 67.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Slot(6), a: 0.1, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 60.0], [115.0, 60.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Slot(6), a: 0.1, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 53.0], [115.0, 53.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Slot(6), a: 0.1, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 46.0], [115.0, 46.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Slot(6), a: 0.1, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[44.0, 39.0], [115.0, 39.0]], + closed: false, + fill: None, + grad: None, + line: Some(L { ink: Ink::Slot(6), a: 0.1, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[79.5, 28.0], [92.49, 35.5], [92.49, 50.5], [79.5, 58.0], [66.51, 50.5], [66.51, 35.5]], + closed: true, + fill: None, + grad: None, + line: None, + }, + Op::Poly { + pts: &[[79.5, 28.0], [92.49, 35.5], [79.5, 43.0], [66.51, 35.5]], + closed: true, + fill: Some(P { ink: Ink::Slot(7), a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Slot(8), a: 1.0, w: 0.8, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[66.51, 35.5], [79.5, 43.0], [79.5, 58.0], [66.51, 50.5]], + closed: true, + fill: Some(P { ink: Ink::Slot(9), a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Slot(8), a: 1.0, w: 0.8, dash: [0.0, 0.0], round: false }), + }, + Op::Poly { + pts: &[[92.49, 35.5], [79.5, 43.0], [79.5, 58.0], [92.49, 50.5]], + closed: true, + fill: Some(P { ink: Ink::Slot(10), a: 1.0 }), + grad: None, + line: Some(L { ink: Ink::Slot(8), a: 1.0, w: 0.8, dash: [0.0, 0.0], round: false }), + }, + Op::Circle { c: [65.5, 67.0, 1.7], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Circle { c: [72.5, 67.0, 1.7], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Circle { c: [79.5, 67.0, 1.7], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Circle { c: [86.5, 67.0, 1.7], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Circle { c: [93.5, 67.0, 1.7], fill: Some(P { ink: Ink::Slot(2), a: 1.0 }), line: None }, + Op::Rect { + r: [0.5, 0.5, 123.0, 75.0], + radius: 5.5, + fill: None, + line: Some(L { ink: Ink::Slot(11), a: 1.0, w: 1.0, dash: [0.0, 0.0], round: false }), + }, + ], +}; + +// Theme thumbnail slots (light, dark, gruvbox, imported sample colours): +// 0: #F4F6F9 #2A2F3A #282828 #2B2F52 +// 1: #FFFFFF #323845 #3C3836 #3B4170 +// 2: #9AA7B6 #6C7689 #7C6F64 #9CA3DE +// 3: #236EAD #8CBEF5 #83A598 #B6A6FF +// 4: #EEF1F5 #3A4150 #32302F #6A5AC8 +// 5: #D9DFE7 #252A34 #1D2021 #2E5A9E +// 6: #7B8798 #99A5BA #EBDBB2 #FFFFFF +// 7: #FFFFFF #7E8AA0 #D5C4A1 #E7E1FF +// 8: #7B8798 #99A5BA #EBDBB2 None +// 9: #C3CBD6 #566176 #A89984 #9C8FE8 +// 10: #A8B3C1 #3F485A #7C6F64 #6E8FE0 +// 11: #C9D1DB #454D5E #504945 #6E76B8 + +use super::preferences_figure_ops::paint; +use egui::{Painter, Rect}; + +/// The `aa-2x` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_aa_2x(p: &Painter, rect: Rect) { + paint(p, rect, &AA_2X, None, None); +} + +/// The `aa-4x` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_aa_4x(p: &Painter, rect: Rect) { + paint(p, rect, &AA_4X, None, None); +} + +/// The `aa-8x` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_aa_8x(p: &Painter, rect: Rect) { + paint(p, rect, &AA_8X, None, None); +} + +/// The `aa-off` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_aa_off(p: &Painter, rect: Rect) { + paint(p, rect, &AA_OFF, None, None); +} + +/// The `agent-pointer-speed` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_agent_pointer_speed(p: &Painter, rect: Rect) { + paint(p, rect, &AGENT_POINTER_SPEED, None, None); +} + +/// The `ao-on` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_ao_on(p: &Painter, rect: Rect) { + paint(p, rect, &AO_ON, None, None); +} + +/// The `assembly-move` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_assembly_move(p: &Painter, rect: Rect) { + paint(p, rect, &ASSEMBLY_MOVE, None, None); +} + +/// The `browser-card` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_browser_card(p: &Painter, rect: Rect) { + paint(p, rect, &BROWSER_CARD, None, None); +} + +/// The `browser-column` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_browser_column(p: &Painter, rect: Rect) { + paint(p, rect, &BROWSER_COLUMN, None, None); +} + +/// The `colour-vision-axes` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_axes(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_AXES, None, None); +} + +/// The `colour-vision-bends` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_bends(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_BENDS, None, None); +} + +/// The `colour-vision-draft` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_draft(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_DRAFT, None, None); +} + +/// The `colour-vision-failed` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_failed(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_FAILED, None, None); +} + +/// The `colour-vision-fixed` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_fixed(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_FIXED, None, None); +} + +/// The `colour-vision-projected` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_colour_vision_projected(p: &Painter, rect: Rect) { + paint(p, rect, &COLOUR_VISION_PROJECTED, None, None); +} + +/// The `direct-interaction` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_direct_interaction(p: &Painter, rect: Rect) { + paint(p, rect, &DIRECT_INTERACTION, None, None); +} + +/// The `frame-rate` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_frame_rate(p: &Painter, rect: Rect) { + paint(p, rect, &FRAME_RATE, None, None); +} + +/// The `history-bottom` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_history_bottom(p: &Painter, rect: Rect) { + paint(p, rect, &HISTORY_BOTTOM, None, None); +} + +/// The `history-in-browser` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_history_in_browser(p: &Painter, rect: Rect) { + paint(p, rect, &HISTORY_IN_BROWSER, None, None); +} + +/// The `history-left` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_history_left(p: &Painter, rect: Rect) { + paint(p, rect, &HISTORY_LEFT, None, None); +} + +/// The `history-under-browser` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_history_under_browser(p: &Painter, rect: Rect) { + paint(p, rect, &HISTORY_UNDER_BROWSER, None, None); +} + +/// The `layout-schematic` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_layout_schematic(p: &Painter, rect: Rect) { + paint(p, rect, &LAYOUT_SCHEMATIC, None, None); +} + +/// The `measure-axis-distances` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_measure_axis_distances(p: &Painter, rect: Rect) { + paint(p, rect, &MEASURE_AXIS_DISTANCES, None, None); +} + +/// The `mouse-mapping` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_mouse_mapping(p: &Painter, rect: Rect) { + paint(p, rect, &MOUSE_MAPPING, None, None); +} + +/// The `navigator-axes` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_navigator_axes(p: &Painter, rect: Rect) { + paint(p, rect, &NAVIGATOR_AXES, None, None); +} + +/// The `navigator-cube` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_navigator_cube(p: &Painter, rect: Rect) { + paint(p, rect, &NAVIGATOR_CUBE, None, None); +} + +/// The `orbit-centre` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_orbit_centre(p: &Painter, rect: Rect) { + paint(p, rect, &ORBIT_CENTRE, None, None); +} + +/// The `orbit-cursor` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_orbit_cursor(p: &Painter, rect: Rect) { + paint(p, rect, &ORBIT_CURSOR, None, None); +} + +/// The `orbit-origin` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_orbit_origin(p: &Painter, rect: Rect) { + paint(p, rect, &ORBIT_ORIGIN, None, None); +} + +/// The `quick-measure` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_quick_measure(p: &Painter, rect: Rect) { + paint(p, rect, &QUICK_MEASURE, None, None); +} + +/// The `select-bodies` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_select_bodies(p: &Painter, rect: Rect) { + paint(p, rect, &SELECT_BODIES, None, None); +} + +/// The `select-faces-edges` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_select_faces_edges(p: &Painter, rect: Rect) { + paint(p, rect, &SELECT_FACES_EDGES, None, None); +} + +/// The `sketch-conflict` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_conflict(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_CONFLICT, None, None); +} + +/// The `sketch-exit-keep` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_exit_keep(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_EXIT_KEEP, None, None); +} + +/// The `sketch-exit-previous` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_exit_previous(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_EXIT_PREVIOUS, None, None); +} + +/// The `sketch-exit-unless-turned` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_exit_unless_turned(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_EXIT_UNLESS_TURNED, None, None); +} + +/// The `sketch-guides` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_guides(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_GUIDES, None, None); +} + +/// The `sketch-hide-glyphs` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_hide_glyphs(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_HIDE_GLYPHS, None, None); +} + +/// The `sketch-state-icons` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_sketch_state_icons(p: &Painter, rect: Rect) { + paint(p, rect, &SKETCH_STATE_ICONS, None, None); +} + +/// The `tess-coarse` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tess_coarse(p: &Painter, rect: Rect) { + paint(p, rect, &TESS_COARSE, None, None); +} + +/// The `tess-fine` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tess_fine(p: &Painter, rect: Rect) { + paint(p, rect, &TESS_FINE, None, None); +} + +/// The `tess-normal` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tess_normal(p: &Painter, rect: Rect) { + paint(p, rect, &TESS_NORMAL, None, None); +} + +/// The `tess-ultra` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tess_ultra(p: &Painter, rect: Rect) { + paint(p, rect, &TESS_ULTRA, None, None); +} + +/// The `tool-cursor` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tool_cursor(p: &Painter, rect: Rect) { + paint(p, rect, &TOOL_CURSOR, None, None); +} + +/// The `tool-extrude` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tool_extrude(p: &Painter, rect: Rect) { + paint(p, rect, &TOOL_EXTRUDE, None, None); +} + +/// The `tool-hole` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tool_hole(p: &Painter, rect: Rect) { + paint(p, rect, &TOOL_HOLE, None, None); +} + +/// The `tool-placement` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_tool_placement(p: &Painter, rect: Rect) { + paint(p, rect, &TOOL_PLACEMENT, None, None); +} + +/// The `vertex-markers` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_vertex_markers(p: &Painter, rect: Rect) { + paint(p, rect, &VERTEX_MARKERS, None, None); +} + +/// The `view-angles` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_view_angles(p: &Painter, rect: Rect) { + paint(p, rect, &VIEW_ANGLES, None, None); +} + +/// The `view-grid` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_view_grid(p: &Painter, rect: Rect) { + paint(p, rect, &VIEW_GRID, None, None); +} + +/// The `view-perspective` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_view_perspective(p: &Painter, rect: Rect) { + paint(p, rect, &VIEW_PERSPECTIVE, None, None); +} + +/// The `view-shadow` figure of `docs/design/preferences/figures`. +pub(crate) fn paint_view_shadow(p: &Painter, rect: Rect) { + paint(p, rect, &VIEW_SHADOW, None, None); +} + +/// Every figure painter by file name, for the gallery and the tests. +pub(crate) const FIGURES: &[(&str, [f32; 2], fn(&Painter, Rect))] = &[ + ("aa-2x", AA_2X.size, paint_aa_2x), + ("aa-4x", AA_4X.size, paint_aa_4x), + ("aa-8x", AA_8X.size, paint_aa_8x), + ("aa-off", AA_OFF.size, paint_aa_off), + ("agent-pointer-speed", AGENT_POINTER_SPEED.size, paint_agent_pointer_speed), + ("ao-on", AO_ON.size, paint_ao_on), + ("assembly-move", ASSEMBLY_MOVE.size, paint_assembly_move), + ("browser-card", BROWSER_CARD.size, paint_browser_card), + ("browser-column", BROWSER_COLUMN.size, paint_browser_column), + ("colour-vision-axes", COLOUR_VISION_AXES.size, paint_colour_vision_axes), + ("colour-vision-bends", COLOUR_VISION_BENDS.size, paint_colour_vision_bends), + ("colour-vision-draft", COLOUR_VISION_DRAFT.size, paint_colour_vision_draft), + ("colour-vision-failed", COLOUR_VISION_FAILED.size, paint_colour_vision_failed), + ("colour-vision-fixed", COLOUR_VISION_FIXED.size, paint_colour_vision_fixed), + ("colour-vision-projected", COLOUR_VISION_PROJECTED.size, paint_colour_vision_projected), + ("direct-interaction", DIRECT_INTERACTION.size, paint_direct_interaction), + ("frame-rate", FRAME_RATE.size, paint_frame_rate), + ("history-bottom", HISTORY_BOTTOM.size, paint_history_bottom), + ("history-in-browser", HISTORY_IN_BROWSER.size, paint_history_in_browser), + ("history-left", HISTORY_LEFT.size, paint_history_left), + ("history-under-browser", HISTORY_UNDER_BROWSER.size, paint_history_under_browser), + ("layout-schematic", LAYOUT_SCHEMATIC.size, paint_layout_schematic), + ("measure-axis-distances", MEASURE_AXIS_DISTANCES.size, paint_measure_axis_distances), + ("mouse-mapping", MOUSE_MAPPING.size, paint_mouse_mapping), + ("navigator-axes", NAVIGATOR_AXES.size, paint_navigator_axes), + ("navigator-cube", NAVIGATOR_CUBE.size, paint_navigator_cube), + ("orbit-centre", ORBIT_CENTRE.size, paint_orbit_centre), + ("orbit-cursor", ORBIT_CURSOR.size, paint_orbit_cursor), + ("orbit-origin", ORBIT_ORIGIN.size, paint_orbit_origin), + ("quick-measure", QUICK_MEASURE.size, paint_quick_measure), + ("select-bodies", SELECT_BODIES.size, paint_select_bodies), + ("select-faces-edges", SELECT_FACES_EDGES.size, paint_select_faces_edges), + ("sketch-conflict", SKETCH_CONFLICT.size, paint_sketch_conflict), + ("sketch-exit-keep", SKETCH_EXIT_KEEP.size, paint_sketch_exit_keep), + ("sketch-exit-previous", SKETCH_EXIT_PREVIOUS.size, paint_sketch_exit_previous), + ("sketch-exit-unless-turned", SKETCH_EXIT_UNLESS_TURNED.size, paint_sketch_exit_unless_turned), + ("sketch-guides", SKETCH_GUIDES.size, paint_sketch_guides), + ("sketch-hide-glyphs", SKETCH_HIDE_GLYPHS.size, paint_sketch_hide_glyphs), + ("sketch-state-icons", SKETCH_STATE_ICONS.size, paint_sketch_state_icons), + ("tess-coarse", TESS_COARSE.size, paint_tess_coarse), + ("tess-fine", TESS_FINE.size, paint_tess_fine), + ("tess-normal", TESS_NORMAL.size, paint_tess_normal), + ("tess-ultra", TESS_ULTRA.size, paint_tess_ultra), + ("tool-cursor", TOOL_CURSOR.size, paint_tool_cursor), + ("tool-extrude", TOOL_EXTRUDE.size, paint_tool_extrude), + ("tool-hole", TOOL_HOLE.size, paint_tool_hole), + ("tool-placement", TOOL_PLACEMENT.size, paint_tool_placement), + ("vertex-markers", VERTEX_MARKERS.size, paint_vertex_markers), + ("view-angles", VIEW_ANGLES.size, paint_view_angles), + ("view-grid", VIEW_GRID.size, paint_view_grid), + ("view-perspective", VIEW_PERSPECTIVE.size, paint_view_perspective), + ("view-shadow", VIEW_SHADOW.size, paint_view_shadow), +]; diff --git a/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs b/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs new file mode 100644 index 000000000..b3656dc3f --- /dev/null +++ b/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs @@ -0,0 +1,583 @@ +//! The drawing engine behind the Preferences figures: a figure is a short list of operations in its +//! own coordinates (`preferences_figure_data.rs`, compiled from the SVGs in +//! `docs/design/preferences/figures/`), painted with egui shapes in the colours of the current +//! `Tokens`. Nothing is rasterised and no image is loaded; every figure costs a few dozen shapes. +//! Any rectangle, including an empty, infinite or enormous one, is safe to paint into. +use crate::theme::Tokens; +use egui::{Align2, Color32, CornerRadius, FontId, Mesh, Painter, Pos2, Rect, Shape, Stroke, StrokeKind, pos2, vec2}; + +/// Colour roles of the figures. Each reads one `Tokens` field (`docs/design/preferences/tokens.md`). +#[derive(Clone, Copy, Debug)] +pub(super) enum Ink { + Ground, + Line, + Top, + Left, + Right, + Card, + Accent, + Reference, + AxisX, + AxisY, + AxisZ, + Ok, + Warn, + Dim, + Text, + Border, + ControlBorder, + Control, + Note, + NoteFill, + White, + Black, + /// Colour vision sample colours: Z axis blue, projected, X axis, bend up and bend down. + Cv0, + Cv1, + Cv2, + Cv3, + Cv4, + /// A colour of a theme thumbnail, from its `ThemeSample`. + Slot(u8), +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct P { + pub ink: Ink, + pub a: f32, +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct L { + pub ink: Ink, + pub a: f32, + pub w: f32, + /// Dash and gap, `[0.0, 0.0]` for a solid line. + pub dash: [f32; 2], + pub round: bool, +} + +/// A vertical gradient over the figure's `y` range. +#[derive(Clone, Copy, Debug)] +pub(super) struct G { + pub top: Ink, + pub bottom: Ink, + pub y: [f32; 2], +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum Op { + Rect { + r: [f32; 4], + radius: f32, + fill: Option

, + line: Option, + }, + Circle { + c: [f32; 3], + fill: Option

, + line: Option, + }, + Poly { + pts: &'static [[f32; 2]], + closed: bool, + fill: Option

, + grad: Option, + line: Option, + }, + /// A soft black ellipse: opaque `a` at the centre, clear at the edge. + Glow { + c: [f32; 4], + a: f32, + }, + Text { + at: [f32; 2], + size: f32, + anchor: u8, + ink: Ink, + a: f32, + s: &'static str, + bold: bool, + }, + Clip(&'static [[f32; 2]]), + Unclip, +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct Figure { + pub size: [f32; 2], + pub ops: &'static [Op], +} + +/// The twelve colours a theme thumbnail is drawn with: ground, bar and side panel, muted marks, +/// accent, the window face's top and bottom, grid, cube top, cube outline, cube left, cube right +/// and the thumbnail's border. A colour may carry alpha (a glass theme's panels). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ThemeSample { + pub slots: [Color32; 12], +} + +impl ThemeSample { + /// A thumbnail of the theme whose tokens these are. + pub fn from_tokens(t: &Tokens) -> ThemeSample { + let mix = |a: Color32, b: Color32, f: f32| a.lerp_to_gamma(b, f); + ThemeSample { + slots: [ + t.dialog_footer, + t.control_fill, + t.form_dim.gamma_multiply(0.7), + t.form_primary, + t.viewport_top, + t.viewport_bottom, + t.form_dim.gamma_multiply(0.1), + t.body, + t.form_dim, + mix(t.body, t.body_edge, 0.25), + mix(t.body, t.body_edge, 0.5), + t.dialog_border, + ], + } + } + + /// The same colours with every alpha scaled (a glass theme's fills). + pub fn glass(mut self, alpha: f32) -> ThemeSample { + for slot in &mut self.slots[1..2] { + *slot = slot.gamma_multiply(alpha); + } + self + } +} + +/// Largest side, in points, a figure is painted at; anything larger is skipped, not drawn wrong. +const MAX_SIDE: f32 = 16_384.0; +const MAX_POINTS: usize = 512; + +struct Ctx<'a> { + t: &'a Tokens, + sample: Option<&'a ThemeSample>, + origin: Pos2, + scale: f32, +} + +impl Ctx<'_> { + fn ink(&self, ink: Ink, a: f32) -> Color32 { + let t = self.t; + let c = match ink { + Ink::Ground => t.figure_ground, + Ink::Line => t.figure_line, + Ink::Top => t.figure_face_top, + Ink::Left => t.figure_face_left, + Ink::Right => t.figure_face_right, + Ink::Card => t.figure_card, + Ink::Accent => t.figure_accent, + Ink::Reference => t.figure_reference, + Ink::AxisX => t.figure_axis_x, + Ink::AxisY => t.figure_axis_y, + Ink::AxisZ => t.figure_axis_z, + Ink::Ok => t.figure_ok, + Ink::Warn => t.figure_warn, + Ink::Dim => t.form_dim, + Ink::Text => t.form_ink, + Ink::Border => t.dialog_border, + Ink::ControlBorder => t.control_border, + Ink::Control => t.control_fill, + Ink::Note => t.pref_note, + Ink::NoteFill => t.pref_note_fill, + Ink::White => t.figure_white, + Ink::Black => t.figure_black, + Ink::Cv0 => t.axis_z, + Ink::Cv1 => t.sketch_projected, + Ink::Cv2 => t.axis_x, + Ink::Cv3 => t.bend_up, + Ink::Cv4 => t.bend_down, + Ink::Slot(n) => self.sample.and_then(|s| s.slots.get(n as usize).copied()).unwrap_or(Color32::TRANSPARENT), + }; + if a >= 1.0 { c } else { c.gamma_multiply(a.clamp(0.0, 1.0)) } + } + + fn at(&self, p: [f32; 2]) -> Pos2 { + self.origin + vec2(p[0] * self.scale, p[1] * self.scale) + } + + fn stroke(&self, line: &L) -> Stroke { + Stroke::new((line.w * self.scale).clamp(0.0, 64.0), self.ink(line.ink, line.a)) + } +} + +/// Paints `figure` into `rect`, scaled to fit and centred, with `Tokens::get()` colours. +pub(super) fn paint(p: &Painter, rect: Rect, figure: &Figure, sample: Option<&ThemeSample>, clip: Option<&[[f32; 2]]>) { + let size = rect.size(); + if !rect.min.is_finite() || !size.is_finite() || size.x < 1.0 || size.y < 1.0 || size.x > MAX_SIDE || size.y > MAX_SIDE { + return; + } + let [fw, fh] = figure.size; + if !(fw > 0.0 && fh > 0.0) { + return; + } + let scale = (size.x / fw).min(size.y / fh); + let fitted = Rect::from_center_size(rect.center(), vec2(fw * scale, fh * scale)); + let t = Tokens::get(); + let ctx = Ctx { t: &t, sample, origin: fitted.min, scale }; + let p = p.with_clip_rect(fitted.intersect(p.clip_rect())); + let outer: Option> = clip.map(|c| c.iter().map(|&q| ctx.at(q)).collect()); + // Nested clips are inside one another in every figure, so the innermost one is the clip. + let mut stack: Vec> = Vec::new(); + for op in figure.ops { + match op { + Op::Clip(points) if outer.is_none() => stack.push(points.iter().map(|&q| ctx.at(q)).collect()), + Op::Unclip if outer.is_none() => { + stack.pop(); + } + Op::Clip(_) | Op::Unclip => {} + _ => draw(&p, &ctx, op, outer.as_deref().or(stack.last().map(Vec::as_slice))), + } + } +} + +fn draw(p: &Painter, ctx: &Ctx, op: &Op, clip: Option<&[Pos2]>) { + match op { + Op::Rect { r, radius, fill, line } => { + let rect = Rect::from_min_size(ctx.at([r[0], r[1]]), vec2(r[2] * ctx.scale, r[3] * ctx.scale)); + if clip.is_some() { + let pts = rounded(rect, radius * ctx.scale); + poly(p, ctx, &pts, true, fill, None, line, clip); + return; + } + let corner = CornerRadius::same((radius * ctx.scale).clamp(0.0, 255.0).round() as u8); + if let Some(f) = fill { + p.rect_filled(rect, corner, ctx.ink(f.ink, f.a)); + } + if let Some(l) = line { + p.rect_stroke(rect, corner, ctx.stroke(l), StrokeKind::Middle); + } + } + Op::Circle { c, fill, line } => { + let centre = ctx.at([c[0], c[1]]); + let radius = c[2] * ctx.scale; + if clip.is_some() { + let pts: Vec = (0..24) + .map(|i| { + let a = i as f32 * std::f32::consts::TAU / 24.0; + centre + vec2(a.cos(), a.sin()) * radius + }) + .collect(); + poly(p, ctx, &pts, true, fill, None, line, clip); + return; + } + if let Some(f) = fill { + p.circle_filled(centre, radius, ctx.ink(f.ink, f.a)); + } + if let Some(l) = line { + p.circle_stroke(centre, radius, ctx.stroke(l)); + } + } + Op::Poly { pts, closed, fill, grad, line } => { + let points: Vec = pts.iter().map(|&q| ctx.at(q)).collect(); + poly(p, ctx, &points, *closed, fill, grad.as_ref(), line, clip); + } + Op::Glow { c, a } => { + let centre = ctx.at([c[0], c[1]]); + let radius = vec2(c[2] * ctx.scale, c[3] * ctx.scale); + glow(p, centre, radius, ctx.ink(Ink::Black, *a)); + } + Op::Text { at, size, anchor, ink, a, s, .. } => { + if clip.is_some() { + return; + } + let align = match anchor { + 1 => Align2::CENTER_CENTER, + 2 => Align2::RIGHT_CENTER, + _ => Align2::LEFT_CENTER, + }; + // The board's captions are 6.5 to 7.5 units: too small to read at card size, so they + // are drawn a third larger (never under 8 points). The SVG's `y` is the baseline, which + // sits about 0.36 em below the middle of a line of digits and capitals. + // Longer captions sit in tight pills and on cube faces, so they are drawn slightly smaller than the board (egui's monospace face is wider than the board's). + let grow = match s.chars().count() { + 0..=4 => 1.2, + 5..=6 => 0.9, + _ => 0.76, + }; + let size = (size * ctx.scale * grow).clamp(7.0, 256.0); + let at = ctx.at(*at) - vec2(0.0, size * 0.36); + p.text(at, align, s, FontId::monospace(size), ctx.ink(*ink, *a)); + } + Op::Clip(_) | Op::Unclip => {} + } +} + +#[allow(clippy::too_many_arguments)] +fn poly(p: &Painter, ctx: &Ctx, pts: &[Pos2], closed: bool, fill: &Option

, grad: Option<&G>, line: &Option, clip: Option<&[Pos2]>) { + if pts.len() < 2 || pts.len() > MAX_POINTS || pts.iter().any(|q| !q.is_finite()) { + return; + } + let clipped; + let (shape, fillable) = match clip { + Some(c) if pts.len() >= 3 && closed => { + clipped = clip_polygon(pts, c); + (&clipped[..], clipped.len() >= 3) + } + _ => (pts, pts.len() >= 3 && closed), + }; + if fillable { + if let Some(g) = grad { + let (top, bottom) = (ctx.ink(g.top, 1.0), ctx.ink(g.bottom, 1.0)); + let (y0, y1) = (ctx.at([0.0, g.y[0]]).y, ctx.at([0.0, g.y[1]]).y); + let span = (y1 - y0).max(1e-3); + fill_polygon(p, shape, |q| top.lerp_to_gamma(bottom, ((q.y - y0) / span).clamp(0.0, 1.0))); + } else if let Some(f) = fill { + let c = ctx.ink(f.ink, f.a); + fill_polygon(p, shape, |_| c); + } + } + if let Some(l) = line { + let stroke = ctx.stroke(l); + if stroke.width <= 0.0 || stroke.color == Color32::TRANSPARENT { + return; + } + let mut path = pts.to_vec(); + if closed { + path.push(pts[0]); + } + let runs = match clip { + Some(c) => clip_path(&path, c), + None => vec![path], + }; + for run in runs { + if l.dash[0] > 0.0 && l.dash[1] > 0.0 { + let dash = (l.dash[0] * ctx.scale).max(0.5); + let gap = (l.dash[1] * ctx.scale).max(0.5); + p.extend(crate::viewport::dashed_line(&run, p.clip_rect(), stroke, dash, gap)); + } else { + p.add(Shape::line(run, stroke)); + } + } + } +} + +fn rounded(rect: Rect, radius: f32) -> Vec { + let r = radius.min(rect.width() * 0.5).min(rect.height() * 0.5).max(0.0); + if r < 0.01 { + return vec![rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom()]; + } + let mut out = Vec::with_capacity(28); + for (centre, start) in [ + (rect.right_top() + vec2(-r, r), -90.0_f32), + (rect.right_bottom() + vec2(-r, -r), 0.0), + (rect.left_bottom() + vec2(r, -r), 90.0), + (rect.left_top() + vec2(r, r), 180.0), + ] { + for k in 0..=6 { + let a = (start + 90.0 * k as f32 / 6.0).to_radians(); + out.push(centre + vec2(a.cos(), a.sin()) * r); + } + } + out +} + +fn cross(o: Pos2, a: Pos2, b: Pos2) -> f32 { + (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) +} + +fn is_convex(pts: &[Pos2]) -> bool { + let n = pts.len(); + let mut sign = 0.0_f32; + for i in 0..n { + let c = cross(pts[i], pts[(i + 1) % n], pts[(i + 2) % n]); + if c.abs() < 1e-4 { + continue; + } + if sign == 0.0 { + sign = c.signum(); + } else if c.signum() != sign { + return false; + } + } + true +} + +/// Fills a simple polygon with `colour_at` per vertex: as a convex polygon when it is one, else by +/// ear clipping (at most `MAX_POINTS` vertices). +fn fill_polygon(p: &Painter, pts: &[Pos2], colour_at: impl Fn(Pos2) -> Color32) { + let n = pts.len(); + if !(3..=MAX_POINTS).contains(&n) { + return; + } + let mut mesh = Mesh::default(); + for &q in pts { + mesh.colored_vertex(q, colour_at(q)); + } + if is_convex(pts) { + for i in 1..n as u32 - 1 { + mesh.add_triangle(0, i, i + 1); + } + } else { + let area: f32 = (0..n).map(|i| pts[i].x * pts[(i + 1) % n].y - pts[(i + 1) % n].x * pts[i].y).sum(); + let mut idx: Vec = if area >= 0.0 { (0..n).collect() } else { (0..n).rev().collect() }; + let mut guard = 0; + while idx.len() > 3 && guard < n * n { + guard += 1; + let m = idx.len(); + let mut cut = None; + for k in 0..m { + let (a, b, c) = (idx[(k + m - 1) % m], idx[k], idx[(k + 1) % m]); + if cross(pts[a], pts[b], pts[c]) <= 0.0 { + continue; + } + let inside = idx.iter().any(|&o| { + o != a + && o != b + && o != c + && cross(pts[a], pts[b], pts[o]) >= 0.0 + && cross(pts[b], pts[c], pts[o]) >= 0.0 + && cross(pts[c], pts[a], pts[o]) >= 0.0 + }); + if !inside { + cut = Some(k); + break; + } + } + let Some(k) = cut else { break }; + let (a, b, c) = (idx[(k + m - 1) % m], idx[k], idx[(k + 1) % m]); + mesh.add_triangle(a as u32, b as u32, c as u32); + idx.remove(k); + } + if idx.len() == 3 { + mesh.add_triangle(idx[0] as u32, idx[1] as u32, idx[2] as u32); + } + } + p.add(Shape::mesh(mesh)); +} + +fn glow(p: &Painter, centre: Pos2, radius: egui::Vec2, ink: Color32) { + const SEGMENTS: u32 = 32; + if !(radius.x > 0.0 && radius.y > 0.0) { + return; + } + let mut mesh = Mesh::default(); + mesh.colored_vertex(centre, ink); + for i in 0..=SEGMENTS { + let a = std::f32::consts::TAU * i as f32 / SEGMENTS as f32; + mesh.colored_vertex(centre + vec2(a.cos() * radius.x, a.sin() * radius.y), Color32::TRANSPARENT); + } + for i in 1..=SEGMENTS { + mesh.add_triangle(0, i, i + 1); + } + p.add(Shape::mesh(mesh)); +} + +/// Sutherland-Hodgman clip of a polygon against a convex clip polygon of either winding. +fn clip_polygon(subject: &[Pos2], clip: &[Pos2]) -> Vec { + let n = clip.len(); + if n < 3 { + return Vec::new(); + } + let area: f32 = (0..n).map(|i| clip[i].x * clip[(i + 1) % n].y - clip[(i + 1) % n].x * clip[i].y).sum(); + let side = if area >= 0.0 { 1.0 } else { -1.0 }; + let mut out = subject.to_vec(); + for i in 0..n { + let (a, b) = (clip[i], clip[(i + 1) % n]); + let inside = |q: Pos2| side * cross(a, b, q) >= 0.0; + let input = std::mem::take(&mut out); + if input.is_empty() { + break; + } + for j in 0..input.len() { + let (cur, prev) = (input[j], input[(j + input.len() - 1) % input.len()]); + if inside(cur) { + if !inside(prev) { + out.push(intersect(prev, cur, a, b)); + } + out.push(cur); + } else if inside(prev) { + out.push(intersect(prev, cur, a, b)); + } + } + } + out +} + +fn intersect(p1: Pos2, p2: Pos2, a: Pos2, b: Pos2) -> Pos2 { + let (d1, d2) = (p2 - p1, b - a); + let den = d1.x * d2.y - d1.y * d2.x; + if den.abs() < 1e-9 { + return p1; + } + let t = ((a.x - p1.x) * d2.y - (a.y - p1.y) * d2.x) / den; + pos2(p1.x + d1.x * t, p1.y + d1.y * t) +} + +/// The parts of a polyline inside a convex clip polygon (Cyrus-Beck per segment). +fn clip_path(path: &[Pos2], clip: &[Pos2]) -> Vec> { + let n = clip.len(); + if n < 3 { + return Vec::new(); + } + let area: f32 = (0..n).map(|i| clip[i].x * clip[(i + 1) % n].y - clip[(i + 1) % n].x * clip[i].y).sum(); + let side = if area >= 0.0 { 1.0 } else { -1.0 }; + let mut runs: Vec> = Vec::new(); + for w in path.windows(2) { + let (mut t0, mut t1) = (0.0_f32, 1.0_f32); + let d = w[1] - w[0]; + let mut visible = true; + for i in 0..n { + let (a, b) = (clip[i], clip[(i + 1) % n]); + let num = side * cross(a, b, w[0]); + // The signed distance of the point at t from this edge is num + t * den. + let den = side * cross(a, b, w[1]) - num; + if den.abs() < 1e-9 { + if num < 0.0 { + visible = false; + break; + } + } else { + let t = -num / den; + if den > 0.0 { + t0 = t0.max(t); + } else { + t1 = t1.min(t); + } + } + } + if visible && t0 < t1 { + let (a, b) = (w[0] + d * t0, w[0] + d * t1); + match runs.last_mut() { + Some(run) if run.last().is_some_and(|l| l.distance(a) < 1e-3) => run.push(b), + _ => runs.push(vec![a, b]), + } + } + } + runs +} + +#[cfg(test)] +mod tests { + use super::*; + + fn square() -> Vec { + vec![pos2(0.0, 0.0), pos2(10.0, 0.0), pos2(10.0, 10.0), pos2(0.0, 10.0)] + } + + #[test] + fn clipping_a_square_to_a_triangle_keeps_the_overlap() { + let tri = [pos2(0.0, 0.0), pos2(10.0, 0.0), pos2(0.0, 10.0)]; + let out = clip_polygon(&square(), &tri); + let n = out.len(); + let area: f32 = (0..n).map(|i| out[i].x * out[(i + 1) % n].y - out[(i + 1) % n].x * out[i].y).sum::().abs() / 2.0; + assert!((area - 50.0).abs() < 1e-3, "{area}"); + } + + #[test] + fn a_path_is_cut_at_the_clip_edge() { + let tri = [pos2(0.0, 0.0), pos2(10.0, 0.0), pos2(0.0, 10.0)]; + let runs = clip_path(&[pos2(-5.0, 2.0), pos2(15.0, 2.0)], &tri); + assert_eq!(runs.len(), 1); + assert!((runs[0][0].x - 0.0).abs() < 1e-3 && (runs[0][1].x - 8.0).abs() < 1e-3, "{:?}", runs); + } + + #[test] + fn concave_polygons_are_detected() { + assert!(is_convex(&square())); + assert!(!is_convex(&[pos2(0.0, 0.0), pos2(10.0, 0.0), pos2(5.0, 2.0), pos2(10.0, 10.0), pos2(0.0, 10.0)])); + } +} diff --git a/crates/ui-egui/src/ui_kit/preferences_figures.rs b/crates/ui-egui/src/ui_kit/preferences_figures.rs index 2c7ce82b2..7bbcd2895 100644 --- a/crates/ui-egui/src/ui_kit/preferences_figures.rs +++ b/crates/ui-egui/src/ui_kit/preferences_figures.rs @@ -260,6 +260,26 @@ pub(crate) fn paint_layout(ui: &mut egui::Ui, state: super::preferences::LayoutP super::text(ui, crate::i18n::tr("prefs.preview_choices"), super::Text::Note("preview")); } +#[allow(unused_imports, reason = "painted by the Preferences pages of #9875 to #9883")] +pub(crate) use super::preferences_figure_ops::ThemeSample; +use super::preferences_figure_ops::paint; + +#[allow(dead_code, reason = "painted by the Preferences pages of #9875 to #9883")] +/// A theme card's miniature application window, drawn with the theme's own `sample` colours. +pub(crate) fn paint_theme_thumbnail(p: &Painter, rect: Rect, sample: &ThemeSample) { + paint(p, rect, &super::preferences_figure_data::THEME_THUMBNAIL, Some(sample), None); +} + +#[allow(dead_code, reason = "painted by the Preferences pages of #9875 to #9883")] +/// The "System" theme card: `light` with `dark` over a slanted band of it (the board clips the dark +/// half to the polygon 56 %,0 / 100 %,0 / 100 %,100 % / 40 %,100 %). +pub(crate) fn paint_theme_system(p: &Painter, rect: Rect, light: &ThemeSample, dark: &ThemeSample) { + const BAND: [[f32; 2]; 4] = [[69.44, 0.0], [124.0, 0.0], [124.0, 76.0], [49.6, 76.0]]; + let figure = &super::preferences_figure_data::THEME_THUMBNAIL; + paint(p, rect, figure, Some(light), None); + paint(p, rect, figure, Some(dark), Some(&BAND)); +} + #[cfg(test)] mod tests { use super::orientation_axes; @@ -281,4 +301,101 @@ mod tests { } } } + + use super::{ThemeSample, paint_theme_system, paint_theme_thumbnail}; + use crate::theme::Tokens; + use crate::ui_kit::preferences_figure_data::FIGURES; + use egui::{Pos2, Rect, vec2}; + + /// Shapes a figure paints into `rect` on a fresh frame, in the given theme. + fn shapes(rect: Rect, paint: impl Fn(&egui::Painter, Rect)) -> Vec { + let ctx = crate::fonts::test_context(); + let mut output = + ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0))), ..Default::default() }, |ui| { + paint(ui.painter(), rect); + }); + output.textures_delta.clear(); + output.shapes + } + + fn rects() -> Vec { + let nan = f32::NAN; + vec![ + Rect::from_min_size(Pos2::ZERO, vec2(0.0, 0.0)), + Rect::from_min_size(Pos2::ZERO, vec2(0.2, 0.2)), + Rect::from_min_size(Pos2::new(5.0, 5.0), vec2(1.0, 1.0)), + Rect::from_min_size(Pos2::new(5.0, 5.0), vec2(3.0, 200.0)), + Rect::from_min_size(Pos2::new(5.0, 5.0), vec2(120.0, 64.0)), + Rect::from_min_size(Pos2::new(-50.0, -50.0), vec2(300.0, 300.0)), + Rect::from_min_size(Pos2::ZERO, vec2(1.0e5, 1.0e5)), + Rect::from_min_size(Pos2::ZERO, vec2(f32::INFINITY, 10.0)), + Rect::from_min_size(Pos2::new(nan, 0.0), vec2(10.0, 10.0)), + Rect::from_min_size(Pos2::ZERO, vec2(-40.0, 30.0)), + Rect::from_min_size(Pos2::ZERO, vec2(nan, nan)), + ] + } + + /// Every figure, in both themes, paints at size zero, tiny, normal, huge and non-finite without + /// panicking, and at a normal size stays inside its rectangle with a bounded number of shapes. + #[test] + fn every_preference_figure_paints_safely_at_any_size_in_both_themes() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + assert!(!FIGURES.is_empty()); + for (name, size, paint) in FIGURES { + for rect in rects() { + let _ = shapes(rect, paint); + } + let rect = Rect::from_min_size(Pos2::new(20.0, 10.0), vec2(size[0] * 2.0, size[1] * 2.0)); + let painted = shapes(rect, paint); + assert!(!painted.is_empty() && painted.len() < 700, "{name}: {} shapes", painted.len()); + for shape in &painted { + let bounds = shape.shape.visual_bounding_rect().intersect(shape.clip_rect); + if bounds.is_positive() { + assert!(rect.expand(1.0).contains_rect(bounds), "{name}: {bounds:?} outside {rect:?}"); + } + } + } + } + crate::theme::set_dark(previous); + } + + /// The figures read the theme: the same figure paints different colours in light and dark. + #[test] + fn preference_figures_follow_the_theme() { + let previous = crate::theme::is_dark(); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(120.0, 64.0)); + let colours = |dark: bool| { + crate::theme::set_dark(dark); + let mut all = Vec::new(); + for shape in shapes(rect, super::super::preferences_figure_data::paint_orbit_origin) { + if let egui::Shape::Rect(r) = shape.shape { + all.push(r.fill); + } + } + all + }; + let (light, dark) = (colours(false), colours(true)); + assert!(!light.is_empty() && light != dark); + crate::theme::set_dark(previous); + } + + #[test] + fn theme_thumbnails_paint_with_the_sample_colours_and_a_slanted_system_band() { + let (light, dark) = (ThemeSample::from_tokens(&Tokens::light()), ThemeSample::from_tokens(&Tokens::dark())); + assert_ne!(light, dark); + let rect = Rect::from_min_size(Pos2::new(4.0, 4.0), vec2(124.0, 76.0)); + for rect in rects().into_iter().chain([rect]) { + let _ = shapes(rect, |p, r| paint_theme_thumbnail(p, r, &light)); + let _ = shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark)); + } + let single = shapes(rect, |p, r| paint_theme_thumbnail(p, r, &light)).len(); + let system = shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark)).len(); + assert!(system > single, "the dark band adds shapes over the light card"); + for shape in shapes(rect, |p, r| paint_theme_system(p, r, &light, &dark)) { + let bounds = shape.shape.visual_bounding_rect().intersect(shape.clip_rect); + assert!(!bounds.is_positive() || rect.expand(1.0).contains_rect(bounds), "{bounds:?}"); + } + } } diff --git a/docs/ui-kit.md b/docs/ui-kit.md index 9e95888e0..f0f19882a 100644 --- a/docs/ui-kit.md +++ b/docs/ui-kit.md @@ -858,3 +858,52 @@ and its shared gap above an inline result toolbar. `number_pair` extends the shared value-pair row to bounded numeric fields (such as image width and height), preserving label alignment, clipping and number-field behavior. + +## Preferences cards, figures and help (redesign) + +The redesigned Preferences pages (tracker #9863, reference in `docs/design/preferences/`) compose +these shared pieces; the pages themselves arrive in later steps. Sizes follow +`docs/design/preferences/measurements.md`. + +| Element | Use | Main tokens | +| --- | --- | --- | +| `picture_card(ui, &Card, width)` | A radio card: a figure, a label, an optional sub-label, an optional "has options" disc (its text is the hover) and an optional accent check. The figure keeps its aspect ratio and fills the card's inside width; the card sizes to the `width` its container gives it (`card_width(available, columns, gap)` divides a row). Selected: 2 pt `form_primary` border, `selected_bg` fill, `selected_ink` semibold label. Disabled: dimmed, no hover, no click, no focus ring. Keyboard focus draws a ring outside the border. Reports `RadioButton` to accessibility. | `form_primary`, `selected_bg`, `selected_ink`, `hover`, `control_fill`, `dialog_border`, `form_ink`, `form_dim`, `on_accent`, `radius_lg`, `space_*`, `font_label/small` | +| `toggle_tile(ui, &Card, width)` | The same picture with a 15 pt checkbox in the top-right corner (`Card::selected` is "on"). Reports `Checkbox`. | as above, `control_border` | +| `preset_card(ui, name, word, selected, enabled, &icon, width)` | A 70 pt card with a 38 pt icon box (`icon` paints into it in the ink it is given), a name, one word and an accent check. Used for Performance, Quality and Custom. | as above, `pref_well` | +| `help_icon(ui, text)` | The (i) after a label. Shows `text` as a tooltip and exposes it as the widget's label. | `form_dim`, `form_ink` | +| `carousel(ui, id, count, item_width, item_height, item)` | A row of items between a previous and a next arrow (both labelled from the `prefs.carousel_*` messages). `carousel_window(count, offset, available, item_width, gap, arrow)` says which items show; the arrow at an end is dimmed (0.35) and inert. The first shown index is kept in the Ui's temporary memory under `id`. | `dialog_border`, `control_fill`, `hover`, `form_ink`, `radius_lg` | + +`card_look(selected, enabled, hovered, focused)` holds the state rules (border width, fill, ink, weight, +dimming, focus ring) apart from the painting so they can be tested. + +### Figures + +`ui_kit/preferences_figures.rs` paints the illustrations of the Preferences boards. The geometry of +each comes from its SVG in `docs/design/preferences/figures/`: `tools/preferences-figures/generate.py` +compiles those files into `ui_kit/preferences_figure_data.rs`, one constant and one painter per +figure (`paint_tess_normal`, `paint_orbit_origin`, ...; `FIGURES` lists them all), and +`preferences_figure_ops.rs` paints the operations with egui shapes. A figure is a list of rectangles, +circles, polygons, soft shadows and tiny captions in the figure's own coordinates. Nothing is +rasterised and no image is loaded; a figure costs a few dozen shapes and scales to any rectangle, +keeping its aspect ratio. A zero, tiny, huge or non-finite rectangle paints nothing or something +clipped, never panics. + +To change a figure, edit its SVG (light and dark) and run +`python3 tools/preferences-figures/generate.py`; never edit `preferences_figure_data.rs`. The colour +of each element is a role read from `Tokens`: `figure_ground`, `figure_line`, `figure_face_top`, +`figure_face_left`, `figure_face_right`, `figure_card`, `figure_accent`, `figure_reference`, +`figure_axis_x/y/z`, `figure_ok`, `figure_warn`, plus `form_ink`, `form_dim`, `dialog_border`, +`control_border` and `control_fill` (`docs/design/preferences/tokens.md`). The new tokens, with light +and dark values, are in `assets/styles/ui/palettes.rs`; theme files cannot override them yet and keep +the built-in values. The colour vision samples read `axis_z`, `sketch_projected`, `axis_x`, `bend_up` +and `bend_down`, so they follow the colour vision mode. + +Theme thumbnails (`paint_theme_thumbnail`, `paint_theme_system`) take a `ThemeSample` (12 colours, +`ThemeSample::from_tokens(&tokens)`), not the dialog's tokens, because a card shows its own theme. +The Orientation figures and the visual-style icon are not repeated here: the app already has them. + +New pieces and figures each have an entry in `gallery::ELEMENTS` (`picture_card`, `toggle_tile`, +`preset_card`, `help_icon`, `carousel`, `preference_theme_thumbnails`, `preference_figures`), checked +in both themes. `SOLIDCRAFT_PREFERENCE_WIDGET_EVIDENCE=

` keeps the CPU-rendered boards +(`preferences-widgets-*.png`, `preferences-figures-*.png`) from +`preference_widgets_and_figures_board_in_both_themes`. diff --git a/tools/preferences-figures/generate.py b/tools/preferences-figures/generate.py new file mode 100644 index 000000000..b45bd392e --- /dev/null +++ b/tools/preferences-figures/generate.py @@ -0,0 +1,588 @@ +#!/usr/bin/env python3 +"""Compile docs/design/preferences/figures/*.svg into ui_kit/preferences_figure_data.rs. + +Each figure becomes a list of drawing operations (rectangles, circles, flattened polygons, text) in +the figure's own coordinates, with colours as roles (`Ink`) instead of hex values. A role is the +light/dark colour pair the board used at that position; docs/design/preferences/tokens.md says which +`theme::Tokens` field each role reads. Run from the repository root: + + python3 tools/preferences-figures/generate.py +""" +import collections +import json +import math +import os +import re +import sys +import xml.etree.ElementTree as ET + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) +FIGS = os.path.join(ROOT, 'docs/design/preferences/figures') +OUT = os.path.join(ROOT, 'crates/ui-egui/src/ui_kit/preferences_figure_data.rs') + +# Skipped: the Orientation figures already exist in ui_kit and stay as they are. +SKIP = {'orientation-z-up', 'orientation-y-up', 'style-shaded-edges'} +THEMES = ['theme-light', 'theme-dark', 'theme-gruvbox', 'theme-imported'] + +PAIRS = { + ('#F7F8FA', '#1C1F26'): 'Ground', + ('#6F7C8F', '#A3AEC2'): 'Line', + ('#236EAD', '#8CBEF5'): 'Accent', + ('#FFFFFF', '#6B7790'): 'Top', + ('#4A5868', '#B4BBC8'): 'Dim', + ('#E4E9F0', '#515B72'): 'Left', + ('#C9D2DE', '#394256'): 'Right', + ('#D5DBE3', '#3F4552'): 'Border', + ('#C3CBD6', '#4A5262'): 'ControlBorder', + ('#FFFFFF', '#2F343E'): 'Card', + ('#1B2430', '#DEE2E8'): 'Text', + ('#8A5300', '#E8C24A'): 'Reference', + ('#2F6FD0', '#6CA8F7'): 'AxisZ', + ('#D64545', '#F27A7A'): 'AxisX', + ('#2E9E5B', '#62D48E'): 'AxisY', + ('#FFFFFF', '#FFFFFF'): 'White', + ('#B84A00', '#F0A27A'): 'Note', + ('#FBEBDD', '#4A3326'): 'NoteFill', + ('#2F7D5B', '#7FD1AE'): 'Ok', + ('#C98A00', '#E8C24A'): 'Warn', + ('#FFFFFF', '#1C1F26'): 'Control', + ('#0072B2', '#56B4E9'): 'Cv0', + ('#E69F00', '#F0C060'): 'Cv1', + ('#E69F00', '#E69F00'): 'Cv1', + ('#D55E00', '#F0A27A'): 'Cv2', + ('#56B4E9', '#8CBEF5'): 'Cv3', + ('#56B4E9', '#56B4E9'): 'Cv3', + ('#CC79A7', '#CC79A7'): 'Cv4', +} + + +def num(v, d=0.0): + return d if v is None else float(re.match(r'-?[\d.]+(?:e-?\d+)?', v.strip()).group(0)) + + +def parse_color(v): + """(hex6 upper, alpha) or None for none/url.""" + if v is None or v == 'none': + return None + v = v.strip() + if v.startswith('url('): + return ('url', re.search(r'#([\w-]+)', v).group(1)) + m = re.fullmatch(r'#([0-9A-Fa-f]{3,8})', v) + if not m: + raise ValueError(v) + h = m.group(1) + if len(h) == 3: + h = ''.join(c * 2 for c in h) + a = 1.0 + if len(h) == 8: + a = int(h[6:], 16) / 255.0 + h = h[:6] + return ('#' + h.upper(), a) + + +def mat_mul(a, b): + return (a[0] * b[0] + a[2] * b[1], a[1] * b[0] + a[3] * b[1], a[0] * b[2] + a[2] * b[3], a[1] * b[2] + a[3] * b[3], + a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]) + + +def parse_transform(s): + m = (1, 0, 0, 1, 0, 0) + for name, args in re.findall(r'(\w+)\(([^)]*)\)', s or ''): + v = [float(x) for x in re.split(r'[ ,]+', args.strip())] + if name == 'translate': + t = (1, 0, 0, 1, v[0], v[1] if len(v) > 1 else 0) + elif name == 'scale': + t = (v[0], 0, 0, v[1] if len(v) > 1 else v[0], 0, 0) + elif name == 'matrix': + t = tuple(v) + else: + raise ValueError(name) + m = mat_mul(m, t) + return m + + +def ap(m, x, y): + return (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]) + + +def flatten_path(d, m): + toks = re.findall(r'[MmLlHhVvZzAaQqCc]|-?[\d.]+(?:e-?\d+)?', d) + i = 0 + subs = [] + cur = None + x = y = sx = sy = 0.0 + cmd = None + + def nxt(): + nonlocal i + v = float(toks[i]) + i += 1 + return v + + def add(px, py): + cur.append(ap(m, px, py)) + + while i < len(toks): + if re.fullmatch(r'[A-Za-z]', toks[i]): + cmd = toks[i] + i += 1 + if cmd in 'Zz': + if cur: + subs.append((cur, True)) + cur = None + x, y = sx, sy + continue + c = cmd + if c in 'Mm': + if cur and len(cur) > 0: + subs.append((cur, False)) + nx, ny = nxt(), nxt() + if c == 'm': + nx, ny = x + nx, y + ny + x, y = sx, sy = nx, ny + cur = [] + add(x, y) + cmd = 'L' if c == 'M' else 'l' + elif c in 'Ll': + nx, ny = nxt(), nxt() + if c == 'l': + nx, ny = x + nx, y + ny + x, y = nx, ny + if cur is None: + cur = [] + add(sx, sy) + add(x, y) + elif c in 'Hh': + nx = nxt() + x = x + nx if c == 'h' else nx + if cur is None: + cur = [] + add(sx, sy) + add(x, y) + elif c in 'Vv': + ny = nxt() + y = y + ny if c == 'v' else ny + if cur is None: + cur = [] + add(sx, sy) + add(x, y) + elif c in 'Qq': + a, b, e, f = nxt(), nxt(), nxt(), nxt() + if c == 'q': + a, b, e, f = x + a, y + b, x + e, y + f + for k in range(1, 13): + t = k / 12 + add((1 - t) ** 2 * x + 2 * (1 - t) * t * a + t * t * e, (1 - t) ** 2 * y + 2 * (1 - t) * t * b + t * t * f) + x, y = e, f + elif c in 'Cc': + a, b, e, f, g, h = (nxt() for _ in range(6)) + if c == 'c': + a, b, e, f, g, h = x + a, y + b, x + e, y + f, x + g, y + h + for k in range(1, 17): + t = k / 16 + u = 1 - t + add(u ** 3 * x + 3 * u * u * t * a + 3 * u * t * t * e + t ** 3 * g, u ** 3 * y + 3 * u * u * t * b + 3 * u * t * t * f + t ** 3 * h) + x, y = g, h + elif c in 'Aa': + rx, ry, rot, la, sw, ex, ey = (nxt() for _ in range(7)) + if c == 'a': + ex, ey = x + ex, y + ey + pts = arc(x, y, rx, ry, rot, int(la), int(sw), ex, ey) + for px, py in pts: + add(px, py) + x, y = ex, ey + else: + raise ValueError(c) + if cur: + subs.append((cur, False)) + return subs + + +def arc(x1, y1, rx, ry, phi, fa, fs, x2, y2): + if rx == 0 or ry == 0: + return [(x2, y2)] + ph = math.radians(phi) + cp, sp = math.cos(ph), math.sin(ph) + dx, dy = (x1 - x2) / 2, (y1 - y2) / 2 + x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy + rx, ry = abs(rx), abs(ry) + lam = x1p ** 2 / rx ** 2 + y1p ** 2 / ry ** 2 + if lam > 1: + rx *= math.sqrt(lam) + ry *= math.sqrt(lam) + num_ = rx ** 2 * ry ** 2 - rx ** 2 * y1p ** 2 - ry ** 2 * x1p ** 2 + den = rx ** 2 * y1p ** 2 + ry ** 2 * x1p ** 2 + co = math.sqrt(max(0, num_ / den)) * (-1 if fa == fs else 1) + cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx + cx, cy = cp * cxp - sp * cyp + (x1 + x2) / 2, sp * cxp + cp * cyp + (y1 + y2) / 2 + + def ang(ux, uy, vx, vy): + a = math.atan2(ux * vy - uy * vx, ux * vx + uy * vy) + return a + + th1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry) + dth = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry) + if not fs and dth > 0: + dth -= 2 * math.pi + if fs and dth < 0: + dth += 2 * math.pi + n = max(6, int(abs(dth) / (math.pi / 16))) + out = [] + for k in range(1, n + 1): + t = th1 + dth * k / n + out.append((cp * rx * math.cos(t) - sp * ry * math.sin(t) + cx, sp * rx * math.cos(t) + cp * ry * math.sin(t) + cy)) + return out + + +def rr_poly(x, y, w, h, r, m, seg=6): + pts = [] + if r <= 0: + for px, py in ((x, y), (x + w, y), (x + w, y + h), (x, y + h)): + pts.append(ap(m, px, py)) + return pts + r = min(r, w / 2, h / 2) + for cx, cy, a0 in ((x + w - r, y + r, -90), (x + w - r, y + h - r, 0), (x + r, y + h - r, 90), (x + r, y + r, 180)): + for k in range(seg + 1): + a = math.radians(a0 + 90 * k / seg) + pts.append(ap(m, cx + r * math.cos(a), cy + r * math.sin(a))) + return pts + + +class Walker: + """Walks one SVG into a flat op list; colours stay as hex until paired.""" + + def __init__(self, root): + self.defs = {} + self.clips = {} + self.ops = [] + self.root = root + + @staticmethod + def tag(e): + return e.tag.split('}')[-1] + + def collect(self, e): + for c in e: + t = self.tag(c) + if t in ('linearGradient', 'radialGradient'): + self.defs[c.get('id')] = c + elif t == 'clipPath': + self.clips[c.get('id')] = c + elif t == 'defs': + self.collect(c) + else: + self.collect(c) + + def run(self): + self.collect(self.root) + vb = [float(v) for v in self.root.get('viewBox').split()] + self.size = (vb[2], vb[3]) + self.walk(self.root, (1, 0, 0, 1, -vb[0], -vb[1]), None, root=True) + return self.ops + + def style(self, e, mscale): + f = parse_color(e.get('fill', '#000000')) + s = parse_color(e.get('stroke')) + fo = num(e.get('fill-opacity'), 1.0) * num(e.get('opacity'), 1.0) + so = num(e.get('stroke-opacity'), 1.0) * num(e.get('opacity'), 1.0) + sw = num(e.get('stroke-width'), 1.0) * mscale if s else 0 + dash = None + if e.get('stroke-dasharray'): + dv = [float(v) for v in re.split(r'[ ,]+', e.get('stroke-dasharray').strip())] + if len(dv) >= 2 and dv[1] > 0: + dash = (dv[0] * mscale, dv[1] * mscale) + round_cap = e.get('stroke-linecap') == 'round' + return f, fo, s, so, sw, dash, round_cap + + def walk(self, e, m, clip, root=False): + for c in e: + t = self.tag(c) + if t in ('defs', 'linearGradient', 'radialGradient', 'clipPath', 'stop'): + continue + mc = m + if t == 'svg': + x, y = num(c.get('x'), 0), num(c.get('y'), 0) + w, h = num(c.get('width')), num(c.get('height')) + vb = [float(v) for v in c.get('viewBox').split()] + mc = mat_mul(m, (1, 0, 0, 1, x, y)) + mc = mat_mul(mc, (w / vb[2], 0, 0, h / vb[3], -vb[0] * w / vb[2], -vb[1] * h / vb[3])) + self.collect_clips(c) + # A nested svg clips its content to its own viewport. + self.ops.append(('clip', rr_poly(x, y, w, h, 0, m))) + self.walk(c, mc, clip) + self.ops.append(('unclip',)) + continue + if t == 'g': + mc = mat_mul(m, parse_transform(c.get('transform'))) + cl = clip + if c.get('clip-path'): + cid = re.search(r'#([\w-]+)', c.get('clip-path')).group(1) + cp = self.clips[cid] + pts = self.clip_points(cp, mc) + self.ops.append(('clip', pts)) + self.walk(c, mc, cl) + self.ops.append(('unclip',)) + else: + self.walk(c, mc, cl) + continue + if c.get('transform'): + mc = mat_mul(m, parse_transform(c.get('transform'))) + det = abs(mc[0] * mc[3] - mc[1] * mc[2]) + ms = math.sqrt(det) + f, fo, s, so, sw, dash, rc = self.style(c, ms) + axis = abs(mc[1]) < 1e-9 and abs(mc[2]) < 1e-9 + if t == 'rect': + x, y, w, h = num(c.get('x'), 0), num(c.get('y'), 0), num(c.get('width')), num(c.get('height')) + r = num(c.get('rx'), 0) + if f and f[0] == 'url' and f[1] in self.defs: + g = self.defs[f[1]] + stops = [(num(st.get('offset')), parse_color(st.get('stop-color'))[0]) for st in g] + self.ops.append(('poly', rr_poly(x, y, w, h, r, mc), True, ('grad', stops[0][1], stops[-1][1], ap(mc, 0, y)[1], ap(mc, 0, y + h)[1]), fo, s, so, sw, dash, rc)) + elif axis and mc[0] > 0 and mc[3] > 0: + p0 = ap(mc, x, y) + self.ops.append(('rect', p0[0], p0[1], w * mc[0], h * mc[3], r * mc[0], f, fo, s, so, sw, dash)) + else: + self.ops.append(('poly', rr_poly(x, y, w, h, r, mc), True, f and ('solid', f), fo, s, so, sw, dash, rc)) + elif t == 'circle': + cx, cy, r = num(c.get('cx')), num(c.get('cy')), num(c.get('r')) + if abs(mc[1]) < 1e-9 and abs(mc[2]) < 1e-9 and abs(mc[0] - mc[3]) < 1e-9: + p0 = ap(mc, cx, cy) + self.ops.append(('circle', p0[0], p0[1], r * mc[0], f, fo, s, so, sw, dash)) + else: + pts = [ap(mc, cx + r * math.cos(a * math.pi / 12), cy + r * math.sin(a * math.pi / 12)) for a in range(24)] + self.ops.append(('poly', pts, True, f and ('solid', f), fo, s, so, sw, dash, rc)) + elif t == 'ellipse': + cx, cy, rx, ry = num(c.get('cx')), num(c.get('cy')), num(c.get('rx')), num(c.get('ry')) + if f and f[0] == 'url': + g = self.defs[f[1]] + stops = [num(st.get('stop-opacity'), 1.0) for st in g] + p0 = ap(mc, cx, cy) + self.ops.append(('glow', p0[0], p0[1], rx * mc[0], ry * mc[3], stops[0] * fo)) + else: + pts = [ap(mc, cx + rx * math.cos(a * math.pi / 16), cy + ry * math.sin(a * math.pi / 16)) for a in range(32)] + self.ops.append(('poly', pts, True, f and ('solid', f), fo, s, so, sw, dash, rc)) + elif t in ('polygon', 'polyline'): + nums = [float(v) for v in re.split(r'[ ,]+', c.get('points').strip())] + pts = [ap(mc, nums[k], nums[k + 1]) for k in range(0, len(nums), 2)] + self.ops.append(('poly', pts, t == 'polygon', f and ('solid', f), fo, s, so, sw, dash, rc)) + elif t == 'path' and s and s[0] == 'url': + g = self.defs[s[1]] + stops = [(num(st.get('offset')), parse_color(st.get('stop-color')), num(st.get('stop-opacity'), 1.0)) for st in g] + for pts, closed in flatten_path(c.get('d'), mc): + (x0, y0), (x1, y1) = pts[0], pts[-1] + n = 10 + for k in range(n): + a0, a1 = k / n, (k + 1) / n + am = (a0 + a1) / 2 + al = stops[0][2] + (stops[-1][2] - stops[0][2]) * am + seg = [(x0 + (x1 - x0) * a0, y0 + (y1 - y0) * a0), (x0 + (x1 - x0) * a1, y0 + (y1 - y0) * a1)] + self.ops.append(('poly', seg, False, None, 1.0, stops[0][1], al, sw, None, rc)) + elif t == 'path': + for pts, closed in flatten_path(c.get('d'), mc): + if len(pts) >= 2: + fill = f and ('solid', f) if (closed or len(pts) >= 3) else None + self.ops.append(('poly', pts, closed, fill, fo, s, so, sw, dash, rc)) + elif t == 'text': + x, y = num(c.get('x')), num(c.get('y')) + p0 = ap(mc, x, y) + self.ops.append(('text', p0[0], p0[1], num(c.get('font-size')) * ms, c.get('text-anchor', 'start'), f, fo, ''.join(c.itertext()), num(c.get('font-weight'), 400) >= 600)) + elif t == 'g': + pass + else: + raise ValueError('unhandled ' + t) + + def collect_clips(self, e): + for c in e: + if self.tag(c) == 'clipPath': + self.clips[c.get('id')] = c + + def clip_points(self, cp, m): + out = [] + for c in cp: + t = self.tag(c) + if t == 'path': + for pts, _ in flatten_path(c.get('d'), m): + out.extend(pts) + elif t == 'rect': + out.extend(rr_poly(num(c.get('x'), 0), num(c.get('y'), 0), num(c.get('width')), num(c.get('height')), 0, m)) + else: + raise ValueError('clip ' + t) + return out + + +def load(name, theme): + tree = ET.parse(os.path.join(FIGS, '%s.%s.svg' % (name, theme))) + w = Walker(tree.getroot()) + return w.run(), w.size + + +def color_fields(op): + """Positions of (colour, alpha) tuples in an op, as (index) list.""" + k = op[0] + if k == 'rect': + return [6, 9] + if k == 'circle': + return [4, 7] + if k == 'poly': + return [None, 5] + if k == 'text': + return [5] + return [] + + +def ink_of(l, d, slots=None): + if slots is not None: + key = tuple(slots) + if key not in SLOTS: + SLOTS[key] = len(SLOTS) + return 'Slot(%d)' % SLOTS[key] + if l == '#000000': + return 'Black' + r = PAIRS.get((l, d)) + if r is None: + raise KeyError((l, d)) + return r + + +SLOTS = collections.OrderedDict() + + +def f32(v): + s = ('%.3f' % v).rstrip('0').rstrip('.') + if s in ('', '-0'): + s = '0' + return s + ('' if '.' in s else '.0') + + +def paint(l, d, alpha, slots=None): + """Option source.""" + if l is None: + return 'None' + return 'Some(P { ink: Ink::%s, a: %s })' % (ink_of(l[0], d[0], slots), f32(alpha)) + + +def line(sl, sd, so, sw, dash, rc, slots=None): + if sl is None or sw <= 0: + return 'None' + ds = dash or (0, 0) + return 'Some(L { ink: Ink::%s, a: %s, w: %s, dash: [%s, %s], round: %s })' % (ink_of(sl[0], sd[0], slots), f32(so), f32(sw), f32(ds[0]), f32(ds[1]), 'true' if rc else 'false') + + +def emit(name, ops_l, ops_d, slotsets=None): + out = [] + assert len(ops_l) == len(ops_d), (name, len(ops_l), len(ops_d)) + for idx, (a, b) in enumerate(zip(ops_l, ops_d)): + assert a[0] == b[0], (name, idx, a[0], b[0]) + sl = None + if slotsets is not None: + sl = [s[idx] for s in slotsets] + k = a[0] + if k == 'rect': + _, x, y, w, h, r, f, fo, s, so, sw, dash = a + _, _, _, _, _, _, fd, _, sd, _, _, _ = b + fs = fsl = None + if slotsets is not None: + fs = [t[6][0] if t[6] else None for t in sl] + ss = [t[8][0] if t[8] else None for t in sl] + out.append('Op::Rect { r: [%s, %s, %s, %s], radius: %s, fill: %s, line: %s }' % ( + f32(x), f32(y), f32(w), f32(h), f32(r), + paint(f, fd, fo, fs if slotsets is not None and f else None), + line(s, sd, so, sw, dash, False, ss if slotsets is not None and s else None))) + elif k == 'circle': + _, x, y, r, f, fo, s, so, sw, dash = a + fd, sd = b[4], b[6] + fs = ss = None + if slotsets is not None: + fs = [t[4][0] if t[4] else None for t in sl] + ss = [t[6][0] if t[6] else None for t in sl] + out.append('Op::Circle { c: [%s, %s, %s], fill: %s, line: %s }' % ( + f32(x), f32(y), f32(r), paint(f, fd, fo, fs if f and slotsets is not None else None), + line(s, sd, so, sw, dash, False, ss if s and slotsets is not None else None))) + elif k == 'poly': + _, pts, closed, fill, fo, s, so, sw, dash, rc = a + fd, sd = b[3], b[5] + pts_s = ', '.join('[%s, %s]' % (f32(px), f32(py)) for px, py in pts) + fs = ss = None + if slotsets is not None: + fs = [t[3][1][0] if t[3] and t[3][0] == 'solid' else None for t in sl] + ss = [t[5][0] if t[5] else None for t in sl] + grad = 'None' + fill_s = 'None' + if fill and fill[0] == 'grad': + _, top, bot, y0, y1 = fill + gd = b[3] + if slotsets is not None: + tops = [t[3][1] for t in sl] + bots = [t[3][2] for t in sl] + grad = 'Some(G { top: Ink::%s, bottom: Ink::%s, y: [%s, %s] })' % (ink_of(top, gd[1], tops), ink_of(bot, gd[2], bots), f32(y0), f32(y1)) + else: + grad = 'Some(G { top: Ink::%s, bottom: Ink::%s, y: [%s, %s] })' % (ink_of(top, gd[1]), ink_of(bot, gd[2]), f32(y0), f32(y1)) + elif fill: + fill_s = paint(fill[1], fd[1], fo, fs if slotsets is not None else None) + out.append('Op::Poly { pts: &[%s], closed: %s, fill: %s, grad: %s, line: %s }' % ( + pts_s, 'true' if closed else 'false', fill_s, grad, + line(s, sd, so, sw, dash, rc, ss if s and slotsets is not None else None))) + elif k == 'glow': + _, x, y, rx, ry, al = a + out.append('Op::Glow { c: [%s, %s, %s, %s], a: %s }' % (f32(x), f32(y), f32(rx), f32(ry), f32(al))) + elif k == 'text': + _, x, y, size, anchor, f, fo, txt, bold = a + fd = b[5] + fs = [t[5][0] for t in sl] if slotsets is not None else None + out.append('Op::Text { at: [%s, %s], size: %s, anchor: %d, ink: Ink::%s, a: %s, s: %s, bold: %s }' % ( + f32(x), f32(y), f32(size), {'start': 0, 'middle': 1, 'end': 2}[anchor], ink_of(f[0], fd[0], fs), f32(fo), '"' + txt.replace('\\', '\\\\').replace('"', '\\"') + '"', 'true' if bold else 'false')) + elif k == 'clip': + pts_s = ', '.join('[%s, %s]' % (f32(px), f32(py)) for px, py in a[1]) + out.append('Op::Clip(&[%s])' % pts_s) + elif k == 'unclip': + out.append('Op::Unclip') + else: + raise ValueError(k) + return out + + +def const_name(n): + return n.upper().replace('-', '_') + + +def fn_name(n): + return 'paint_' + n.replace('-', '_') + + +def main(): + man = sorted({f.split('.')[0] for f in os.listdir(FIGS) if f.endswith('.svg')}) + parts = [] + parts.append('//! Generated by `tools/preferences-figures/generate.py` from `docs/design/preferences/figures/*.svg`.\n' + '//! Do not edit by hand: change the SVG and run the script again.\n' + '#![allow(clippy::approx_constant, clippy::excessive_precision)]\n' + 'use super::preferences_figure_ops::{Figure, G, Ink, L, Op, P};\n') + fns = [] + names = [] + for name in man: + if name in SKIP or name.startswith('theme-'): + continue + ol, size = load(name, 'light') + od, size2 = load(name, 'dark') + assert size == size2 + ops = emit(name, ol, od) + parts.append('pub(super) const %s: Figure = Figure { size: [%s, %s], ops: &[\n %s,\n] };\n' % (const_name(name), f32(size[0]), f32(size[1]), ',\n '.join(ops))) + names.append(name) + # theme thumbnail: slots from the four themes + loaded = [load(t, 'light')[0] for t in THEMES] + size = load('theme-light', 'light')[1] + ops = emit('theme-thumbnail', loaded[0], loaded[0], slotsets=loaded) + parts.append('pub(super) const THEME_THUMBNAIL: Figure = Figure { size: [%s, %s], ops: &[\n %s,\n] };\n' % (f32(size[0]), f32(size[1]), ',\n '.join(ops))) + slot_table = ['// Theme thumbnail slots (light, dark, gruvbox, imported sample colours):'] + for key, i in SLOTS.items(): + slot_table.append('// %d: %s' % (i, ' '.join(str(k) for k in key))) + parts.append('\n'.join(slot_table) + '\n') + parts.append('use egui::{Painter, Rect};\nuse super::preferences_figure_ops::paint;\n') + for n in names: + parts.append('/// The `%s` figure of `docs/design/preferences/figures`.\npub(crate) fn %s(p: &Painter, rect: Rect) {\n paint(p, rect, &%s, None, None);\n}\n' % (n, fn_name(n), const_name(n))) + parts.append('/// Every figure painter by file name, for the gallery and the tests.\npub(crate) const FIGURES: &[(&str, [f32; 2], fn(&Painter, Rect))] = &[\n%s];\n' % ''.join(' ("%s", %s.size, %s),\n' % (n, const_name(n), fn_name(n)) for n in names)) + open(OUT, 'w', encoding='utf8', newline='\n').write('\n'.join(parts)) + print('figures', len(names), 'slots', len(SLOTS), file=sys.stderr) + + +if __name__ == '__main__': + main() From 58c64ca4d4d32201daef090b2046c77d757e95a3 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:29:27 +0000 Subject: [PATCH 36/55] Regenerate generated files and fold pending files [skip ci] --- assets/locales/ar.json | 2 ++ assets/locales/de.json | 2 ++ assets/locales/en.json | 2 ++ assets/locales/he.json | 2 ++ assets/locales/ja.json | 2 ++ assets/locales/ko.json | 2 ++ assets/locales/pending/preferences-v2.json | 10 ---------- assets/locales/vi.json | 2 ++ assets/locales/zh.json | 2 ++ 9 files changed, 16 insertions(+), 10 deletions(-) delete mode 100644 assets/locales/pending/preferences-v2.json diff --git a/assets/locales/ar.json b/assets/locales/ar.json index 41668bdbd..e95a72284 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -2152,6 +2152,8 @@ "prefs.button_left": "سحب بالزر الأيسر", "prefs.button_middle": "سحب بالزر الأوسط", "prefs.button_right": "سحب بالزر الأيمن", + "prefs.carousel_next": "التالي", + "prefs.carousel_previous": "السابق", "prefs.choose_font": "اختيار ملف خط…", "prefs.click": "نقر", "prefs.contact_shading": "تظليل التلامس الناعم", diff --git a/assets/locales/de.json b/assets/locales/de.json index 27446fe97..84143597e 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -2149,6 +2149,8 @@ "prefs.button_left": "Ziehen mit der linken Maustaste", "prefs.button_middle": "Ziehen mit der mittleren Maustaste", "prefs.button_right": "Ziehen mit der rechten Maustaste", + "prefs.carousel_next": "Weiter", + "prefs.carousel_previous": "Zurück", "prefs.choose_font": "Schriftdatei auswählen…", "prefs.click": "Klicken", "prefs.contact_shading": "Weiche Kontaktschattierung", diff --git a/assets/locales/en.json b/assets/locales/en.json index afefba8c4..a6f85f3f0 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -2152,6 +2152,8 @@ "prefs.button_left": "Left drag", "prefs.button_middle": "Middle drag", "prefs.button_right": "Right drag", + "prefs.carousel_next": "Next", + "prefs.carousel_previous": "Previous", "prefs.choose_font": "Choose font file…", "prefs.click": "Click", "prefs.contact_shading": "Soft contact shading", diff --git a/assets/locales/he.json b/assets/locales/he.json index f3adc473b..c779c609c 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -2152,6 +2152,8 @@ "prefs.button_left": "גרירה שמאלית", "prefs.button_middle": "גרירה אמצעית", "prefs.button_right": "גרירה ימנית", + "prefs.carousel_next": "הבא", + "prefs.carousel_previous": "הקודם", "prefs.choose_font": "בחירת קובץ גופן…", "prefs.click": "לחיצה", "prefs.contact_shading": "הצללת מגע רכה", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 81485c32f..ce2d53ded 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -2152,6 +2152,8 @@ "prefs.button_left": "左ドラッグ", "prefs.button_middle": "中央ドラッグ", "prefs.button_right": "右ドラッグ", + "prefs.carousel_next": "次へ", + "prefs.carousel_previous": "前へ", "prefs.choose_font": "フォントファイルを選択…", "prefs.click": "クリック", "prefs.contact_shading": "柔らかな接触陰影", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index cb833cc6e..80a3ec9e5 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -1548,6 +1548,8 @@ "prefs.button_left": "왼쪽 드래그", "prefs.button_middle": "가운데 드래그", "prefs.button_right": "오른쪽 드래그", + "prefs.carousel_next": "다음", + "prefs.carousel_previous": "이전", "prefs.choose_font": "글꼴 파일 선택…", "prefs.click": "클릭", "prefs.contact_shading": "부드러운 접촉 음영", diff --git a/assets/locales/pending/preferences-v2.json b/assets/locales/pending/preferences-v2.json deleted file mode 100644 index 60ba54424..000000000 --- a/assets/locales/pending/preferences-v2.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "ar": { "prefs.carousel_next": "التالي", "prefs.carousel_previous": "السابق" }, - "de": { "prefs.carousel_next": "Weiter", "prefs.carousel_previous": "Zurück" }, - "en": { "prefs.carousel_next": "Next", "prefs.carousel_previous": "Previous" }, - "he": { "prefs.carousel_next": "הבא", "prefs.carousel_previous": "הקודם" }, - "ja": { "prefs.carousel_next": "次へ", "prefs.carousel_previous": "前へ" }, - "ko": { "prefs.carousel_next": "다음", "prefs.carousel_previous": "이전" }, - "vi": { "prefs.carousel_next": "Tiếp", "prefs.carousel_previous": "Trước" }, - "zh": { "prefs.carousel_next": "下一个", "prefs.carousel_previous": "上一个" } -} diff --git a/assets/locales/vi.json b/assets/locales/vi.json index e62b851b4..14076240b 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -2152,6 +2152,8 @@ "prefs.button_left": "Kéo chuột trái", "prefs.button_middle": "Kéo chuột giữa", "prefs.button_right": "Kéo chuột phải", + "prefs.carousel_next": "Tiếp", + "prefs.carousel_previous": "Trước", "prefs.choose_font": "Chọn tệp phông chữ…", "prefs.click": "Nhấp chuột", "prefs.contact_shading": "Đổ bóng tiếp xúc mềm", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index ac532b0c4..44e899873 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -2152,6 +2152,8 @@ "prefs.button_left": "左键拖动", "prefs.button_middle": "中键拖动", "prefs.button_right": "右键拖动", + "prefs.carousel_next": "下一个", + "prefs.carousel_previous": "上一个", "prefs.choose_font": "选择字体文件…", "prefs.click": "单击", "prefs.contact_shading": "柔和接触阴影", From cfc46448a8268c0d5da856d31fd481ff52ff3991 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=B6pfl?= <44141543+Sebastion@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:51:42 +0000 Subject: [PATCH 37/55] Joints: an edge origin shares the joint faces' measurement (#10866) `face_of` called `Body::faces`, which tessellates the whole body, on every solve. Face origins went through the cached `ModelBody::joint_faces`, at the same tolerance, but edge origins never did, so one edge origin on a large body cost a drag or a Drive Joints step far more than the solve. Co-authored-by: Claude Opus 5.5 --- crates/doc/src/eval_cost_tests.rs | 19 +++++++++++++++++++ crates/doc/src/joints_edge.rs | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/eval_cost_tests.rs b/crates/doc/src/eval_cost_tests.rs index 85d76b9fd..a851e33b9 100644 --- a/crates/doc/src/eval_cost_tests.rs +++ b/crates/doc/src/eval_cost_tests.rs @@ -174,6 +174,25 @@ fn joint_face_measurements_never_follow_a_replaced_body_or_stale_offset() { assert_eq!(work.joint_faces, 0, "offsets are applied after the shared face measurements"); } +/// Every solve of a drag resolves its edge origins again: they share the joint faces' one +/// measurement, as a face origin does, instead of tessellating the whole body each time. +#[test] +fn an_edge_origin_measures_its_faces_once() { + use crate::joints::{JointOrigin, Snap}; + let doc = Document::new("edge origin"); + let mut state = ModelState::default(); + state.bodies.push(ModelBody::new("Block".into(), kernel::box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap(), 0)); + let pick = Vec3::new(5.0, 0.0, 10.0); + let origin = JointOrigin { occurrence: 0, snap: Snap::Edge { pick, edge: None, face: None, corner: None, axis: None } }; + let work = counted(|| { + for _ in 0..8 { + let frame = joints::resolve_origin(&doc, &state.clone(), &origin).unwrap(); + assert!(apply_point(&frame, Vec3::ZERO).dist(pick) < 1e-9); + } + }); + assert_eq!(work.joint_faces, 1, "a solve must not measure the faces again: {work:?}"); +} + /// `parts` imported files of two boxes each, every one in its own component placed away from /// the origin (as inserted parts are). fn placed_imports(parts: usize) -> Document { diff --git a/crates/doc/src/joints_edge.rs b/crates/doc/src/joints_edge.rs index afa006976..e62b90c28 100644 --- a/crates/doc/src/joints_edge.rs +++ b/crates/doc/src/joints_edge.rs @@ -50,7 +50,7 @@ fn edge_index(b: &ModelBody, name: Option<&str>, pick: Vec3) -> Option { fn face_of(b: &ModelBody, i: usize, name: Option<&str>, pick: Vec3) -> Result<(usize, Vec3, Vec3)> { let m = b.mesh(); let beside: Vec = m.edge_faces.get(i).map(|fs| fs.iter().map(|f| *f as usize).collect()).unwrap_or_default(); - let infos = b.body.faces(tol(b))?; + let infos = b.joint_faces()?; let planar = |f: usize| infos.iter().find(|x| x.index == f).and_then(|x| x.plane_normal.map(|n| (x.index, n, x.centroid, x.area))); let chosen = match name { Some(n) => { From afa4f72f7d7b8e1fc6b783f1cd02bb5143fdeec6 Mon Sep 17 00:00:00 2001 From: SilentWolf75 <134335235+SilentWolf75@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:37:55 +0000 Subject: [PATCH 38/55] Insert SVG: say why a sketch is too large (#10874) (#10880) * claim: #10874 Co-authored-by: Cursor * Insert drawing: name the sketch size cap when a file is too dense (#10874) A large SVG/DXF failed with opaque \"sketch is too large\". Say the 20000 point/curve limit and that scale alone does not reduce entity count, and refuse dense drawings before adding them. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- crates/engine/src/cmd/sketch_import.rs | 21 +++++++++++++++++++++ crates/sketch/src/model.rs | 9 ++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/sketch_import.rs b/crates/engine/src/cmd/sketch_import.rs index a8d80d332..eae00ba3d 100644 --- a/crates/engine/src/cmd/sketch_import.rs +++ b/crates/engine/src/cmd/sketch_import.rs @@ -245,6 +245,11 @@ fn insert(s: &mut Session, p: &Value, cmd: &str, svg: bool) -> Result { let v = (q - pivot) * k; Vec2::new(v.x * cos - v.y * sin, v.x * sin + v.y * cos) + off }; + // A dense SVG/DXF (a floorplan) can yield far more entities than a sketch takes; refuse + // before adding so the message names the cap (#10874). Scale alone does not shrink the count. + if geom.len() > solidcraft_sketch::MAX_POINTS { + return Err(solidcraft_sketch::SketchError::TooLarge.into()); + } let ((curves, texts), info) = edit(s, p, cmd, false, |sk, _| { let (cs, texts) = add_geometry(sk, &geom, &f, k, tol)?; Ok((ids_of(sk, &cs), texts)) @@ -371,6 +376,22 @@ mod tests { } } + /// #10874: a drawing with more entities than a sketch can hold is refused with the point + /// cap and that scale alone does not help (a floorplan SVG often hits this). + #[test] + fn a_drawing_with_too_many_entities_names_the_sketch_cap() { + let n = solidcraft_sketch::MAX_POINTS + 1; + let mut dxf = String::from("0\nSECTION\n2\nENTITIES\n"); + for i in 0..n { + dxf.push_str(&format!("0\nLINE\n10\n{i}\n20\n0\n11\n{}\n21\n1\n", i + 1)); + } + dxf.push_str("0\nENDSEC\n0\nEOF\n"); + let mut s = Session::default(); + let e = s.execute("sketch.insert_dxf", &json!({"text": dxf})).unwrap_err().to_string(); + assert!(e.contains("20000") && e.contains("scale"), "{e}"); + assert!(s.active_sketch.is_none(), "a refused insert leaves no empty sketch behind"); + } + /// #9641: an SVG with nothing SolidCraft can draw (here only an embedded picture) is refused /// with a message naming the file and saying why, not "invalid parameters … no geometry"; a /// UTF-16 SVG file inserts. diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index 3b32a4304..b696bb955 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -8,6 +8,8 @@ pub const MAX_POINTS: usize = 20_000; pub const MAX_CONSTRAINTS: usize = 40_000; /// Curves need points, so this follows the point cap. pub const MAX_CURVES: usize = MAX_POINTS; +// [`SketchError::TooLarge`]'s message names this number; keep them matched (#10874). +const _: () = assert!(MAX_POINTS == 20_000); /// Largest coordinate or dimension value (mm) a sketch accepts. pub const MAX_COORD: f64 = 1e9; @@ -37,7 +39,12 @@ pub enum SketchError { Duplicate(String), #[error("invalid value: {0}")] Invalid(String), - #[error("sketch is too large")] + /// Cap hit on points, curves or constraints ([`MAX_POINTS`], [`MAX_CURVES`], + /// [`MAX_CONSTRAINTS`]). Insert SVG/DXF of a dense drawing (a floorplan) often hits this; + /// scale alone does not reduce how many curves the file has (#10874). + #[error( + "sketch is too large (at most 20000 points or curves); simplify the drawing or split it across sketches — changing scale does not reduce how many curves it has" + )] TooLarge, } From 0b9073109666bd0f154bd7cbe31989dc46baef91 Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Mon, 2 Nov 2026 00:02:37 +0000 Subject: [PATCH 39/55] Dialogs: readable sketch selection labels (#10752) (#10770) * claim: #10752 * Fix readable sketch selection labels in dialogs (#10752) --- .../pending/dialog-selection-labels.json | 50 +++++++++++++++++ crates/ui-egui/src/dialogs.rs | 10 ++++ crates/ui-egui/src/dialogs_all_tests.rs | 53 +++++++++++++++++++ 3 files changed, 113 insertions(+) create mode 100644 assets/locales/pending/dialog-selection-labels.json diff --git a/assets/locales/pending/dialog-selection-labels.json b/assets/locales/pending/dialog-selection-labels.json new file mode 100644 index 000000000..b91596ecc --- /dev/null +++ b/assets/locales/pending/dialog-selection-labels.json @@ -0,0 +1,50 @@ +{ + "ar": { + "dialog.selection_constraint": "قيد {id}", + "dialog.selection_external_curve": "{sketch} · منحنى {id}", + "dialog.selection_midpoint": "نقطة المنتصف · {id}", + "dialog.selection_profile": "{sketch} · المقطع {number}" + }, + "de": { + "dialog.selection_constraint": "Bedingung {id}", + "dialog.selection_external_curve": "{sketch} · Kurve {id}", + "dialog.selection_midpoint": "Mittelpunkt · {id}", + "dialog.selection_profile": "{sketch} · Profil {number}" + }, + "en": { + "dialog.selection_constraint": "Constraint {id}", + "dialog.selection_external_curve": "{sketch} · curve {id}", + "dialog.selection_midpoint": "Midpoint · {id}", + "dialog.selection_profile": "{sketch} · profile {number}" + }, + "he": { + "dialog.selection_constraint": "אילוץ {id}", + "dialog.selection_external_curve": "{sketch} · עקומה {id}", + "dialog.selection_midpoint": "נקודת אמצע · {id}", + "dialog.selection_profile": "{sketch} · פרופיל {number}" + }, + "ja": { + "dialog.selection_constraint": "拘束 {id}", + "dialog.selection_external_curve": "{sketch} · 曲線 {id}", + "dialog.selection_midpoint": "中点 · {id}", + "dialog.selection_profile": "{sketch} · プロファイル {number}" + }, + "ko": { + "dialog.selection_constraint": "구속 조건 {id}", + "dialog.selection_external_curve": "{sketch} · 곡선 {id}", + "dialog.selection_midpoint": "중점 · {id}", + "dialog.selection_profile": "{sketch} · 프로파일 {number}" + }, + "vi": { + "dialog.selection_constraint": "Ràng buộc {id}", + "dialog.selection_external_curve": "{sketch} · đường cong {id}", + "dialog.selection_midpoint": "Trung điểm · {id}", + "dialog.selection_profile": "{sketch} · biên dạng {number}" + }, + "zh": { + "dialog.selection_constraint": "约束 {id}", + "dialog.selection_external_curve": "{sketch} · 曲线 {id}", + "dialog.selection_midpoint": "中点 · {id}", + "dialog.selection_profile": "{sketch} · 轮廓 {number}" + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c935ad23c..d85c08138 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2635,9 +2635,19 @@ fn occurrence_paths(s: &Session, items: &[Sel]) -> Vec> { /// the name the preferences give it. pub(crate) fn selection_label(s: &Session, names: crate::prefs::OriginPlaneNames, d: &Dialog, inp: &SelInput, item: &Sel) -> String { let axis = inp.accept == selection::AXIS_PICKS && round_axis(s, item).is_some(); + let sketch_name = + |id| s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_else(|| crate::i18n::format("browser.sketch_name", &[("number", &id.to_string())])); match item { Sel::SketchCurve { id, .. } => id.clone(), Sel::SketchPoint { id } => crate::sketch_modify_ui::point_id(s, item).unwrap_or(id).to_string(), + Sel::SketchMidpoint { id } => crate::i18n::format("dialog.selection_midpoint", &[("id", id)]), + Sel::ExternalSketchCurve { sketch, id } => { + crate::i18n::format("dialog.selection_external_curve", &[("sketch", &sketch_name(*sketch)), ("id", id)]) + } + Sel::SketchConstraint { id } => crate::i18n::format("dialog.selection_constraint", &[("id", id)]), + Sel::Profile { sketch, index } => { + crate::i18n::format("dialog.selection_profile", &[("sketch", &sketch_name(*sketch)), ("number", &index.saturating_add(1).to_string())]) + } Sel::Plane { name } => names.label(name).to_string(), Sel::Axis { name } | Sel::ConstructionPoint { name } | Sel::Body { name } => name.clone(), Sel::Face { body, index, .. } if axis => format!("{body} · face {index} axis"), diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs index 5a59b364e..6e0d5d746 100644 --- a/crates/ui-egui/src/dialogs_all_tests.rs +++ b/crates/ui-egui/src/dialogs_all_tests.rs @@ -1344,3 +1344,56 @@ fn stored_bare_numbers_edit_with_their_units() { assert_eq!(h.app.session.doc.features.len(), count, "{command}: the feature is redefined in place"); } } + +#[test] +fn dialog_profile_labels_name_the_sketch_in_coil_and_mirror() { + for command in ["solid.coil", "sketch.mirror"] { + let mut h = Harness::new(); + h.app.run("sketch.create", json!({"plane": "XY", "name": "Panel"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [40, 30]})).unwrap(); + let sketch = h.app.session.active_sketch.unwrap(); + if command == "solid.coil" { + h.app.run("sketch.finish", json!({})).unwrap(); + } + h.call("ui.view", json!({"view": "top"})); + h.call("ui.camera", json!({"target": [20, 15, 0], "distance": 100})); + h.step(&json!({"click": {"world": [20, 15, 0]}})).unwrap(); + assert_eq!(h.app.session.selection, vec![Sel::Profile { sketch, index: 0 }]); + h.app.start(command); + h.app.dialog.as_mut().unwrap().preview_enabled = false; + h.frames(3); + let d = h.app.dialog.as_ref().unwrap(); + let input = &d.inputs[0]; + assert_eq!(input.items, vec![Sel::Profile { sketch, index: 0 }]); + assert_eq!(selection_label(&h.app.session, h.app.preferences.origin_plane_names, d, input, &input.items[0]), "Panel · profile 1"); + let mut painted = false; + for clipped in &h.shapes { + crate::test_support::each_shape(&clipped.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape { + painted |= text.galley.text() == "Panel · profile 1"; + } + }); + } + assert!(painted, "{command}: the painted selection label"); + } +} + +#[test] +fn dialog_sketch_selection_labels_translate_and_keep_identifiers() { + let mut h = Harness::new(); + let sketch = h.app.run("sketch.create", json!({"plane": "XY", "name": "Panel"})).unwrap()["sketch"].as_u64().unwrap(); + let d = Dialog::for_command(&h.app, "sketch.mirror").unwrap(); + for (sel, english, german) in [ + (Sel::Profile { sketch, index: 1 }, "Panel · profile 2", "Panel · Profil 2"), + (Sel::SketchMidpoint { id: "l7".into() }, "Midpoint · l7", "Mittelpunkt · l7"), + (Sel::ExternalSketchCurve { sketch, id: "l7".into() }, "Panel · curve l7", "Panel · Kurve l7"), + (Sel::SketchConstraint { id: "k3".into() }, "Constraint k3", "Bedingung k3"), + ] { + for (language, expected) in [("en", english), ("de", german)] { + let _language = crate::i18n::scope(language); + assert_eq!(selection_label(&h.app.session, h.app.preferences.origin_plane_names, &d, &d.inputs[0], &sel), expected); + } + } + let missing = Sel::Profile { sketch: 999, index: 0 }; + assert_eq!(selection_label(&h.app.session, h.app.preferences.origin_plane_names, &d, &d.inputs[0], &missing), "Sketch999 · profile 1"); +} From cea07cbc66c09a329ec88a83f53d98d8439a26a6 Mon Sep 17 00:00:00 2001 From: semmelrinde <124386289+semmelrinde@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:02:59 +0000 Subject: [PATCH 40/55] Sketch Slice: cut at the sketch plane while a Section Analysis is on (#10705) (#10768) With a section on, Slice in the Sketch Palette lit up but the model was still cut only by the section: the viewport took the sketch's plane only when there was no section. Slice now takes it whenever it is on in the sketch being edited; the section comes back when Slice is turned off or the sketch closes. A slice is hatched as it is without a section. Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/viewport.rs | 49 +++++++++++++++++++++++++++------- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 074e2c05b..e4451ba67 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2766,22 +2766,25 @@ pub fn section_plane(app: &SolveApp) -> Option<(Vec3, Vec3)> { scratch.execute("inspect.section", &p).ok()?; return scratch.section; } - // Slice (Sketch Palette): cut the model at the plane of the sketch being edited. - if app.session.section.is_none() { - let st = crate::open_meshing::shown_world(app); - if let Some(ss) = app.session.active_sketch.and_then(|s| st.sketch(s)).filter(|ss| ss.sketch.view.slice) { - return Some((ss.plane.origin, ss.plane.normal())); - } - } - app.session.section + slice_plane(app).or(app.session.section) +} + +/// Slice (Sketch Palette): the plane of the sketch being edited, when Slice is on in it. It +/// stands in for a Section Analysis until it is turned off or the sketch closes: with the +/// section first, turning Slice on did nothing (#10705). +fn slice_plane(app: &SolveApp) -> Option<(Vec3, Vec3)> { + let id = app.session.active_sketch?; + let st = crate::open_meshing::shown_world(app); + let ss = st.sketch(id).filter(|ss| ss.sketch.view.slice)?; + Some((ss.plane.origin, ss.plane.normal())) } /// Whether the section [`section_plane`] shows has hatched cut faces: an open Section Analysis -/// dialog's Hatch option, else the section's own. +/// dialog's Hatch option, a Slice's always, else the section's own. pub fn section_hatch(app: &SolveApp) -> bool { match app.dialog.as_ref().map(|d| &d.kind) { Some(crate::dialogs::Kind::Section { hatch, .. }) => *hatch, - _ => app.session.section_hatch, + _ => app.session.section_hatch || slice_plane(app).is_some(), } } @@ -9929,6 +9932,32 @@ mod tests { assert!(!legend(&mut h)); } + #[test] + fn a_sketch_slice_cuts_at_the_sketch_while_a_section_is_on() { + // #10705: with a Section Analysis on, turning Slice on in a sketch did nothing. + let mut h = crate::scenario::Harness::new(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20,"body_name":"Block"})).unwrap(); + h.app.run("construct.plane.offset", json!({"base":"XY","offset":10,"name":"Mid"})).unwrap(); + h.app.run("sketch.create", json!({"plane":"Mid"})).unwrap(); + h.app.run("inspect.section", json!({"plane":"XZ","offset":15,"hatch":false})).unwrap(); + h.frames(2); + let across_y = |h: &crate::scenario::Harness| section_plane(&h.app).is_some_and(|(o, n)| n.y.abs() > 0.99 && (o.y.abs() - 15.0).abs() < 1e-9); + assert!(across_y(&h)); + assert!(!section_hatch(&h.app)); + h.app.run("sketch.options", json!({"slice":true})).unwrap(); + h.frames(2); + let (o, n) = section_plane(&h.app).expect("the slice"); + assert!(n.z.abs() > 0.99 && (o.z - 10.0).abs() < 1e-9, "{o:?} {n:?}"); + assert!(section_hatch(&h.app), "a slice is hatched as it is without a section"); + // Slice off, or the sketch closed: the section is back. + h.app.run("sketch.options", json!({"slice":false})).unwrap(); + assert!(across_y(&h)); + h.app.run("sketch.options", json!({"slice":true})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.frames(2); + assert!(across_y(&h)); + } + #[test] fn a_section_leaves_the_origin_planes_and_axes_whole() { // #1229: the origin planes and axes are reference geometry; the section plane cuts the From 7d86a8cfd3e8d67f86e7844cf7ce64514f88de24 Mon Sep 17 00:00:00 2001 From: rugbymauri Date: Mon, 2 Nov 2026 00:04:38 +0000 Subject: [PATCH 41/55] Sketch: dragging a constrained centre point of a centre rectangle moves it, not resizes it (#10510) (#10535) * claim: #10510 Signed-off-by: Maurizio Monticelli * Sketch: dragging a centre rectangle's constrained centre point keeps the rectangle's size A centre rectangle's centre sits on the middle of its diagonal, and a press there picked the diagonal's midpoint before the centre point. The drag then took the diagonal by its middle: with the centre free the rectangle moved along, but with the centre held (on the origin, on a line) the diagonal turned and stretched about it, and the rectangle grew or shrank with the pointer, many times its size. A drag that starts on a line's middle where a point is held by a Midpoint constraint now drags that point, as a drag that starts on the point does. A centre held on the origin stays there and the rectangle keeps its size; a centre on a line slides the whole rectangle along it; a free centre still moves the rectangle. Clicking the middle still selects the line's midpoint for constraints. Fixes #10510 Signed-off-by: Maurizio Monticelli --------- Signed-off-by: Maurizio Monticelli --- crates/ui-egui/src/sketch_drag_ui_tests.rs | 31 ++++++++++++++++++++++ crates/ui-egui/src/viewport.rs | 22 +++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/crates/ui-egui/src/sketch_drag_ui_tests.rs b/crates/ui-egui/src/sketch_drag_ui_tests.rs index a641ad0be..6b5f25b3f 100644 --- a/crates/ui-egui/src/sketch_drag_ui_tests.rs +++ b/crates/ui-egui/src/sketch_drag_ui_tests.rs @@ -461,3 +461,34 @@ fn a_freed_circle_centre_on_the_origin_drags_instead_of_the_origin() { assert!(point(&h, "c1.center").dist(Vec2::new(15.0, 10.0)) < 0.05, "{:?}", point(&h, "c1.center")); assert!(point(&h, "origin").dist(Vec2::new(0.0, 0.0)) < 1e-9); } + +/// A centre rectangle's centre held on the origin stays there when dragged, and the rectangle +/// keeps its size. The press lands on the middle of the rectangle's diagonal as well as on the +/// centre; the drag took the diagonal by its middle and turned and stretched it about the held +/// centre, resizing the rectangle (#10510). +#[test] +fn a_centre_rectangles_centre_held_on_the_origin_keeps_the_rectangle_when_dragged() { + let mut h = Harness::new(); + run(&mut h, "sketch.create", json!({"plane": "XY"})); + run(&mut h, "sketch.rectangle.center", json!({"center": [3, 2], "corner": [13, 9]})); + run(&mut h, "sketch.constraint.coincident", json!({"a": "p5", "b": "origin"})); + run(&mut h, "sketch.options", json!({"snap": false, "show_dimensions": false, "show_constraints": false})); + h.call("ui.view", json!({"view": "top"})); + h.app.cam.distance = 150.0; + h.frames(3); + let corners = ["p1", "p2", "p3", "p4"].map(|p| point(&h, p)); + assert!(point(&h, "p5").len() < 1e-9, "{:?}", point(&h, "p5")); + // A press a little off the centre, as a hand presses. + let a = screen(&mut h, 0.3, 0.2); + let b = screen(&mut h, 12.0, 8.0); + let mut path = vec![a]; + path.extend(steps(a, b, 6)); + press_and_move(&mut h, &path); + assert_eq!(h.app.viewport.point_drag.as_ref().map(|(id, _, _)| id.as_str()), Some("p5"), "grabbed the centre, not the diagonal"); + h.frames(4); + release(&mut h, b); + assert!(point(&h, "p5").len() < 1e-6, "the centre left the origin: {:?}", point(&h, "p5")); + for (p, was) in ["p1", "p2", "p3", "p4"].into_iter().zip(corners) { + assert!(point(&h, p).dist(was) < 1e-6, "{p} moved from {was:?} to {:?}", point(&h, p)); + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index e4451ba67..250f7f804 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -4817,6 +4817,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { // the text, also from the space between its letters (#8835). let own = matches!(&hit, Some(Hit::SketchPoint { sketch, .. } | Hit::SketchMidpoint { sketch, .. } | Hit::SketchCurve { sketch, .. }) if Some(*sketch) == active); let hit = if own { hit } else { crate::sketch_text_handles::grab_inside(app, &proj, a).or(hit) }; + let hit = hit.map(|hit| point_at_midpoint(app, hit)); match hit { Some(Hit::SketchPoint { sketch, id, .. }) if Some(sketch) == active => { // A point dragged with the rest of a selection slides with it, from where it @@ -5816,6 +5817,27 @@ pub(crate) fn select(app: &mut SolveApp, sel: Option, add: bool, toggle: bo /// The rest of the selected sketch geometry when the point or curve `id` is part of it (#2621): /// a drag that starts on a selected entity moves the whole selection with it. +/// A drag that starts on a line's middle where a point is held (a centre rectangle's centre on +/// its diagonal) drags that point, as a drag that starts on the point does. Dragging the line by +/// its middle instead moved its ends: with the point constrained (on the origin, on a line) the +/// line turned and stretched about it, and the rectangle round it changed size (#10510). +fn point_at_midpoint(app: &SolveApp, hit: Hit) -> Hit { + let Hit::SketchMidpoint { sketch, id, .. } = &hit else { return hit }; + let st = app.session.world_state(); + let held = st.sketch(*sketch).and_then(|ss| { + let sk = &ss.sketch; + let line = sk.curve_index(id)?; + sk.constraints.iter().filter(|c| !c.driven).find_map(|c| match c.kind { + solidcraft_engine::sketch::ConstraintKind::Midpoint { p, l } if l == line => sk.points.get(p).map(|q| (q.id.clone(), q.pos)), + _ => None, + }) + }); + match held { + Some((id, at)) => Hit::SketchPoint { sketch: *sketch, id, at }, + None => hit, + } +} + fn dragged_with(app: &SolveApp, id: &str) -> Vec { fn geometry(s: &Sel) -> Option<&str> { match s { From d68d86dae94cf363560176585614fcdb210b0fb5 Mon Sep 17 00:00:00 2001 From: Dahak Builds Date: Mon, 2 Nov 2026 00:04:41 +0000 Subject: [PATCH 42/55] Dialog form cards widen their label column for the current language (#10620) (#10646) * claim: #10620 * widen dialog form-card label columns to the measured label width (#10620) * fix compile of the grow tests * grow the card only past the label cap and tag the form scope in place (#10620) * keep scope_grow crate-internal so the gallery scan stays element-only (#10620) --------- Co-authored-by: Dahak Builds --- crates/ui-egui/src/dialogs.rs | 26 ++++++++++++------ crates/ui-egui/src/dialogs_all_tests.rs | 32 ++++++++++++++++++++++ crates/ui-egui/src/ui_kit/layout.rs | 19 ++++++++++++- crates/ui-egui/src/ui_kit/metrics.rs | 16 ++++++++++- crates/ui-egui/src/ui_kit/metrics_tests.rs | 31 +++++++++++++++++++++ crates/ui-egui/src/ui_kit/panel.rs | 17 ++++++++++-- 6 files changed, 128 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index d85c08138..c32e8665b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -3372,6 +3372,20 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let (ok_label, close_label) = action_labels(&d.kind); // What the footer's OK takes, for the check in the view's corner too (#6709). let ok_enabled = valid && !ok_label.is_empty() && app.applying.is_none(); + // #10620: the card widens to fit its widest label in the current language. The body + // publishes the extra it needs under this key each pass; the card applies it next pass, + // so the label column grows and the control column keeps its design width. Manager cards + // keep their approved fixed width. + let manager = matches!( + d.kind, + Kind::Material { .. } + | Kind::Appearance(_) + | Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. }) + | Kind::Sheet(crate::dialogs_sheet::Sm::Rules { .. }) + | Kind::Plastic(crate::dialogs_plastic::Pl::Rules { .. }) + ); + let grow_key = egui::Id::new(("sc_dialog_label_grow", raw_title)); + let label_grow = ctx.data(|data| data.get_temp::(grow_key)).unwrap_or(0.0).min((vp.width() - t.space_24 - card_width(&d)).max(0.0)); let panel = crate::ui_kit::Panel::new(&heading, egui::Id::new(("sc_dialog", title(&d.kind))), anchor, drag_bounds, side, frame) .actions(ok_label, close_label); let panel = if let Some(column) = column { @@ -3379,8 +3393,10 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } else if wide && side == crate::frame::Side::Left { let available = app.viewport.palette_rect.map_or(vp.width(), |r| (r.left() - vp.left() - t.space_8).max(0.0)); panel.width(card_width(&d).min(available)) - } else { + } else if manager { panel.width(card_width(&d)) + } else { + panel.width(card_width(&d) + label_grow).grow_label(grow_key) }; let reset_scroll = d.reset_scroll; let panel = @@ -3414,14 +3430,6 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let heading = crate::ui_kit::FeatureOptions { icon, title: label, drag_key, moved, docked, apply_label: repeatable.then_some("Apply") }; let applying = app.applying.is_some(); let mut collapsed = d.collapsed; - let manager = matches!( - d.kind, - Kind::Material { .. } - | Kind::Appearance(_) - | Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. }) - | Kind::Sheet(crate::dialogs_sheet::Sm::Rules { .. }) - | Kind::Plastic(crate::dialogs_plastic::Pl::Rules { .. }) - ); // A study/configuration owns Enter for its cells, including when folded. let cell_enter = matches!(&d.kind, Kind::Motion(k) if k.wide()) || matches!(&d.kind, Kind::Material { editor, .. } if editor.editing()); if cell_enter && collapsed { diff --git a/crates/ui-egui/src/dialogs_all_tests.rs b/crates/ui-egui/src/dialogs_all_tests.rs index 6e0d5d746..4cd548cc5 100644 --- a/crates/ui-egui/src/dialogs_all_tests.rs +++ b/crates/ui-egui/src/dialogs_all_tests.rs @@ -578,6 +578,38 @@ fn new_cards_settle_before_the_first_click_in_both_layouts() { } } +#[test] +fn the_loft_dialog_widens_its_label_column_for_the_current_language() { + // #10620: German "Anpassung an Leitkurve" (Rail Fit) clipped to "Anpassung an Leit…" in + // the fixed-width Loft card. The label column now measures the dialog's labels in the + // active language and the card widens by the same amount, so the label fits and the + // control column keeps its design width. English, whose labels fit the design, is unchanged. + let t = Tokens::get(); + let shoot = |language: &str| { + let mut h = fixture(); + h.call("ui.resize", json!({"width": 1400, "height": 950})); + h.app.preferences.language = language.into(); + h.app.dialog = Some(representative(&h, "solid.loft")); + h.frames(4); + (h, scenario::rect_of("dialog:card").unwrap(), scenario::rect_of("dialog:label:Rail Fit").unwrap()) + }; + let (h, card, label) = shoot("de"); + let (_, english_card, english_label) = shoot("en"); + assert!(card.width() > english_card.width(), "the German card widened: {card:?} vs {english_card:?}"); + assert!(label.width() > t.form_label_width * 1.6, "past the ordinary cap: {label:?}"); + assert!(english_label.width() <= t.form_label_width * 1.6, "English keeps the design's label column: {english_label:?}"); + // The drawn galley holds the whole translation: no ellipsis. + let drawn = h + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.job.text.contains("Anpassung") => Some(text.galley.job.text.to_string()), + _ => None, + }) + .expect("the Rail Fit row drew its German label"); + assert!(drawn.contains("Leitkurve") && !drawn.contains('…'), "the label is not ellipsized: {drawn:?}"); +} + #[test] fn remaining_dialogs_keep_kit_chrome_and_cancel_restores_preview() { for command in [ diff --git a/crates/ui-egui/src/ui_kit/layout.rs b/crates/ui-egui/src/ui_kit/layout.rs index d299fc7ed..a76da8b19 100644 --- a/crates/ui-egui/src/ui_kit/layout.rs +++ b/crates/ui-egui/src/ui_kit/layout.rs @@ -7,6 +7,15 @@ pub(super) const FORM: &str = "sc_dense_form"; pub(super) const LABEL: &str = "sc_form_label"; pub(super) const FIXED_LABEL: &str = "sc_fixed_label_width"; +pub(super) const GROW_LABEL: &str = "sc_grow_label_column"; + +/// A form whose card widens so its widest label fits (#10620). Each pass the form publishes, +/// under `key`, the width its label column needs beyond the design's 1.6x cap; the card's +/// owner reads that before opening the card, so the card settles one frame later. +/// Tokens: `form_label_width, font_label, dialog_label, space_4`. +pub(super) fn scope_grow(ui: &mut Ui, key: egui::Id, add: impl FnOnce(&mut Ui) -> R) -> R { + scope_inner(ui, Some(key), add) +} /// A deliberate label grid for multi-column settings, inherited by the existing shared rows. pub(crate) fn settings_form(ui: &mut Ui, label_width: f32, add: impl FnOnce(&mut Ui) -> R) -> R { @@ -17,7 +26,15 @@ pub(crate) fn settings_form(ui: &mut Ui, label_width: f32, add: impl FnOnce(& /// Mark a form without global state: children inherit this tag through their UI stack. /// Inherited form styling and label-column identity. Tokens: `space_4/8, form_gap_y, control_height, font_label, accent, selected_bg, dialog_rule, control_fill/border/radius, text`. pub(crate) fn scope(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { - ui.scope_builder(egui::UiBuilder::new().ui_stack_info(egui::UiStackInfo::default().with_tag(FORM)), |ui| { + scope_inner(ui, None, add) +} + +fn scope_inner(ui: &mut Ui, grow: Option, add: impl FnOnce(&mut Ui) -> R) -> R { + let mut info = egui::UiStackInfo::default().with_tag(FORM); + if let Some(key) = grow { + info = info.with_tag_value(GROW_LABEL, key); + } + ui.scope_builder(egui::UiBuilder::new().ui_stack_info(info), |ui| { let t = Tokens::get(); ui.spacing_mut().item_spacing = vec2(t.space_4, t.form_gap_y); ui.spacing_mut().interact_size.y = row_height(); diff --git a/crates/ui-egui/src/ui_kit/metrics.rs b/crates/ui-egui/src/ui_kit/metrics.rs index 775523829..6990ea468 100644 --- a/crates/ui-egui/src/ui_kit/metrics.rs +++ b/crates/ui-egui/src/ui_kit/metrics.rs @@ -107,7 +107,21 @@ pub(super) fn label_column(ui: &Ui, text: &str, row_width: f32) -> f32 { } None => natural, }; - (widest + t.space_4).clamp(base, base * LABEL_COLUMN_MAX).min(row_width * 0.5) + let needed = widest + t.space_4; + if let Some(&key) = ui.stack().iter().find_map(|node| node.tags().get_downcast::(super::layout::GROW_LABEL)) { + // A growing card (#10620): labels up to the ordinary 1.6x cap keep the design's card + // width; a longer label grows the column past the cap, and the extra the card must + // gain is published under `key` so the card widens by the same amount and the + // control column keeps its design width. + let extra = (needed - base * LABEL_COLUMN_MAX).max(0.0); + let previous = ui.ctx().data(|d| d.get_temp::(key)).unwrap_or(0.0); + if (extra - previous).abs() > 0.5 { + ui.ctx().request_discard("dialog label column width"); + } + ui.ctx().data_mut(|d| d.insert_temp(key, extra)); + return needed.max(base).min(row_width * 0.7); + } + needed.clamp(base, base * LABEL_COLUMN_MAX).min(row_width * 0.5) } #[cfg(test)] diff --git a/crates/ui-egui/src/ui_kit/metrics_tests.rs b/crates/ui-egui/src/ui_kit/metrics_tests.rs index 963642f9e..2ee9025a2 100644 --- a/crates/ui-egui/src/ui_kit/metrics_tests.rs +++ b/crates/ui-egui/src/ui_kit/metrics_tests.rs @@ -1,3 +1,4 @@ +use crate::theme::Tokens; use crate::ui_kit::metrics::dimension; use crate::ui_kit::test_support::*; use crate::ui_kit::*; @@ -22,6 +23,36 @@ fn non_finite_and_tiny_row_widths_are_sanitized() { } } +#[test] +fn a_growing_form_widens_past_the_cap_and_publishes_the_card_extra() { + // #10620: inside `grow_form` the label column takes the width the widest label needs, + // past the 1.6x cap an ordinary form clamps to, and the card's owner is told by how much + // the card must widen so the control column keeps its room. + let ctx = egui::Context::default(); + crate::fonts::setup_fonts(&ctx); + let t = Tokens::get(); + let key = egui::Id::new("grow-test"); + let long = "Anpassung an Leitkurve"; + let mut label = None; + for _ in 0..3 { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + ui.set_width(300.0); + scope_grow(ui, key, |ui| { + let mut value = String::new(); + row(ui, long, |ui| field(ui, &mut value)); + }); + }); + output.textures_delta.clear(); + label = scenario::rect_of(&format!("dialog:label:{long}")); + } + let label = label.unwrap(); + let measured = ctx.fonts_mut(|f| f.layout_no_wrap(long.to_owned(), egui::FontId::proportional(t.font_label), t.dialog_label)).size().x; + assert!(label.width() > t.form_label_width * 1.6, "past the ordinary cap: {label:?}"); + assert!(label.width() >= measured, "the label fits its column: {label:?} vs {measured}"); + let extra = ctx.data(|d| d.get_temp::(key)).unwrap(); + assert!((extra - (label.width() - t.form_label_width * 1.6)).abs() < 0.01, "the card grows only past the cap: {extra}"); +} + #[test] fn file_tiles_are_fixed_height_bounded_and_disabled_actions_stay_inert() { let ctx = crate::fonts::test_context(); diff --git a/crates/ui-egui/src/ui_kit/panel.rs b/crates/ui-egui/src/ui_kit/panel.rs index a686c4122..d9bd34b29 100644 --- a/crates/ui-egui/src/ui_kit/panel.rs +++ b/crates/ui-egui/src/ui_kit/panel.rs @@ -282,6 +282,7 @@ pub(crate) struct Panel<'a> { cancel: &'a str, reset_scroll: bool, joined: Option, + grow_key: Option, } pub(crate) struct WorkspaceOptions<'a> { @@ -600,6 +601,7 @@ impl<'a> Panel<'a> { cancel: "Cancel", reset_scroll: false, joined: None, + grow_key: None, } } @@ -621,6 +623,13 @@ impl<'a> Panel<'a> { self } + /// The feature card's form measures its labels and publishes the width it needs under + /// this key, so the card can widen for the current language (#10620). + pub(crate) fn grow_label(mut self, key: egui::Id) -> Self { + self.grow_key = Some(key); + self + } + /// The footer's primary and closing actions when they are not OK and Cancel. An empty `ok` /// leaves the primary action out (a card that only closes, e.g. Measure). pub(crate) fn actions(mut self, ok: &'a str, cancel: &'a str) -> Self { @@ -759,7 +768,7 @@ impl<'a> Panel<'a> { mut collapsed: Option<&mut bool>, body: impl FnOnce(&mut Ui) -> ComputeStatus, ) -> (bool, super::Action) { - super::scope(ui, |ui| { + let card = |ui: &mut Ui| { let t = Tokens::get(); let min = ui.cursor().min; let band = egui::Rect::from_min_size(min, vec2(ui.available_width(), super::header_height())); @@ -845,7 +854,11 @@ impl<'a> Panel<'a> { ); super::Container::finish_content(ui, self.positioned_frame(ui.ctx())); (close, action) - }) + }; + match self.grow_key { + Some(key) => super::scope_grow(ui, key, card), + None => super::scope(ui, card), + } } /// Palette composition retains its compact padding and whole-card scrolling on short views. From 0734616104f375c6c82adf3b86ac7e4129137c6c Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Mon, 2 Nov 2026 00:04:43 +0000 Subject: [PATCH 43/55] View cube: follow the selected projection (#10634) (#10640) * claim: #10634 * Make navigation cube follow viewport projection (#10634) --- crates/ui-egui/src/navigation_cube.rs | 126 +++++++++++++++++++++++--- crates/ui-egui/src/viewport.rs | 2 +- 2 files changed, 112 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/navigation_cube.rs b/crates/ui-egui/src/navigation_cube.rs index 7ab002301..f43c8ce22 100644 --- a/crates/ui-egui/src/navigation_cube.rs +++ b/crates/ui-egui/src/navigation_cube.rs @@ -11,10 +11,39 @@ const HALF: f64 = 40.0; // The remaining regions belong to the face, including the middle of each edge. const INSET: f64 = 0.68; +fn camera(app: &SolveApp) -> Camera { + let mut cam = app.cam; + if !crate::render_workspace::active(app) { + cam.fov = app.view_fov(); + } + cam +} + +fn inverse_focal_length(cam: &Camera) -> f64 { + // The field of view spans the whole navigator, including the margin around its cube. + let half_height = f64::from(DESIGN_SIZE) / (2.0 * HALF); + if cam.fov.is_finite() { (cam.fov.clamp(0.0, std::f64::consts::FRAC_PI_2) * 0.5).tan() / half_height } else { 0.0 } +} + fn project(cam: &Camera, v: Vec3, scale: f64) -> egui::Vec2 { - let (r, u, _) = cam.basis(); + let (r, u, b) = cam.basis(); let v = cam.from_frame(v); - vec2((v.dot(r) * scale) as f32, -(v.dot(u) * scale) as f32) + // A unit cube has its own camera, independent of model size and zoom. Place its eye + // one unit beyond the focal distance: the front face keeps its size beside the arrows. + // At the maximum 90-degree field of view the eye is still outside the cube's sphere, + // so every vertex stays in front of it. Zero fov gives the original parallel projection. + let denominator = 1.0 + inverse_focal_length(cam) * (1.0 - v.dot(b)); + vec2((v.dot(r) * scale / denominator) as f32, -(v.dot(u) * scale / denominator) as f32) +} + +/// Local projected axes at a label's centre; a direction alone has no perspective position. +fn project_direction(cam: &Camera, at: Vec3, direction: Vec3) -> egui::Vec2 { + let (r, u, b) = cam.basis(); + let inverse_focal = inverse_focal_length(cam); + let direction = cam.from_frame(direction); + let denominator = 1.0 + inverse_focal * (1.0 - cam.from_frame(at).dot(b)); + let parallel = vec2(direction.dot(r) as f32, -direction.dot(u) as f32); + (parallel + project(cam, at, 1.0) * (inverse_focal * direction.dot(b)) as f32) / denominator as f32 } fn direction_label(d: Vec3) -> String { @@ -38,16 +67,21 @@ fn facets(cam: &Camera, c: Pos2, half: f64) -> Vec { return Vec::new(); } let mut out = Vec::new(); + let inverse_focal = inverse_focal_length(cam); + let inverse_eye_distance = inverse_focal / (1.0 + inverse_focal); let mut add = |d: Vec3, normal: Vec3, mut vertices: Vec, axes: Option<(Vec3, Vec3)>| { let depth = cam.from_frame(normal).dot(cam.back()); - if depth <= 1e-5 { + // All face planes are one unit from the origin. In perspective a face must look + // toward the finite eye, not merely toward the parallel view direction. + if depth <= inverse_eye_distance + 1e-5 { return; } let centre = vertices.iter().copied().fold(Vec3::ZERO, |sum, p| sum + p) / vertices.len() as f64; - let at = c + project(cam, centre, half); + let projected_centre = project(cam, centre, half); + let at = c + projected_centre; vertices.sort_by(|a, b| { - let a = project(cam, *a - centre, half); - let b = project(cam, *b - centre, half); + let a = project(cam, *a, half) - projected_centre; + let b = project(cam, *b, half) - projected_centre; a.y.atan2(a.x).total_cmp(&b.y.atan2(b.x)) }); let vertices = Ring::new(vertices); @@ -62,7 +96,7 @@ fn facets(cam: &Camera, c: Pos2, half: f64) -> Vec { outer_edges, centre: at, label: direction_label(d), - text_axes: axes.map(|(r, u)| (project(cam, r, 1.0), -project(cam, u, 1.0))), + text_axes: axes.map(|(r, u)| (project_direction(cam, centre, r), -project_direction(cam, centre, u))), depth, }); }; @@ -115,8 +149,8 @@ fn hit(faces: &[Facet], p: Pos2) -> Option { faces.iter().enumerate().rev().find(|(_, f)| contains(&f.points, p)).map(|(i, _)| i) } -pub(super) fn drag_origin(cam: &Camera, centre: Pos2, pointer: Pos2, scale: f32) -> bool { - hit(&facets(cam, centre, HALF * f64::from(scale)), pointer).is_some() +pub(super) fn drag_origin(app: &SolveApp, centre: Pos2, pointer: Pos2, scale: f32) -> bool { + hit(&facets(&camera(app), centre, HALF * f64::from(scale)), pointer).is_some() } fn navigate(app: &mut SolveApp, action: Option<&str>, dir: Option) { @@ -188,7 +222,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { let active = orbiting || ui.rect_contains_pointer(outer); let t = Tokens::get().navigation_cube(active); crate::scenario::publish_count("navigation_cube:active", f64::from(u8::from(active))); - let faces = facets(&app.cam, c, HALF * f64::from(scale)); + let faces = facets(&camera(app), c, HALF * f64::from(scale)); let hover = ui.input(|i| i.pointer.hover_pos()).filter(|p| ui.is_enabled() && ui.rect_contains_pointer(rect) && !crate::shell::covered(app, *p)); let hovered = if orbiting { None } else { hover.and_then(|p| hit(&faces, p)) }; let painter = ui.painter_at(outer); @@ -298,6 +332,64 @@ mod tests { output } + #[test] + fn cube_projection_foreshortens_depth_only_in_perspective() { + for up in [UpAxis::Z, UpAxis::Y] { + let mut cam = Camera { up, ..Default::default() }; + cam.set_view(StandardView::Front); + let near = Vec3::new(0.5, -1.0, 0.0); + let far = Vec3::new(0.5, 1.0, 0.0); + assert_eq!(project(&cam, near, HALF), project(&cam, far, HALF)); + for fov in [0.2618, 0.6, std::f64::consts::FRAC_PI_2] { + cam.fov = fov; + let front = project(&cam, near, HALF); + let back = project(&cam, far, HALF); + assert!(back.x < front.x, "perspective must make the far edge smaller: {up:?}, {fov}"); + assert!((front.x - HALF as f32 * 0.5).abs() < 1e-4, "the front face must retain its size beside the orbit arrows"); + let focal_distance = f64::from(DESIGN_SIZE) / (2.0 * HALF * (fov * 0.5).tan()); + let ratio = focal_distance / (focal_distance + 2.0); + assert!((f64::from(back.x / front.x) - ratio).abs() < 1e-6); + } + } + } + + #[test] + fn perspective_toggle_changes_the_cube_and_its_faces_still_navigate() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.prefs", json!({"navigator_style":"cube", "look_at_anim":false})); + h.call("ui.view", json!({"view":"iso"})); + let orthographic = crate::scenario::handle_at("navigation_cube:front").unwrap(); + h.call("ui.set", json!({"perspective":true})); + let fov = camera(&h.app).fov; + assert!(fov > 0.0); + let p = crate::scenario::handle_at("navigation_cube:front").unwrap(); + assert_ne!(p, orthographic, "the drawn cube must follow the viewport's projection selection"); + h.call("ui.click", json!({"x":p.x,"y":p.y})); + assert_eq!(h.app.cam.aligned_standard_view(1e-5), Some(StandardView::Front)); + assert_eq!(camera(&h.app).fov, fov); + h.call("ui.set", json!({"autoOrthoFaces":true})); + assert_eq!(camera(&h.app).fov, 0.0, "automatic orthographic axis views also apply to the cube"); + h.call("ui.view", json!({"view":"iso"})); + assert_eq!(camera(&h.app).fov, fov); + } + + #[test] + fn perspective_cube_culls_sides_facing_away_and_ignores_model_framing() { + let cam = Camera { yaw: -0.1, pitch: 0.1, fov: 0.6, ..Default::default() }; + let faces = facets(&cam, Pos2::ZERO, HALF); + assert_eq!(faces.len(), 9, "only the front face is visible from this finite eye"); + assert!(faces.iter().all(|face| face.direction.y == -1.0)); + let points = |cam: &Camera| facets(cam, Pos2::ZERO, HALF).into_iter().flat_map(|face| face.points).collect::>(); + let expected = points(&cam); + for distance in [1e-3, 100.0, 1e12] { + assert_eq!(points(&Camera { distance, target: Vec3::new(123.0, -456.0, 789.0), ..cam }), expected); + } + let parallel = Camera { fov: 0.0, ..cam }; + for fov in [f64::NAN, f64::INFINITY, -1.0] { + assert_eq!(points(&Camera { fov, ..cam }), points(¶llel)); + } + } + #[test] fn cube_targets_are_only_six_faces_and_eight_corners_in_both_up_frames() { for up in [UpAxis::Z, UpAxis::Y] { @@ -463,12 +555,16 @@ mod tests { cam.set_view(view); for roll in [0.0, 0.7, std::f64::consts::FRAC_PI_2] { cam.roll = roll; - let faces = facets(&cam, Pos2::ZERO, HALF); - assert!(!faces.is_empty()); - for (i, face) in faces.iter().enumerate() { - assert_eq!(hit(&faces, face.centre), Some(i), "{up:?} {view:?} {roll} {}", face.label); + for fov in [0.0, 0.2618, 0.6, std::f64::consts::FRAC_PI_2] { + cam.fov = fov; + let faces = facets(&cam, Pos2::ZERO, HALF); + assert!(!faces.is_empty()); + for (i, face) in faces.iter().enumerate() { + assert_eq!(hit(&faces, face.centre), Some(i), "{up:?} {view:?} {roll} {fov} {}", face.label); + assert!(face.points.iter().all(|p| p.is_finite() && p.to_vec2().length() <= (HALF * 3.0_f64.sqrt()) as f32 + 1e-4)); + } + assert!(hit(&faces, pos2(80.0, 80.0)).is_none()); } - assert!(hit(&faces, pos2(80.0, 80.0)).is_none()); } } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 250f7f804..cb6a947ee 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -6645,7 +6645,7 @@ fn axis_view_orbit(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) -> bool { app.viewport.axis_drag = origin.filter(|p| match app.preferences.navigator_style { crate::prefs::NavigatorStyle::Axes => axis_rect(app, rect).contains(*p), crate::prefs::NavigatorStyle::Cube => { - navigation_cube::drag_origin(&app.cam, axis_center(app, rect), *p, axis_rect(app, rect).width() / navigation_cube::DESIGN_SIZE) + navigation_cube::drag_origin(app, axis_center(app, rect), *p, axis_rect(app, rect).width() / navigation_cube::DESIGN_SIZE) } }); if app.viewport.axis_drag.is_some() { From 83fe1f874fc7dc03edd6d63a91f0d878b9d60ce3 Mon Sep 17 00:00:00 2001 From: Dahak Builds Date: Mon, 2 Nov 2026 00:04:45 +0000 Subject: [PATCH 44/55] Sketch Project: keep hidden origin planes hidden in Project (#10778) (#10834) * claim: #10778 * Sketch Project: keep hidden origin planes hidden (#10778) WIP from dead worker: fix + test written, gates not yet run. --------- Co-authored-by: Dahak Builds --- crates/ui-egui/src/lib.rs | 13 ++++++++++++- crates/ui-egui/src/viewport.rs | 35 +++++++++++++++++++++++++++++++--- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 95f8f95ef..9e566db1c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2301,7 +2301,9 @@ impl SolveApp { /// Is the origin widget shown? Origin planes and axes are drawn and pickable. While a dialog /// picks a plane ([`SolveApp::picking_plane`]) the Origin is always shown, drawn through the - /// model (a plane inside a body stays visible), even when the browser hides it. + /// model (a plane inside a body stays visible), even when the browser hides it — except the + /// origin planes for Project ([`SolveApp::picking_project_geometry`], #10778), which keep a + /// hidden Origin hidden. pub fn origin_visible(&self) -> bool { self.origin_shown() || self.picking_plane() } @@ -2318,6 +2320,15 @@ impl SolveApp { self.picking_sketch_plane() || self.dialog.as_ref().is_some_and(|d| d.inputs.get(d.active).is_some_and(|i| i.accept & selection::PLANES != 0)) } + /// Is the Sketch Project dialog open, picking its geometry? Its pick takes origin planes, + /// but Project must not bring hidden origin planes back (#10778): every line a plane + /// projects, an origin axis already gives, so the planes only add noise over the geometry + /// being picked. Other dialogs that pick a plane keep the reveal ([`Self::picking_plane`], + /// #2581). + pub fn picking_project_geometry(&self) -> bool { + self.dialog.as_ref().is_some_and(|d| matches!(d.kind, dialogs::Kind::SketchProject { .. })) + } + /// The field of view the view is drawn with: the `perspective_fov` preference while the view is /// in perspective ([`Self::perspective_view`]), and 0 (parallel) otherwise. The one place the /// drawn angle is decided. diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index cb6a947ee..378688c28 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1944,11 +1944,16 @@ pub fn origin_planes(app: &SolveApp) -> Vec<(&'static str, Vec3, [Vec3; 4])> { return Vec::new(); } // While the Origin is hidden, a dialog picking a plane brings the planes back: then every - // plane; otherwise only those not hidden one by one. - let creating = !app.origin_shown() && app.picking_plane(); + // plane; otherwise only those not hidden one by one. Project is the exception (#10778): + // its pick takes planes too, but each line a plane gives, an axis already gives, so a + // hidden Origin stays hidden for it. + let reveal = !app.origin_shown() && app.picking_plane() && !app.picking_project_geometry(); + if !app.origin_shown() && !reveal { + return Vec::new(); + } origin_quads(origin_size(app.cam.half_height())) .into_iter() - .filter(|(n, _, _)| creating || !app.session.visibility.hidden_origin.iter().any(|h| h == n)) + .filter(|(n, _, _)| reveal || !app.session.visibility.hidden_origin.iter().any(|h| h == n)) .collect() } @@ -12695,6 +12700,30 @@ mod grid_plane_tests { assert!(origin_planes(&app).is_empty()); } + /// #10778: Project's pick takes origin planes, but it must not bring hidden origin planes + /// back: every line a plane projects, an origin axis already gives. The axes and point stay + /// as today; other dialogs that pick a plane keep the reveal (#2581). + #[test] + fn project_leaves_hidden_origin_planes_hidden() { + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.run("solid.box", json!({"length":40,"width":40,"height":40})).unwrap(); + app.run("sketch.create", json!({"plane": "XY"})).unwrap(); + app.set_origin_shown(false); + app.start("sketch.project"); + assert!(app.picking_project_geometry()); + assert!(app.picking_plane(), "Project's pick takes origin planes"); + assert!(origin_planes(&app).is_empty(), "Project leaves hidden origin planes hidden"); + assert!(!origin_axes(&app).is_empty(), "the origin axes stay as today"); + // Other dialogs that pick a plane keep today's reveal. + app.dialog = None; + app.start("solid.mirror"); + app.dialog.as_mut().unwrap().active = 1; + assert_eq!(origin_planes(&app).len(), 3, "Mirror still offers every origin plane"); + app.dialog = None; + app.start("sketch.create"); + assert_eq!(origin_planes(&app).len(), 3, "Create Sketch still offers every origin plane"); + } + /// Primary rolls a live preview back for reselect, but not while a manipulator is dragged /// (same gate [`show`] uses via [`preview_should_roll_back`]). #[test] From 4c4c768d5732e971d98490598c31a3b01b09e2e8 Mon Sep 17 00:00:00 2001 From: thocsmith Date: Mon, 2 Nov 2026 00:04:53 +0000 Subject: [PATCH 45/55] Cancel button on the Computing toast (#8266) (#10366) * claim: #8266 * Computing toast: a Cancel that gives up on the move (#8266) The Computing toast for a history command (marker move, undo, redo, suppress, reorder) or a delete's check computing off the window thread now has a Cancel button. It drops the job and the commands queued behind it; the design stays as it was, since a deferred command only runs for real once its evaluation is in. A feature edit applying keeps its dialog's own Cancel, so its toast shows none. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: thocsmith <193096300+thocsmith@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/deferred.rs | 30 +++++++++++++++ .../ui-egui/src/history_off_thread_tests.rs | 37 +++++++++++++++++++ crates/ui-egui/src/viewport.rs | 12 +++++- 3 files changed, 78 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/deferred.rs b/crates/ui-egui/src/deferred.rs index ab75509c7..30991ac8b 100644 --- a/crates/ui-egui/src/deferred.rs +++ b/crates/ui-egui/src/deferred.rs @@ -52,6 +52,17 @@ impl Deferred { } } +#[cfg(test)] +impl Deferred { + /// A command that never finishes computing, with the sender that keeps it so, for the tests + /// of what waits for one (the real worker would finish in a moment). + pub(crate) fn never_done(id: &str, params: Value, revision: u64) -> (Self, std::sync::mpsc::Sender>) { + let (tx, rx) = std::sync::mpsc::channel(); + let job = Deferred { done: rx, evaluated: None, started: crate::now_ms(), command: (id.to_string(), params), revision, kept: None }; + (job, tx) + } +} + /// How a command asked to run off the window thread goes. enum Start { /// It computes off the window thread. @@ -176,6 +187,25 @@ impl SolveApp { started.into_iter().flatten().reduce(f64::min) } + /// Whether the "Computing" toast can stop what it waits for (#8266): a history command or a + /// delete's check computing off the window thread. A feature edit applying has its own + /// dialog, with its own Cancel. + pub fn can_cancel_computing(&self) -> bool { + self.deferred.is_some() || self.delete_check.is_some() + } + + /// Stop waiting for the history command, and the delete check, computing off the window thread + /// (#8266), and drop the commands waiting behind them. The design is as it was before they + /// started: a command only runs for real once its evaluation is in. The worker threads run + /// to the end of what they evaluate and their results are dropped (the same as Cancel while a + /// feature is applying). + pub fn cancel_computing(&mut self) { + self.deferred = None; + self.deferred_queue.clear(); + self.delete_check = None; + self.start_after_roll = None; + } + /// Run a delete's check `commands` and carry on with `then` once their replies are in: off /// the window thread when it takes longer than the app's wait (see the module notes), /// otherwise right away. A Delete while another delete is being checked is left out. diff --git a/crates/ui-egui/src/history_off_thread_tests.rs b/crates/ui-egui/src/history_off_thread_tests.rs index 36cd0263a..60e7897fe 100644 --- a/crates/ui-egui/src/history_off_thread_tests.rs +++ b/crates/ui-egui/src/history_off_thread_tests.rs @@ -209,6 +209,43 @@ fn a_marker_moved_again_replaces_the_move_still_waiting() { assert_eq!(marker(&h), None, "where the drag ended: the end of the history"); } +/// The "Computing" toast has a Cancel (#8266): it gives up on a marker move that takes too long, and +/// on the moves waiting behind it, and the design stays as it was. +#[test] +fn cancel_on_the_computing_toast_gives_up_on_the_move() { + let mut h = block_boss_hole(); + // A move that does not finish, with another waiting behind it. + let (job, _keep) = crate::deferred::Deferred::never_done("timeline.roll_to", json!({"position": 1}), h.app.session.revision); + h.app.deferred = Some(job); + h.app.deferred_queue.push(("timeline.roll_to".into(), json!({"position": 2}))); + h.frames(2); + let toast = crate::scenario::rect_of("toast:computing").expect("the computing toast"); + let cancel = crate::scenario::handle_at("toast:computing:cancel").expect("its Cancel"); + assert!(toast.contains(cancel), "{cancel:?} in {toast:?}"); + assert!(h.widget("Cancel").is_some(), "Cancel has an accessible name"); + h.step(&json!({"click": {"handle": "toast:computing:cancel"}})).unwrap(); + h.frames(2); + assert!(h.app.deferred.is_none() && h.app.deferred_queue.is_empty(), "nothing computes or waits"); + assert!(h.app.computing_since().is_none()); + assert!(crate::scenario::rect_of("toast:computing").is_none(), "the toast is gone"); + assert_eq!(marker(&h), None, "the marker stays where it was"); + // And the history moves again afterwards. + h.app.run_heavy("timeline.roll_to", json!({"position": 1})).unwrap(); + until_settled(&mut h); + assert_eq!(marker(&h), Some(1)); +} + +/// A feature edit applying has the dialog's own Cancel, so its toast has none. +#[test] +fn the_computing_toast_has_no_cancel_for_what_cannot_be_given_up() { + let mut h = block_boss_hole(); + assert!(!h.app.can_cancel_computing(), "nothing computes"); + h.app.run_heavy("timeline.roll_to", json!({"position": 1})).unwrap(); + assert!(h.app.can_cancel_computing(), "a move can be given up"); + until_settled(&mut h); + assert!(!h.app.can_cancel_computing()); +} + #[test] fn undo_computes_off_the_window_thread() { let mut h = block_boss_hole(); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 378688c28..74e69eb76 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -5348,7 +5348,17 @@ pub(crate) fn transient_messages(app: &mut SolveApp, ui: &egui::Ui, viewport: Re if let Some(since) = app.computing_since() { let seconds = ((crate::now_ms() - since) / 1000.0).floor().max(0.0); let text = crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))]); - if let Some(r) = paint_toast(ui, free, text, false, true) { + // A history command or a delete's check can be given up on (#8266); a feature edit + // applying has the dialog's Cancel instead. + let cancel = app.tr_label("Cancel").to_string(); + let actions: Vec<(&str, ToastKind)> = if app.can_cancel_computing() { vec![(cancel.as_str(), ToastKind::Secondary)] } else { Vec::new() }; + if let Some((r, clicked, buttons)) = paint_toast_with(ui, free, text, ToastLead::Spinner, &actions) { + if let Some(button) = buttons.first() { + crate::scenario::publish_handle("toast:computing:cancel", button.center()); + } + if clicked == Some(0) { + app.cancel_computing(); + } obstacles.push(r); crate::scenario::publish_rect("toast:computing", r); if app.status.is_none() { From 9e30ff58782c93287f56a949a47d65b1f3001df9 Mon Sep 17 00:00:00 2001 From: Homero Thompson Date: Mon, 2 Nov 2026 00:05:09 +0000 Subject: [PATCH 46/55] fix(#5505): a zero length dimension keeps constraining the sketch (#10790) The residual of a length dimension is the magnitude of the distance between the line's two ends. At zero the magnitude has no derivative, so the rank analysis read the constraint as if it were not there and the sketch reported a degree of freedom that was not there. At zero the two ends of the line meet, so the residual says it with the vector between them, the way a coincidence does. That is the treatment a distance of zero already gets (upstream #4397); the length family was left out of it. Regression test: crates/sketch/src/tests.rs, zero_length_keeps_the_line_constrained. Co-authored-by: Homero Thompson --- crates/sketch/src/solver.rs | 7 +++++++ crates/sketch/src/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/crates/sketch/src/solver.rs b/crates/sketch/src/solver.rs index 8f74c2887..87213765d 100644 --- a/crates/sketch/src/solver.rs +++ b/crates/sketch/src/solver.rs @@ -609,6 +609,13 @@ fn residuals(s: &State, k: &ConstraintKind, out: &mut Vec) { LineCircleDistance { l, c, value, inside } => out.push(s.line_circle_gap(l, c, inside) - value), PointCircleDistance { p, c, value, inside } => out.push(s.point_circle_gap(p, c, inside) - value), CircleCircleDistance { a, b, value, circles } => out.push(s.circle_circle_gap(a, b, circles) - value), + // A length within convergence tolerance of zero means the line's two ends meet: + // the component rows keep both directions constrained even when they do, the way a + // coincidence does (the same treatment a distance of zero gets above). + Length { l, value } if value.abs() <= TOL => { + let (a, b) = s.line(l); + out.extend([b.x - a.x, b.y - a.y]); + } Length { l, value } => { let (a, b) = s.line(l); out.push(a.dist(b) - value); diff --git a/crates/sketch/src/tests.rs b/crates/sketch/src/tests.rs index 26c693344..feaa87cad 100644 --- a/crates/sketch/src/tests.rs +++ b/crates/sketch/src/tests.rs @@ -210,6 +210,27 @@ fn zero_distance_edits_preserve_dimension_rank() { } } +/// A length dimension of zero still constrains the sketch: the two ends of the line meet, and +/// the dimension holds them together instead of leaving a degree of freedom behind (#5505). +#[test] +fn zero_length_keeps_the_line_constrained() { + for seed in [false, true] { + seeded(seed, || { + let mut sk = Sketch::new(); + let a = sk.add_point(v(0.0, 0.0), None).unwrap(); + let b = sk.add_point(v(10.0, 0.0), None).unwrap(); + let l = sk.add_line_pts(a, b, None).unwrap(); + sk.add_constraint(ConstraintKind::Fix { p: a }, None).unwrap(); + let id = sk.add_constraint(ConstraintKind::Length { l, value: 0.0 }, None).unwrap(); + let report = solve(&mut sk); + assert!(report.ok(), "{report:?}"); + assert_eq!(report.dof, 0, "a zero length holds the line's ends together: {report:?}"); + assert!(!report.redundant.contains(&id), "a zero length is not redundant: {report:?}"); + assert!(sk.point(b).unwrap().dist(v(0.0, 0.0)) < 1e-6, "{:?}", sk.point(b)); + }); + } +} + #[test] fn under_constrained_reports_dof() { let mut sk = Sketch::new(); From 88dbda42a7ea5d26da0ea7cb12d53faf1f48089c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:31:12 +0000 Subject: [PATCH 47/55] Regenerate generated files and fold pending files [skip ci] --- assets/locales/ar.json | 4 ++ assets/locales/de.json | 4 ++ assets/locales/en.json | 4 ++ assets/locales/he.json | 4 ++ assets/locales/ja.json | 4 ++ assets/locales/ko.json | 4 ++ .../pending/dialog-selection-labels.json | 50 ------------------- assets/locales/vi.json | 4 ++ assets/locales/zh.json | 4 ++ 9 files changed, 32 insertions(+), 50 deletions(-) delete mode 100644 assets/locales/pending/dialog-selection-labels.json diff --git a/assets/locales/ar.json b/assets/locales/ar.json index e95a72284..7cd962526 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -1370,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "اختر أجسامًا أو ميزات: الرسم ليس أيًّا منهما. كرّر منحنياته بأداة النمط أو المرآة داخل الرسم، أو ابثقه أولًا.", "dialog.select": "↖ تحديد", "dialog.selected_count": "↖ {count} محدد", + "dialog.selection_constraint": "قيد {id}", + "dialog.selection_external_curve": "{sketch} · منحنى {id}", "dialog.selection_guidance": "حدد مُدخلًا لتغييره. انقر على العناصر المحددة لإزالتها؛ Ctrl/Cmd مع النقر يبدّل تحديدها أيضًا. راجع المعاينة ثم اضغط موافق.", + "dialog.selection_midpoint": "نقطة المنتصف · {id}", + "dialog.selection_profile": "{sketch} · المقطع {number}", "dialog.selection_step": "{step} من {total}: حدد {input}", "dialog.step": "الخطوة", "document.changed_on_disk": "تغيّر {name} على القرص", diff --git a/assets/locales/de.json b/assets/locales/de.json index 84143597e..48c9a7026 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -1367,7 +1367,11 @@ "dialog.pattern_sketch_not_object": "Körper oder Funktionen wählen: Eine Skizze ist keines von beiden. Ihre Kurven mit Muster oder Spiegeln in der Skizze wiederholen oder sie zuerst extrudieren.", "dialog.select": "↖ Auswählen", "dialog.selected_count": "↖ {count} ausgewählt", + "dialog.selection_constraint": "Bedingung {id}", + "dialog.selection_external_curve": "{sketch} · Kurve {id}", "dialog.selection_guidance": "Wählen Sie eine Eingabe aus, um sie zu ändern. Klicken Sie auf ausgewählte Objekte, um sie zu entfernen; Strg/Cmd-Klick schaltet sie ebenfalls um. Prüfen Sie die Vorschau und drücken Sie dann OK.", + "dialog.selection_midpoint": "Mittelpunkt · {id}", + "dialog.selection_profile": "{sketch} · Profil {number}", "dialog.selection_step": "{step} von {total}: {input} auswählen", "dialog.step": "Schritt", "document.changed_on_disk": "{name} wurde auf dem Datenträger geändert", diff --git a/assets/locales/en.json b/assets/locales/en.json index a6f85f3f0..a5bbeaec8 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -1370,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "Pick bodies or features: a sketch is neither. Repeat its curves with the sketch's own Pattern or Mirror, or extrude it first.", "dialog.select": "↖ Select", "dialog.selected_count": "↖ {count} selected", + "dialog.selection_constraint": "Constraint {id}", + "dialog.selection_external_curve": "{sketch} · curve {id}", "dialog.selection_guidance": "Select an input to change it. Click selected objects to remove them; Ctrl/Cmd-click also toggles them. Review the preview, then press OK.", + "dialog.selection_midpoint": "Midpoint · {id}", + "dialog.selection_profile": "{sketch} · profile {number}", "dialog.selection_step": "{step} of {total}: Select {input}", "dialog.step": "Step", "document.changed_on_disk": "{name} changed on disk", diff --git a/assets/locales/he.json b/assets/locales/he.json index c779c609c..bfe5cb53a 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -1370,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "בחרו גופים או פיצ'רים: סקיצה אינה אף אחד מהם. חזרו על העקומות שלה בעזרת המערך או השיקוף של הסקיצה עצמה, או בצעו לה שליפה קודם.", "dialog.select": "↖ בחירה", "dialog.selected_count": "↖ {count} נבחרו", + "dialog.selection_constraint": "אילוץ {id}", + "dialog.selection_external_curve": "{sketch} · עקומה {id}", "dialog.selection_guidance": "יש לבחור קלט כדי לשנות אותו. לחיצה על אובייקט שנבחר מסירה אותו; גם Ctrl/Cmd+לחיצה מחליפה את מצבו. לאחר בדיקת התצוגה המקדימה יש ללחוץ על אישור.", + "dialog.selection_midpoint": "נקודת אמצע · {id}", + "dialog.selection_profile": "{sketch} · פרופיל {number}", "dialog.selection_step": "{step} מתוך {total}: בחירת {input}", "dialog.step": "שלב", "document.changed_on_disk": "{name} השתנה בדיסק", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index ce2d53ded..47a1cafb3 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -1370,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "ボディかフィーチャーを選んでください。スケッチはどちらでもありません。曲線はスケッチ内のパターンかミラーで繰り返すか、先に押し出してください。", "dialog.select": "↖ 選択", "dialog.selected_count": "↖ {count} 個選択中", + "dialog.selection_constraint": "拘束 {id}", + "dialog.selection_external_curve": "{sketch} · 曲線 {id}", "dialog.selection_guidance": "入力欄を選んで変更します。選択済みのオブジェクトをクリックすると解除できます。Ctrl/Cmd を押しながらクリックしても切り替えられます。プレビューを確認してから OK を押してください。", + "dialog.selection_midpoint": "中点 · {id}", + "dialog.selection_profile": "{sketch} · プロファイル {number}", "dialog.selection_step": "{total} ステップ中 {step}: {input} を選択", "dialog.step": "ステップ", "document.changed_on_disk": "{name} がディスク上で変更されました", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 80a3ec9e5..3f6b3ecbc 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -1174,7 +1174,11 @@ "dialog.pattern_sketch_not_object": "바디나 피처를 선택하세요. 스케치는 둘 다 아닙니다. 곡선은 스케치 안의 패턴이나 대칭 복사로 반복하거나, 먼저 돌출하세요.", "dialog.select": "↖ 선택", "dialog.selected_count": "↖ {count}개 선택됨", + "dialog.selection_constraint": "구속 조건 {id}", + "dialog.selection_external_curve": "{sketch} · 곡선 {id}", "dialog.selection_guidance": "변경할 입력을 선택하세요. 선택한 객체를 클릭하면 선택이 해제되며, Ctrl/Cmd를 누른 채 클릭해도 전환됩니다. 미리 보기를 확인한 다음 확인을 누르세요.", + "dialog.selection_midpoint": "중점 · {id}", + "dialog.selection_profile": "{sketch} · 프로파일 {number}", "dialog.selection_step": "{step}/{total} 단계: {input} 선택", "dialog.step": "단계", "document.save_changes": "{name}의 변경 사항을 저장하시겠습니까?", diff --git a/assets/locales/pending/dialog-selection-labels.json b/assets/locales/pending/dialog-selection-labels.json deleted file mode 100644 index b91596ecc..000000000 --- a/assets/locales/pending/dialog-selection-labels.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "ar": { - "dialog.selection_constraint": "قيد {id}", - "dialog.selection_external_curve": "{sketch} · منحنى {id}", - "dialog.selection_midpoint": "نقطة المنتصف · {id}", - "dialog.selection_profile": "{sketch} · المقطع {number}" - }, - "de": { - "dialog.selection_constraint": "Bedingung {id}", - "dialog.selection_external_curve": "{sketch} · Kurve {id}", - "dialog.selection_midpoint": "Mittelpunkt · {id}", - "dialog.selection_profile": "{sketch} · Profil {number}" - }, - "en": { - "dialog.selection_constraint": "Constraint {id}", - "dialog.selection_external_curve": "{sketch} · curve {id}", - "dialog.selection_midpoint": "Midpoint · {id}", - "dialog.selection_profile": "{sketch} · profile {number}" - }, - "he": { - "dialog.selection_constraint": "אילוץ {id}", - "dialog.selection_external_curve": "{sketch} · עקומה {id}", - "dialog.selection_midpoint": "נקודת אמצע · {id}", - "dialog.selection_profile": "{sketch} · פרופיל {number}" - }, - "ja": { - "dialog.selection_constraint": "拘束 {id}", - "dialog.selection_external_curve": "{sketch} · 曲線 {id}", - "dialog.selection_midpoint": "中点 · {id}", - "dialog.selection_profile": "{sketch} · プロファイル {number}" - }, - "ko": { - "dialog.selection_constraint": "구속 조건 {id}", - "dialog.selection_external_curve": "{sketch} · 곡선 {id}", - "dialog.selection_midpoint": "중점 · {id}", - "dialog.selection_profile": "{sketch} · 프로파일 {number}" - }, - "vi": { - "dialog.selection_constraint": "Ràng buộc {id}", - "dialog.selection_external_curve": "{sketch} · đường cong {id}", - "dialog.selection_midpoint": "Trung điểm · {id}", - "dialog.selection_profile": "{sketch} · biên dạng {number}" - }, - "zh": { - "dialog.selection_constraint": "约束 {id}", - "dialog.selection_external_curve": "{sketch} · 曲线 {id}", - "dialog.selection_midpoint": "中点 · {id}", - "dialog.selection_profile": "{sketch} · 轮廓 {number}" - } -} diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 14076240b..dde6422ba 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -1370,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "Hãy chọn thân khối hoặc tính năng: bản phác thảo không phải là cả hai. Lặp lại các đường cong của nó bằng Mảng hoặc Lấy đối xứng trong chính bản phác thảo, hoặc đùn khối nó trước.", "dialog.select": "↖ Chọn", "dialog.selected_count": "↖ {count} đã chọn", + "dialog.selection_constraint": "Ràng buộc {id}", + "dialog.selection_external_curve": "{sketch} · đường cong {id}", "dialog.selection_guidance": "Chọn một mục đầu vào để thay đổi. Nhấp vào đối tượng đã chọn để bỏ chọn; Ctrl/Cmd-nhấp để bật/tắt chọn. Xem trước kết quả, sau đó nhấn OK.", + "dialog.selection_midpoint": "Trung điểm · {id}", + "dialog.selection_profile": "{sketch} · biên dạng {number}", "dialog.selection_step": "{step} / {total}: Chọn {input}", "dialog.step": "Bước", "document.changed_on_disk": "{name} đã thay đổi trên đĩa", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 44e899873..030b0c79c 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -1370,7 +1370,11 @@ "dialog.pattern_sketch_not_object": "请选择实体或特征:草图两者都不是。请用草图自身的阵列或镜像重复其曲线,或先将其拉伸。", "dialog.select": "↖ 选择", "dialog.selected_count": "↖ 已选择 {count} 个", + "dialog.selection_constraint": "约束 {id}", + "dialog.selection_external_curve": "{sketch} · 曲线 {id}", "dialog.selection_guidance": "选择输入项进行修改。点击已选对象可取消选择;按住 Ctrl/Cmd 点击也可切换选择。检查预览后,再按“确定”。", + "dialog.selection_midpoint": "中点 · {id}", + "dialog.selection_profile": "{sketch} · 轮廓 {number}", "dialog.selection_step": "第 {step} 步,共 {total} 步:选择{input}", "dialog.step": "步骤", "document.changed_on_disk": "{name} 已在磁盘上更改", From eac14256619025c99e890662681f9e001a1c70d8 Mon Sep 17 00:00:00 2001 From: semmelrinde <124386289+semmelrinde@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:06:43 +0000 Subject: [PATCH 48/55] Hole: a face name shared by two bodies is no split face (#10699) (#10872) * Face names: one name on two bodies is no split face (#10699) A hole placed on the top of one of two bodies an extrude made, or on a piece of a split body, warned "face `F2:top` was split; using the piece nearest the picked point": the face name is on both bodies, and any name found more than once counted as split. A name on several bodies, one face on each, now finds the face the point lies on without the note; pieces on one body, or a point on none of them, still say split. Co-Authored-By: Claude Opus 5.5 * Hole: look for a face name shared by two bodies on the body the point is on (#10699) The lookup over every body counts a name on several bodies as split on purpose (a copy's face is not a piece of the source's, see `the_same_face_on_a_copy_is_not_a_piece_of_the_named_bodys_face`), so the first change, which made it unique there, is undone. A hole whose face name is found split while its point lies on one of those faces now looks again on that body alone: one face of the name there is the face, whole; pieces on that body still say split. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/doc/src/eval.rs | 12 +++++++++++- crates/engine/src/face_name_tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 6f3b328e9..f16456499 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -6676,7 +6676,17 @@ fn with_named_face_points(doc: &Document, state: &ModelState, f: &Feature) -> Op if n.is_empty() { continue; } - match crate::name_lookup::locate_face_on_body(&fst, f.kind.face_body(), n, *p) { + let hit = crate::name_lookup::locate_face_on_body(&fst, f.kind.face_body(), n, *p); + // A hole on one of two bodies with the same face name (two bodies of one extrude, the + // pieces of a split body) is on that body's face, whole: the name is not split there + // unless that body has pieces of it too (#10699). + let hit = match hit { + Some(h) if hole_axis.is_some() && h.split && h.on_point => { + fst.bodies.get(h.body).and_then(|b| crate::name_lookup::locate_face_on_body(&fst, Some(&b.name), n, *p)).or(Some(h)) + } + other => other, + }; + match hit { Some(hit) => { if let Some(note) = hit.note(n) { notes.push(note); diff --git a/crates/engine/src/face_name_tests.rs b/crates/engine/src/face_name_tests.rs index e2e5b9b13..946907640 100644 --- a/crates/engine/src/face_name_tests.rs +++ b/crates/engine/src/face_name_tests.rs @@ -240,3 +240,28 @@ fn replace_face_takes_the_face_by_name() { // A's top moves up to B's, 15 high: 10 x 10 x 15. assert!((volume(&mut s, "A") - 1500.0).abs() < 1e-6, "{}", volume(&mut s, "A")); } + +/// A face name on two bodies, each with one such face (two bodies one extrude made, the pieces of +/// a split body), is not a split face: a hole placed on one of them gives no warning (#10699). +#[test] +fn a_face_name_on_two_bodies_is_no_split_face() { + let said = |s: &Session, feature: &str| { + let r = s.model.result(s.doc.find_feature(feature).unwrap().id).unwrap(); + format!("{}{}", r.error.clone().unwrap_or_default(), r.warning.clone().unwrap_or_default()) + }; + let mut s = Session::default(); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [10, 10]})); + run(&mut s, "sketch.rectangle.two_point", json!({"p0": [14, 0], "p1": [24, 10]})); + run(&mut s, "sketch.finish", json!({})); + run(&mut s, "solid.extrude", json!({"distance": 10, "operation": "new"})); + run(&mut s, "solid.hole", json!({"position": [5, 5, 10], "diameter": 5, "depth": 5, "name": "Hole1"})); + assert_eq!(said(&s, "Hole1"), ""); + assert!((volume(&mut s, "Body1") - (1000.0 - PI * 2.5 * 2.5 * 5.0)).abs() < 0.1); + assert!((volume(&mut s, "Body2") - 1000.0).abs() < 1e-6); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 10})); + run(&mut s, "solid.split_body", json!({"body": "Body1", "plane": {"origin": [20, 0, 0], "normal": [1, 0, 0]}})); + run(&mut s, "solid.hole", json!({"position": [30, 10, 10], "diameter": 5, "name": "Hole1", "targets": ["Body1"]})); + assert_eq!(said(&s, "Hole1"), ""); +} From 2b9261050f070fe8f47feb0b41d1523ec2267540 Mon Sep 17 00:00:00 2001 From: Dahak Builds Date: Mon, 2 Nov 2026 00:06:51 +0000 Subject: [PATCH 49/55] Sketch: stop tying expression-placed points to the origin with an automatic Coincident (#10703) (#10722) * claim: #10703 * Sketch: do not tie expression-placed points to the origin with an automatic Coincident A point whose coordinates are parameter expressions follows those expressions. When they came to 0 at draw time the point landed on the origin and connect_points tied it there with a Coincident, exactly like a snapped click; the next parameter change then conflicted with the tie. connect_points now skips points that carry exprs; plain-number points keep the snap. --------- Co-authored-by: Dahak Builds --- crates/engine/src/cmd/sketch.rs | 6 +++ .../engine/src/cmd/sketch_point_expr_tests.rs | 47 +++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs index 59e6c5992..df826210a 100644 --- a/crates/engine/src/cmd/sketch.rs +++ b/crates/engine/src/cmd/sketch.rs @@ -472,6 +472,9 @@ const CONNECT_TOL: f64 = 1e-6; /// New points (index `first` on) that land on an existing point, the origin included, get a /// coincident constraint to it, as when a click snaps there; `connect: false` leaves them free. +/// A point placed by parameter expressions is never tied: it follows its expressions, and a +/// Coincident to where the expressions happened to come to at draw time conflicts with the +/// next parameter change (#10703). fn connect_points(sk: &mut Sketch, first: usize, p: &Value) -> Result> { if !bool_(p, "connect").unwrap_or(true) { return Ok(Vec::new()); @@ -481,6 +484,9 @@ fn connect_points(sk: &mut Sketch, first: usize, p: &Value) -> Result Date: Mon, 2 Nov 2026 00:06:59 +0000 Subject: [PATCH 50/55] Construction planes: refuse duplicate feature names (#10707) (#10743) * claim: #10707 * Fix construction plane name collisions (#10707) --- crates/doc/src/document.rs | 10 ++++-- crates/doc/src/tests.rs | 22 +++++++++++++ crates/engine/src/cmd/edit.rs | 5 +++ crates/engine/src/construct_tests.rs | 49 ++++++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 51c2fb760..f48f083b8 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -3765,12 +3765,18 @@ impl Document { } else { 0 }; - let id = self.next_id.max(1); - self.next_id = id.checked_add(1).ok_or_else(|| DocError::Invalid("too many items in the design".into()))?; let name = match name { Some(n) if !n.trim().is_empty() => n.trim().to_string(), _ => self.unique_name(kind.base_name()), }; + // Plane references share the feature namespace. A duplicate would silently select + // the first feature. Other shared names (a sketch and its extrude) remain supported. + let is_plane = matches!(kind, FeatureKind::ConstructionPlane { .. }); + if self.features.iter().any(|f| f.name == name && (is_plane || matches!(f.kind, FeatureKind::ConstructionPlane { .. }))) { + return Err(DocError::Invalid(format!("another feature is called `{name}`"))); + } + let id = self.next_id.max(1); + self.next_id = id.checked_add(1).ok_or_else(|| DocError::Invalid("too many items in the design".into()))?; let f = Feature { id, name, diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 263889763..3141559b6 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -668,6 +668,28 @@ fn new_names_take_the_first_free_number() { assert_eq!(name(&doc, next), names[0], "the first freed number is taken again"); } +#[test] +fn construction_plane_name_collisions_leave_the_document_unchanged() { + let plane = || FeatureKind::ConstructionPlane { plane: PlaneRef::Origin { name: "XY".into() } }; + let sketch = || FeatureKind::Sketch { plane: PlaneRef::Origin { name: "XY".into() }, sketch: Sketch::new() }; + for (first, second) in [(plane(), plane()), (plane(), sketch()), (sketch(), plane())] { + let mut doc = Document::new("names"); + let id = doc.add_feature(first, Some("Mid")).unwrap(); + // A suppressed feature beyond the marker still owns its name. + doc.feature_mut(id).unwrap().suppressed = true; + doc.marker = Some(0); + let before = doc.clone(); + for name in ["Mid", " Mid "] { + let error = doc.add_feature(second.clone(), Some(name)).unwrap_err().to_string(); + assert!(error.contains("another feature is called `Mid`"), "{error}"); + assert_eq!(doc, before, "a refused name must not consume an id or change the timeline"); + } + let other = doc.add_feature(second, Some("Upper")).unwrap(); + assert_eq!(doc.feature(other).unwrap().name, "Upper"); + assert_eq!(other, before.next_id); + } +} + #[test] fn empty_boolean_targets_name_overlapping_component() { for (operation, offset) in [(Operation::Cut, 0.0), (Operation::Intersect, 0.0), (Operation::Cut, 40.0)] { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index bc4ef7d23..188684e1a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1737,6 +1737,11 @@ fn redefine(s: &mut Session, p: &Value) -> Result { } trial.doc_mut().marker = Some(idx + 1); trial.refresh(); + // The edited feature keeps its name. Its temporary replacement needs a fresh one while + // the original remains in the trial as a placeholder (including construction planes). + if let Some(parameters) = params.as_object_mut() { + parameters.remove("name"); + } let r = spec.run_nested(&mut trial, ¶ms)?; let made = r.get("feature").and_then(Value::as_u64).ok_or_else(|| bad(cmd, format!("`{cid}` did not make a feature")))?; let mut new = trial.doc.feature(made).cloned().ok_or_else(|| bad(cmd, format!("`{cid}` did not make a feature")))?; diff --git a/crates/engine/src/construct_tests.rs b/crates/engine/src/construct_tests.rs index 471948b8c..f8fc8b401 100644 --- a/crates/engine/src/construct_tests.rs +++ b/crates/engine/src/construct_tests.rs @@ -43,6 +43,55 @@ fn plane(s: &Session, name: &str) -> Plane { construction_planes(s).into_iter().find(|p| p.1 == name).map(|p| p.2).unwrap_or_else(|| panic!("no plane {name}")) } +#[test] +fn construction_plane_names_cannot_be_reused_by_new_features() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 5, "body_name": "Block"})); + run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 10, "name": "Mid"})); + let before = s.doc.clone(); + for (command, params) in [ + ("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Mid"})), + ("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": " Mid "})), + ("sketch.create", json!({"plane": "XY", "name": "Mid"})), + ("solid.box", json!({"length": 1, "width": 1, "height": 1, "name": "Mid"})), + ("construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Box1"})), + ] { + let error = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(error.contains("another feature is called"), "{command}: {error}"); + assert_eq!(s.doc, before, "{command}: a refused creation changes nothing"); + } + run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 20, "name": "Upper"})); + run(&mut s, "solid.mirror", json!({"bodies": ["Block"], "plane": "Upper"})); + let measured = run(&mut s, "inspect.measure", json!({})); + let mirrored = measured["bodies"].as_array().unwrap().iter().find(|b| b["name"] == "Block (2)").unwrap(); + assert_eq!(mirrored["bbox"]["min"][2], 35.0); + assert_eq!(mirrored["bbox"]["max"][2], 40.0); +} + +#[test] +fn redefining_a_construction_plane_keeps_its_existing_name() { + let mut s = Session::default(); + let id = run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 10, "name": "Mid"}))["feature"].as_u64().unwrap(); + run(&mut s, "sketch.create", json!({"plane": "Mid", "name": "Profile"})); + run(&mut s, "sketch.finish", json!({})); + run( + &mut s, + "timeline.redefine", + json!({"feature": id, "command": "construct.plane.offset", "params": {"base": "XY", "offset": 20, "name": "Mid"}}), + ); + assert_eq!(s.doc.feature(id).unwrap().name, "Mid"); + assert_eq!(s.doc.features.len(), 2); + assert!(near(plane(&s, "Mid").origin, Vec3::new(0.0, 0.0, 20.0))); + run(&mut s, "edit.undo", json!({})); + assert!(near(plane(&s, "Mid").origin, Vec3::new(0.0, 0.0, 10.0))); + run(&mut s, "edit.redo", json!({})); + let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap()); + reopened.refresh(); + assert_eq!(reopened.doc.feature(id).unwrap().name, "Mid"); + assert!(near(plane(&reopened, "Mid").origin, Vec3::new(0.0, 0.0, 20.0))); + assert!(reopened.model.results.iter().all(|r| r.error.is_none())); +} + #[test] fn renamed_construction_references_survive_edits_and_reopening() { let mut s = Session::default(); From afe06a1a3d545158d4203ac245e3238abc51dd66 Mon Sep 17 00:00:00 2001 From: Colin Faulkingham Date: Mon, 2 Nov 2026 00:07:29 +0000 Subject: [PATCH 51/55] Edit Joint: show components for point and frame origins (#7749) (#10838) * claim: #7749 * fix(ui): show components for point and frame joint origins --- crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/dialogs_assembly.rs | 15 ++++- crates/ui-egui/src/dialogs_assembly_tests.rs | 66 ++++++++++++++++++++ 3 files changed, 80 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c32e8665b..39bc40ba0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2660,6 +2660,7 @@ pub(crate) fn selection_label(s: &Session, names: crate::prefs::OriginPlaneNames // A point of the model: a vertex, or the centre a round edge stands for. Sel::Vertex { body, .. } if !body.is_empty() => format!("{body} · point"), Sel::Feature { id } => s.doc.feature(*id).map(|f| f.name.clone()).unwrap_or_else(|| format!("Feature {id}")), + Sel::Occurrence { path } if path.is_empty() => s.doc.name.clone(), Sel::Occurrence { path } => s.occurrence_placement(path).map(|p| p.name).unwrap_or_else(|_| "Component".into()), Sel::Vertex { body, point } if body.is_empty() => { let state = s.world_state(); diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 845cbe9d7..22e52c9ec 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -333,13 +333,24 @@ fn side_inputs() -> Vec { /// The pick a joint side shows in the side inputs: the face or edge of its own occurrence that /// the side's snap names (the piece nearest its pick, when the name has several), else the face -/// or edge nearest the pick. A point or frame side names no face: None. +/// or edge nearest the pick. A point or frame side names no face, so it shows its component. fn side_pick(app: &SolveApp, o: &JointOrigin) -> Option { let s = &app.session; let (pick, face, edge) = match &o.snap { Snap::FaceCenter { pick, face, .. } | Snap::CircleCenter { pick, face, .. } => (*pick, face.as_deref(), None), Snap::Edge { pick, edge, .. } => (*pick, None, edge.as_deref()), - Snap::Point { .. } | Snap::Frame { .. } => return None, + Snap::Point { .. } | Snap::Frame { .. } => { + let path = if o.occurrence == 0 { + Vec::new() + } else { + let occurrence = s.doc.occurrences.iter().find(|p| p.id == o.occurrence)?; + let mut path = s.doc.first_path(occurrence.parent); + path.push(occurrence.id); + s.doc.path_placement(&path)?; + path + }; + return Some(Sel::Occurrence { path }); + } }; // The pick is in the component's coordinates; the placed bodies are in the world. let at = diff --git a/crates/ui-egui/src/dialogs_assembly_tests.rs b/crates/ui-egui/src/dialogs_assembly_tests.rs index 3931c4b6d..691ebb344 100644 --- a/crates/ui-egui/src/dialogs_assembly_tests.rs +++ b/crates/ui-egui/src/dialogs_assembly_tests.rs @@ -325,6 +325,72 @@ fn edit_joint_shows_both_sides_and_a_repick_sends_only_that_side() { assert_ne!(after.b, before.b); } +/// Point and frame origins have no face pick, but Edit Joint must still identify their +/// components (#7749). Showing those components must not replace either stored origin. +#[test] +fn edit_joint_shows_components_for_point_and_frame_origins() { + for command in ["joint.create", "joint.as_built", "joint.rigid_group"] { + let mut app = two_boxes(); + let (a, b) = (occ(&app, "A"), occ(&app, "B")); + let params = match command { + "joint.create" => json!({"type": "rigid", "flip": true, + "a": {"occurrence": a, "point": [10, 10, 10], "z": [0, 0, 1]}, + "b": {"occurrence": b, "point": [40, 10, 10], "z": [0, 0, 1]}}), + "joint.as_built" => json!({"type": "rigid", "a": a, "b": b}), + _ => json!({"occurrences": [a, b]}), + }; + app.run(command, params).unwrap(); + let before = app.session.doc.assembly.joints[0].clone(); + let mut d = edit_joint(&app, before.id).unwrap(); + for (input, (id, name)) in d.inputs.iter().zip([(a, "A:1"), (b, "B:1")]) { + let item = input.items.first().expect("the stored component is shown"); + assert_eq!(item, &Sel::Occurrence { path: vec![id] }, "{command}"); + assert_eq!(crate::dialogs::selection_label(&app.session, app.preferences.origin_plane_names, &d, input, item), name); + } + let commands = apply_commands(&app, &d).unwrap(); + assert!(commands[0].1.get("a").is_none() && commands[0].1.get("b").is_none(), "{commands:?}"); + for (id, params) in commands { + app.run(&id, params).unwrap(); + } + let after = &app.session.doc.assembly.joints[0]; + assert_eq!((&after.a, &after.b), (&before.a, &before.b), "{command}"); + + // Replacing just B with a face still edits only B, preserving A's point/frame. + let body = app.session.world_state().bodies.iter().find(|body| occurrence_of_body(&app.session, &body.name) == Some(b)).unwrap().name.clone(); + let picked = Sel::Face { body, index: 0, point: Vec3::new(40.0, 10.0, 10.0) }; + d.active = 1; + d.pick(&app.session, picked); + let commands = apply_commands(&app, &d).unwrap(); + assert!(commands[0].1.get("a").is_none(), "{commands:?}"); + assert_eq!(commands[0].1["b"]["occurrence"], b); + } +} + +#[test] +fn edit_joint_component_labels_keep_the_nested_instance_and_root() { + let mut app = SolveApp::new(Session::default(), Services::default()); + let parent = app.run("component.create", json!({"name": "Assembly", "activate": false})).unwrap()["occurrence"].as_u64().unwrap(); + let first = + app.run("component.create", json!({"name": "Part", "parent": "Assembly", "activate": false})).unwrap()["occurrence"].as_u64().unwrap(); + let second = app.run("occurrence.copy", json!({"occurrence": first})).unwrap()["occurrence"].as_u64().unwrap(); + let origin = |id| json!({"occurrence": id, "frame": {"origin": [0, 0, 0], "z": [0, 0, 1], "x": [1, 0, 0]}}); + app.run("joint.create", json!({"type": "rigid", "flip": true, "a": origin(0), "b": origin(second)})).unwrap(); + let before = app.session.doc.assembly.joints[0].clone(); + let mut d = edit_joint(&app, before.id).unwrap(); + for (input, (path, label)) in d.inputs.iter().zip([(vec![], app.session.doc.name.as_str()), (vec![parent, second], "Part:2")]) { + let item = input.items.first().expect("the stored component is shown"); + assert_eq!(item, &Sel::Occurrence { path }); + assert_eq!(crate::dialogs::selection_label(&app.session, app.preferences.origin_plane_names, &d, input, item), label); + } + for (id, params) in apply_commands(&app, &d).unwrap() { + app.run(&id, params).unwrap(); + } + let after = &app.session.doc.assembly.joints[0]; + assert_eq!((&after.a, &after.b), (&before.a, &before.b)); + d.inputs[1].items.clear(); + assert!(apply_commands(&app, &d).is_err(), "clearing a side still requires a replacement origin"); +} + /// A side on a hole's wall shows the wall, a cylinder, not the plate's face beside the hole: the /// face its snap names is the one the pre-fill takes, however near the other face's plane lies. #[test] From 3fe2b3386ff984fed93f4c37023e765a87de5e82 Mon Sep 17 00:00:00 2001 From: austin62jake Date: Mon, 2 Nov 2026 00:08:11 +0000 Subject: [PATCH 52/55] Sketch: Remove Spline Point takes one point out of a spline (#10783) (#10793) * Sketch: Remove Spline Point takes one fit point out of a spline (#10783) Co-Authored-By: Claude Opus 5.5 * Sketch: Remove Spline Point takes one point out of a spline (#10783) sketch.spline.remove_point takes one fit or control point out of a spline. The spline keeps its id and runs through its other points, which stay where they are. The point goes with the constraints on it, unless another curve uses it. A closed spline's closing point, an end joined to other geometry, the last 2 points (3 when closed), and projected, offset or patterned splines are refused with a message. The right-click menu of a spline point, picked alone, offers it beside Reverse Spline Direction. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude --- .../locales/pending/spline-remove-point.json | 31 +++++++ crates/engine/src/cmd/sketch_create.rs | 25 +++++- crates/engine/src/cmd/sketch_modify_tests.rs | 58 +++++++++++++ crates/engine/src/schema/sketch_create.rs | 44 ++++++++++ .../engine/src/schema/sketch_create_tests.rs | 24 +++++- crates/sketch/src/model.rs | 4 +- crates/sketch/src/spline_points.rs | 75 ++++++++++++++++- crates/sketch/src/tests.rs | 82 +++++++++++++++++++ crates/ui-egui/src/context_menu.rs | 54 ++++++++++++ 9 files changed, 391 insertions(+), 6 deletions(-) create mode 100644 assets/locales/pending/spline-remove-point.json diff --git a/assets/locales/pending/spline-remove-point.json b/assets/locales/pending/spline-remove-point.json new file mode 100644 index 000000000..17e7511b4 --- /dev/null +++ b/assets/locales/pending/spline-remove-point.json @@ -0,0 +1,31 @@ +{ + "en": { "cmd.sketch_spline_remove_point": "Remove Spline Point" }, + "ar": { "cmd.sketch_spline_remove_point": "إزالة نقطة من المنحنى الشريحي" }, + "bs": { "cmd.sketch_spline_remove_point": "Ukloni tačku splajna" }, + "cs": { "cmd.sketch_spline_remove_point": "Odebrat bod splajnu" }, + "da": { "cmd.sketch_spline_remove_point": "Fjern splinepunkt" }, + "de": { "cmd.sketch_spline_remove_point": "Splinepunkt entfernen" }, + "es": { "cmd.sketch_spline_remove_point": "Eliminar punto de spline" }, + "fi": { "cmd.sketch_spline_remove_point": "Poista splinipiste" }, + "fr": { "cmd.sketch_spline_remove_point": "Supprimer un point de spline" }, + "gl": { "cmd.sketch_spline_remove_point": "Eliminar punto do spline" }, + "he": { "cmd.sketch_spline_remove_point": "הסרת נקודה מהספליין" }, + "hr": { "cmd.sketch_spline_remove_point": "Ukloni točku splinea" }, + "hu": { "cmd.sketch_spline_remove_point": "Splinepont eltávolítása" }, + "id": { "cmd.sketch_spline_remove_point": "Hapus Titik Spline" }, + "it": { "cmd.sketch_spline_remove_point": "Rimuovi punto dalla spline" }, + "ja": { "cmd.sketch_spline_remove_point": "スプライン点を削除" }, + "ms": { "cmd.sketch_spline_remove_point": "Buang Titik Splin" }, + "nb": { "cmd.sketch_spline_remove_point": "Fjern splinepunkt" }, + "nl": { "cmd.sketch_spline_remove_point": "Splinepunt verwijderen" }, + "pl": { "cmd.sketch_spline_remove_point": "Usuń punkt splajnu" }, + "ro": { "cmd.sketch_spline_remove_point": "Elimină punct din spline" }, + "ru": { "cmd.sketch_spline_remove_point": "Удалить точку сплайна" }, + "sr": { "cmd.sketch_spline_remove_point": "Уклони тачку сплајна" }, + "sv": { "cmd.sketch_spline_remove_point": "Ta bort splinepunkt" }, + "tr": { "cmd.sketch_spline_remove_point": "Spline Noktasını Kaldır" }, + "uk": { "cmd.sketch_spline_remove_point": "Видалити точку сплайна" }, + "vi": { "cmd.sketch_spline_remove_point": "Xóa điểm khỏi đường cong Spline" }, + "zh": { "cmd.sketch_spline_remove_point": "删除样条曲线点" }, + "zh-TW": { "cmd.sketch_spline_remove_point": "刪除雲形線點" } +} diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs index 8afe7d695..de8101fa4 100644 --- a/crates/engine/src/cmd/sketch_create.rs +++ b/crates/engine/src/cmd/sketch_create.rs @@ -16,7 +16,7 @@ use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_pa use super::sketch_store; use super::{CommandSpec, in_sketch}; use crate::params::{bad, num, req_vec2, str_, string_list}; -use crate::schema::sketch_create::{SplineReverseParams, SplineReverseResult}; +use crate::schema::sketch_create::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult}; use crate::schema::{TypedContract, output_schema_for}; use crate::{EngineError, Result, Session}; @@ -29,6 +29,7 @@ mod text_move_tests; mod text_expr_tests; const SPLINE_REVERSE_CONTRACT: TypedContract = TypedContract::new(); +const SPLINE_REMOVE_POINT_CONTRACT: TypedContract = TypedContract::new(); pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("sketch.line.midpoint", "Midpoint Line", midpoint_line) @@ -88,6 +89,12 @@ pub static COMMANDS: &[CommandSpec] = &[ .icon("spline") .enabled(in_sketch) .params("curve: fit point spline id, at: [x,y]: a fit point is inserted where the curve passes nearest to it, between its neighbours (the curve still runs through it and all its old points; constraints on them stay); end?: start|end: `at` becomes the spline's new first or last point instead, and the curve runs on to it (refused when that end is joined to other geometry). Control point splines take no new points yet. Returns point: the new point's id"), + CommandSpec::new("sketch.spline.remove_point", "Remove Spline Point", crate::checked!("sketch.spline.remove_point", spline_remove_point)) + .icon("spline") + .enabled(in_sketch) + .contract(&SPLINE_REMOVE_POINT_CONTRACT) + .output(output_schema_for::) + .params("curve: spline id, point: one of its points (a point id, or the curve's start or end such as s1.end): the spline runs through (or over) its other points only, and the point goes with the constraints on it unless another curve uses it. Fit point, control point and closed splines. Refused for a closed spline's closing point, for an end joined to other geometry or held by a constraint, when fewer than 2 points would be left (3 on a closed spline), and for a projected, offset or patterned spline. Returns curve, point: the point's id, deleted: whether the point went too"), CommandSpec::new("sketch.spline.reverse", "Reverse Spline Direction", crate::checked!("sketch.spline.reverse", spline_reverse)) .icon("spline") .enabled(in_sketch) @@ -711,6 +718,22 @@ fn spline_insert_point(s: &mut Session, p: &Value) -> Result { Ok(json!({"point": point, "curve": p.get("curve"), "sketch": info})) } +/// One point taken out of a spline (#10783). +fn spline_remove_point(s: &mut Session, p: &Value) -> Result { + let cmd = "sketch.spline.remove_point"; + let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a spline id"))?.to_string(); + let point = str_(p, "point").ok_or_else(|| bad(cmd, "`point` must be one of the spline's points"))?.to_string(); + let ((point, deleted), info) = edit(s, p, cmd, false, |sk, _| { + let c = sk.curve_index(&id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))?; + let at = sk.resolve_point(&point).ok_or_else(|| bad(cmd, format!("unknown sketch point `{point}`")))?; + let name = sk.points.get(at).map_or(point.clone(), |q| q.id.clone()); + let deleted = sk.remove_spline_point(c, at).map_err(|e| bad(cmd, e.to_string()))?; + Ok((name, deleted)) + })?; + let reply = SplineRemovePointResult { curve: id, point, deleted, sketch: info, param_warnings: Vec::new() }; + serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) +} + fn spline_reverse(s: &mut Session, p: &Value) -> Result { let cmd = "sketch.spline.reverse"; let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a spline id"))?.to_string(); diff --git a/crates/engine/src/cmd/sketch_modify_tests.rs b/crates/engine/src/cmd/sketch_modify_tests.rs index 4a5c66894..ea69228da 100644 --- a/crates/engine/src/cmd/sketch_modify_tests.rs +++ b/crates/engine/src/cmd/sketch_modify_tests.rs @@ -1492,6 +1492,64 @@ fn a_point_added_to_a_spline_keeps_its_constraints_and_undoes() { assert_eq!(sketch(&s), unchanged, "refusals change nothing"); } +/// Remove Spline Point (#10783): one fit point goes, with the dimension on it. The spline runs +/// through its other points, which stay where they were, and the line joined to its end stays. +/// Undo puts the point back. The end the line joins, a line and an unknown point are refused; a +/// control point spline gives up a point too. +#[test] +fn a_point_removed_from_a_spline_goes_with_its_dimension_and_undoes() { + let mut s = new_sketch(); + let sid = + ids(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 0], [10, 8], [20, 0], [30, 6]], "connect": false}))["curves"])[0].clone(); + run(&mut s, "sketch.line", json!({"points": [format!("{sid}.end"), [40, 6]], "connect": false})); + let sk = sketch(&s); + let si = sk.curve_index(&sid).unwrap(); + let names: Vec = sk.curves[si].kind.point_ids().iter().map(|i| sk.points[*i].id.clone()).collect(); + run(&mut s, "sketch.dimension", json!({"entities": [names[1], names[2]], "value": 12.8})); + let before = sketch(&s); + let at = |sk: &solidcraft_sketch::Sketch, id: &str| sk.point(sk.point_index(id).unwrap()).unwrap(); + + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": sid, "point": names[1]})); + assert_eq!((r["curve"].as_str(), r["point"].as_str(), r["deleted"].as_bool()), (Some(sid.as_str()), Some(names[1].as_str()), Some(true)), "{r}"); + let after = sketch(&s); + assert!(after.point_index(&names[1]).is_none(), "the point went"); + let left: Vec = after.curves[si].kind.point_ids().iter().map(|i| after.points[*i].id.clone()).collect(); + assert_eq!(left, [names[0].clone(), names[2].clone(), names[3].clone()]); + let segs = after.exact_segs(si).unwrap(); + for id in &left { + let q = at(&after, id); + assert!(q.dist(at(&before, id)) < 1e-9, "{id} stays where it was"); + let off = segs.iter().map(|seg| seg.point_at(seg.closest_param(q)).dist(q)).fold(f64::INFINITY, f64::min); + assert!(off < 1e-9, "the curve runs through {id}"); + } + assert!(after.constraints.iter().all(|c| c.kind.value().is_none()), "the dimension on the point went"); + let joined = after.curves.iter().any(|c| matches!(c.kind, CurveKind::Line { a, .. } if after.points[a].id == names[3])); + assert!(joined, "the line still starts at the spline's end"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(sketch(&s), before, "undo puts the point back"); + + let line = before.curves.iter().find(|c| matches!(c.kind, CurveKind::Line { .. })).unwrap().id.clone(); + for (p, why) in [ + (json!({"curve": sid, "point": format!("{sid}.end")}), "joined"), + (json!({"curve": line, "point": names[0]}), "spline"), + (json!({"curve": sid, "point": "nope"}), "unknown sketch point"), + (json!({"curve": sid}), "`point`"), + ] { + let e = s.execute("sketch.spline.remove_point", &p).unwrap_err().to_string(); + assert!(e.contains(why), "{p}: {e}"); + } + assert_eq!(sketch(&s), before, "refusals change nothing"); + + let cv = + ids(&run(&mut s, "sketch.spline.control_point", json!({"points": [[0, 20], [10, 30], [20, 20]], "connect": false}))["curves"])[0].clone(); + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": cv, "point": format!("{cv}.start")})); + assert_eq!(r["deleted"], json!(true), "{r}"); + let sk = sketch(&s); + let ci = sk.curve_index(&cv).unwrap(); + let left: Vec = sk.curves[ci].kind.point_ids().iter().map(|i| sk.point(*i).unwrap()).collect(); + assert_eq!(left, [Vec2::new(10.0, 30.0), Vec2::new(20.0, 20.0)]); +} + /// Reverse Spline Direction (#8224): a fit, a control point and a closed spline each run the /// other way along the same path, their ends swapped. Their points, the constraints on them and /// a line joined to an end stay, and undo restores the spline. A line and the source and output diff --git a/crates/engine/src/schema/sketch_create.rs b/crates/engine/src/schema/sketch_create.rs index 558045450..7c6d1971e 100644 --- a/crates/engine/src/schema/sketch_create.rs +++ b/crates/engine/src/schema/sketch_create.rs @@ -80,6 +80,50 @@ pub struct SplineReverseParams { pub sketch: Option, } +/// Take one point out of a spline: it runs through (or over) its other points only, and the point +/// goes with the constraints on it unless another curve uses it. Takes fit point, control point +/// and closed splines; refused for a closed spline's closing point, for an end joined to other +/// geometry or held by a constraint, when fewer than 2 points would be left (3 on a closed +/// spline), and for a projected, offset or patterned spline. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct SplineRemovePointParams { + /// The spline's curve id. + #[serde(deserialize_with = "spline_id")] + pub curve: String, + /// One of the spline's points: a point id, or the curve's `start` or `end` (`s1.end`). + #[serde(deserialize_with = "point_ref")] + pub point: String, + /// The sketch (default: the one being edited). + #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")] + #[schemars(with = "SketchRef")] + pub sketch: Option, +} + +/// What `sketch.spline.remove_point` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct SplineRemovePointResult { + /// The spline's curve id (unchanged). + pub curve: String, + /// The id the point had. + pub point: String, + /// Whether the point went too; `false` when another curve still uses it. + pub deleted: bool, + /// The sketch's solve: `{solved, dof}`. + pub sketch: Value, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// A point reference, with the handler's message for anything else. +fn point_ref<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + match Value::deserialize(d)? { + Value::String(s) => Ok(s), + _ => Err(serde::de::Error::custom("must be one of the spline's points")), + } +} + /// A curve id, with the handler's message for anything else. fn spline_id<'de, D: serde::Deserializer<'de>>(d: D) -> Result { match Value::deserialize(d)? { diff --git a/crates/engine/src/schema/sketch_create_tests.rs b/crates/engine/src/schema/sketch_create_tests.rs index 3f841c626..bea64f761 100644 --- a/crates/engine/src/schema/sketch_create_tests.rs +++ b/crates/engine/src/schema/sketch_create_tests.rs @@ -1,6 +1,6 @@ use serde_json::json; -use super::{SplineReverseParams, SplineReverseResult}; +use super::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult}; use crate::Session; use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; @@ -8,6 +8,7 @@ use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &["curve", "sketch"]); + assert_keys(input_schema_for::(), &["curve", "point", "sketch"]); } #[test] @@ -17,9 +18,30 @@ fn strict_keeps_todays_errors() { ("sketch.spline.reverse", json!({"curve": null})), ("sketch.spline.reverse", json!({"curve": "nope"})), ("sketch.spline.reverse", json!({"curve": "l1"})), + ("sketch.spline.remove_point", json!({"curve": 5, "point": "p1"})), + ("sketch.spline.remove_point", json!({"curve": "nope", "point": "p1"})), + ("sketch.spline.remove_point", json!({"curve": "l1", "point": 3})), + ("sketch.spline.remove_point", json!({"curve": "l1"})), ]); } +#[test] +fn spline_remove_point_reply_matches_its_schema() { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let run = |s: &mut Session, id: &str, p: serde_json::Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}")); + run(&mut s, "sketch.create", json!({"plane": "XY"})); + let c = run(&mut s, "sketch.spline.fit_point", json!({"points": [[5, 0], [10, 5], [20, 0], [30, 5], [40, 0]]})); + let spline = c["curves"][0].as_str().unwrap_or_else(|| panic!("{c}")).to_string(); + let schema = output_schema_for::(); + let schema = schema.as_value(); + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": spline, "point": format!("{spline}.start")})); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + let r = run(&mut s, "sketch.spline.remove_point", json!({"curve": spline, "point": format!("{spline}.end"), "unknown": 1})); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}"); +} + #[test] fn spline_reverse_reply_matches_its_schema() { let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; diff --git a/crates/sketch/src/model.rs b/crates/sketch/src/model.rs index b696bb955..a482e6e8a 100644 --- a/crates/sketch/src/model.rs +++ b/crates/sketch/src/model.rs @@ -1695,7 +1695,7 @@ impl Sketch { /// Points held together only through points about to go stay together: two rectangles' /// corners made coincident with one arc end are tied to each other when a trim takes that /// end away, instead of coming apart where they still meet. - fn keep_ties_through(&mut self, gone: &[usize]) { + pub(crate) fn keep_ties_through(&mut self, gone: &[usize]) { if gone.is_empty() { return; } @@ -1732,7 +1732,7 @@ impl Sketch { } } - fn point_used_by_curve(&self, p: usize) -> bool { + pub(crate) fn point_used_by_curve(&self, p: usize) -> bool { self.curves.iter().any(|c| c.kind.uses(p)) } diff --git a/crates/sketch/src/spline_points.rs b/crates/sketch/src/spline_points.rs index a2ab1308e..bd8e28e67 100644 --- a/crates/sketch/src/spline_points.rs +++ b/crates/sketch/src/spline_points.rs @@ -1,6 +1,6 @@ //! New points on an existing fit spline (#6533): a fit point inserted where the curve already -//! runs, or a new first or last point the spline runs on to. Also a spline's direction reversed -//! (#8224). +//! runs, or a new first or last point the spline runs on to. One point taken out of a spline +//! (#10783). Also a spline's direction reversed (#8224). //! //! The spline keeps its curve index and every point it had (the new point is appended to //! `Sketch::points`), so constraints on its points and on the curve stay as they were. @@ -87,6 +87,77 @@ impl Sketch { Ok(p) } + /// Take point `p` out of spline `ci` (#10783), and return whether the point itself went too. + /// The spline runs through (or over) its other points, and keeps its curve index, so + /// constraints on the curve and on its other points stay. The point goes with the constraints + /// on it, unless another curve uses it (it stays, for that curve) or it is the origin. + /// + /// The spline keeps at least 2 points (a closed one 3 besides its closing point, which stays). + /// An end of an open spline joined to other geometry stays, as for [`Sketch::extend_spline`]: + /// the spline would no longer end where it is joined. + pub fn remove_spline_point(&mut self, ci: usize, p: usize) -> Result { + let curve = self.curves.get(ci).ok_or_else(|| SketchError::Unknown(format!("curve {ci}")))?; + let CurveKind::Spline { pts, periodic, .. } = &curve.kind else { + return Err(SketchError::WrongKind(curve.id.clone(), "only a spline has points to remove".into())); + }; + let (pts, periodic) = (pts.clone(), *periodic); + if curve.link.is_some() { + return Err(SketchError::Invalid("a projected spline follows its source; its points can't be removed".into())); + } + if self.freeform_offsets.iter().any(|o| o.output == curve.id) { + return Err(SketchError::Invalid("an offset spline follows its source; break the offset association first".into())); + } + if self.freeform_offsets.iter().any(|o| o.source == curve.id) { + return Err(SketchError::Invalid( + "not supported yet: removing a point from a spline that has an offset; break the offset association first".into(), + )); + } + if self.patterns.iter().any(|pattern| pattern.contains(&curve.id)) { + return Err(SketchError::Invalid("not supported yet: removing a point from a patterned spline".into())); + } + let at = match pts.iter().enumerate().filter(|(_, q)| **q == p).map(|(i, _)| i).collect::>().as_slice() { + [] => return Err(SketchError::Invalid(format!("that point isn't one of {}'s points", curve.id))), + [at] => *at, + _ => return Err(SketchError::Invalid("that point closes the spline; remove another one".into())), + }; + let last = pts.len().saturating_sub(1); + if periodic && (at == 0 || at == last) { + return Err(SketchError::Invalid("a closed spline's closing point stays; remove another one".into())); + } + if pts.len() < if periodic { 5 } else { 3 } { + return Err(SketchError::Invalid(format!("a spline keeps at least {} points", if periodic { 3 } else { 2 }))); + } + if !periodic && (at == 0 || at == last) { + let joined = self.curves.iter().enumerate().any(|(i, c)| i != ci && c.kind.uses(p)) + || self.constraints.iter().any(|k| { + let (points, curves) = k.kind.indices(); + points.contains(&p) || (curves.contains(&ci) && matches!(k.kind, ConstraintKind::Tangent { .. } | ConstraintKind::Smooth { .. })) + }); + if joined { + return Err(SketchError::Invalid( + "that end of the spline is joined to other geometry or held by a constraint; remove those first".into(), + )); + } + } + let mut left = pts; + left.remove(at); + if periodic { + let pos: Vec = + left.iter().map(|i| self.point(*i).ok_or_else(|| SketchError::Unknown(format!("point {i}")))).collect::>()?; + crate::periodic::validate_periodic_points(&pos)?; + } + if let Some(CurveKind::Spline { pts, .. }) = self.curves.get_mut(ci).map(|c| &mut c.kind) { + *pts = left; + } + // The origin (point 0) is never removed. + if p == 0 || self.point_used_by_curve(p) { + return Ok(false); + } + self.keep_ties_through(&[p]); + self.remove_points(&[p]); + Ok(true) + } + /// Reverse spline `ci`'s direction: its last point becomes its first and the curve runs the /// other way along the same path. Its points are reversed in place, so every point, and every /// constraint on them and on the curve, stays. The shape doesn't change: a fit spline's chord diff --git a/crates/sketch/src/tests.rs b/crates/sketch/src/tests.rs index feaa87cad..89bb53cbd 100644 --- a/crates/sketch/src/tests.rs +++ b/crates/sketch/src/tests.rs @@ -1220,6 +1220,88 @@ fn a_spline_extends_to_a_new_end_unless_the_end_is_joined() { assert!(sk.extend_spline(s, v(-10.0, 5.0), true).is_err(), "already a point there"); } +/// Where spline `s`'s points are, in order. +fn spline_places(sk: &Sketch, s: usize) -> Vec { + let CurveKind::Spline { pts, .. } = &sk.curves[s].kind else { panic!("{s} is no spline") }; + pts.iter().map(|i| sk.point(*i).unwrap()).collect() +} + +/// #10783: a spline gives up one of its points. The curve runs through the others, in order, and +/// the point goes with the constraints on it; a point a line also ends at stays, for the line. +#[test] +fn a_point_removed_from_a_spline_goes_and_the_curve_keeps_the_others() { + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, false); + let mut others = spline_places(&sk, s); + let gone = others.remove(2); + // A free point held on the one that goes: the constraint goes, the free point stays. + let free = sk.add_point(gone, None).unwrap(); + sk.add_constraint(ConstraintKind::Coincident { p: pts[2], q: free }, None).unwrap(); + let count = sk.points.len(); + assert_eq!(sk.remove_spline_point(s, pts[2]), Ok(true)); + assert_eq!(spline_places(&sk, s), others); + for q in &others { + assert!(off_curve(&sk, s, *q) < 1e-9, "the curve still runs through {q:?}"); + } + assert!(matches!(sk.curves[s].kind, CurveKind::Spline { control: false, periodic: false, .. })); + assert_eq!(sk.points.len(), count - 1, "the point went"); + assert!(sk.constraints.is_empty(), "the constraint on it went: {:?}", sk.constraints); + // A free end goes too: the spline starts at the next point. + let start = sk.curves[s].kind.ends().unwrap().0; + assert_eq!(sk.remove_spline_point(s, start), Ok(true)); + others.remove(0); + assert_eq!(spline_places(&sk, s), others); + // An inner point a line also ends at stays, for the line. + let CurveKind::Spline { pts: now, .. } = sk.curves[s].kind.clone() else { panic!() }; + let line = sk.add_line(others[1], v(40.0, 30.0), Some(now[1]), None, None).unwrap(); + assert_eq!(sk.remove_spline_point(s, now[1]), Ok(false)); + assert!(sk.curves[line].kind.uses(now[1]) && !sk.curves[s].kind.uses(now[1])); + others.remove(1); + assert_eq!(spline_places(&sk, s), others); + // Two points are as few as a spline keeps. + assert_eq!(others.len(), 2); + let before = sk.clone(); + assert!(sk.remove_spline_point(s, sk.curves[s].kind.ends().unwrap().1).is_err()); + assert_eq!(sk, before, "a refused removal changes nothing"); +} + +/// #10783: what a spline keeps: an end joined to a line or held by a constraint, a closed +/// spline's closing point and its last three points. A control point spline gives up a point as a +/// fit point spline does. +#[test] +fn a_spline_keeps_its_joined_ends_and_closing_point() { + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, false); + let line = sk.add_line(sk.point(pts[4]).unwrap(), v(60.0, 0.0), Some(pts[4]), None, None).unwrap(); + let tied = sk.add_point(sk.point(pts[0]).unwrap(), None).unwrap(); + sk.add_constraint(ConstraintKind::Coincident { p: pts[0], q: tied }, None).unwrap(); + let before = sk.clone(); + assert!(sk.remove_spline_point(s, pts[4]).is_err(), "a line ends there"); + assert!(sk.remove_spline_point(s, pts[0]).is_err(), "a constraint holds the start"); + assert!(sk.remove_spline_point(s, tied).is_err(), "not one of the spline's points"); + assert!(sk.remove_spline_point(line, pts[4]).is_err(), "a line has no spline points"); + assert_eq!(sk, before, "a refused removal changes nothing"); + + let mut sk = Sketch::new(); + let (pts, s) = wave_spline(&mut sk, true); + assert!(sk.remove_spline_point(s, pts[0]).is_err(), "the closing point"); + assert_eq!(sk.remove_spline_point(s, pts[2]), Ok(true)); + assert_eq!(sk.remove_spline_point(s, pts[1]), Ok(true)); + let CurveKind::Spline { pts: now, periodic, .. } = sk.curves[s].kind.clone() else { panic!() }; + assert!(periodic); + assert_eq!(now.len(), 4, "three points and the closing one: {now:?}"); + assert!(sk.remove_spline_point(s, now[1]).is_err(), "a closed spline keeps three points"); + sk.validate_periodic_splines().unwrap(); + + let mut sk = Sketch::new(); + let places = [v(0.0, 0.0), v(10.0, 10.0), v(20.0, -10.0), v(30.0, 0.0)]; + let cv: Vec = places.iter().map(|q| sk.add_point(*q, None).unwrap()).collect(); + let c = sk.add_curve(CurveKind::Spline { pts: cv.clone(), control: true, degree: 3, periodic: false }, None).unwrap(); + assert_eq!(sk.remove_spline_point(c, cv[1]), Ok(true)); + assert!(matches!(sk.curves[c].kind, CurveKind::Spline { control: true, .. })); + assert_eq!(spline_places(&sk, c), vec![places[0], places[2], places[3]]); +} + /// #755: a line drawn through a junction of a loop, but 2e-5 off it, still splits the loop. The /// junction lies on the loop's two curves only, so it cuts neither of them where the line /// crosses, and that crossing, next to the junction, was taken for one already cut there: the diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 71b80c3da..427284ab2 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -1281,6 +1281,19 @@ fn sketch_entity_items(app: &SolveApp) -> Vec { { v.push(cmd(app, "sketch.spline.reverse", "Reverse Spline Direction").with(json!({ "curve": curve }))); } + // #10783: a point of one spline of the sketch's own, alone, comes out of that spline. + if let ([], [point]) = (curves.as_slice(), points.as_slice()) + && let Some(at) = ss.sketch.resolve_point(point) + && let [spline] = ss + .sketch + .curves + .iter() + .filter(|c| c.link.is_none() && matches!(&c.kind, CurveKind::Spline { pts, .. } if pts.contains(&at))) + .collect::>() + .as_slice() + { + v.push(cmd(app, "sketch.spline.remove_point", "Remove Spline Point").with(json!({ "curve": spline.id, "point": point }))); + } v.push(act("ui.fix", "Fix/Unfix", "c_fix").with(json!({ "entities": ents }))); // The clipboard beside Delete, as in every menu. v.push(act("ui.cut", "Cut", "cut").key("Ctrl+X")); @@ -2943,6 +2956,47 @@ mod tests { assert!(added.dist(at) < 0.5, "the new fit point is where the menu was opened: {added:?}"); } + /// #10783: a right-click on one of a spline's points offers Remove Spline Point, and the item + /// takes that point out: the spline stays, through its other points. A line's end isn't + /// offered it. + #[test] + fn spline_context_menu_removes_the_clicked_point() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + let fit = h.app.run("sketch.spline.fit_point", json!({"points":[[0,0],[10,8],[20,0],[30,6]],"connect":false})).unwrap()["curves"][0] + .as_str() + .unwrap() + .to_owned(); + h.app.run("sketch.line", json!({"points":[[0,-12],[20,-12]],"connect":false})).unwrap(); + let sid = h.app.session.active_sketch.unwrap(); + let places = |h: &crate::scenario::Harness| { + let state = h.app.session.world_state(); + let sk = &state.sketch(sid).unwrap().sketch; + sk.curves[sk.curve_index(&fit).unwrap()].kind.point_ids().iter().map(|i| sk.point(*i).unwrap()).collect::>() + }; + h.call("ui.view", json!({"view":"top"})); + h.app.cam.distance = 80.0; + h.settle(); + + h.step(&json!({"click":{"world":[20,-12,0]},"button":"right"})).unwrap(); + assert!(matches!(h.app.session.selection.as_slice(), [Sel::SketchPoint { .. }]), "{:?}", h.app.session.selection); + assert!(items(&h.app, &Target::Viewport).iter().all(|item| item.id != "sketch.spline.remove_point"), "a line's end"); + close(&mut h.app); + + let mut left = places(&h); + left.remove(1); + h.step(&json!({"click":{"world":[10,8,0]},"button":"right"})).unwrap(); + let [Sel::SketchPoint { id }] = h.app.session.selection.as_slice() else { panic!("{:?}", h.app.session.selection) }; + let id = id.clone(); + let menu = items(&h.app, &Target::Viewport); + let item = menu.iter().find(|item| item.id == "sketch.spline.remove_point").expect("a spline's point offers Remove Spline Point"); + assert_eq!((item.label.as_str(), item.params.clone()), ("Remove Spline Point", Some(json!({"curve": fit, "point": id})))); + assert!(item.enabled); + h.step(&json!({"click":{"handle":"menu:sketch.spline.remove_point"}})).unwrap(); + assert_eq!(places(&h), left, "the spline runs through its other points"); + } + #[test] fn solidworks_face_menu_runs_normal_to_selection_and_rejects_curved_faces() { let mut h = crate::scenario::Harness::new(); From 666356dba0b3952ddb3ea68b58a4c1b31248dbac Mon Sep 17 00:00:00 2001 From: PapaEcho <95265719+PapaEcho13@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:08:23 +0000 Subject: [PATCH 53/55] Assistant: configurable show/hide shortcut (#10764) (#10767) * claim: #10764 * Assistant: make show/hide shortcut configurable (#10764) --- .../locales/pending/assistant-shortcut.json | 26 ++++++ crates/engine/src/cmd/edit.rs | 14 +++ crates/engine/src/cmd/edit_tests.rs | 11 +++ crates/engine/src/schema/edit.rs | 12 ++- crates/ui-egui/src/agent_chat/mod.rs | 10 ++- crates/ui-egui/src/agent_chat/panel.rs | 51 ++++++++--- crates/ui-egui/src/keymap.rs | 87 ++++++++++++++++++- crates/ui-egui/src/lib.rs | 7 ++ crates/ui-egui/src/toolbar.rs | 18 ++-- docs/agent-chat.md | 2 + 10 files changed, 213 insertions(+), 25 deletions(-) create mode 100644 assets/locales/pending/assistant-shortcut.json diff --git a/assets/locales/pending/assistant-shortcut.json b/assets/locales/pending/assistant-shortcut.json new file mode 100644 index 000000000..888dcf986 --- /dev/null +++ b/assets/locales/pending/assistant-shortcut.json @@ -0,0 +1,26 @@ +{ + "ar": { + "cmd.ui.assistant": "إظهار المساعد أو إخفاؤه" + }, + "de": { + "cmd.ui.assistant": "Assistenten ein-/ausblenden" + }, + "en": { + "cmd.ui.assistant": "Toggle Assistant" + }, + "he": { + "cmd.ui.assistant": "הצגה או הסתרה של העוזר" + }, + "ja": { + "cmd.ui.assistant": "アシスタントの表示切り替え" + }, + "ko": { + "cmd.ui.assistant": "도우미 표시 전환" + }, + "vi": { + "cmd.ui.assistant": "Bật/tắt trợ lý" + }, + "zh": { + "cmd.ui.assistant": "切换助手显示" + } +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 188684e1a..fce8f62cb 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -10,6 +10,14 @@ use crate::params::{bad, bool_, name_or_id_values, num, str_}; use crate::{EngineError, Result, Sel, Session, Snapshot}; pub static COMMANDS: &[CommandSpec] = &[ + CommandSpec::new("ui.assistant", "Toggle Assistant", crate::checked!("ui.assistant", assistant)) + .icon("assistant") + .key("Ctrl+Shift+A") + .noundo() + .doc_only() + .contract(&ASSISTANT_CONTRACT) + .output(crate::schema::output_schema_for::) + .params("Show or hide Assistant in the app. Headless calls are refused without changing the design"), CommandSpec::new("edit.undo", "Undo", undo).icon("undo").key("Ctrl+Z").noundo().doc_only(), CommandSpec::new("edit.redo", "Redo", redo).icon("redo").key("Ctrl+Y").noundo().doc_only(), CommandSpec::new("edit.repeat", "Repeat Last Command", crate::checked!("edit.repeat", repeat)) @@ -119,6 +127,12 @@ fn redo(s: &mut Session, _p: &Value) -> Result { Ok(json!({"redone": label})) } +const ASSISTANT_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); + +fn assistant(_s: &mut Session, _p: &Value) -> Result { + Err(EngineError::Other("ui.assistant shows or hides Assistant in the app; no assistant panel exists in a headless session".into())) +} + const REPEAT_CONTRACT: crate::schema::TypedContract = crate::schema::TypedContract::new(); /// Repeat Last Command (#7077) starts a tool, which only the app has: it starts the last one in diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index a6390787c..45c4db6d0 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -1650,3 +1650,14 @@ fn edits_after_a_canvas_share_its_image_with_every_undo_state() { assert_eq!(s.doc.canvases[0].data.as_ptr(), image, "undo brings back the same image"); assert_eq!(s.doc.canvases[0].bytes().as_deref(), Some(png.as_slice())); } + +#[test] +fn assistant_toggle_is_refused_headlessly_without_changing_the_document() { + let mut s = Session::default(); + let before = (s.doc.to_json(), s.undo.len()); + let error = s.execute("ui.assistant", &json!({})).unwrap_err().to_string(); + assert!(error.contains("headless session"), "{error}"); + assert_eq!((s.doc.to_json(), s.undo.len()), before); + let spec = crate::find_command("ui.assistant").unwrap(); + assert_eq!((spec.shortcut, spec.tab, spec.undoable), (Some("Ctrl+Shift+A"), "", false)); +} diff --git a/crates/engine/src/schema/edit.rs b/crates/engine/src/schema/edit.rs index 901f33381..c84cf9674 100644 --- a/crates/engine/src/schema/edit.rs +++ b/crates/engine/src/schema/edit.rs @@ -3,6 +3,15 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; +/// Assistant visibility is UI-owned and takes no parameters. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct AssistantParams {} + +/// Headless sessions refuse Assistant display requests and produce no result. +#[derive(Debug, Serialize, JsonSchema)] +pub struct AssistantResult {} + /// `edit.repeat` takes no parameters: it starts the last tool with its defaults. #[derive(Debug, Deserialize, JsonSchema)] #[schemars(deny_unknown_fields)] @@ -39,12 +48,13 @@ pub struct TimelinePlayResult { #[cfg(test)] mod tests { - use super::RepeatParams; + use super::{AssistantParams, RepeatParams}; use crate::schema::input_schema_for; use crate::schema::tests::assert_keys; #[test] fn schemas_and_the_key_check_agree() { assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &[]); } } diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 9292af175..952fd63cc 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -50,7 +50,7 @@ use crate::{ControlRequest, SolveApp}; use backend::{ChatBackend, Event, PermissionOption, PromptPart, ToolStatus}; pub(crate) use panel::{left_inset, tool_space}; -pub use panel::{show, tip as panel_tip, toggle}; +pub use panel::{show, tip as panel_tip, toggle, toggle_shortcut}; /// Most entries kept in the conversation; older ones are dropped. const MAX_ITEMS: usize = 2000; @@ -907,7 +907,7 @@ pub(crate) fn assistant_mark(app: &SolveApp) -> AssistantMark { ) } -pub(crate) fn assistant_tip(mark: AssistantMark) -> String { +pub(crate) fn assistant_tip(app: &SolveApp, mark: AssistantMark) -> String { let state = match mark { AssistantMark::Quiet => tr("ui.agent_chat_state_off").to_string(), AssistantMark::Ready => tr("ui.agent_chat_state_ready").to_string(), @@ -916,7 +916,11 @@ pub(crate) fn assistant_tip(mark: AssistantMark) -> String { AssistantMark::Stopped => tr("ui.agent_chat_state_exited").to_string(), AssistantMark::Waiting(count) => trf("ui.assistant_waiting", &[("count", &count.to_string())]), }; - format!("{} (Ctrl+Shift+A) — {state}", tr("ui.assistant")) + let name = match crate::keymap::display_for(app, "ui.assistant") { + Some(key) => format!("{} ({key})", tr("ui.assistant")), + None => tr("ui.assistant").to_string(), + }; + format!("{name} — {state}") } /// Whether a permission question is about one of SolidCraft's own tools (which SolidCraft's own diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 8b69a7e89..8529dd01e 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -14,8 +14,34 @@ pub const MIN_WIDTH: f32 = 280.0; pub const MAX_WIDTH: f32 = 760.0; /// The folded panel's width. const STRIP: f32 = 30.0; -/// The keyboard shortcut that shows and hides the panel (also from its own text field). -pub const SHORTCUT: egui::KeyboardShortcut = egui::KeyboardShortcut::new(egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), egui::Key::A); +/// Consume the configured toggle before CAD shortcuts, including in the chat's own window. +/// Bare character keys remain text while a field owns the keyboard; chords still hide chat. +pub fn toggle_shortcut(app: &mut SolveApp, ctx: &egui::Context) { + if !shown(app) || crate::keymap::capturing(app) { + return; + } + let keys = crate::keymap::keys(app, "ui.assistant"); + let typing = ctx.egui_wants_keyboard_input(); + let pressed = ctx.input_mut(|input| { + let mut pressed = false; + input.events.retain(|event| { + if let egui::Event::Key { key, modifiers, pressed: true, repeat, .. } = event { + if typing && !modifiers.command && !modifiers.ctrl && !modifiers.alt { + return true; + } + if keys.contains(&crate::keymap::key_name(*key, *modifiers)) { + pressed |= !repeat; + return false; + } + } + true + }); + pressed + }); + if pressed { + toggle(app); + } +} fn panel_id(left: bool) -> Id { Id::new(if left { "sc_agent_chat_left" } else { "sc_agent_chat_right" }) @@ -50,9 +76,11 @@ pub fn toggle(app: &mut SolveApp) { } /// The tooltip of the chat's buttons: its name and shortcut. -pub fn tip() -> String { - let key = if cfg!(target_os = "macos") { "Cmd+Shift+A" } else { "Ctrl+Shift+A" }; - format!("{} ({key})", tr("ui.agent_chat")) +pub fn tip(app: &SolveApp) -> String { + match crate::keymap::display_for(app, "ui.assistant") { + Some(key) => format!("{} ({key})", tr("ui.agent_chat")), + None => tr("ui.agent_chat").to_string(), + } } /// The panel, when the chat is turned on and open. Call before the central viewport is laid out. @@ -69,9 +97,6 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if !shown(app) { return; } - if ctx.input_mut(|i| i.consume_shortcut(&SHORTCUT)) { - toggle(app); - } // A window that isn't drawn this frame closes; the next one opens at the saved place. if !(app.agent_chat.open && app.preferences.agent_chat_popped) { app.agent_chat.window_placed = false; @@ -531,6 +556,11 @@ fn window(app: &mut SolveApp, ctx: &egui::Context) { // The side panel isn't drawn: its place no longer counts as "in the chat". app.agent_chat.panel_rect = None; ctx.show_viewport_immediate(egui::ViewportId::from_hash_of("sc_agent_chat_window"), builder, |ui, class| { + // Root/embedded inputs are handled by SolveApp::logic. A native chat window owns + // its input and must see the toggle before its text editor can consume the chord. + if class != egui::ViewportClass::EmbeddedWindow { + toggle_shortcut(app, ui.ctx()); + } let t = Tokens::get(); let frame = Container::new(ui.ctx(), Surface::Panel).edge_frame(t.dialog_body); let r = Container::new(ui.ctx(), Surface::Viewport).central().frame(frame).show(ui, |ui| ui_kit::scope(ui, |ui| body(app, ui, false))); @@ -555,9 +585,6 @@ fn window(app: &mut SolveApp, ctx: &egui::Context) { if ctx.input(|i| !i.raw.hovered_files.is_empty()) { drop_hint(&ctx, r.response.rect); } - if ctx.input_mut(|i| i.consume_shortcut(&SHORTCUT)) { - toggle(app); - } // The whole window is the chat, so New chat works anywhere in it. if ctx.input_mut(|i| i.consume_shortcut(&NEW_CHAT_SHORTCUT)) { request_new_chat(app); @@ -667,7 +694,7 @@ fn strip(app: &mut SolveApp, ui: &mut egui::Ui) { if app.preferences.agent_chat_side == "left" { [r.right_top(), r.right_bottom()] } else { [r.left_top(), r.left_bottom()] }, t.primary_border(t.border), ); - let tip = format!("{} · {}", tip(), state.label()); + let tip = format!("{} · {}", tip(app), state.label()); if resp.on_hover_text(tip).clicked() { app.preferences.agent_chat_minimized = false; } diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index e7de0778c..e5d869ab7 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -28,7 +28,6 @@ pub const RESERVED: &[&str] = &[ "Ctrl+O", "Ctrl+W", "Ctrl+Comma", - "Ctrl+Shift+A", "Ctrl+C", "Ctrl+X", "Ctrl+V", @@ -872,6 +871,92 @@ pub fn capturing(app: &SolveApp) -> bool { mod tests { use super::*; + #[test] + fn assistant_shortcut_can_be_rebound_cleared_saved_and_reset() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.frames(2); + assert_eq!(effective(&h.app, "ui.assistant").as_deref(), Some("Ctrl+Shift+A")); + bind(&mut h.app, "ui.assistant", "Ctrl+Shift+J", false).unwrap(); + h.step(&json!({"key":"A", "cmd":true, "shift":true})).unwrap(); + assert!(!h.app.agent_chat.open, "the old key no longer opens Assistant"); + let held_key = |pressed, repeat| egui::Event::Key { + key: egui::Key::J, + physical_key: None, + pressed, + repeat, + modifiers: egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT), + }; + h.frame_with(vec![held_key(true, false)]); + assert!(h.app.agent_chat.open, "the custom key opens Assistant"); + h.frame_with(vec![held_key(true, true)]); + assert!(h.app.agent_chat.open, "holding the key does not repeatedly toggle"); + h.frame_with(vec![held_key(false, false)]); + h.step(&json!({"key":"J", "cmd":true, "shift":true})).unwrap(); + assert!(!h.app.agent_chat.open, "the custom key also hides Assistant"); + let saved = h.app.keymap.prefs(); + let mut restored = app(); + restored.keymap.load(&saved); + assert_eq!(keys(&restored, "ui.assistant"), ["Ctrl+Shift+J"]); + assert!(bind(&mut h.app, "solid.box", "Ctrl+Shift+J", false).is_err(), "conflicts are reported"); + bind(&mut h.app, "ui.assistant", "", false).unwrap(); + h.step(&json!({"key":"J", "cmd":true, "shift":true})).unwrap(); + assert!(!h.app.agent_chat.open, "clearing disables the shortcut"); + reset(&mut h.app, Some("ui.assistant")); + h.step(&json!({"key":"A", "cmd":true, "shift":true})).unwrap(); + assert!(h.app.agent_chat.open, "reset restores the original shortcut"); + } + + #[test] + fn a_released_unbound_assistant_chord_does_not_start_a_plain_letter_command() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + bind(&mut h.app, "ui.assistant", "Ctrl+Shift+J", false).unwrap(); + h.frames(2); + let modifiers = egui::Modifiers::COMMAND.plus(egui::Modifiers::SHIFT); + h.frame_with(vec![ + egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: false, repeat: false, modifiers }, + egui::Event::ModifiersChanged(egui::Modifiers::NONE), + ]); + assert!(!h.app.agent_chat.open, "the old chord is unbound"); + assert!(h.app.dialog.is_none() && h.app.tool.is_none(), "Ctrl+Shift+A must not become plain A (Appearance) after release"); + } + + #[test] + fn assistant_shortcut_respects_text_focus_ai_switch_and_capture() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + bind(&mut h.app, "ui.assistant", "Ctrl+Shift+J", false).unwrap(); + h.app.preferences.ai_features = false; + h.step(&json!({"key":"J", "cmd":true, "shift":true})).unwrap(); + assert!(!h.app.agent_chat.open); + h.app.preferences.ai_features = true; + h.step(&json!({"key":"J", "cmd":true, "shift":true, "alt":true})).unwrap(); + assert!(!h.app.agent_chat.open, "extra modifiers do not match"); + h.step(&json!({"key":"J", "cmd":true, "shift":true})).unwrap(); + assert!(h.app.agent_chat.open); + h.ctx.memory_mut(|m| m.request_focus(egui::Id::new("sc_agent_chat_input"))); + h.frames(2); + h.step(&json!({"key":"J", "cmd":true, "shift":true})).unwrap(); + assert!(!h.app.agent_chat.open, "a chord can hide Assistant from its input field"); + bind(&mut h.app, "ui.assistant", "J", true).unwrap(); + h.call("ui.palette", json!({})); + h.frames(3); + h.step(&json!({"key":"J"})).unwrap(); + assert!(!h.app.agent_chat.open, "a bare letter in a text field remains text"); + h.call("ui.palette", json!({"open":false})); + h.frames(2); + crate::prefs::open_at(&mut h.app, crate::prefs::PAGE_SHORTCUTS); + h.app.keymap.capturing = Some("solid.box".into()); + h.step(&json!({"key":"J"})).unwrap(); + assert!(!h.app.agent_chat.open, "recording a shortcut must not activate it"); + assert!(crate::agent_chat::assistant_tip(&h.app, crate::agent_chat::AssistantMark::Ready).contains("(J)")); + bind(&mut h.app, "ui.assistant", "", false).unwrap(); + assert!(!crate::agent_chat::assistant_tip(&h.app, crate::agent_chat::AssistantMark::Ready).contains("(J)")); + } + fn app() -> SolveApp { SolveApp::new(solidcraft_engine::Session::default(), Default::default()) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9e566db1c..8b8b5e581 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1554,6 +1554,12 @@ impl SolveApp { } return; } + if id == "ui.assistant" { + if agent_chat::shown(self) { + agent_chat::toggle(self); + } + return; + } if id == "ui.palette" { shortcut_box::open(self, None); return; @@ -2822,6 +2828,7 @@ impl SolveApp { if !keymap::capturing(self) { expression_complete::begin_frame(ctx); } + agent_chat::toggle_shortcut(self, ctx); // A digit for a construction line's Length box is not a shortcut (#10258). sketch_construction::claim_typed_length(self, ctx); if !self.embedded { diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 2a565528e..6618df363 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -2148,7 +2148,7 @@ fn assistant_button(app: &mut SolveApp, ui: &mut egui::Ui, at: Rect) { let resp = ui.interact(at, ui.id().with("assistant_button"), Sense::click()); crate::scenario::publish_target("titlebar:assistant", at); let mark = crate::agent_chat::assistant_mark(app); - let tip = crate::agent_chat::assistant_tip(mark); + let tip = crate::agent_chat::assistant_tip(app, mark); resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), &tip)); let state = match mark { AssistantMark::Quiet => crate::ui_kit::AssistantEntryState::Quiet, @@ -3215,13 +3215,15 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) { } return; } - let (keys, mods) = ctx.input(|i| { - let keys: Vec<(egui::Key, bool)> = i - .events + // A quick chord can press and release all modifiers in one frame. Dispatch each key + // with its own modifiers, not the final frame state (an unbound Ctrl+Shift+A is not A). + let keys: Vec<_> = ctx.input(|i| { + i.events .iter() - .filter_map(|e| if let egui::Event::Key { key, pressed: true, repeat, .. } = e { Some((*key, *repeat)) } else { None }) - .collect(); - (keys, i.modifiers) + .filter_map( + |e| if let egui::Event::Key { key, pressed: true, repeat, modifiers, .. } = e { Some((*key, *repeat, *modifiers)) } else { None }, + ) + .collect() }); // A theme pasted on the Interface page is a theme, not copied components (#8226). crate::prefs::take_theme_paste(app, ctx); @@ -3232,7 +3234,7 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) { } else { crate::edit_clipboard::flush(app, ctx); } - for (k, repeat) in keys { + for (k, repeat, mods) in keys { use egui::Key; // Only Esc pressed twice in a row finishes a sketch: any other key in between resets it. if k != Key::Escape { diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 9a06bbd3e..5a3f31b1a 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -501,3 +501,5 @@ the agent and puts your permission setting back. - `--markdown` writes the issue's comment template filled in; add the quantization, download size, and runtime before you post it. `--json` keeps each task's failed rules, conversation, and design before and after. Both files are rewritten after every task. + +The show/hide shortcut defaults to Ctrl+Shift+A (Cmd+Shift+A on macOS). Change, clear or reset **Toggle Assistant** (`ui.assistant`) in Preferences → Shortcuts. The binding is saved with the other keyboard shortcuts; the assistant button tooltip follows it. Disabling AI features also disables the toggle. From 6a7275a5afee1a72415ba7720b1302565937e9ba Mon Sep 17 00:00:00 2001 From: Dahak Builds Date: Mon, 2 Nov 2026 00:08:41 +0000 Subject: [PATCH 54/55] Agent chat: copy an entire sent prompt or assistant message (#10675) (#10741) * claim: #10675 * agent chat: Copy message on each sent prompt and assistant text block (#10675) A visible Copy message button on each copyable transcript message and a right-click menu with the same action. Assistant replies copy their original Markdown, prompts copy the text as entered; picture-only prompts and thoughts get no action. Hover-only message areas keep partial text selection working. * agent chat: complete Copy message locales and tests (#10675) * agent chat: route the message copy menu through ui_kit::Container (ui-containers gate) --------- Co-authored-by: Dahak Builds --- .../pending/agent-chat-copy-message.json | 9 ++ crates/ui-egui/src/agent_chat/panel.rs | 61 ++++++++++++ crates/ui-egui/src/agent_chat/tests.rs | 98 +++++++++++++++++++ 3 files changed, 168 insertions(+) create mode 100644 assets/locales/pending/agent-chat-copy-message.json diff --git a/assets/locales/pending/agent-chat-copy-message.json b/assets/locales/pending/agent-chat-copy-message.json new file mode 100644 index 000000000..cb724aa67 --- /dev/null +++ b/assets/locales/pending/agent-chat-copy-message.json @@ -0,0 +1,9 @@ +{ + "en": { "ui.agent_chat_copy_message": "Copy message" }, + "de": { "ui.agent_chat_copy_message": "Nachricht kopieren" }, + "ar": { "ui.agent_chat_copy_message": "نسخ الرسالة" }, + "he": { "ui.agent_chat_copy_message": "העתק הודעה" }, + "ja": { "ui.agent_chat_copy_message": "メッセージをコピー" }, + "vi": { "ui.agent_chat_copy_message": "Sao chép tin nhắn" }, + "zh": { "ui.agent_chat_copy_message": "复制消息" } +} diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 8529dd01e..201b2f8b8 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -1613,6 +1613,49 @@ fn auth_box(app: &mut SolveApp, ui: &mut egui::Ui) { }); } +/// The visible **Copy message** button of one transcript message (#10675): copies the whole +/// message — the prompt as entered, or the assistant's original Markdown — and nothing else. +/// A streaming reply copies the stable text received so far, which is what `text` holds. +#[cfg(not(target_arch = "wasm32"))] +fn copy_message_button(ui: &mut egui::Ui, n: usize, text: &str) { + let b = ui_kit::button(ui, tr("ui.agent_chat_copy_message"), ui_kit::Button::Small); + crate::scenario::publish_handle(&format!("agent_chat:copy:{n}"), b.rect.center()); + if b.clicked() { + ui.ctx().copy_text(text.to_owned()); + } +} + +/// The right-click menu of one transcript message (#10675): the same single action as the +/// visible button, on the whole message area, beside the composer's own text menu. +/// The area stays hover-only so partial text selection keeps working, so the menu opens on a +/// right-click released over it rather than on a click the response itself would report. +#[cfg(not(target_arch = "wasm32"))] +fn copy_message_menu(ui: &egui::Ui, response: &egui::Response, n: usize, text: &str) { + crate::scenario::publish_rect(&format!("agent_chat:msg:{n}"), response.rect); + let opened = ui + .input(|i| i.pointer.button_released(egui::PointerButton::Secondary) && i.pointer.interact_pos().is_some_and(|p| response.rect.contains(p))); + let mut copy = false; + Container::new(ui.ctx(), Surface::Popup) + .menu(response) + .at_pointer_fixed() + .frame(ui_kit::Menu::frame()) + .open_memory(if opened { Some(egui::SetOpenCommand::Bool(true)) } else { None }) + .show(|ui| { + ui_kit::Menu::show(ui, crate::context_menu::LIST_W, |ui| { + let item = ui_kit::MenuItem::new("copy_message", tr("ui.agent_chat_copy_message"), "copy"); + let row = item.show(ui); + crate::scenario::publish_handle(&format!("agent_chat:copy_menu:{n}"), row.rect.center()); + if row.clicked() { + copy = true; + ui.close(); + } + }); + }); + if copy { + ui.ctx().copy_text(text.to_owned()); + } +} + #[cfg(not(target_arch = "wasm32"))] fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); @@ -1626,6 +1669,9 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { for (n, item) in app.agent_chat.items.iter().enumerate() { match item { Item::User { text, image, pictures, context, files } => { + // A picture-only prompt has no text to copy: no action rather than an empty copy (#10675). + let copyable = !text.is_empty(); + let before = ui.cursor(); ui_kit::assistant_bubble(ui, |ui| { if !text.is_empty() { ui.add(egui::Label::new(RichText::new(text).color(t.text)).selectable(true).wrap()); @@ -1640,13 +1686,28 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) { } context_chips(ui, context, false); files_line(ui, files.iter().map(String::as_str)); + if copyable { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| copy_message_button(ui, n, text)); + } }); + if copyable { + let drawn = egui::Rect::from_x_y_ranges(before.x_range(), before.min.y..=ui.cursor().min.y); + let resp = ui.interact(drawn, Id::new(("agent_chat_msg", n)), Sense::hover()); + copy_message_menu(ui, &resp, n, text); + } } Item::Agent { thought, text } => { if *thought { ui.add(egui::Label::new(RichText::new(text).italics().color(t.text_dim)).selectable(true).wrap()); } else { + let before = ui.cursor(); ui_kit::assistant_prose(ui, |ui| super::markdown_view::show(ui, n, text)); + if !text.is_empty() { + copy_message_button(ui, n, text); + let drawn = egui::Rect::from_x_y_ranges(before.x_range(), before.min.y..=ui.cursor().min.y); + let resp = ui.interact(drawn, Id::new(("agent_chat_msg", n)), Sense::hover()); + copy_message_menu(ui, &resp, n, text); + } } } Item::Tool { .. } => { diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 9f2054c91..7040dd891 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -4159,3 +4159,101 @@ fn tool_room_beside_the_docked_assistant_survives_an_inside_out_view() { assert!(free.min.x.is_finite() && free.max.x.is_finite(), "{side}: {free:?}"); } } + +// ---- Copy message (#10675) ---- + +/// A chat with a multi-paragraph prompt and a Markdown reply, both drawn. +fn chat_with_copiable_messages() -> crate::scenario::Harness { + let mut h = crate::scenario::Harness::new(); + h.call("ui.agent_chat", json!({"open": true})); + h.frames(3); + h.app.agent_chat.items.push(Item::User { + text: "make a plate\n\nwith two holes:\n- 6 mm\n- 8 mm".into(), + image: false, + pictures: Vec::new(), + files: Vec::new(), + context: Context::default(), + }); + h.app.agent_chat.items.push(Item::Agent { thought: false, text: "# Result\n\nA plate with holes.\n\n```rust\nlet x = 1;\n```".into() }); + h.frames(3); + h +} + +/// The text the last frame copied to the clipboard, if any. +fn copied_text(h: &crate::scenario::Harness) -> Option { + h.output.commands.iter().rev().find_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t.clone()), + _ => None, + }) +} + +fn click_at(h: &mut crate::scenario::Harness, at: egui::Pos2, button: egui::PointerButton) { + h.frame_with(vec![egui::Event::PointerMoved(at)]); + h.frame_with(vec![egui::Event::PointerButton { pos: at, button, pressed: true, modifiers: egui::Modifiers::NONE }]); + h.frame_with(vec![egui::Event::PointerButton { pos: at, button, pressed: false, modifiers: egui::Modifiers::NONE }]); +} + +/// The visible button on a sent prompt copies the whole prompt, as entered. +#[test] +fn the_copy_message_button_copies_the_prompt_as_entered() { + let mut h = chat_with_copiable_messages(); + let at = crate::scenario::handle_at("agent_chat:copy:0").expect("the prompt's Copy message button"); + click_at(&mut h, at, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("make a plate\n\nwith two holes:\n- 6 mm\n- 8 mm"), "the whole prompt, paragraphs and list items"); +} + +/// The visible button on a reply copies its original Markdown: heading, paragraphs, list and +/// fenced code, not the laid-out text. +#[test] +fn the_copy_message_button_copies_the_reply_as_original_markdown() { + let mut h = chat_with_copiable_messages(); + let at = crate::scenario::handle_at("agent_chat:copy:1").expect("the reply's Copy message button"); + click_at(&mut h, at, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("# Result\n\nA plate with holes.\n\n```rust\nlet x = 1;\n```")); +} + +/// Right-clicking a message opens its menu, and its row copies the same whole reply. +#[test] +fn right_clicking_a_message_offers_copy_message() { + let mut h = chat_with_copiable_messages(); + let msg = crate::scenario::rect_of("agent_chat:msg:1").expect("the reply's message area"); + click_at(&mut h, msg.center(), egui::PointerButton::Secondary); + h.frames(1); // let the popup settle at its final place before clicking its row + let item = crate::scenario::handle_at("agent_chat:copy_menu:1").expect("the right-click menu's Copy message row"); + click_at(&mut h, item, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("# Result\n\nA plate with holes.\n\n```rust\nlet x = 1;\n```")); +} + +/// A reply that is still streaming copies the stable text received so far. +#[test] +fn a_streaming_reply_copies_the_text_received_so_far() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.agent_chat", json!({"open": true})); + h.frames(3); + h.app.agent_chat.items.push(Item::Agent { thought: false, text: "half a repl".into() }); + h.frames(3); + let at = crate::scenario::handle_at("agent_chat:copy:0").expect("the streaming reply's button"); + click_at(&mut h, at, egui::PointerButton::Primary); + assert_eq!(copied_text(&h).as_deref(), Some("half a repl")); +} + +/// A picture-only prompt has no text to copy: no button, no menu, and a thought has none +/// either — the clipboard is never overwritten with an empty string. +#[test] +fn a_picture_only_prompt_and_a_thought_have_no_copy_message_action() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.agent_chat", json!({"open": true})); + h.frames(3); + h.app.agent_chat.items.push(Item::User { + text: String::new(), + image: true, + pictures: Vec::new(), + files: Vec::new(), + context: Context::default(), + }); + h.app.agent_chat.items.push(Item::Agent { thought: true, text: "pondering".into() }); + h.frames(3); + assert!(crate::scenario::handle_at("agent_chat:copy:0").is_none(), "a picture-only prompt hides the text-copy action"); + assert!(crate::scenario::handle_at("agent_chat:copy:1").is_none(), "a thought has no copy action"); + assert!(h.widget("Copy message").is_none(), "nothing to click"); +} From e9b08f4af4f56718581691df7e87c30f316b89b9 Mon Sep 17 00:00:00 2001 From: froglemonade2 <64703083+froglemonade2@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:08:48 +0000 Subject: [PATCH 55/55] Control channel: report the dialog as data, the open tool windows, and what ui.start opened (#9087) (#10740) * claim: #9087 * Control channel: report the dialog as data, the open windows, and what ui.start opened (#9087) `ui.inspect.dialog` (and `ui.editFeature`'s reply) was the dialog's Rust Debug text, which changed with every refactor and couldn't be parsed. It is now an object: the dialog's command, title, the feature an edit rebuilds, its selection inputs, its error, and the commands OK runs (or what it waits for). `hover` in `ui.inspect` and `ui.selection` is a selection-like item instead of Debug text. `ui.inspect` gains `windows`: the tool windows open beside the model (Parameters, Bill of Materials, Design Properties, Sketch Report, material card review) by the command that opens each, and the Help menu's (About, Updates, Shortcuts, Crash Reports, Report, Messages) by their `ui.help` item. Before, an agent couldn't tell these windows were open. `ui.start` and `ui.editFeature` reply with what they opened (tool, dialog, windows), the status line, and `pending` when the start waits for the history and opens on a later frame. Scenario `dialog` checks match words of the dialog's state from the app directly, so the scenario files are unchanged. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/ui-egui/src/control.rs | 114 +++++++++++++++++++++++++++++++-- crates/ui-egui/src/scenario.rs | 10 +-- crates/ui-egui/src/viewport.rs | 6 +- docs/control-protocol.md | 25 +++++++- 4 files changed, 141 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d2e9994ba..086d52f15 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -187,6 +187,55 @@ fn wrap(r: Result) -> Outcome { /// The design's own Sketches folder (`Visibility::hidden_folders`), which `showSketches` sets. const SKETCHES_FOLDER: &str = "c0/sketches"; +/// The open dialog as `ui.inspect`, `ui.start` and `ui.editFeature` report it: its command, its +/// picks and what OK runs, in the commands' own terms rather than the form's internals (#9087). +fn dialog_state(app: &SolveApp) -> Value { + let Some(d) = app.dialog.as_ref() else { return Value::Null }; + let runs = crate::dialogs::apply_commands(app, d); + json!({ + "command": d.command(), + "title": crate::dialogs::report_title(d), + "editing": d.editing.map(|(feature, _)| feature), + "inputs": d.inputs.iter().enumerate().map(|(i, input)| json!({"label": input.label, "items": input.items, "active": i == d.active})).collect::>(), + "error": d.error, + "commands": runs.as_ref().ok().map(|cmds| cmds.iter().map(|(command, params)| json!({"command": command, "params": params})).collect::>()), + "waiting": runs.err(), + }) +} + +/// The windows open beside the model (#9087), each named by what opens it: the command +/// `ui.start` takes, or the `ui.help` item. +fn open_windows(app: &SolveApp) -> Vec<&'static str> { + [ + (app.params.is_some(), "parameters.change"), + (app.design_properties.is_some(), "document.metadata"), + (app.sketch_report.is_some(), "sketch.inspect"), + (app.bom.is_some(), "assembly.bom"), + (app.material_card_review.is_some(), "material.properties.validate"), + (app.help.about, "about"), + (app.updater.open, "updates"), + (app.keymap.open, "shortcuts"), + (app.crashes.open, "crashes"), + (app.issue_report.draft.is_some(), "report"), + (app.messages.open, "messages"), + ] + .into_iter() + .filter_map(|(open, command)| open.then_some(command)) + .collect() +} + +/// What a start or an edit opened: the tool, the dialog and the windows. `pending` while it +/// waits for the history to compute first; it opens on a later frame (`ui.inspect` shows it). +fn started(app: &SolveApp) -> Value { + json!({ + "tool": app.tool.as_ref().map(|t| t.cmd), + "dialog": dialog_state(app), + "windows": open_windows(app), + "pending": app.pending_feature_edit.is_some() || app.start_after_roll.is_some(), + "status": app.status.as_ref().map(|(text, _, error)| json!({"text": text, "error": error})), + }) +} + /// `UiState` as `ui.inspect` and `ui.set` report it, with the browser's view of the design /// (kept in the session) under the names the UI state used to give it. fn ui_state(app: &SolveApp) -> Value { @@ -665,9 +714,10 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> "viewport": app.viewport.rect.map(|r| json!([r.left(), r.top(), r.width(), r.height()])), "camera": app.cam, "tool": app.tool.as_ref().map(|t| t.cmd), - "dialog": app.dialog.as_ref().map(|d| format!("{d:?}")), + "dialog": dialog_state(app), + "windows": open_windows(app), "status": app.status.as_ref().map(|(text, _, error)| json!({"text": text, "error": error})), - "hover": app.viewport.hover.as_ref().map(|h| format!("{h:?}")), + "hover": app.viewport.hover, "renderer": if app.viewport.gpu.is_some() { "gpu" } else { "cpu" }, "frame_ms": app.frame_ms, "draw": app.viewport.draw_stats.as_ref().and_then(|s| s.lock().ok().map(|d| json!({ @@ -841,7 +891,7 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> return err(e); } } - ok(json!({"tool": app.tool.as_ref().map(|t| t.cmd), "dialog": app.dialog.as_ref().map(|d| format!("{d:?}"))})) + ok(started(app)) } "ui.move" | "ui.click" => { let (Some(x), Some(y)) = (f("x"), f("y")) else { return err("missing x/y") }; @@ -921,12 +971,16 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) -> }; let Some(id) = app.session.doc.find_feature(&key).map(|f| f.id) else { return err(format!("no feature `{key}`")) }; app.edit_feature(id); - ok(json!({"dialog": app.dialog.as_ref().map(|d| format!("{d:?}")), "marker": app.session.doc.marker})) + let mut reply = started(app); + if let Some(o) = reply.as_object_mut() { + o.insert("marker".into(), json!(app.session.doc.marker)); + } + ok(reply) } "ui.selection" => ok(json!({ "selection": app.session.selection, "dialog": app.dialog.as_ref().map(|d| d.inputs.iter().map(|i| json!({"label": i.label, "items": i.items})).collect::>()), - "hover": app.viewport.hover.as_ref().map(|h| format!("{h:?}")), + "hover": app.viewport.hover, "dimensions": crate::dim_view::drawn().into_iter().map(|(id, p)| json!({"id": id, "x": p.x, "y": p.y})).collect::>(), "shown_dimensions": crate::dim_view::model_drawn() .into_iter() @@ -2496,6 +2550,56 @@ mod tests { } } + /// #9087: the dialog is reported as data (its command, inputs and what OK runs), not as the + /// form's Debug text; `ui.start` and `ui.editFeature` reply with what they opened, and the + /// tool windows (Parameters, Bill of Materials) are reported by the command that opens them. + #[test] + fn dialogs_and_tool_windows_are_reported_as_data() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 40, "width": 30, "height": 20})).unwrap(); + let mut h = crate::scenario::Harness::new(); + h.app = SolveApp::new(s, Services::default()); + let r = h.call("ui.start", json!({"command": "solid.fillet"})); + let d = &r["result"]["dialog"]; + assert_eq!((&d["command"], &d["title"], &d["editing"]), (&json!("solid.fillet"), &json!("FILLET"), &Value::Null), "{r}"); + assert_eq!((&d["inputs"][0]["active"], &d["inputs"][0]["items"]), (&json!(true), &json!([])), "{r}"); + assert!(d["commands"].is_null() && d["waiting"].is_string(), "no edge picked yet: {r}"); + assert_eq!((&r["result"]["pending"], &r["result"]["windows"]), (&json!(false), &json!([])), "{r}"); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["dialog"], *d, "ui.inspect reports the same"); + crate::dialogs::cancel(&mut h.app); + + let feature = h.app.session.doc.features[0].id; + let r = h.call("ui.editFeature", json!({"feature": feature})); + let d = &r["result"]["dialog"]; + assert_eq!((&d["command"], &d["editing"]), (&json!("solid.box"), &json!(feature)), "{r}"); + // OK rebuilds the feature in place, from what the form holds. + let runs = &d["commands"][0]; + assert_eq!((&runs["command"], &runs["params"]["command"]), (&json!("timeline.redefine"), &json!("solid.box")), "{r}"); + assert_eq!((&runs["params"]["feature"], &runs["params"]["params"]["length"]), (&json!(feature), &json!("40")), "{r}"); + assert!(r["result"].get("marker").is_some(), "{r}"); + crate::dialogs::cancel(&mut h.app); + + for (command, windows) in + [("parameters.change", json!(["parameters.change"])), ("assembly.bom", json!(["parameters.change", "assembly.bom"]))] + { + let r = h.call("ui.start", json!({"command": command})); + assert_eq!((&r["result"]["dialog"], &r["result"]["tool"], &r["result"]["windows"]), (&Value::Null, &Value::Null, &windows), "{r}"); + assert_eq!(h.call("ui.inspect", json!({}))["result"]["windows"], windows, "{command}"); + } + h.call("ui.help", json!({"item": "about"})); + assert_eq!( + h.call("ui.inspect", json!({}))["result"]["windows"], + json!(["parameters.change", "assembly.bom", "about"]), + "the Help menu's windows too" + ); + + // What is under the pointer is a selection-like item, not the viewport's Debug text. + h.app.viewport.hover = + Some(crate::viewport::Hit::Face { body: "Body1".into(), index: 2, point: solidcraft_engine::geom::Vec3::new(1.0, 2.0, 3.0) }); + let hover = json!({"type": "face", "body": "Body1", "index": 2, "point": [1.0, 2.0, 3.0]}); + assert_eq!(h.call("ui.selection", json!({}))["result"]["hover"], hover); + } + /// #9087: a sample index that names no sample is refused, so an agent can tell a typo from /// a sample that opened. The index is checked before it reaches `open_sample`, which would /// otherwise drop it and reply `ok`. diff --git a/crates/ui-egui/src/scenario.rs b/crates/ui-egui/src/scenario.rs index 757141daf..e8c9c333a 100644 --- a/crates/ui-egui/src/scenario.rs +++ b/crates/ui-egui/src/scenario.rs @@ -897,14 +897,16 @@ pub fn check(h: &mut Harness, e: &Value) -> Result<(), String> { } } "dialog" => { - let d = &ui["dialog"]; + // A word of the dialog's state as the code holds it: scenarios check fields that + // `ui.inspect` reports only as the command OK runs. + let d = h.app.dialog.as_ref().map(|d| format!("{d:?}")); let ok = match v { - Value::Null => d.is_null(), - Value::String(w) => d.as_str().is_some_and(|d| d.contains(w.as_str())), + Value::Null => d.is_none() && ui["dialog"].is_null(), + Value::String(w) => d.as_deref().is_some_and(|d| d.contains(w.as_str())), _ => false, }; if !ok { - return Err(format!("dialog: got {d}, want {v}")); + return Err(format!("dialog: got {d:?}, want {v}")); } } "tool" => { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 74e69eb76..f9c78e174 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -229,8 +229,10 @@ pub struct ViewportState { pub(crate) grid_plane: std::sync::Mutex, } -/// Something under the cursor. -#[derive(Clone, Debug, PartialEq)] +/// Something under the cursor. The control channel reports it in the selection's own form +/// (`{"type": "edge", "body", "index", …}`, #9087). +#[derive(Clone, Debug, PartialEq, serde::Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] pub enum Hit { SketchPoint { sketch: u64, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7bcd5ea29..78d8ac7b6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -372,11 +372,11 @@ no box selection. | Method | Params | Notes | |---|---|---| -| `ui.inspect` | — | UI state, pending file picker (`file_picker_busy`; compatibility alias `file_dialog_open`, no path), what is hidden (`visibility`: bodies, origin and construction items, sketches, joints (`hidden_joints`, joint ids); set it with the `browser.visibility` command), viewport rect, camera, active tool/dialog, the status line (`status`: text and whether it is an error), hover, renderer, timings, what the GPU drew last frame (`draw`: `draw_calls`, `triangles`, `line_segments`, `supersampled`; null without a GPU) and the graphics `adapter`, live preview (`active`, `busy`, `error`, `ms`, bodies it stands in for) | +| `ui.inspect` | — | UI state, pending file picker (`file_picker_busy`; compatibility alias `file_dialog_open`, no path), what is hidden (`visibility`: bodies, origin and construction items, sketches, joints (`hidden_joints`, joint ids); set it with the `browser.visibility` command), viewport rect, camera, the active tool (its command id), the open dialog (`dialog`, below), the windows open beside the model (`windows`, each named by what opens it: the `ui.start` command `parameters.change`, `document.metadata`, `sketch.inspect`, `assembly.bom` or `material.properties.validate`, or the `ui.help` item `about`, `updates`, `shortcuts`, `crashes`, `report`, or `messages`), what is under the pointer (`hover`, in the form of a selection item: `{"type": "edge", "body", "index", "mid", "point"}`, or null), the status line (`status`: text and whether it is an error), renderer, timings, what the GPU drew last frame (`draw`: `draw_calls`, `triangles`, `line_segments`, `supersampled`; null without a GPU) and the graphics `adapter`, live preview (`active`, `busy`, `error`, `ms`, bodies it stands in for) | | `ui.set` | any `UiState` field (`tab`, `perspective`, `showGrid`, `dark`, `layout`, …), and the browser's view of the design, saved with it: `showOrigin` (the Origin folder's eye), `showSketches` (the design's Sketches folder, `c0/sketches` in `hiddenFolders`), `hiddenBodies`, `hiddenOrigin`, `hiddenSketches`, `shownSketches`, `hiddenJoints`, `hiddenFolders`, `hiddenProfiles`, `shownDims`, `lockedBodies` (whole lists; `browser.visibility` changes single items) | `dark: false` switches to the light theme; `layout: "floating"` (default) or `"compact"` (`"docked"` is also accepted) selects the transient shell layout without saving a preference. Scenarios use `{"call":"ui.set","params":{"layout":"docked"}}` | | `ui.view` | `view`: `front`, `back`, `top`, `bottom`, `left`, `right`, `iso`, `home`, `fit`; `animate` (bool, default false: snap) | | | `ui.camera` | `target?`: `[x, y, z]` (mm), `yaw?`, `pitch?`, `roll?` (radians), `distance?` (mm), `fov?`, `up?`; `fit?`: `true`, `false` or `[occurrence id or name…]` (`root`: the bodies outside every component) | the viewport's orbit camera: it looks at `target` from `distance` away; `yaw` 0 looks along +Y (from the front), `pitch` is the elevation (±π/2: straight down or up), `roll` turns the image. Fields given are set first (the others keep their values), then `fit` frames the listed occurrences (or everything), keeping the direction. The reply, passed back, sets the same view again, so a framing can be stored and replayed. `fov` is the angle the view is drawn with: 0 (parallel) with Perspective view off or while a sketch is open, else `perspective_fov`; in Render, the Render camera's own. `fov` and `up` follow the perspective setting (`ui.set`), its angle (`ui.prefs {perspective_fov}`) and the up axis preference (`ui.prefs`) and can't change here; a refused field changes nothing | -| `ui.start` | `command`, `params?` | like a toolbar click: starts the sketch tool or dialog for the command. `params` sets what the dialog opens on, and nothing runs until OK: `joint.drive` takes `joint` (id or name; without it, the joint picked in the browser, else the first joint that moves; a rigid joint opens to say why it has nothing to drive, with an Edit Joint button, handle `drive:edit_joint`) and `values` (numbers in degrees or millimetres, or expressions); `motion.study` takes `study` (id or name), which opens that study to edit and chart. A command that takes no params is refused before it starts; a param the dialog doesn't take is refused and the dialog closes | +| `ui.start` | `command`, `params?` | like a toolbar click: starts the sketch tool or dialog for the command. `params` sets what the dialog opens on, and nothing runs until OK: `joint.drive` takes `joint` (id or name; without it, the joint picked in the browser, else the first joint that moves; a rigid joint opens to say why it has nothing to drive, with an Edit Joint button, handle `drive:edit_joint`) and `values` (numbers in degrees or millimetres, or expressions); `motion.study` takes `study` (id or name), which opens that study to edit and chart. A command that takes no params is refused before it starts; a param the dialog doesn't take is refused and the dialog closes. Replies what it opened: `tool`, `dialog` and `windows` as `ui.inspect` gives them, `status` (where a command that starts nothing says why), and `pending: true` when the start waits for the history to compute and opens on a later frame | | `ui.click` | `x`, `y` (screen points), `button?`: left/right/middle, `shift?`, `ctrl?`, `double?` | real pointer input | | `ui.move` | `x`, `y`, `shift?`, `alt?`, `ctrl?`, `cmd?` | pointer movement without a button; modifiers apply until the next synthetic move/click; a move with omitted modifiers releases them. With `nav: "touchpad"`, Shift pans and Alt/Option orbits. | | `ui.drag` | `x0`, `y0`, `x1`, `y1`, `via?`, `button?`, `shift?`, `ctrl?`, `steps?`, `hold?`, `hold_end?` | press, move, release; `via` is a list of `[x, y]` points passed through on the way (`steps` moves to each); a left drag on the model is a box selection (left to right: window, right to left: crossing), or with `lassoSelect` on (`ui.set`, the SELECT panel's Lasso) a freehand lasso that takes what is wholly inside it; with OpenSCAD navigation, plain left-drag on empty space orbits, Shift+left-drag box-selects, and drags starting on sketch geometry edit it; `hold` keeps the button down that many frames first (a right press-and-hold opens the marking menu, releasing over a direction picks it), `hold_end` that many frames at the end (a sketch drag shows its snap) | @@ -393,7 +393,7 @@ no box selection. | `ui.at` | `world: [x,y,z]` \| `sketch: [x,y]` \| `plane: "XY"` \| `axis: "Z"` \| `dimension: "d1"` (its value text) \| `handle: "arrow"` (a manipulator handle, see `scenario::publish_handle`) | the screen point (a scenario step's target; see `crates/ui-egui/src/scenario.rs`) | | `ui.pick` | `pixels?: [[x,y]…]`, `rays?: [{origin, dir}…]`, `frame?: "window"\|"model"`, `width?`, `height?`, `edges?` (default true), `edge_px?` (default 6), `all?`, `include_ghosted?` | read-only geometry under each pixel or ray (#6304): one entry per input, `null` where nothing is hit — body, face index, exact world `point` and outward `normal`, `depth`, `occurrence`/`component` for placed parts, `edge`/`vertex` within `edge_px` of a pixel, `section_cap: true` on a cut face. `window` pixels are physical pixels of a window screenshot; `model` pixels are pixels of a `ui.render` of `width`×`height` (default 960×600), so it works headless. As `view.pick` through `engine.execute`/`engine.batch`. See `crates/ui-egui/src/view_pick.rs` | | `ui.handles` | `prefix?` | the handles drawn last frame, `[{name, x, y}]`: toolbar buttons and drop-down items `toolbar:` (the button alone: `button:`; a drop-down row: `dropdown:`, highlighted `dropdown_hot:`, its pin `dropdown_pin:`; Customize Toolbar's check boxes `customize:`), ribbon tabs `tab:` (MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW, SHEET METAL, WELDMENTS; contextual SKETCH; workspace RENDER), the toolbar menu button `ribbon:add_tab`, the hint when every tab is hidden `ribbon:tabs_hidden`, Preferences tab check boxes `prefs:toolbar_tab:`, panel labels `panel::` (also `ribbon:section::
`), document overflow list `tab:overflow`, workspace column `ribbon:workspace`, command-search launcher `ribbon:search`, browser rows `row: