From 9685ef571150b267ec68de3e3e43b7313cd2c40c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 04:33:18 -0800 Subject: [PATCH 01/69] =?UTF-8?q?Image=20Trace:=20Edit=20>=20Tracing=20Pre?= =?UTF-8?q?sets=E2=80=A6=20manages,=20imports=20and=20exports=20tracing=20?= =?UTF-8?q?presets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Edit > Tracing Presets… opens a manager that lists the built-in presets (in brackets, read-only) and the saved ones, with the selected preset's settings. New… makes a preset from the selected one, and Edit… and Delete change saved presets, through an editor with the Image Trace panel's settings; Cancel saves nothing. Import… and Export… exchange saved presets through a .vctracepresets file, and an import asks before it replaces saved presets of the same names. - imageTrace.presets.export {names?, path?} and imageTrace.presets.import {path? | data? | dataBase64?, replace?}: a versioned JSON file of at most 4 MiB and 1,000 presets; an import checks every preset first and a file with a fault changes nothing. - imageTrace.presets.save refuses a new preset when 1,000 are saved. - ui.tracingPresetsDialog {selected?}; opening a .vctracepresets file imports it. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd.rs | 4 + crates/engine/src/cmd/buildcmds.rs | 24 +- crates/engine/src/cmd/buildcmds/trace.rs | 159 ++++++ crates/engine/src/tests/build.rs | 105 ++++ crates/mcp/src/ui_catalog.rs | 6 + crates/ui-egui/src/dialogs.rs | 4 + crates/ui-egui/src/dialogs/tracing_presets.rs | 493 ++++++++++++++++++ .../src/dialogs/tracing_presets/tests.rs | 329 ++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/io/open.rs | 4 + crates/ui-egui/src/io/save.rs | 1 + crates/ui-egui/src/menus/run.rs | 4 + crates/ui-egui/src/menus/tree.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/panels/image_trace.rs | 25 +- crates/ui-egui/src/shortcuts/tests.rs | 3 +- docs/mcp.md | 21 +- docs/target-app-parity.md | 1 + 44 files changed, 1280 insertions(+), 18 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/tracing_presets.rs create mode 100644 crates/ui-egui/src/dialogs/tracing_presets/tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 80ed19d145..601f6e9dab 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -831,6 +831,10 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry}; /// A saved Image Trace preset ([`crate::Prefs::trace_presets`]), and a change to the saved presets. pub use buildcmds::{TracePreset, TracePresetChange}; +/// The `format`, extensions and largest size of the tracing presets files +/// `imageTrace.presets.export` writes and `imageTrace.presets.import` reads. +pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES}; + /// An Image Trace made off the UI thread, and what it traced (#3098). pub use buildcmds::{TraceRun, Traced}; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 94fe55c119..e2f0c28179 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -41,8 +41,10 @@ pub use live_paint::live_paint_gaps; use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; use shape_builder::{sb_merge, sb_regions}; pub(crate) use trace::TracePresetChanges; -pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced}; -use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view}; +pub use trace::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced}; +use trace::{ + trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view, +}; /// Name of an Image Trace group. pub const TRACE_NAME: &str = "Image Trace"; @@ -207,6 +209,24 @@ pub fn specs() -> Vec { always, trace_presets_delete ), + cmd!( + query "imageTrace.presets.import", + "Import Image Trace Presets", + [], + None, + "{path? | data?: file text | dataBase64?, replace?: false (true: a preset whose name a saved preset has replaces that preset's settings; false: it is skipped)} add the presets of a .vctracepresets file (as imageTrace.presets.export writes, at most 4 MiB and 1,000 presets) to the saved ones → {imported: [names added], replaced: [names], skipped: [names]}; every preset is checked first, and a file with a built-in preset's or Custom's name, two presets of one name, a preset without a name or with settings imageTrace.presets.save refuses, or a newer version changes nothing", + always, + trace_presets_import + ), + cmd!( + query "imageTrace.presets.export", + "Export Image Trace Presets", + [], + None, + "{names?: [saved preset names] (default: every saved preset; built-in ones are refused), path?} write the saved tracing presets as a .vctracepresets file (JSON: format, version 1, presets: [{name, params}]) → {path, count}; without path → {data: the file's text, count}; more than 1,000 presets, or a file over 4 MiB, is refused, as imageTrace.presets.import would refuse it", + always, + trace_presets_export + ), ] } diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 9c6c28b900..55b09d6681 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -134,6 +134,9 @@ pub(super) fn trace_presets_save(s: &mut Session, p: &Value) -> Result { if old.is_none() && new_name.is_some() { return Err(bad(C, format!("no saved preset named `{name}` to rename"))); } + if old.is_none() && s.prefs.trace_presets.len() >= TRACE_PRESET_MAX_COUNT { + return Err(bad(C, format!("{TRACE_PRESET_MAX_COUNT} tracing presets are saved, the most there can be: delete one first"))); + } // A saved preset changes from its own settings unless `preset` says where to start. let mut q = p.clone(); if let (Some(old), Some(o), None) = (&old, q.as_object_mut(), preset) { @@ -169,6 +172,162 @@ pub(super) fn trace_presets_delete(s: &mut Session, p: &Value) -> Result Ok(json!({ "deleted": deleted })) } +/// The `format` of a tracing presets file, also its extension. +pub const TRACE_PRESET_FORMAT: &str = "vctracepresets"; + +/// The extensions of tracing presets files (opening one imports it). +pub const TRACE_PRESET_EXTS: &[&str] = &[TRACE_PRESET_FORMAT]; + +/// The `version` `imageTrace.presets.export` writes; `imageTrace.presets.import` reads files of +/// this version and earlier ones. +const TRACE_PRESET_VERSION: u64 = 1; + +/// The largest tracing presets file `imageTrace.presets.import` reads. +pub const TRACE_PRESET_MAX_BYTES: usize = 4 << 20; + +/// The most presets one tracing presets file may hold, and the most tracing presets that can be +/// saved (so every saved preset fits in one exported file). +const TRACE_PRESET_MAX_COUNT: usize = 1000; + +pub(super) fn trace_presets_export(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.presets.export"; + let presets: Vec<&TracePreset> = match p.get("names").filter(|v| !v.is_null()) { + Some(Value::Array(names)) => { + let mut out: Vec<&TracePreset> = vec![]; + for n in names { + let n = n.as_str().ok_or_else(|| bad(C, "`names` must hold preset names"))?; + if tr::preset(n).is_some() { + return Err(bad(C, format!("`{n}` is a built-in preset: only saved presets are exported"))); + } + let q = s.trace_preset(n).ok_or_else(|| bad(C, format!("no saved preset named `{n}`")))?; + if !out.iter().any(|o| o.name == q.name) { + out.push(q); + } + } + out + } + Some(_) => return Err(bad(C, "`names` must be an array of preset names")), + None => s.prefs.trace_presets.iter().collect(), + }; + if presets.is_empty() { + return Err(bad(C, "no saved tracing presets to export")); + } + // A file is written only when `imageTrace.presets.import` can read it back. + let count = presets.len(); + if count > TRACE_PRESET_MAX_COUNT { + return Err(bad(C, format!("{count} presets are more than one file holds ({TRACE_PRESET_MAX_COUNT}): export fewer with `names`"))); + } + let rows: Vec = presets.iter().map(|q| json!({"name": q.name, "params": q.params})).collect(); + let file = json!({"format": TRACE_PRESET_FORMAT, "version": TRACE_PRESET_VERSION, "presets": rows}); + let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))?; + if text.len() > TRACE_PRESET_MAX_BYTES { + return Err(bad(C, format!("the file would be larger than {} MiB: export fewer with `names`", TRACE_PRESET_MAX_BYTES >> 20))); + } + match opt_str(C, p, "path")? { + Some(path) => { + crate::cmd::fileio::write_file(path, text.as_bytes())?; + Ok(json!({"path": path, "count": count})) + } + None => Ok(json!({"data": text, "count": count})), + } +} + +/// The bytes of the tracing presets file `p` names (`path`, `data` or `dataBase64`), at most +/// [`TRACE_PRESET_MAX_BYTES`] of them. +fn trace_preset_file(c: &str, p: &Value) -> Result> { + let too_big = || bad(c, format!("the file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20)); + let bytes = match (opt_str(c, p, "path")?, opt_str(c, p, "data")?, opt_str(c, p, "dataBase64")?) { + (Some(path), ..) => crate::cmd::fileio::read_file_head(path, TRACE_PRESET_MAX_BYTES + 1)?, + (None, Some(text), _) => { + if text.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + text.as_bytes().to_vec() + } + (None, None, Some(b64)) => { + if vectorcraft_format::base64_decoded_len(b64) > TRACE_PRESET_MAX_BYTES as u64 { + return Err(too_big()); + } + vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))? + } + _ => return Err(bad(c, "give `path`, `data` or `dataBase64`")), + }; + if bytes.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + Ok(bytes) +} + +pub(super) fn trace_presets_import(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.presets.import"; + let replace = switch_or(p, "replace", false, C)?; + let bytes = trace_preset_file(C, p)?; + let not_file = |why: String| bad(C, format!("not a tracing presets file: {why}")); + let file: Value = serde_json::from_slice(&bytes).map_err(|e| not_file(e.to_string()))?; + if file["format"] != TRACE_PRESET_FORMAT { + return Err(not_file(format!("format `{}`", file["format"].as_str().unwrap_or_default()))); + } + match file["version"].as_u64() { + Some(v) if (1..=TRACE_PRESET_VERSION).contains(&v) => {} + Some(v) => return Err(bad(C, format!("the file's version {v} is newer than this version of VectorCraft reads ({TRACE_PRESET_VERSION})"))), + None => return Err(not_file("no `version`".into())), + } + let rows = file["presets"].as_array().ok_or_else(|| not_file("no `presets` list".into()))?; + if rows.len() > TRACE_PRESET_MAX_COUNT { + return Err(bad(C, format!("the file holds {} presets, more than {TRACE_PRESET_MAX_COUNT}", rows.len()))); + } + // Every preset is checked before any is saved, so a file with a fault changes nothing. + let mut presets: Vec = Vec::with_capacity(rows.len()); + for (i, row) in rows.iter().enumerate() { + let name = row["name"].as_str().map(str::trim).unwrap_or_default(); + if name.is_empty() { + return Err(bad(C, format!("preset {} has no name", i + 1))); + } + if tr::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") { + return Err(bad(C, format!("`{name}` is the name of a built-in preset: rename it in the file"))); + } + if presets.iter().any(|q| q.name.eq_ignore_ascii_case(name)) { + return Err(bad(C, format!("the file holds two presets named `{name}`"))); + } + let params = match row.get("params").filter(|v| v.is_object()) { + Some(params) => trace_params(s, C, &json!({"preset": "Default", "params": params})).map_err(|e| match e { + EngineError::BadParams { msg, .. } => bad(C, format!("`{name}`: {msg}")), + e => e, + })?, + None => return Err(bad(C, format!("`{name}` has no `params`"))), + }; + presets.push(TracePreset { name: name.to_string(), params }); + } + let added = presets.iter().filter(|q| s.trace_preset_index(&q.name).is_none()).count(); + if s.prefs.trace_presets.len() + added > TRACE_PRESET_MAX_COUNT { + return Err(bad( + C, + format!("the file's {added} new presets would make more than {TRACE_PRESET_MAX_COUNT} saved tracing presets: delete some first"), + )); + } + let (mut imported, mut replaced, mut skipped) = (vec![], vec![], vec![]); + for preset in presets { + let name = preset.name.clone(); + match s.trace_preset_index(&name) { + Some(i) if replace => { + let Some(slot) = s.prefs.trace_presets.get_mut(i) else { continue }; + // The saved preset keeps its name as it was saved. + let kept = slot.name.clone(); + *slot = TracePreset { name: kept.clone(), params: preset.params }; + s.trace_preset_changes.note(TracePresetChange { revision: 0, name: kept.clone(), renamed_from: None, deleted: false }); + replaced.push(kept); + } + Some(_) => skipped.push(name), + None => { + s.prefs.trace_presets.push(preset); + s.trace_preset_changes.note(TracePresetChange { revision: 0, name: name.clone(), renamed_from: None, deleted: false }); + imported.push(name); + } + } + } + Ok(json!({"imported": imported, "replaced": replaced, "skipped": skipped})) +} + /// The string `key` of `p` (`None` when it is missing or null); any other type is an error of /// command `c`. fn opt_str<'a>(c: &str, p: &'a Value, key: &str) -> Result> { diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 49a806b258..c3481c7443 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4770,6 +4770,111 @@ fn image_trace_built_in_presets_cannot_be_saved_over_or_deleted() { assert_eq!(six["params"], serde_json::to_value(vectorcraft_trace::preset("6 Colors").unwrap()).unwrap()); } +/// Saved tracing presets go out to a .vctracepresets file and come back with their names and +/// settings; a hand-written file in the documented layout imports too. +#[test] +fn image_trace_presets_export_and_import_round_trip() { + let mut s = session(); + assert!(s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string().contains("no saved tracing presets")); + s.execute("imageTrace.presets.save", &json!({"name": "Poster", "preset": "6 Colors", "params": {"noise": 40, "ignoreWhite": true}})).unwrap(); + s.execute("imageTrace.presets.save", &json!({"name": "Ink", "params": {"threshold": 90, "fills": false, "strokes": true}})).unwrap(); + let e = s.execute("imageTrace.presets.export", &json!({"names": ["Default"]})).unwrap_err().to_string(); + assert!(e.contains("only saved presets are exported"), "{e}"); + assert!(s.execute("imageTrace.presets.export", &json!({"names": ["Nope"]})).is_err()); + let all = s.execute("imageTrace.presets.export", &json!({})).unwrap(); + assert_eq!(all["count"], 2); + let one = s.execute("imageTrace.presets.export", &json!({"names": ["poster", "Poster"]})).unwrap(); + assert_eq!(one["count"], 1); + let file: Value = serde_json::from_str(all["data"].as_str().unwrap()).unwrap(); + assert_eq!((file["format"].as_str(), file["version"].as_u64()), (Some("vctracepresets"), Some(1))); + let saved = s.prefs.trace_presets.clone(); + // Into a session without them: the same names and settings, and a new revision the panel follows. + let mut t = session(); + let before = t.trace_presets_revision(); + let r = t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap(); + assert_eq!(r, json!({"imported": ["Poster", "Ink"], "replaced": [], "skipped": []})); + assert_eq!(t.prefs.trace_presets, saved); + assert_eq!(t.trace_presets_revision(), before + 2); + // A file written by hand in the documented layout: missing settings are Default's. + let hand = r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Hand", "params": {"mode": "grayscale", "colors": 12}}]}"#; + t.execute("imageTrace.presets.import", &json!({ "dataBase64": vectorcraft_format::base64_encode(hand.as_bytes()) })).unwrap(); + let hand = t.trace_preset("hand").unwrap().params.clone(); + assert_eq!((hand.mode, hand.colors, hand.threshold), (vectorcraft_trace::Mode::Grayscale, 12, 128)); +} + +/// Export writes no file that import would refuse (more than 1,000 presets, or more than 4 MiB), +/// and no more than 1,000 tracing presets can be saved. +#[test] +fn image_trace_presets_export_keeps_to_what_import_reads() { + let mut s = session(); + let params = vectorcraft_trace::preset("Default").unwrap(); + let preset = |name: String| crate::cmd::TracePreset { name, params: params.clone() }; + s.prefs.trace_presets = (1..=1001).map(|i| preset(format!("P{i}"))).collect(); + let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string(); + assert!(e.contains("more than one file holds (1000)"), "{e}"); + s.prefs.trace_presets.pop(); + let all = s.execute("imageTrace.presets.export", &json!({})).unwrap(); + assert_eq!(all["count"], 1000); + let mut t = session(); + assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap()["imported"].as_array().map(Vec::len), Some(1000)); + // No more can be saved or imported then, so every saved preset still fits in one file; a + // saved preset can still change, and a file of saved names still replaces them. + let e = t.execute("imageTrace.presets.save", &json!({"name": "One More"})).unwrap_err().to_string(); + assert!(e.contains("delete one first"), "{e}"); + t.execute("imageTrace.presets.save", &json!({"name": "P1", "params": {"noise": 9}})).unwrap(); + let one = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "Fresh", "params": {}}]}).to_string(); + let e = t.execute("imageTrace.presets.import", &json!({ "data": one })).unwrap_err().to_string(); + assert!(e.contains("more than 1000 saved"), "{e}"); + let again = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "P2", "params": {}}]}).to_string(); + assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": again, "replace": true})).unwrap()["replaced"], json!(["P2"])); + assert_eq!(t.prefs.trace_presets.len(), 1000); + s.prefs.trace_presets = vec![preset("x".repeat(4 << 20))]; + let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string(); + assert!(e.contains("larger than 4 MiB"), "{e}"); +} + +/// A saved preset of the same name is skipped unless `replace` is on; a file with a fault, or one +/// too large, changes nothing. +#[test] +fn image_trace_presets_import_checks_the_whole_file_first() { + let mut s = session(); + s.execute("imageTrace.presets.save", &json!({"name": "Poster", "params": {"noise": 40}})).unwrap(); + let file = |rows: Value| json!({"format": "vctracepresets", "version": 1, "presets": rows}).to_string(); + let data = file(json!([{"name": "poster", "params": {"noise": 7}}, {"name": "Fresh", "params": {}}])); + let r = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap(); + assert_eq!(r, json!({"imported": ["Fresh"], "replaced": [], "skipped": ["poster"]})); + assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 40); + let r = s.execute("imageTrace.presets.import", &json!({"data": data, "replace": true})).unwrap(); + assert_eq!(r, json!({"imported": [], "replaced": ["Poster", "Fresh"], "skipped": []})); + assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 7); + assert!(s.execute("imageTrace.presets.import", &json!({"data": data, "replace": "yes"})).is_err()); + let saved = s.prefs.trace_presets.clone(); + let revision = s.trace_presets_revision(); + let bad_files = [ + (file(json!([{"name": "New One", "params": {}}, {"name": "[Default]", "params": {}}])), "built-in preset"), + (file(json!([{"name": "custom", "params": {}}])), "built-in preset"), + (file(json!([{"name": "Twice", "params": {}}, {"name": "twice", "params": {}}])), "two presets named"), + (file(json!([{"name": " ", "params": {}}])), "has no name"), + (file(json!([{"name": "No Params"}])), "has no `params`"), + (file(json!([{"name": "Neither", "params": {"fills": false, "strokes": false}}])), "Create needs fills"), + (file(json!([{"name": "Typo", "params": {"nosie": 3}}])), "nosie"), + (json!({"format": "vctracepresets", "version": 2, "presets": []}).to_string(), "newer"), + (json!({"format": "vcflattener", "version": 1, "presets": []}).to_string(), "not a tracing presets file"), + ("{".to_string(), "not a tracing presets file"), + (file(Value::Array(vec![json!({"name": "x", "params": {}}); 1001])), "more than 1000"), + (" ".repeat((4 << 20) + 1), "larger than 4 MiB"), + ]; + for (data, why) in bad_files { + let e = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap_err().to_string(); + assert!(e.contains(why), "{why}: {e}"); + } + let big = vectorcraft_format::base64_encode(&vec![b' '; (4 << 20) + 1]); + assert!(s.execute("imageTrace.presets.import", &json!({ "dataBase64": big })).unwrap_err().to_string().contains("larger than 4 MiB")); + assert!(s.execute("imageTrace.presets.import", &json!({})).is_err()); + assert_eq!(s.prefs.trace_presets, saved, "nothing changed"); + assert_eq!(s.trace_presets_revision(), revision); +} + /// Saved tracing presets are kept with the preferences, are not a preference key, and survive /// resetting the preferences. #[test] diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 342feb568c..8c95496776 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1029,6 +1029,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings", ), + ( + "ui.tracingPresetsDialog", + "Tracing Presets…", + "", + "{selected?: preset name (default Default)} open Edit → Tracing Presets (dialog `tracingPresets`, field `selected`): the built-in presets (in brackets, read-only) and the saved ones, with the selected one's settings. New… (from the selected preset) and Edit… (a saved one) open the preset editor (dialog `tracingPreset`, fields `name` and `params`, the tracing settings): OK runs imageTrace.presets.save and returns to Tracing Presets, and a name of a built-in preset, Custom or another saved preset keeps the editor open; Cancel returns with nothing saved. Delete runs imageTrace.presets.delete; Import… runs imageTrace.presets.import, and when saved presets have names in the file, asks (dialog `tracingPresetsReplace`) whether to replace them (OK) or keep them (Cancel); Export… runs imageTrace.presets.export on every saved preset", + ), ( "ui.flattenerPreview", "Flattener Preview", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 197f8faaaa..06b4a159f9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -138,6 +138,7 @@ mod tiff_bmp_tga; pub mod tile_edge_color; mod tools; pub mod trace_presets; +pub mod tracing_presets; pub(crate) mod transform; pub mod transform_each; pub mod variables; @@ -352,6 +353,9 @@ registry! { FlattenTransparency: [flatten::KIND] => flatten::SPEC, FlattenerPresets: [flattener_presets::KIND] => flattener_presets::SPEC, ImageTracePreset: [trace_presets::KIND] => trace_presets::SPEC, + TracingPresets: [tracing_presets::KIND] => tracing_presets::SPEC, + TracingPreset: [tracing_presets::PRESET_KIND] => tracing_presets::PRESET_SPEC, + TracingPresetsReplace: [tracing_presets::REPLACE_KIND] => tracing_presets::REPLACE_SPEC, SaveStyleLibrary: [save_style_library::KIND] => save_style_library::SPEC, SaveSymbolLibrary: [save_symbol_library::KIND] => save_symbol_library::SPEC, SaveBrushLibrary: [save_brush_library::KIND] => save_brush_library::SPEC, diff --git a/crates/ui-egui/src/dialogs/tracing_presets.rs b/crates/ui-egui/src/dialogs/tracing_presets.rs new file mode 100644 index 0000000000..4fe9cedd58 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tracing_presets.rs @@ -0,0 +1,493 @@ +//! Edit → Tracing Presets: every tracing preset in a list (built-in ones in brackets, protected, +//! then the saved ones) with the selected one's settings beside it; New… (a preset starting from +//! the selected one), Edit… and Delete (saved presets), Import… and Export… (every saved preset) +//! under the list. New… and Edit… open the preset editor (kind `tracingPreset`): its OK saves the +//! preset with `imageTrace.presets.save` and comes back here on it, and its Cancel comes back with +//! nothing saved. An import whose file holds presets with the names of saved ones asks whether to +//! replace them (kind `tracingPresetsReplace`); Cancel keeps the saved ones. The saved presets are +//! the ones the Image Trace panel, the Control bar and Properties list. +//! +//! Fields: `selected` (a preset's name). The editor's: `name`, `params` (the tracing settings, as +//! `imageTrace.presets.save` takes them) and `editing` (the saved preset it edits; empty for a new +//! one). The question's: `names` (the presets the import skipped) and `file` (the file, as +//! `imageTrace.presets.import` takes it: `{path}` or `{dataBase64}`). Opening a `.vctracepresets` +//! file (File › Open, a drop, the web's Import… pick) imports it the same way. + +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES; +use vectorcraft_engine::cmd::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES}; + +use super::{DialogSpec, form}; +use crate::panels::image_trace::{self, MODES, PALETTES, Preset}; +use crate::panels::swatches; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Tracing Presets. +pub const KIND: &str = "tracingPresets"; + +/// The dialog kind of the tracing preset editor. +pub const PRESET_KIND: &str = "tracingPreset"; + +/// The dialog kind of the question whether an import replaces saved presets of the same names. +pub const REPLACE_KIND: &str = "tracingPresetsReplace"; + +/// The editor's field naming the saved preset it edits. +const EDITING: &str = "editing"; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Tracing Presets").into(), + body, + confirm: |app, _| { + app.ui.dialog = None; + Ok(Value::Null) + }, + ok: None, + min_width: 620.0, + ..DialogSpec::FORM +}; + +pub(super) const PRESET_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Save Preset").into(), + body: preset_body, + confirm: confirm_preset, + ok_enabled: Some(|_, d| !d.str("name").trim().is_empty()), + min_width: 380.0, + ..DialogSpec::FORM +}; + +pub(super) const REPLACE_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Replace the saved presets that have these names?").into(), + body: |_, ui, d| { + let names: Vec<&str> = d.fields.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + ui.label(egui::RichText::new(names.join("\n")).color(Tokens::get(ui.ctx()).text_dim)); + false + }, + confirm: confirm_replace, + ok: Some("Replace"), + max_width: Some(420.0), + ..DialogSpec::FORM +}; + +/// Open the presets manager on `selected` (default: the first preset, Default). +pub fn open(app: &mut VectorcraftApp, selected: Option<&str>) { + app.ui.dialog = Some(Dialog::new(KIND, json!({ "selected": selected.unwrap_or("Default") }))); +} + +/// The index in `all` of the preset `selected` names, found as the engine finds presets (the first +/// when none). +fn shown(all: &[Preset], selected: &str) -> usize { + image_trace::find_preset(all, selected).and_then(|p| all.iter().position(|q| std::ptr::eq(p, q))).unwrap_or(0) +} + +/// A preset's name as the list shows it: a built-in one translated and in brackets, a saved one as +/// the user named it. +fn list_label(p: &Preset) -> String { + if p.3 { format!("[{}]", image_trace::preset_label(&p.0)) } else { p.0.clone() } +} + +/// What a button asked for, done once the list and the settings are drawn. +enum Action { + Select(String), + New, + Edit, + Delete, + Import, + Export, +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + let all = image_trace::presets(app, ui.ctx()); + let i = shown(&all, &d.str("selected")); + let Some(preset) = all.get(i).cloned() else { return false }; + let builtin = preset.3; + let any_saved = all.iter().any(|p| !p.3); + let mut act = None; + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(260.0); + widgets::dim_label(ui, tl!("Presets:")); + widgets::list_box(ui, |ui| { + egui::ScrollArea::vertical().id_salt("tracing-presets").min_scrolled_height(300.0).max_height(300.0).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.set_min_height(300.0); + for (k, p) in all.iter().enumerate() { + if ui.selectable_label(k == i, list_label(p)).clicked() { + act = Some(Action::Select(p.0.clone())); + } + } + }); + }); + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + if widgets::flat_button(ui, tl!("New…"), 48.0).on_hover_text(tl!("A new preset starting from the selected one")).clicked() { + act = Some(Action::New); + } + if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Edit…"), 48.0)).inner.clicked() { + act = Some(Action::Edit); + } + if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Delete"), 52.0)).inner.clicked() { + act = Some(Action::Delete); + } + if widgets::flat_button(ui, tl!("Import…"), 60.0).clicked() { + act = Some(Action::Import); + } + if ui.add_enabled_ui(any_saved, |ui| widgets::flat_button(ui, tl!("Export…"), 60.0)).inner.clicked() { + act = Some(Action::Export); + } + }); + }); + ui.add_space(18.0); + ui.vertical(|ui| { + ui.set_width(320.0); + ui.label(egui::RichText::new(list_label(&preset)).color(t.text_strong).strong()); + ui.add_space(8.0); + // The selected preset's settings, as the editor shows them, to read only. + let mut params = preset.1.clone(); + ui.add_enabled_ui(false, |ui| settings_editor(app, ui, "tracing-presets", &mut params)); + if builtin { + ui.add_space(6.0); + ui.label(egui::RichText::new(tl!("Built-in presets don't change: New makes a copy you can edit.")).color(t.text_dim).size(11.5)); + } + }); + }); + if let Some(a) = act { + let r = match a { + // Their file dialogs, shown off the UI thread, import into or export from the dialog + // as it is then. + Action::Import | Action::Export => { + let export = matches!(a, Action::Export); + crate::picks::in_app_dialog(app, d, move |app, d| run(app, d, if export { Action::Export } else { Action::Import }, "")) + } + a => run(app, d, a, &preset.0), + }; + if let Err(e) = r { + app.status(e); + } + } + false +} + +fn select(d: &mut Dialog, name: &str) { + d.fields.insert("selected".into(), json!(name)); +} + +fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) -> Result<(), String> { + match act { + Action::Select(name) => select(d, &name), + // The editor replaces this dialog; its OK and its Cancel come back here. + Action::New => *d = editor(app, d, current, false)?, + Action::Edit => *d = editor(app, d, current, true)?, + Action::Delete => { + let i = app.session.prefs.trace_presets.iter().position(|p| p.name == current); + app.run("imageTrace.presets.delete", json!({ "name": current }))?; + // The saved preset below it takes its place, else the one above it, else Default. + let saved = &app.session.prefs.trace_presets; + let next = i.and_then(|i| saved.get(i).or_else(|| i.checked_sub(1).and_then(|k| saved.get(k)))).map(|p| p.name.clone()); + select(d, next.as_deref().unwrap_or("Default")); + } + Action::Import => { + // On the web the picked file arrives later and imports through `io::open_bytes`. + if crate::picks::open_async(app) { + return Ok(()); + } + let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Tracing presets", TRACE_PRESET_EXTS)], ..Default::default() }; + let path = crate::picks::open(app, &pick).ok_or("cancelled")?; + import(app, d, json!({ "path": path }))?; + } + Action::Export => { + crate::io::save_command_output(app, "imageTrace.presets.export", TRACE_PRESET_FORMAT, json!({}))?; + } + } + Ok(()) +} + +/// Import the tracing presets file `file` (`{path}` or `{dataBase64}`) into the saved presets, +/// keeping saved presets of the same names → the presets the file added and the names it skipped. +fn import_file(app: &mut VectorcraftApp, file: &Value) -> Result<(Value, Vec), String> { + let r = crate::io::import_presets(app, "imageTrace.presets.import", "tracing presets", file.clone())?; + let skipped = r["skipped"].as_array().cloned().unwrap_or_default(); + Ok((r["imported"].clone(), skipped)) +} + +/// The question whether the import of `file` replaces the saved presets `skipped` kept, over the +/// dialog `under` (Cancel shows it again). +fn ask_replace(under: Option<&Dialog>, skipped: Vec, file: Value) -> Dialog { + let under = under.and_then(|d| serde_json::to_value(d).ok()).unwrap_or(Value::Null); + Dialog::new(REPLACE_KIND, json!({ "names": skipped, "file": file, super::PARENT: under })) +} + +/// The error for a tracing presets file over the size limit. +fn too_big() -> String { + format!("the tracing presets file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20) +} + +/// The tracing presets file `file` as `{dataBase64}`: a `{path}` is read here, once, so the +/// question and its Replace act on the contents the first import checked. +fn file_contents(app: &VectorcraftApp, file: Value) -> Result { + let Some(path) = file.get("path").and_then(Value::as_str) else { return Ok(file) }; + vectorcraft_engine::file_access::check_read(path)?; + if std::fs::metadata(path).is_ok_and(|m| m.len() > TRACE_PRESET_MAX_BYTES as u64) { + return Err(too_big()); + } + // One byte past the limit tells a larger file apart without reading all of it. + let bytes = match (&app.services.read_head, &app.services.read) { + (Some(read_head), _) => read_head(path, TRACE_PRESET_MAX_BYTES + 1)?, + (None, Some(read)) => read(path)?, + (None, None) => return Err("no file reader".into()), + }; + if bytes.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + Ok(json!({ "dataBase64": vectorcraft_format::base64_encode(&bytes) })) +} + +/// Import… on the manager `d`: the import of `file` ([`import_file`]) selects the first preset it +/// added, and when it kept saved presets of the file's names, `d` goes under the question whether +/// to replace them. +fn import(app: &mut VectorcraftApp, d: &mut Dialog, file: Value) -> Result<(), String> { + let file = file_contents(app, file)?; + let (imported, skipped) = import_file(app, &file)?; + if let Some(first) = imported.get(0).and_then(Value::as_str) { + select(d, first); + } + if !skipped.is_empty() { + *d = ask_replace(Some(d), skipped, file); + } + Ok(()) +} + +/// A tracing presets file opened (File › Open, a drop, or the file picked for Import… on the web): +/// it imports as Import… does, over the dialog open now (the manager selects the first preset it +/// added), and asks whether to replace saved presets of the file's names. +pub(crate) fn open_file(app: &mut VectorcraftApp, bytes: &[u8]) -> Result<(), String> { + if bytes.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + let file = json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }); + let (imported, skipped) = import_file(app, &file)?; + let mut under = app.ui.dialog.take(); + if let (Some(d), Some(first)) = (under.as_mut().filter(|d| d.kind == KIND), imported.get(0).and_then(Value::as_str)) { + select(d, first); + } + app.ui.dialog = if skipped.is_empty() { under } else { Some(ask_replace(under.as_ref(), skipped, file)) }; + Ok(()) +} + +/// Replace (the question's OK): the file imports again, replacing the saved presets of its names, +/// and the dialog it was asked over shows again (the manager on the first of them). +fn confirm_replace(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut p = d.fields.get("file").cloned().filter(Value::is_object).ok_or("no tracing presets file")?; + p["replace"] = json!(true); + let r = app.run("imageTrace.presets.import", p)?; + let mut back = super::parent(d); + if let (Some(b), Some(first)) = (back.as_mut().filter(|b| b.kind == KIND), d.fields.get("names").and_then(|n| n.get(0)).and_then(Value::as_str)) { + select(b, first); + } + app.ui.dialog = back; + Ok(r) +} + +/// The preset editor over the manager `d`: on the saved preset `name` (`edit`), else on a new +/// preset starting from the preset `name`, under the first free "Tracing Preset N". +fn editor(app: &mut VectorcraftApp, d: &Dialog, name: &str, edit: bool) -> Result { + let (editing, new_name, params) = if edit { + let saved = app.session.trace_preset(name).ok_or_else(|| format!("no saved preset named `{name}`"))?; + (saved.name.clone(), saved.name.clone(), serde_json::to_value(&saved.params).map_err(|e| e.to_string())?) + } else { + let params = app.session.execute("imageTrace.presets", &json!({})).map_err(|e| e.to_string())?["presets"] + .as_array() + .and_then(|all| { + let found = |p: &&Value| p["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name)); + all.iter().find(|p| p["builtIn"] != false && found(p)).or_else(|| all.iter().find(found)).map(|p| p["params"].clone()) + }) + .ok_or_else(|| format!("no preset named `{name}`"))?; + (String::new(), app.session.new_trace_preset_name(), params) + }; + let under = serde_json::to_value(d).map_err(|e| e.to_string())?; + Ok(Dialog::new(PRESET_KIND, json!({ "name": new_name, "params": params, EDITING: editing, super::PARENT: under }))) +} + +fn preset_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Name:")); + form::text(ui, d, "name", 240.0); + }); + ui.add_space(8.0); + let mut params = d.fields.get("params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); + if settings_editor(app, ui, "tracing-preset", &mut params) { + d.fields.insert("params".into(), params); + } + false +} + +/// Save Preset (the editor's OK): `imageTrace.presets.save`, then back to the manager on the +/// preset. A preset may not take the name of a built-in preset, of Custom or of another saved +/// preset: the editor stays open to change it. +fn confirm_preset(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let (name, editing) = (d.str("name"), d.str(EDITING)); + let name = name.trim(); + let params = d.fields.get("params").cloned().unwrap_or(Value::Null); + let p = if editing.is_empty() { + if app.session.trace_preset(name).is_some() { + return Err(format!("a preset named `{name}` exists")); + } + // The settings are whole: a new preset starts from none of the saved ones. + json!({ "name": name, "preset": "Default", "params": params }) + } else { + json!({ "name": editing, "newName": name, "params": params }) + }; + let r = app.run("imageTrace.presets.save", p)?; + let mut back = super::parent(d).filter(|p| p.kind == KIND).unwrap_or_else(|| Dialog::new(KIND, json!({}))); + select(&mut back, r["name"].as_str().unwrap_or_default()); + app.ui.dialog = Some(back); + Ok(r) +} + +/// The tracing settings `params` as the Image Trace panel shows them (mode, palette, the count or +/// threshold, Document Library's library and colors, and the Advanced settings), changed by the user +/// → whether they changed. +fn settings_editor(app: &VectorcraftApp, ui: &mut egui::Ui, id: &str, params: &mut Value) -> bool { + let mut changed = false; + let mode = params["mode"].as_str().unwrap_or("blackAndWhite").to_string(); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Mode:")); + let label = MODES.iter().find(|m| m.0 == mode).map_or("Black and White", |m| m.1); + let labels: Vec<&str> = MODES.iter().map(|m| m.1).collect(); + if let Some(i) = widgets::dropdown(ui, (id, "mode"), label, &labels, 170.0) { + if MODES[i].0 != "color" { + params["colorGroup"] = Value::Null; + } + params["mode"] = json!(MODES[i].0); + changed = true; + } + }); + let palette = params["palette"].as_str().unwrap_or("limited").to_string(); + if mode == "color" { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Palette:")); + let labels = PALETTES.map(image_trace::palette_label); + if let Some(p) = + widgets::dropdown_names(ui, (id, "palette"), image_trace::palette_label(&palette), &labels, 170.0).and_then(|i| PALETTES.get(i)) + { + if *p != "documentLibrary" { + params["colorGroup"] = Value::Null; + } + params["palette"] = json!(p); + changed = true; + } + }); + if palette == "documentLibrary" { + let key = params["library"].as_str().unwrap_or(DOCUMENT_SWATCHES).to_string(); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Library:")); + let label = swatches::library_label(app, &key); + if let Some(k) = widgets::combo(ui, (id, "library"), &label, 170.0, |ui| swatches::library_list(app, ui, &key)) { + if k != DOCUMENT_SWATCHES { + params["colorGroup"] = Value::Null; + } + params["library"] = json!(k); + changed = true; + } + }); + // The document's swatches: every one, or one color group's (kept by name, so a preset + // names a group the open document may not have). + if key == DOCUMENT_SWATCHES { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Colors:")); + let group = params["colorGroup"].as_str().filter(|g| !g.is_empty()).map(str::to_string); + let label = group.clone().unwrap_or_else(|| tl!("All").to_string()); + if let Some(g) = + widgets::combo(ui, (id, "color-group"), &label, 170.0, |ui| image_trace::color_group_list(app, ui, group.as_deref())) + { + params["colorGroup"] = json!(g); + changed = true; + } + }); + } + } + } + let (key, label, range, suffix) = match mode.as_str() { + "blackAndWhite" => ("threshold", tl!("Threshold"), 0.0..=255.0, ""), + "grayscale" => ("colors", tl!("Grays"), 2.0..=256.0, ""), + "logo" => ("colors", tl!("Colors"), 2.0..=10.0, ""), + _ if matches!(palette.as_str(), "fullTone" | "automatic") => ("colorDetail", tl!("Colors"), 0.0..=100.0, "%"), + _ => ("colors", tl!("Colors"), 2.0..=256.0, ""), + }; + let mut slider = |params: &mut Value, key: &str, label: &str, range: std::ops::RangeInclusive, suffix: &str, whole: bool| { + let mut v = params[key].as_f64().unwrap_or(0.0); + if image_trace::slider(ui, label, &mut v, range, suffix).0 { + params[key] = if whole { json!(v.round() as u64) } else { json!(v.round()) }; + changed = true; + } + }; + slider(params, key, label, range, suffix, key != "colorDetail"); + for (key, label, range, suffix) in + [("paths", tl!("Paths"), 0.0..=100.0, "%"), ("corners", tl!("Corners"), 0.0..=100.0, "%"), ("noise", tl!("Noise"), 1.0..=100.0, " px")] + { + slider(params, key, label, range, suffix, key == "noise"); + } + if mode != "logo" { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Method:")); + for (m, l) in [("abutting", tl!("Abutting")), ("overlapping", tl!("Overlapping"))] { + if ui.selectable_label(params["method"] == m, l).clicked() && params["method"] != m { + params["method"] = json!(m); + changed = true; + } + } + }); + // Create: Fills and/or Strokes (one of them stays on), and the widest line stroked. + let create = |p: &Value, key: &str| p[key].as_bool().unwrap_or(key == "fills"); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Create:")); + for (key, other, label) in [("fills", "strokes", tl!("Fills")), ("strokes", "fills", tl!("Strokes"))] { + let on = create(params, key); + if widgets::check(ui, label, on, !on || create(params, other)) { + params[key] = json!(!on); + changed = true; + } + } + }); + let mut v = params["strokeWidth"].as_f64().unwrap_or(10.0); + let strokes = create(params, "strokes"); + if ui.add_enabled_ui(strokes, |ui| image_trace::slider(ui, tl!("Stroke"), &mut v, 1.0..=100.0, " px")).inner.0 { + params["strokeWidth"] = json!(v.round()); + changed = true; + } + } + let gradients = mode == "grayscale" || mode == "color"; + for (key, label, enabled) in [ + ("snapCurvesToLines", tl!("Snap Curves To Lines"), true), + ("shapes", tl!("Shapes"), true), + ("autoGrouping", tl!("Auto Grouping"), true), + ("gradients", tl!("Gradients"), gradients), + ] { + let on = params[key].as_bool().unwrap_or(false); + if widgets::check(ui, label, on, enabled) { + params[key] = json!(!on); + changed = true; + } + } + ui.horizontal(|ui| { + let on = params["ignoreWhite"].as_bool().unwrap_or(false); + if widgets::check(ui, tl!("Ignore Color"), on, true) { + params["ignoreWhite"] = json!(!on); + changed = true; + } + if on { + let mut rgb = image_trace::ignore_color(params); + if ui.color_edit_button_srgb(&mut rgb).changed() { + params["ignoreColor"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])); + changed = true; + } + } + }); + changed +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/tracing_presets/tests.rs b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs new file mode 100644 index 0000000000..4ef5217420 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs @@ -0,0 +1,329 @@ +//! Edit → Tracing Presets: the menu item, New… and Edit… through the preset editor, Delete, +//! Import… (with the question about saved presets of the same names) and Export…. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use super::*; + +fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); +} + +/// Press a manager button on the preset `current`, as the body does. +fn press(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), String> { + let mut d = app.ui.dialog.take().expect("a dialog is open"); + let r = run(app, &mut d, act, current); + app.ui.dialog = Some(d); + frame(app); + r +} + +/// The texts the dialog paints on a 1200 × 900 window, once it has taken its sizing frame and +/// faded in (each frame is a quarter second on). +fn frame_texts(app: &mut VectorcraftApp) -> Vec { + fn walk(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0)); + let mut texts = vec![]; + for k in 0..4 { + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + texts.clear(); + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + } + texts +} + +fn kind(app: &VectorcraftApp) -> Option<&str> { + app.ui.dialog.as_ref().map(|d| d.kind.as_str()) +} + +fn field(app: &VectorcraftApp, k: &str) -> Value { + app.ui.dialog.as_ref().and_then(|d| d.fields.get(k).cloned()).unwrap_or_default() +} + +fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().expect("a dialog is open").fields.insert(k.into(), v); +} + +/// The tracing settings of the preset `name` as `imageTrace.presets` lists them. +fn listed(app: &mut VectorcraftApp, name: &str) -> Value { + let all = app.session.execute("imageTrace.presets", &json!({})).unwrap(); + all["presets"].as_array().unwrap().iter().find(|p| p["name"] == name).map(|p| p["params"].clone()).unwrap_or_default() +} + +fn saved_names(app: &VectorcraftApp) -> Vec<&str> { + app.session.prefs.trace_presets.iter().map(|p| p.name.as_str()).collect() +} + +#[test] +fn edit_menu_opens_the_manager_without_a_document() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let entries = crate::menus::menu_entries(&app); + let item = entries.iter().find(|e| e.command.as_deref() == Some("ui.tracingPresetsDialog")).expect("Edit → Tracing Presets…"); + assert!(item.path == ["Edit"] && item.label == "Tracing Presets…" && item.enabled); + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + frame(&mut app); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Default"))); + app.run("ui.tracingPresetsDialog", json!({"selected": "[6 Colors]"})).unwrap(); + frame(&mut app); + assert_eq!(field(&app, "selected"), json!("[6 Colors]")); + // Built-in presets can't be edited or deleted. + assert!(press(&mut app, Action::Edit, "6 Colors").is_err()); + assert!(press(&mut app, Action::Delete, "6 Colors").is_err()); + assert!(app.session.prefs.trace_presets.is_empty()); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "Close"); +} + +#[test] +fn new_and_edit_save_through_the_editor_and_cancel_saves_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let revision = app.session.trace_presets_revision(); + app.run("ui.tracingPresetsDialog", json!({"selected": "6 Colors"})).unwrap(); + frame(&mut app); + // New… starts from the selected built-in preset; Cancel comes back with nothing saved. + press(&mut app, Action::New, "6 Colors").unwrap(); + assert_eq!((kind(&app), field(&app, "name")), (Some(PRESET_KIND), json!("Tracing Preset 1"))); + let six = listed(&mut app, "6 Colors"); + assert_eq!(field(&app, "params"), six); + set(&mut app, "name", json!("Poster")); + super::super::cancel(&mut app); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("6 Colors")), "back to the manager"); + assert!(app.session.prefs.trace_presets.is_empty()); + assert_eq!(app.session.trace_presets_revision(), revision); + // OK saves the preset with the editor's settings and selects it. + press(&mut app, Action::New, "6 Colors").unwrap(); + set(&mut app, "name", json!(" Poster ")); + let mut params = field(&app, "params"); + params["noise"] = json!(40); + set(&mut app, "params", params); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster"))); + assert_eq!(saved_names(&app), ["Poster"]); + let poster = listed(&mut app, "Poster"); + assert_eq!((poster["noise"].clone(), poster["colors"].clone()), (json!(40), six["colors"].clone())); + // The Image Trace panel's list (also the Control bar's and Properties') has it. + let ctx = egui::Context::default(); + let all = crate::panels::image_trace::presets(&mut app, &ctx); + assert!(all.iter().any(|p| p.0 == "Poster" && !p.3)); + // Edit… changes the saved preset; Cancel leaves it as it was. + frame(&mut app); + press(&mut app, Action::Edit, "Poster").unwrap(); + assert_eq!((kind(&app), field(&app, "name"), field(&app, "params")), (Some(PRESET_KIND), json!("Poster"), poster.clone())); + let mut params = field(&app, "params"); + params["noise"] = json!(3); + set(&mut app, "params", params); + super::super::cancel(&mut app); + assert_eq!(listed(&mut app, "Poster"), poster); + press(&mut app, Action::Edit, "Poster").unwrap(); + let mut params = field(&app, "params"); + params["noise"] = json!(3); + params["mode"] = json!("grayscale"); + set(&mut app, "params", params); + set(&mut app, "name", json!("Posters")); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Posters"))); + assert_eq!(saved_names(&app), ["Posters"]); + let edited = listed(&mut app, "Posters"); + assert_eq!((edited["noise"].clone(), edited["mode"].clone()), (json!(3), json!("grayscale"))); + // New… from a saved preset starts from its settings. + press(&mut app, Action::New, "Posters").unwrap(); + assert_eq!((field(&app, "name"), field(&app, "params")), (json!("Tracing Preset 1"), edited)); +} + +#[test] +fn the_editor_shows_document_library_s_library_and_colors() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + frame(&mut app); + press(&mut app, Action::New, "Default").unwrap(); + let mut params = field(&app, "params"); + params["mode"] = json!("color"); + params["palette"] = json!("documentLibrary"); + params["colorGroup"] = json!("Brand Colors"); + set(&mut app, "params", params.clone()); + let texts = frame_texts(&mut app); + for t in ["Library:", "Colors:", "Brand Colors"] { + assert!(texts.iter().any(|s| s == t), "{t}: {texts:?}"); + } + // Another library's colors are all its swatches: no Colors menu. + params["library"] = json!("lib:Other"); + params["colorGroup"] = Value::Null; + set(&mut app, "params", params.clone()); + let texts = frame_texts(&mut app); + assert!(texts.iter().any(|s| s == "Library:") && !texts.iter().any(|s| s == "Colors:"), "{texts:?}"); + // Other palettes show neither. + params["palette"] = json!("limited"); + set(&mut app, "params", params); + let texts = frame_texts(&mut app); + assert!(!texts.iter().any(|s| s == "Library:" || s == "Colors:"), "{texts:?}"); +} + +#[test] +fn a_taken_or_protected_name_keeps_the_editor_open() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("imageTrace.presets.save", json!({"name": "Ink", "params": {"threshold": 90}})).unwrap(); + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 40}})).unwrap(); + let saved = app.session.prefs.trace_presets.clone(); + app.run("ui.tracingPresetsDialog", json!({"selected": "Ink"})).unwrap(); + frame(&mut app); + press(&mut app, Action::New, "Ink").unwrap(); + for name in ["Default", "[6 Colors]", "custom", "poster"] { + set(&mut app, "name", json!(name)); + assert!(super::super::confirm(&mut app).is_err(), "{name}"); + assert_eq!((kind(&app), field(&app, "name")), (Some(PRESET_KIND), json!(name)), "{name}: stays open"); + } + super::super::cancel(&mut app); + press(&mut app, Action::Edit, "Ink").unwrap(); + for name in ["Poster", "Default", "Custom"] { + set(&mut app, "name", json!(name)); + assert!(super::super::confirm(&mut app).is_err(), "{name}"); + assert_eq!(kind(&app), Some(PRESET_KIND), "{name}: stays open"); + } + assert_eq!(app.session.prefs.trace_presets, saved, "nothing changed"); +} + +#[test] +fn delete_selects_the_next_saved_preset_then_default() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for name in ["A", "B", "C"] { + app.run("imageTrace.presets.save", json!({ "name": name })).unwrap(); + } + app.run("ui.tracingPresetsDialog", json!({"selected": "B"})).unwrap(); + frame(&mut app); + press(&mut app, Action::Delete, "B").unwrap(); + assert_eq!((saved_names(&app), field(&app, "selected")), (vec!["A", "C"], json!("C"))); + press(&mut app, Action::Delete, "C").unwrap(); + assert_eq!((saved_names(&app), field(&app, "selected")), (vec!["A"], json!("A"))); + press(&mut app, Action::Delete, "A").unwrap(); + assert!(app.session.prefs.trace_presets.is_empty()); + assert_eq!(field(&app, "selected"), json!("Default")); +} + +#[test] +fn import_asks_before_replacing_saved_presets_and_export_writes_every_saved_one() { + let dir = std::env::temp_dir().join(format!("vc-tracing-presets-ui-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("mine.vctracepresets").to_string_lossy().to_string(); + let picked = file.clone(); + let services = crate::Services { + pick_save: Some(Box::new(move |_: &crate::FilePick| Some(picked.clone()))), + write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), + read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 40}})).unwrap(); + app.run("imageTrace.presets.save", json!({"name": "Ink", "params": {"threshold": 90}})).unwrap(); + app.run("ui.tracingPresetsDialog", json!({"selected": "Default"})).unwrap(); + frame(&mut app); + press(&mut app, Action::Export, "").unwrap(); + let text = std::fs::read_to_string(&file).unwrap(); + let written: Value = serde_json::from_str(&text).unwrap(); + let names: Vec<&str> = written["presets"].as_array().unwrap().iter().filter_map(|p| p["name"].as_str()).collect(); + assert_eq!((written["format"].as_str(), names), (Some(TRACE_PRESET_FORMAT), vec!["Poster", "Ink"])); + // Saved presets of the same names stay unless the question's Replace is pressed. + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap(); + app.run("imageTrace.presets.delete", json!({"name": "Ink"})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + import(&mut app, &mut d, json!({ "path": file })).unwrap(); + app.ui.dialog = Some(d); + frame(&mut app); + assert_eq!((kind(&app), field(&app, "names")), (Some(REPLACE_KIND), json!(["Poster"]))); + assert_eq!(saved_names(&app), ["Poster", "Ink"], "Ink came in"); + super::super::cancel(&mut app); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Ink")), "Cancel keeps the saved one"); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 7); + let mut d = app.ui.dialog.take().unwrap(); + import(&mut app, &mut d, json!({ "path": file })).unwrap(); + app.ui.dialog = Some(d); + // Replace acts on the contents the question was asked about, though the file changed since. + let changed = + r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Poster", "params": {"noise": 3}}, {"name": "Extra", "params": {}}]}"#; + std::fs::write(&file, changed).unwrap(); + super::super::confirm(&mut app).unwrap(); + std::fs::write(&file, &text).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster"))); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40); + assert_eq!(saved_names(&app), ["Poster", "Ink"]); + // Opening the file imports it, and asks the same question over the manager (also how the web's + // picked file arrives). + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap(); + app.run("imageTrace.presets.delete", json!({"name": "Ink"})).unwrap(); + let bytes = std::fs::read(&file).unwrap(); + crate::io::open_bytes(&mut app, &file, &bytes, Some(file.clone())).unwrap(); + assert_eq!(saved_names(&app), ["Poster", "Ink"]); + assert!(app.ui.status.contains("tracing presets"), "{}", app.ui.status); + assert_eq!((kind(&app), field(&app, "names")), (Some(REPLACE_KIND), json!(["Poster"]))); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster"))); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40); + // With no dialog open, Cancel keeps the saved preset and leaves no dialog. + app.ui.dialog = None; + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap(); + crate::io::open_bytes(&mut app, &file, &bytes, Some(file.clone())).unwrap(); + assert_eq!(kind(&app), Some(REPLACE_KIND)); + super::super::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 7); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_file_with_a_fault_changes_nothing() { + let dir = std::env::temp_dir().join(format!("vc-tracing-presets-bad-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("bad.vctracepresets"); + std::fs::write( + &file, + r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Fine", "params": {}}, {"name": "Default", "params": {}}]}"#, + ) + .unwrap(); + // The file is read no further than one byte past the limit. + let read_head = |p: &str, max: usize| { + use std::io::Read as _; + assert_eq!(max, TRACE_PRESET_MAX_BYTES + 1); + let mut bytes = vec![]; + std::fs::File::open(p).and_then(|f| f.take(max as u64).read_to_end(&mut bytes)).map_err(|e| e.to_string())?; + Ok(bytes) + }; + let services = crate::Services { read_head: Some(Box::new(read_head)), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + frame(&mut app); + let mut d = app.ui.dialog.take().unwrap(); + let e = import(&mut app, &mut d, json!({ "path": file.to_string_lossy() })).unwrap_err(); + assert!(e.contains("built-in preset"), "{e}"); + assert_eq!(d.kind, KIND, "no question"); + assert!(app.session.prefs.trace_presets.is_empty()); + app.ui.dialog = Some(d); + // An opened file over the size limit is refused before its bytes are encoded for the import. + let big = vec![b' '; TRACE_PRESET_MAX_BYTES + 1]; + let e = open_file(&mut app, &big).unwrap_err(); + assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}"); + assert_eq!(kind(&app), Some(KIND), "the manager stays open"); + let big_file = dir.join("big.vctracepresets"); + std::fs::write(&big_file, &big).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + let e = import(&mut app, &mut d, json!({ "path": big_file.to_string_lossy() })).unwrap_err(); + assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}"); + app.ui.dialog = Some(d); + assert!(app.session.prefs.trace_presets.is_empty()); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3828d9ba2d..7d93400eb1 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1619,6 +1619,10 @@ font-technology Variable Променливи Rename Preset Преименуване на предварителна настройка Save Image Trace Preset Запази предварителна настройка за трасиране на изображения Delete Image Trace Preset Изтриване на предварителна настройка за трасиране на изображения + Tracing Presets… Предварителни настройки за трасиране… + Import Image Trace Presets Импортиране на предварителни настройки за трасиране на изображения + Export Image Trace Presets Експортиране на предварителни настройки за трасиране на изображения + Replace the saved presets that have these names? Да се заменят ли запазените предварителни настройки с тези имена? Image Trace Presets Предварителни настройки за трасиране на изображения Image: Изображение: Images: Изображения: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 81fee3a079..79e3a4d221 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1854,6 +1854,10 @@ digits Malayalam Malajalam Rename Preset Preimenuj unaprijed postavljeno Save Image Trace Preset Sačuvaj unaprijed postavljeno praćenje slike Delete Image Trace Preset Izbriši unaprijed postavljeno praćenje slike + Tracing Presets… Predlošci praćenja… + Import Image Trace Presets Uvezi predloške praćenja slike + Export Image Trace Presets Izvezi predloške praćenja slike + Replace the saved presets that have these names? Zamijeniti sačuvane predloške s ovim imenima? Method: Metoda: Pad Produži Repeats Broj ponavljanja diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ae0f4a09..0d9126414f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1110,6 +1110,10 @@ antiAlias Sharp Nítid Delete Guide Suprimeix la guia Delete Guides Suprimeix les guies Delete Image Trace Preset Suprimeix el preajust de traçat d’imatge + Tracing Presets… Preajustos de traçat… + Import Image Trace Presets Importa preajustos de traçat d’imatge + Export Image Trace Presets Exporta els preajustos de traçat d’imatge + Replace the saved presets that have these names? Voleu substituir els preajustos desats que tenen aquests noms? Delete Layer Suprimeix la capa Delete Library Suprimeix la biblioteca Delete Library Group Suprimeix el grup de biblioteca diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e3794e8a1..ea52d815f0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1885,6 +1885,10 @@ digits Malayalam Malajálamské Rename Preset Přejmenovat přednastavení Save Image Trace Preset Uložit přednastavení vektorizace obrazu Delete Image Trace Preset Odstranit přednastavení vektorizace obrazu + Tracing Presets… Přednastavení vektorizace… + Import Image Trace Presets Importovat přednastavení vektorizace obrazu + Export Image Trace Presets Exportovat přednastavení vektorizace obrazu + Replace the saved presets that have these names? Nahradit uložená přednastavení s těmito názvy? Method: Metoda: Pad Prodloužit Repeats Počet opakování diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f7011e23bf..c1866acb8f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1712,6 +1712,10 @@ digits Malayalam Malayalam Rename Preset Omdøb forudindstilling Save Image Trace Preset Gem forudindstilling til billedsporing Delete Image Trace Preset Slet forudindstilling til billedsporing + Tracing Presets… Vektoriseringsforudindstillinger… + Import Image Trace Presets Importér forudindstillinger til billedsporing + Export Image Trace Presets Eksportér forudindstillinger til billedsporing + Replace the saved presets that have these names? Vil du erstatte de gemte forudindstillinger med disse navne? Method: Metode: Pad Forlæng Repeats Gentagelser diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4174537f87..0f3f9f348a 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1678,6 +1678,10 @@ file-filter Templates Vorlagen Rename Preset Vorgabe umbenennen Save Image Trace Preset Bildnachzeichner-Vorgabe speichern Delete Image Trace Preset Bildnachzeichner-Vorgabe löschen + Tracing Presets… Nachzeichnervorgaben… + Import Image Trace Presets Bildnachzeichner-Vorgaben importieren + Export Image Trace Presets Bildnachzeichner-Vorgaben exportieren + Replace the saved presets that have these names? Gespeicherte Vorgaben mit diesen Namen ersetzen? Image Trace Presets Bildnachzeichner-Vorgaben Image: Bild: Images: Bilder: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bde2fbee78..7309c550f3 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1593,6 +1593,10 @@ font-technology Variable Μεταβλητές Rename Preset Μετονομασία προεπιλογής Save Image Trace Preset Αποθήκευση προεπιλογής ανίχνευσης περιγραμμάτων εικόνας Delete Image Trace Preset Διαγραφή προεπιλογής ανίχνευσης περιγραμμάτων εικόνας + Tracing Presets… Προεπιλογές ανίχνευσης περιγραμμάτων… + Import Image Trace Presets Εισαγωγή προεπιλογών ανίχνευσης περιγραμμάτων εικόνας + Export Image Trace Presets Εξαγωγή προεπιλογών ανίχνευσης περιγραμμάτων εικόνας + Replace the saved presets that have these names? Αντικατάσταση των αποθηκευμένων προεπιλογών με αυτά τα ονόματα; Image Trace Presets Προεπιλογές ανίχνευσης περιγραμμάτων εικόνας Image: Εικόνα: Images: Εικόνες: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff28d9dfc5..b0a975102e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1674,6 +1674,10 @@ font-technology Variable Variables Rename Preset Cambiar nombre del preajuste Save Image Trace Preset Guardar preajuste de calco de imagen Delete Image Trace Preset Eliminar preajuste de calco de imagen + Tracing Presets… Preajustes de calco… + Import Image Trace Presets Importar preajustes de calco de imagen + Export Image Trace Presets Exportar preajustes de calco de imagen + Replace the saved presets that have these names? ¿Reemplazar los preajustes guardados que tienen estos nombres? Image Trace Presets Preajustes de calco de imagen Image: Imagen: Images: Imágenes: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bb74188ed8..2e60a27191 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1858,6 +1858,10 @@ digits Malayalam Malajalam Rename Preset Nimeä esiasetus uudelleen Save Image Trace Preset Tallenna kuvan jäljityksen esiasetus Delete Image Trace Preset Poista kuvan jäljityksen esiasetus + Tracing Presets… Jäljityksen esiasetukset… + Import Image Trace Presets Tuo kuvan jäljityksen esiasetukset + Export Image Trace Presets Vie kuvan jäljityksen esiasetukset + Replace the saved presets that have these names? Korvataanko tallennetut esiasetukset, joilla on nämä nimet? Method: Menetelmä: Pad Jatka Repeats Toistokerrat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 09c9c35b0d..a167547f16 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1668,6 +1668,10 @@ font-technology Variable Variables Rename Preset Renommer le paramètre prédéfini Save Image Trace Preset Enregistrer le paramètre prédéfini de vectorisation de l’image Delete Image Trace Preset Supprimer le paramètre prédéfini de vectorisation de l’image + Tracing Presets… Paramètres prédéfinis de vectorisation… + Import Image Trace Presets Importer des paramètres prédéfinis de vectorisation de l’image + Export Image Trace Presets Exporter les paramètres prédéfinis de vectorisation de l’image + Replace the saved presets that have these names? Remplacer les paramètres prédéfinis enregistrés qui portent ces noms ? Image Trace Presets Paramètres prédéfinis de vectorisation de l’image Image: Image : Images: Images : diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9aa4bd7b99..802d0c56bc 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1250,6 +1250,10 @@ antiAlias Sharp शार्प Delete Guide गाइड हटाएँ Delete Guides गाइड्स हटाएँ Delete Image Trace Preset डिलीट इमेज ट्रेस प्रीसेट + Tracing Presets… ट्रेसिंग प्रीसेट… + Import Image Trace Presets आयात इमेज ट्रेस प्रीसेट्स + Export Image Trace Presets निर्यात इमेज ट्रेस प्रीसेट्स + Replace the saved presets that have these names? इन नामों वाले सहेजे गए प्रीसेट बदलें? Delete Instances इंस्टेंस हटाएँ Delete Layer लेयर हटाएँ Delete Library लाइब्रेरी हटाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af6f586880..f9fd810a0b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4416,6 +4416,10 @@ mark-style Japanese Japán Rename Preset Előbeállítás átnevezése Save Image Trace Preset Képvektorizálási előbeállítás mentése Delete Image Trace Preset Képvektorizálási előbeállítás törlése + Tracing Presets… Vektorizálási előbeállítások… + Import Image Trace Presets Képvektorizálási előbeállítások importálása + Export Image Trace Presets Képvektorizálási előbeállítások exportálása + Replace the saved presets that have these names? Lecseréli az ilyen nevű mentett előbeállításokat? Tracing Result Vektorizálás eredménye Tracing Result with Outlines Vektorizálás eredménye vázlattal Tracking Betűköz diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e0ba31ecd5..4e826ba908 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1712,6 +1712,10 @@ digits Malayalam Malayalam Rename Preset Ganti nama preset Save Image Trace Preset Simpan preset telusur gambar Delete Image Trace Preset Hapus preset telusur gambar + Tracing Presets… Preset penelusuran… + Import Image Trace Presets Impor preset telusur gambar + Export Image Trace Presets Ekspor preset telusur gambar + Replace the saved presets that have these names? Ganti preset tersimpan yang memiliki nama-nama ini? Method: Metode: Pad Perpanjang Repeats Jumlah ulangan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce0bc58ce5..3da957d6b4 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1709,6 +1709,10 @@ file-filter Templates Modelli Rename Preset Rinomina preset Save Image Trace Preset Salva preset ricalco immagine Delete Image Trace Preset Elimina preset ricalco immagine + Tracing Presets… Preset di ricalco… + Import Image Trace Presets Importa preset ricalco immagine + Export Image Trace Presets Esporta preset ricalco immagine + Replace the saved presets that have these names? Sostituire i preset salvati con questi nomi? Image Trace Presets Preset ricalco immagine Image: Immagine: Images: Immagini: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1ecce4618a..d53882f52b 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -346,6 +346,10 @@ digits Malayalam マラヤーラム数字 Rename Preset プリセット名を変更 Save Image Trace Preset 画像トレースプリセットを保存 Delete Image Trace Preset 画像トレースプリセットを削除 + Tracing Presets… トレースプリセット… + Import Image Trace Presets 画像トレースプリセットを読み込み + Export Image Trace Presets 画像トレースプリセットを書き出し + Replace the saved presets that have these names? これらの名前の保存済みプリセットを置き換えますか? Text Wrap テキストの回り込み Text Wrap Options… テキストの回り込みオプション… Clipping Mask クリッピングマスク diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d6425c373..ff43cc6c68 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1649,6 +1649,10 @@ digits Malayalam მალაიალამური Rename Preset პრესეტის სახელის შეცვლა Save Image Trace Preset გამოსახულების ვექტორიზაციის პრესეტის შენახვა Delete Image Trace Preset გამოსახულების ვექტორიზაციის პრესეტის წაშლა + Tracing Presets… ვექტორიზაციის პრესეტები… + Import Image Trace Presets გამოსახულების ვექტორიზაციის პრესეტების იმპორტირება + Export Image Trace Presets გამოსახულების ვექტორიზაციის პრესეტების ექსპორტირება + Replace the saved presets that have these names? ჩავანაცვლოთ ამ სახელების მქონე შენახული პრესეტები? Cancel Image Trace გამოსახულების ვექტორიზაციის გაუქმება Method: მეთოდი: Pad გაგრძელება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fb87488d64..75c8496cb3 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -339,6 +339,10 @@ digits Malayalam 말라얄람어 Rename Preset 프리셋 이름 바꾸기 Save Image Trace Preset 이미지 추적 프리셋 저장 Delete Image Trace Preset 이미지 추적 프리셋 삭제 + Tracing Presets… 추적 프리셋… + Import Image Trace Presets 이미지 추적 프리셋 가져오기 + Export Image Trace Presets 이미지 추적 프리셋 내보내기 + Replace the saved presets that have these names? 이 이름을 가진 저장된 프리셋을 대체하시겠습니까? Text Wrap 문자 감싸기 Text Wrap Options… 문자 감싸기 옵션… Clipping Mask 클리핑 마스크 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b3388fa82a..5d940f307f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1726,6 +1726,10 @@ digits Malayalam Malayalam Rename Preset Voorinstelling hernoemen Save Image Trace Preset Voorinstelling voor afbeeldingtracering opslaan Delete Image Trace Preset Voorinstelling voor afbeeldingtracering verwijderen + Tracing Presets… Traceervoorinstellingen… + Import Image Trace Presets Voorinstellingen voor afbeeldingtracering importeren + Export Image Trace Presets Voorinstellingen voor afbeeldingtracering exporteren + Replace the saved presets that have these names? Opgeslagen voorinstellingen met deze namen vervangen? Method: Methode: Pad Doortrekken Repeats Herhalingen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0729e35c79..e0e020f3ad 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1803,6 +1803,10 @@ digits Malayalam Malajalam Rename Preset Zmień nazwę ustawienia Save Image Trace Preset Zapisz ustawienie obrysu obrazu Delete Image Trace Preset Usuń ustawienie obrysu obrazu + Tracing Presets… Ustawienia obrysu… + Import Image Trace Presets Importuj ustawienia obrysu obrazu + Export Image Trace Presets Eksportuj ustawienia obrysu obrazu + Replace the saved presets that have these names? Zastąpić zapisane ustawienia o tych nazwach? Method: Metoda: Pad Przedłuż Repeats Liczba powtórzeń diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36f778dbd5..0de8447965 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3550,6 +3550,10 @@ font-technology Variable Variáveis Rename Preset Renomear Predefinido Save Image Trace Preset Salvar Predefinido de Rastreamento de Imagem Delete Image Trace Preset Excluir Predefinido de Rastreamento de Imagem + Tracing Presets… Predefinições de vetorização… + Import Image Trace Presets Importar Predefinidos de Rastreamento de Imagem + Export Image Trace Presets Exportar Predefinidos de Rastreamento de Imagem + Replace the saved presets that have these names? Substituir os predefinidos salvos que têm esses nomes? Japanese Japonês Keep a link to an image file instead of only embedding it Manter um link para o arquivo de imagem em vez de apenas incorporá-lo Latin Latim diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 442a9612d4..4b2fe58e4a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1698,6 +1698,10 @@ file-filter Templates Шаблоны Rename Preset Переименовать набор Save Image Trace Preset Сохранить набор трассировки изображения Delete Image Trace Preset Удалить набор трассировки изображения + Tracing Presets… Наборы трассировки… + Import Image Trace Presets Импортировать наборы трассировки изображения + Export Image Trace Presets Экспортировать наборы трассировки изображения + Replace the saved presets that have these names? Заменить сохранённые наборы с этими именами? Image Trace Presets Наборы трассировки изображения Image: Изображение: Images: Изображения: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8a8f8453b6..fa93d98a38 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1632,6 +1632,10 @@ font-technology Variable Variabla Rename Preset Byt namn på förinställning Save Image Trace Preset Spara förinställning för bildkalkering Delete Image Trace Preset Radera förinställning för bildkalkering + Tracing Presets… Förinställningar för vektorisering… + Import Image Trace Presets Importera förinställningar för bildkalkering + Export Image Trace Presets Exportera förinställningar för bildkalkering + Replace the saved presets that have these names? Ersätta sparade förinställningar med dessa namn? Image Trace Presets Förinställningar för bildkalkering Image: Bild: Images: Bilder: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef8773c31b..f2959f6b62 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1512,6 +1512,10 @@ font-technology Variable Değişken Rename Preset Ön Ayarı Yeniden Adlandır Save Image Trace Preset Görüntü İzleme Ön Ayarını Kaydet Delete Image Trace Preset Görüntü İzleme Ön Ayarını Sil + Tracing Presets… İzleme Ön Ayarları… + Import Image Trace Presets Görüntü İzleme Ön Ayarlarını İçe Aktar + Export Image Trace Presets Görüntü İzleme Ön Ayarlarını Dışa Aktar + Replace the saved presets that have these names? Bu adlara sahip kayıtlı ön ayarlar değiştirilsin mi? Image Trace Presets Görüntü İzleme Ön Ayarları Image: Resim: Images: Görseller: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0bccbd8cb6..90eb39e4dc 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1703,6 +1703,10 @@ file-filter Templates Шаблони Rename Preset Перейменувати набір Save Image Trace Preset Зберегти набір трасування зображення Delete Image Trace Preset Видалити набір трасування зображення + Tracing Presets… Набори трасування… + Import Image Trace Presets Імпортувати набори трасування зображення + Export Image Trace Presets Експортувати набори трасування зображення + Replace the saved presets that have these names? Замінити збережені набори з цими назвами? Image Trace Presets Набір трасування зображення Image: Зображення: Images: Зображення: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4f084029db..ce39ce7eed 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4127,6 +4127,10 @@ mark-style Japanese Kiểu Nhật Rename Preset Đổi tên thiết lập sẵn Save Image Trace Preset Lưu thiết lập sẵn vector hóa ảnh Delete Image Trace Preset Xóa thiết lập sẵn vector hóa ảnh + Tracing Presets… Thiết lập sẵn vector hóa… + Import Image Trace Presets Nhập thiết lập sẵn vector hóa ảnh + Export Image Trace Presets Xuất thiết lập sẵn vector hóa ảnh + Replace the saved presets that have these names? Thay thế các thiết lập sẵn đã lưu có những tên này? Tracing Result Kết quả vector hóa Tracing Result with Outlines Kết quả vector hóa với đường bao Tracking Giãn chữ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b04e65a65b..6772e5353c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1628,6 +1628,10 @@ file-filter Templates 模板 Rename Preset 重命名预设 Save Image Trace Preset 保存图像描摹预设 Delete Image Trace Preset 删除图像描摹预设 + Tracing Presets… 描摹预设… + Import Image Trace Presets 导入图像描摹预设 + Export Image Trace Presets 导出图像描摹预设 + Replace the saved presets that have these names? 替换具有这些名称的已存储预设? Image Trace Presets 图像描摹预设 Image: 图像: Images: 图像: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index be62fde8a7..dd2af98385 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1674,6 +1674,10 @@ file-filter Templates 範本 Rename Preset 重新命名預設集 Save Image Trace Preset 儲存影像描圖預設集 Delete Image Trace Preset 刪除影像描圖預設集 + Tracing Presets… 描圖預設集… + Import Image Trace Presets 匯入影像描圖預設集 + Export Image Trace Presets 匯出影像描圖預設集 + Replace the saved presets that have these names? 要取代具有這些名稱的已儲存預設集嗎? Image Trace Presets 影像描圖預設集 Image: 影像: Images: 影像: diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index ae52b599b7..4816684748 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -35,6 +35,9 @@ fn open_bytes_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opt }; return dialogs::script_check::command(app, &p).map(|_| Value::Null); } + if let Some(OpensAs::Presets { import: "imageTrace.presets.import", .. }) = opens { + return dialogs::tracing_presets::open_file(app, bytes).map(|_| Value::Null); + } if let Some(OpensAs::Presets { import, what }) = opens { import_presets(app, import, what, serde_json::json!({"dataBase64": vectorcraft_format::base64_encode(bytes)}))?; return Ok(Value::Null); @@ -106,6 +109,7 @@ pub fn opens_as(name: &str) -> Option { (vectorcraft_engine::cmd::pdfcmds::PRESET_EXTS, "pdf.preset.import", "PDF presets"), (vectorcraft_engine::cmd::printpresets::PRESET_EXTS, "print.presets.import", "print presets"), (vectorcraft_engine::cmd::perspgrid::PRESET_EXTS, "perspective.presets.import", "perspective grid presets"), + (vectorcraft_engine::cmd::TRACE_PRESET_EXTS, "imageTrace.presets.import", "tracing presets"), (fileio::SCREEN_EXPORT_PRESET_EXTS, "document.exportPresets.import", EXPORT_PRESETS), (vectorcraft_engine::cmd::compositefonts::EXTS, "type.compositeFonts.import", "composite fonts"), ]; diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index 6e38e8cc63..ba1f64b661 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -127,6 +127,7 @@ const FILE_TYPES: &[(&str, &[&str])] = &[ ("PDF presets", vectorcraft_engine::cmd::pdfcmds::PRESET_EXTS), ("Perspective grid presets", vectorcraft_engine::cmd::perspgrid::PRESET_EXTS), ("Print presets", vectorcraft_engine::cmd::printpresets::PRESET_EXTS), + ("Tracing presets", vectorcraft_engine::cmd::TRACE_PRESET_EXTS), ("Action sets", &[crate::panels::actions::ACTIONS_EXT]), ("Export presets", fileio::SCREEN_EXPORT_PRESET_EXTS), ("Composite fonts", vectorcraft_engine::cmd::compositefonts::EXTS), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index efa4e95ac4..03612edcb6 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -857,6 +857,10 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::trace_presets::open(app, p), + "ui.tracingPresetsDialog" => { + crate::dialogs::tracing_presets::open(app, s("selected").as_deref()); + Ok(Value::Null) + } "ui.flattenerPreview" => crate::panels::flattener_preview::command(app, p), "ui.copyScriptConsole" => crate::panels::script_console::copy(app, p), "window.graphicStyleLibrary" => crate::panels::graphic_styles::open_library(app, p), diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 5b88346f82..efc1118c45 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -136,6 +136,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Transparency Flattener Presets…", "ui.flattenerPresetsDialog"), c("Print Presets…", "ui.printPresetsDialog"), c("PDF Presets…", "ui.pdfPresetsDialog"), + c("Tracing Presets…", "ui.tracingPresetsDialog"), c("Perspective Grid Presets…", "ui.perspectivePresetsDialog"), Sep, c("Color Settings…", "edit.colorSettings"), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 20a2c58314..c7c20a5859 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1030,6 +1030,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings", ), + ( + "ui.tracingPresetsDialog", + "Tracing Presets…", + "", + "{selected?: preset name (default Default)} open Edit → Tracing Presets (dialog `tracingPresets`, field `selected`): the built-in presets (in brackets, read-only) and the saved ones, with the selected one's settings. New… (from the selected preset) and Edit… (a saved one) open the preset editor (dialog `tracingPreset`, fields `name` and `params`, the tracing settings): OK runs imageTrace.presets.save and returns to Tracing Presets, and a name of a built-in preset, Custom or another saved preset keeps the editor open; Cancel returns with nothing saved. Delete runs imageTrace.presets.delete; Import… runs imageTrace.presets.import, and when saved presets have names in the file, asks (dialog `tracingPresetsReplace`) whether to replace them (OK) or keep them (Cancel); Export… runs imageTrace.presets.export on every saved preset", + ), ( "ui.flattenerPreview", "Flattener Preview", diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index ce5a5955b8..856bd68894 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -21,14 +21,14 @@ use super::{first_selected, pstate, set_pstate, swatches}; use crate::VectorcraftApp; use crate::widgets::{self, menu_item}; -const MODES: [(&str, &str); 4] = [("blackAndWhite", "Black and White"), ("grayscale", "Grayscale"), ("color", "Color"), ("logo", "Flat Logo")]; +pub(crate) const MODES: [(&str, &str); 4] = + [("blackAndWhite", "Black and White"), ("grayscale", "Grayscale"), ("color", "Color"), ("logo", "Flat Logo")]; /// Color mode's palettes (`palette` param ids), in panel order. -const PALETTES: [&str; 4] = ["limited", "fullTone", "automatic", "documentLibrary"]; +pub(crate) const PALETTES: [&str; 4] = ["limited", "fullTone", "automatic", "documentLibrary"]; -/// Palette `id`, in the UI language. /// The colour Ignore Color leaves out in `params` (`ignoreColor`, `#rrggbb`): white when there is none. -fn ignore_color(params: &Value) -> [u8; 3] { +pub(crate) fn ignore_color(params: &Value) -> [u8; 3] { let hex = params["ignoreColor"].as_str().unwrap_or("").trim_start_matches('#'); let channel = |i: usize| hex.get(i * 2..i * 2 + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); match (hex.len(), channel(0), channel(1), channel(2)) { @@ -37,7 +37,8 @@ fn ignore_color(params: &Value) -> [u8; 3] { } } -fn palette_label(id: &str) -> &'static str { +/// Palette `id`, in the UI language. +pub(crate) fn palette_label(id: &str) -> &'static str { match id { "fullTone" => tl!("Full Tone"), "automatic" => tl!("Automatic"), @@ -48,7 +49,7 @@ fn palette_label(id: &str) -> &'static str { /// Document Library's Colors choices with the document's swatches: All, then the document's color /// groups (`current` checked; `None` is All) → the choice, `Some(None)` for All. -fn color_group_list(app: &VectorcraftApp, ui: &mut Ui, current: Option<&str>) -> Option> { +pub(crate) fn color_group_list(app: &VectorcraftApp, ui: &mut Ui, current: Option<&str>) -> Option> { let mut chosen = menu_item(ui, "All", true, current.is_none()).then_some(None); let groups: Vec = app.session.active().map(|d| d.doc.swatch_groups.iter().map(|g| g.name.clone()).collect()).unwrap_or_default(); if !groups.is_empty() { @@ -95,7 +96,7 @@ struct TraceUi { /// A preset: its name, its parameters, those of its enhanced version (null if it has none), and /// whether it is built in (else the user saved it). -type Preset = (String, Value, Value, bool); +pub(crate) type Preset = (String, Value, Value, bool); /// The presets as `imageTrace.presets` listed them at a revision of the saved presets. #[derive(Clone)] @@ -112,8 +113,8 @@ thread_local! { /// Every preset, built-in then saved. `imageTrace.presets` runs once for each revision of the saved /// presets ([`vectorcraft_engine::Session::trace_presets_revision`]); the list is kept in `ctx`'s -/// memory, which the panel, the Control bar and Properties share. -fn presets(app: &mut VectorcraftApp, ctx: &egui::Context) -> Arc> { +/// memory, which the panel, the Control bar, Properties and Edit → Tracing Presets share. +pub(crate) fn presets(app: &mut VectorcraftApp, ctx: &egui::Context) -> Arc> { let id = egui::Id::unique("trace-presets"); let revision = app.session.trace_presets_revision(); if let Some(list) = ctx.data(|d| d.get_temp::(id)).filter(|l| l.revision == revision) { @@ -137,7 +138,7 @@ fn presets(app: &mut VectorcraftApp, ctx: &egui::Context) -> Arc> { /// The listed preset that `name` finds, as the engine finds presets: a built-in one by its name in /// any case, also in brackets (`[Default]`), else a saved one by its exact name in any case. -fn find_preset<'a>(all: &'a [Preset], name: &str) -> Option<&'a Preset> { +pub(crate) fn find_preset<'a>(all: &'a [Preset], name: &str) -> Option<&'a Preset> { let name = name.trim(); let key = name.trim_start_matches('[').trim_end_matches(']'); all.iter().find(|p| p.3 && p.0.eq_ignore_ascii_case(key)).or_else(|| all.iter().find(|p| !p.3 && p.0.eq_ignore_ascii_case(name))) @@ -266,7 +267,7 @@ pub(crate) fn open_settings(app: &mut VectorcraftApp) { /// while the menu is open. /// A preset's name as shown: translated as a preset's name where the catalog has it so (the /// Outline preset is not the Outline view), as any other string else. -fn preset_label(name: &str) -> &str { +pub(crate) fn preset_label(name: &str) -> &str { crate::i18n::tr_ctx(crate::i18n::current(), "imageTrace", name) } @@ -403,7 +404,7 @@ pub(crate) fn traced(app: &VectorcraftApp, r: &Value) { set_pstate(&ctx, "image-trace", st); } -fn slider(ui: &mut Ui, label: &str, v: &mut f64, range: std::ops::RangeInclusive, suffix: &str) -> (bool, bool) { +pub(crate) fn slider(ui: &mut Ui, label: &str, v: &mut f64, range: std::ops::RangeInclusive, suffix: &str) -> (bool, bool) { let mut out = (false, false); ui.horizontal(|ui| { ui.add_sized([74.0, 22.0], egui::Label::new(egui::RichText::new(tl!(label)).size(12.0))); diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 60b8c5eacd..057ffb3649 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -300,7 +300,7 @@ fn a_shortcut_runs_what_its_menu_item_runs() { /// tools, the select add-on and Select by Link Status…), four "…" items whose menu entry gives /// params, Edit Custom Dictionary…, Composite Fonts…, Recolor Artwork…, the Edit menu's preset /// dialogs and Apply SVG Filter…. -const MENU_DIALOG_COMMANDS: [&str; 39] = [ +const MENU_DIALOG_COMMANDS: [&str; 40] = [ "object.path.smooth", "object.path.simplify", "object.path.offsetPath", @@ -338,6 +338,7 @@ const MENU_DIALOG_COMMANDS: [&str; 39] = [ "ui.flattenerPresetsDialog", "ui.printPresetsDialog", "ui.pdfPresetsDialog", + "ui.tracingPresetsDialog", "ui.perspectivePresetsDialog", "ui.svgFilterDialog", ]; diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..993e7083d6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3220,8 +3220,23 @@ already walks Image Trace. Short agent entry points: `builtIn: true`, then the saved ones with `builtIn: false`, and returns a `revision` that grows each time the saved presets change. `imageTrace.make {preset}` takes a saved preset's name, with ASCII letters matching in either case. Its journal entry records the saved preset's settings as `savedPreset`, so a replay traces with them after the preset - is changed, renamed or deleted. In the app, - `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog. + is changed, renamed or deleted. `imageTrace.presets.export {names?, path?}` writes saved presets (default: every one; + a built-in preset's name is an error) as a `.vctracepresets` file, VectorCraft's own JSON layout + (`{"format": "vctracepresets", "version": 1, "presets": [{"name", "params"}]}`), to `path`, else returns its text as + `data`; it refuses more than 1,000 presets or a file over 4 MiB, the limits of the import. + `imageTrace.presets.import {path? | data? | dataBase64?, replace?}` adds the presets of such a file (at most + 4 MiB and 1,000 presets) → `{imported, replaced, skipped}`: a preset with a saved preset's name is skipped unless + `replace` is true. Every preset in the file is checked first, and a file with a built-in preset's or `Custom`'s name, + two presets of one name, a preset without a name or `params`, settings `imageTrace.presets.save` refuses, or a newer + `version` changes nothing. In the app, opening a `.vctracepresets` file (File › Open, a drop, or the file picked + for Import… on the web) imports it as Import… does. Also in the app, + `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog, + and `ui.tracingPresetsDialog {selected?}` opens Edit › Tracing Presets…: the built-in presets in brackets (read-only) + and the saved ones, with the selected preset's settings. Its New… (from the selected preset) and Edit… (a saved + preset) open an editor with the Image Trace panel's settings; OK saves with `imageTrace.presets.save` and Cancel saves + nothing, and a built-in preset's name, `Custom` or another saved preset's name keeps the editor open. Delete selects + the saved preset below the deleted one, else the one above it, else Default. Import… asks whether to replace saved presets whose names the file holds (Cancel + keeps them), and Export… writes every saved preset. - Live Paint: `livePaint.make`, `livePaint.merge`, `livePaint.fill {group?, point}`, `livePaint.strokeEdge`, `livePaint.info {group}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?, color?, closeGaps?}` (Object › Live Paint › Gap Options). Make gives each covered face the fill of its front-most @@ -5250,7 +5265,7 @@ commands are listed this way: (Object › Perspective), under Perspective; - `text.spelling.dictionary` (Edit › Edit Custom Dictionary…), under Text; - the UI commands `ui.recolorDialog` (Edit › Edit Colors › Recolor Artwork…), `ui.flattenerPresetsDialog`, - `ui.printPresetsDialog`, `ui.pdfPresetsDialog`, `ui.perspectivePresetsDialog`, `ui.svgFilterDialog`, + `ui.printPresetsDialog`, `ui.pdfPresetsDialog`, `ui.tracingPresetsDialog`, `ui.perspectivePresetsDialog`, `ui.svgFilterDialog`, `ui.saveSwatchLibrary`, `ui.saveBrushLibrary`, `ui.saveGraphicStyleLibrary` and `ui.saveSymbolLibrary`, under Ui; `file.exportAs` and `file.exportSelection`, under File; `links.editOriginal`, under Links; `type.applyBullets` and `type.applyNumbers`, under Type; and `window.toolbar.new`, `window.toolbarColumns`, `window.toolsBesideCanvas`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..676a0cfd65 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1320,6 +1320,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, Preview:** the Image Trace panel's Preview checkbox, before Trace, is on by default, and a setting change traces the selected Image Trace object again at once. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected. When Preview is turned on with that object not selected, the object is traced with its changes when it is selected again. Preview is kept with the UI preferences, and Reset to Default leaves it. The `imageTrace.preview` command turns it on or off. - **Image Trace small contours:** closed fits too small to form an editable subpath retain their positioned outline, including holes. Source-generated island, hole/winding and stepped-region regressions cover Corners and Noise; defaults, parity scores and estimates are unchanged. - **Image Trace, custom presets:** Manage Presets next to the Image Trace panel's Preset dropdown saves the panel's settings as a new preset under a name (Save as New Preset…) and renames or deletes the saved preset shown; built-in presets don't change. Saved presets are kept with the preferences and follow the built-in ones in the panel, Control bar and Properties preset lists. `imageTrace.presets.save` and `imageTrace.presets.delete` save, rename and delete them, `imageTrace.presets` lists them, and `imageTrace.make {preset}` traces with one by name. +- **Image Trace, Edit › Tracing Presets…:** the menu item opens a manager for the same presets, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=106) describes: New… makes a preset from the selected one, Edit… and Delete change saved presets only (built-in presets, in brackets, don't change), and Import… and Export… exchange the saved presets through a `.vctracepresets` file (`imageTrace.presets.import` / `.export`, `ui.tracingPresetsDialog`). The file layout, the question before an import replaces saved presets of the same names (Cancel keeps them), the selection after Delete and the editor's Cancel are VectorCraft's own. - **Image Trace, preset buttons:** six buttons above the Image Trace panel's Preset dropdown choose a preset as the dropdown does, for the options the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/image-trace-panel-options.html) lists before Preset. The presets each button chooses are VectorCraft's own: Auto Color chooses Auto Color, High Color chooses High Fidelity Photo, Low Color chooses Low Fidelity Photo, Grayscale chooses Shades of Gray, Black and White chooses Black and White Logo, and Outline chooses Outline. With Preview on, a click traces the selected Image Trace object again as one undo step; with nothing traced selected, it changes the panel's settings only. The button of the panel's preset shows as selected. - **Create Strokes baseline (2026-10-17, measured):** the ignored centre-lines class covers 23 exact code-drawn scenes in aa and hard variants, including junctions, crossings, fills meeting strokes and varying widths. [Baseline and metric definitions](image-trace-quality.md#centre-lines). Topology is recovered from emitted geometry; width-profile metrics remain unavailable. No behaviour change or score increase. - **Image Trace, collapsed loops keep few segments:** a loop whose fit collapses to one cubic keeps the fewest segments that hold its area and course, so a higher Paths gives no fewer segments; a code-drawn Paths sweep in `crates/trace` (see [quality notes](image-trace-quality.md#collapsed-loops-keep-few-segments)). From 6e1f7359a79c79c48fde75acee09edcc027b3b4e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 09:11:05 -0800 Subject: [PATCH 02/69] i18n: Hindi glossary term for the tracing presets replace prompt --- crates/ui-egui/src/i18n/hi.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 67e54795f0..50fe9db1be 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1253,7 +1253,7 @@ antiAlias Sharp शार्प Tracing Presets… ट्रेसिंग प्रीसेट… Import Image Trace Presets आयात इमेज ट्रेस प्रीसेट्स Export Image Trace Presets निर्यात इमेज ट्रेस प्रीसेट्स - Replace the saved presets that have these names? इन नामों वाले सहेजे गए प्रीसेट बदलें? + Replace the saved presets that have these names? इन नामों वाले सेव किए गए प्रीसेट बदलें? Delete Instances इंस्टेंस हटाएँ Delete Layer लेयर हटाएँ Delete Library लाइब्रेरी हटाएँ From b83cec1545bb607da56bc966da9df4bec33194fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 09:20:00 -0800 Subject: [PATCH 03/69] Color Wheel: Show Document Colors lists the colors the art uses The Color Wheel panel menu gets Show Document Colors. It adds a row under the wheel or the box with the colors of the selection, headed Selection Colors, or with nothing selected the colors of the art Select All takes, headed Document Colors, most used first and as many as fit in one row. A color's tooltip gives its hex value and how many times the art uses it. A click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone. Alt+click applies it to the other proxy. The row keeps its colors during a drag. In art with more than 5,000 color uses, it reads them again at most once every half second after an edit; a change of document or selection reads them at once. color.used {selection?, limit?} lists the colors recolor.colors lists, each with the color in its own model and the tint of its swatch to three decimals. The swatch and tint come from the color's first linked use in paint order, a plain use before a gradient stop that mixes a spot ink with process inks; a color that only such stops link has no swatch there. ui.colorWheel {documentColors} sets the option, which is kept with the preferences. Docs: docs/control-protocol.md, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/recolor.rs | 113 ++++-- crates/engine/src/tests/recolor.rs | 116 +++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 4 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels.rs | 2 + crates/ui-egui/src/panels/color_wheel.rs | 179 +++++++++- .../src/panels/tests_color_wheel_box.rs | 26 +- .../tests_color_wheel_document_colors.rs | 323 ++++++++++++++++++ docs/control-protocol.md | 10 + docs/mcp.md | 4 + docs/target-app-parity.md | 1 + 40 files changed, 845 insertions(+), 46 deletions(-) create mode 100644 crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5329f23331..f1555d8a49 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -138,6 +138,7 @@ pub(super) const ALLOWED: &[&str] = &[ "color.gamutCheck", "color.harmony", "color.plates", + "color.used", "dataset.capture", "dataset.delete", "dataset.list", diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 07f1f4c46b..08e8c48657 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -29,6 +29,15 @@ pub fn specs() -> Vec { has_doc, colors ), + cmd!( + query "color.used", + "Document Colors", + [], + None, + "{selection?: true (false: the objects select.all takes, also while something is selected), limit?: n (only the n most used; default all)} → {colors: [{key, hex, color: the color in its own model ({model, …}), count, swatch?: the global swatch it is linked to (from its first linked use in paint order, a plain use before a gradient stop that mixes the swatch's ink with process inks; left out when only such stops link it), tint?: 0..100 to three decimals (the percent of that swatch's color the same use stores)}] as recolor.colors lists them, selection: true when they are the selection's, uses: the uses of every color, those past limit included} the unique colors of the selection, or with nothing selected or selection false of the objects select.all takes without the hidden and locked objects inside them, most used first; the selection is left as it is", + has_doc, + used + ), cmd!( "recolor.apply", "Recolor Artwork", @@ -945,11 +954,15 @@ fn pick_theme(s: &mut Session, p: &Value) -> Result { Ok(json!({"colors": colors.iter().map(key_str).collect::>(), "objects": theme.objects})) } -/// A colour the art uses: how often, and the global swatch it is linked to. +/// A color the art uses: how often, and the global swatch it is linked to with the tint (0..1) of +/// the swatch its paint stores, when the paint gives one. struct Used { color: Color, count: usize, swatch: Option, + tint: Option, + /// The link comes from a gradient stop that mixes the swatch's ink with process inks. + mixed: bool, } /// The unique colours of the objects `ids` and the objects inside them, most used first (ties by @@ -967,16 +980,23 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> } let mut index: HashMap = HashMap::new(); let mut used: Vec<(ColorKey, Used)> = vec![]; - let mut count = |c: &Color, link: Option<&str>| { + let mut count_tint = |c: &Color, link: Option<&str>, tint: Option, mixed: bool| { let k = ColorKey::of(c); let i = *index.entry(k).or_insert_with(|| { - used.push((k, Used { color: *c, count: 0, swatch: None })); + used.push((k, Used { color: *c, count: 0, swatch: None, tint: None, mixed: false })); used.len() - 1 }); let u = &mut used[i].1; u.count += 1; - if u.swatch.is_none() { - u.swatch = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())).map(str::to_string); + // The first linked use in paint order gives the swatch and tint; a plain linked use + // replaces one from a stop that mixes the swatch's ink with process inks. + if u.swatch.is_none() || (u.mixed && !mixed) { + let linked = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())); + if let Some(l) = linked { + u.swatch = Some(l.to_string()); + u.tint = tint; + u.mixed = mixed; + } } }; // The patterns used as fills or strokes: their tiles count once each. @@ -986,25 +1006,32 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> read(n, only, &mut nodes); } for m in nodes { - for p in node_paints(m).chain(override_paints(m)) { - match p { - Paint::Solid { color, swatch, .. } => count(color, swatch.as_deref()), - Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref())), - Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern), - _ => {} - } - } - if let NodeKind::Mesh(mesh) = &m.kind { - mesh.points.iter().for_each(|p| count(&p.color, None)); - } + paints(m, &mut count_tint, &mut patterns); } for def in patterns.iter().filter_map(|p| d.pattern(p)) { - def.art.iter().for_each(|n| node_colors(n, &mut count)); + def.art.iter().for_each(|n| n.walk(&mut |m| paints(m, &mut count_tint, &mut vec![]))); } used.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(&b.0))); used.into_iter().map(|(_, u)| u).collect() } +/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint +/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and +/// add the patterns it is painted with to `patterns`. +fn paints<'a>(m: &'a Node, count: &mut impl FnMut(&Color, Option<&str>, Option, bool), patterns: &mut Vec<&'a str>) { + for p in node_paints(m).chain(override_paints(m)) { + match p { + Paint::Solid { color, swatch, tint } => count(color, swatch.as_deref(), Some(*tint), false), + Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref(), Some(s.tint), s.plates.is_some())), + Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern), + _ => {} + } + } + if let NodeKind::Mesh(mesh) = &m.kind { + mesh.points.iter().for_each(|p| count(&p.color, None, None, false)); + } +} + /// The colors `n` shows, in paint order ([`node_colors`]), then the colors of the tiles of the /// patterns it uses as fills or strokes, and of the patterns those tiles use (each pattern once). fn shown_colors<'a>(d: &'a Document, n: &'a Node) -> Vec { @@ -1047,30 +1074,58 @@ fn scope_ids(s: &Session, p: &Value, cmd: &str) -> Result<(Vec, Option checked_ids_param(s, p, "ids", cmd)?, - None if st.selection.is_empty() => { - let only = super::select::selectable_ids(&st.doc, st.isolation); - return Ok((super::select::selectable(&st.doc, st.isolation), Some(only))); - } + None if st.selection.is_empty() => return Ok(all_art(st)), None => st.selection.objects.clone(), }; let mut seen = BTreeSet::new(); Ok((super::edit::outermost(&st.doc, ids).into_iter().filter(|id| seen.insert(*id)).collect(), None)) } -fn colors(s: &mut Session, p: &Value) -> Result { - let (ids, only) = scope_ids(s, p, "recolor.colors")?; - let st = s.doc()?; - let v: Vec = used_colors(&st.doc, &ids, only.as_ref()) - .iter() +/// The objects Select All takes, and the objects whose colors count ([`scope_ids`] with nothing +/// selected). +fn all_art(st: &crate::DocState) -> (Vec, Option>) { + let only = super::select::selectable_ids(&st.doc, st.isolation); + (super::select::selectable(&st.doc, st.isolation), Some(only)) +} + +/// The `colors` list of `recolor.colors` and `color.used` for the objects `ids` (see +/// [`used_colors`]). With `with_color`, each has its color in its own model and the tint of its +/// swatch, and a gradient stop's color that mixes the swatch's ink with process inks has no swatch. +fn colors_json(used: &[Used], with_color: bool) -> Vec { + used.iter() .map(|u| { let mut v = json!({"key": key_str(&u.color), "hex": u.color.to_hex(), "count": u.count}); - if let Some(w) = &u.swatch { + if with_color { + v["color"] = json!(u.color); + } + if let Some(w) = u.swatch.as_ref().filter(|_| !(with_color && u.mixed)) { v["swatch"] = json!(w); + if let Some(t) = u.tint.filter(|_| with_color) { + v["tint"] = json!((f64::from(t) * 100_000.0).round() / 1000.0); + } } v }) - .collect(); - Ok(json!({ "colors": v })) + .collect() +} + +fn colors(s: &mut Session, p: &Value) -> Result { + let (ids, only) = scope_ids(s, p, "recolor.colors")?; + let st = s.doc()?; + Ok(json!({ "colors": colors_json(&used_colors(&st.doc, &ids, only.as_ref()), false) })) +} + +/// `color.used {selection?, limit?}`: the colors of the selection, or of the art Select All takes. +fn used(s: &mut Session, p: &Value) -> Result { + const C: &str = "color.used"; + let limit = super::index_opt(p, "limit", C)?.unwrap_or(usize::MAX); + let selection = switch_or(p, "selection", true, C)? && !s.doc()?.selection.is_empty(); + let (ids, only) = if selection { scope_ids(s, &json!({}), C)? } else { all_art(s.doc()?) }; + let st = s.doc()?; + let used = used_colors(&st.doc, &ids, only.as_ref()); + let uses: usize = used.iter().map(|u| u.count).sum(); + let shown = used.get(..limit.min(used.len())).unwrap_or_default(); + Ok(json!({ "colors": colors_json(shown, true), "selection": selection, "uses": uses })) } /// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 90e7822ef8..e402956a1c 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -133,6 +133,122 @@ fn colors_with_nothing_selected_leave_out_what_select_all_leaves_out() { assert_eq!(hexes(&run(&mut s, "recolor.colors", json!({"ids": [hidden.0]}))), ["#0000ff"]); } +#[test] +fn used_colors_list_the_most_used_first_with_their_colors() { + let mut s = session(); + let reds: Vec = (0..3).map(|_| rect(&mut s, json!("#ff0000"))).collect(); + let blue = rect(&mut s, json!({"c": 100, "m": 100, "y": 0, "k": 0})); + run(&mut s, "select.set", json!({"ids": []})); + let r = run(&mut s, "color.used", json!({})); + assert_eq!(r["selection"], false, "{r}"); + let colors = r["colors"].as_array().unwrap(); + assert_eq!(colors.len(), 2, "{r}"); + assert_eq!((colors[0]["key"].as_str(), colors[0]["hex"].as_str(), colors[0]["count"].as_u64()), (Some("rgb 255 0 0"), Some("#ff0000"), Some(3))); + assert_eq!(colors[1]["count"], 1); + let first = run(&mut s, "color.used", json!({"limit": 1})); + assert_eq!(first["colors"], json!([colors[0]]), "`limit` keeps the most used"); + assert_eq!((r["uses"].clone(), first["uses"].clone()), (json!(4), json!(4)), "`uses` counts every color"); + // `color` is the color in its own model, which the paint commands take back. + assert_eq!(colors[1]["color"]["model"], "cmyk", "{r}"); + assert!(close(color_value(&colors[1]["color"]).unwrap(), fill(&s, blue))); + // The selection's colors while something is selected; `selection: false` reads all the art. + run(&mut s, "select.set", json!({"ids": [blue.0]})); + let r = run(&mut s, "color.used", json!({})); + assert_eq!((r["selection"].clone(), r["colors"].as_array().unwrap().len()), (json!(true), 1), "{r}"); + let all = run(&mut s, "color.used", json!({"selection": false})); + assert_eq!((all["selection"].clone(), all["colors"][0]["count"].clone()), (json!(false), json!(3)), "{all}"); + assert_eq!(s.doc().unwrap().selection.objects, [blue], "the selection is left as it was"); + // A hidden object's color is left out with nothing selected, as Select All leaves it out. + run(&mut s, "object.hide", json!({"ids": [reds[0].0]})); + assert_eq!(run(&mut s, "color.used", json!({"selection": false}))["colors"][0]["count"], 2); + let e = s.execute("color.used", &json!({"selection": "no"})).unwrap_err().to_string(); + assert!(e.contains("`selection` must be true or false"), "{e}"); + assert!(s.execute("color.used", &json!({"ids": [blue.0]})).is_err(), "an unknown key is refused"); +} + +#[test] +fn used_colors_name_the_swatch_and_tint_a_color_is_linked_to() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let tinted = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [tinted.0], "swatch": "Ink", "tint": 40})); + run(&mut s, "select.set", json!({"ids": []})); + let r = run(&mut s, "color.used", json!({})); + let c = &r["colors"][0]; + assert_eq!(c["swatch"].as_str(), Some("Ink"), "{r}"); + assert!((c["tint"].as_f64().unwrap() - 40.0).abs() < 1e-4, "{r}"); + // recolor.colors keeps its own fields. + assert_eq!(run(&mut s, "recolor.colors", json!({}))["colors"][0].get("tint"), None); + // A swatch of paper white looks the same at every tint; the tint comes from the paint. + run(&mut s, "swatch.new", json!({"name": "Paper", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})); + let paper = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [paper.0], "swatch": "Paper", "tint": 33.333})); + run(&mut s, "select.set", json!({"ids": [paper.0]})); + let c = run(&mut s, "color.used", json!({}))["colors"][0].clone(); + assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}"); + // The tint is the paint's own, unrounded. + let vectorcraft_color::Paint::Solid { tint, .. } = s.doc().unwrap().doc.node(paper).unwrap().appearance.fill_paint() else { + panic!("a solid fill") + }; + assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}"); + assert!((tint - 0.33333).abs() < 1e-5); + // A pattern's tile keeps its tint as well. + run(&mut s, "select.set", json!({"ids": [paper.0]})); + run(&mut s, "object.pattern.make", json!({"name": "Sheet", "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + let filled = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [filled.0], "swatch": "Sheet"})); + run(&mut s, "select.set", json!({"ids": [filled.0]})); + let c = run(&mut s, "color.used", json!({}))["colors"][0].clone(); + assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}"); + assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}"); +} + +#[test] +fn used_colors_give_no_swatch_for_a_stop_that_mixes_its_ink_with_process_inks() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let shape = rect(&mut s, json!("#000000")); + let mixed = Color::Cmyk { c: 0.3, m: 0.5, y: 0.3, k: 0.0 }; + let stop = |color, plates| GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates, ..GradientStop::new(0.0, color) }; + let mut end = stop(Color::Cmyk { c: 0.0, m: 0.5, y: 0.3, k: 0.0 }, None); + end.offset = 1.0; + let g = Gradient::new(GradientKind::Linear, vec![stop(mixed, Some([0.3, 0.0, 0.0, 0.0])), end]); + let st = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g)))); + let r = run(&mut s, "color.used", json!({})); + let entry = |key: &str| r["colors"].as_array().unwrap().iter().find(|c| c["key"] == key).cloned().unwrap(); + let mix = entry("cmyk 30 50 30 0"); + assert_eq!((mix.get("swatch"), mix.get("tint")), (None, None), "{r}"); + assert_eq!(entry("cmyk 0 50 30 0")["swatch"], "Ink", "{r}"); + // recolor.colors keeps the swatch it lists. + let listed = run(&mut s, "recolor.colors", json!({})); + assert!(listed["colors"].as_array().unwrap().iter().all(|c| c["swatch"] == "Ink"), "{listed}"); +} + +#[test] +fn used_colors_take_the_swatch_of_a_plain_use_painted_after_a_mixed_stop_of_the_same_color() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let shape = rect(&mut s, json!("#000000")); + let plain = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Ink", "tint": 50})); + let ink = fill(&s, plain); + // The stop below the plain fill has the same color, and process plates that add nothing. + let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) }; + let mut end = stop.clone(); + end.offset = 1.0; + let g = Gradient::new(GradientKind::Linear, vec![stop, end]); + let st = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g)))); + run(&mut s, "select.set", json!({"ids": []})); + let r = run(&mut s, "color.used", json!({})); + let c = r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap(); + assert_eq!((c["swatch"].as_str(), c["tint"].as_f64()), (Some("Ink"), Some(50.0)), "{r}"); +} + #[test] fn colors_with_nothing_selected_leave_out_hidden_and_locked_objects_in_groups() { let mut s = session(); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 943faa4782..bf98f8f772 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1324,7 +1324,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, all three are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, documentColors}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 348ac7b881..df1edd2590 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -124,6 +124,10 @@ Add to Selection Добавяне към селекцията Add to Swatches Добавяне към образци Add Used Colors Добавяне на използваните цветове + Show Document Colors Показване на цветовете на документа + Document Colors Цветове на документа + Selection Colors Цветове на селекцията +@plural Used {n} time|Used {n} times Използван {n} път|Използван {n} пъти Additional Plug-ins Folder Допълнителна папка за плъгини Additional Fonts Folder Допълнителна папка за шрифтове Adjust Adjoining Width Points Регулиране на прилежащите точки за ширина diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 3b1a9e001c..f82871372a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3996,6 +3996,10 @@ theme Appearance Izgled Add to Graphic Styles Dodaj u grafičke stilove Graphic Style Library Biblioteka grafičkih stilova Add Used Colors Dodaj korištene boje + Show Document Colors Prikaži boje dokumenta + Document Colors Boje dokumenta + Selection Colors Boje odabira +@plural Used {n} time|Used {n} times Korišteno {n} put|Korišteno {n} puta|Korišteno {n} puta Delete Swatch Izbriši uzorak boje Duplicate Swatch Dupliciraj uzorak boje Merge Swatches Spoji uzorke boja diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 488b46c4f5..29e1ee4c7b 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -220,6 +220,10 @@ Add to Symbols Afegeix als símbols Add to the Current Shortcuts Afegeix a les dreceres actuals Add Used Colors Afegeix els colors utilitzats + Show Document Colors Mostra els colors del document + Document Colors Colors del document + Selection Colors Colors de la selecció +@plural Used {n} time|Used {n} times Utilitzat {n} vegada|Utilitzat {n} vegades Additional Fonts Folder Carpeta addicional de tipus de lletra Additional Plug-ins Folder Carpeta addicional de complements Adjust Adjoining Width Points Ajusta els punts d’amplada contigus diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 6a57e90e37..022f7a27c6 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4052,6 +4052,10 @@ theme Appearance Motiv Add to Graphic Styles Přidat do grafických stylů Graphic Style Library Knihovna grafických stylů Add Used Colors Přidat použité barvy + Show Document Colors Zobrazit barvy dokumentu + Document Colors Barvy dokumentu + Selection Colors Barvy výběru +@plural Used {n} time|Used {n} times Použito {n}krát|Použito {n}krát|Použito {n}krát Delete Swatch Odstranit položku vzorníku Duplicate Swatch Duplikovat položku vzorníku Merge Swatches Sloučit položky vzorníku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 54a79e38e5..867e270455 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3769,6 +3769,10 @@ theme Appearance Udseende Add to Graphic Styles Føj til grafikstile Graphic Style Library Grafikstilbibliotek Add Used Colors Tilføj anvendte farver + Show Document Colors Vis dokumentfarver + Document Colors Dokumentfarver + Selection Colors Markeringens farver +@plural Used {n} time|Used {n} times Brugt {n} gang|Brugt {n} gange Delete Swatch Slet farveprøve Duplicate Swatch Duplikér farveprøve Merge Swatches Flet farveprøver diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index ab77cb0dd7..1dea2713e5 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -113,6 +113,10 @@ Add to Selection Zur Auswahl hinzufügen Add to Swatches Zu Farbfeldern hinzufügen Add Used Colors Verwendete Farben hinzufügen + Show Document Colors Dokumentfarben einblenden + Document Colors Dokumentfarben + Selection Colors Farben der Auswahl +@plural Used {n} time|Used {n} times {n}-mal verwendet|{n}-mal verwendet Additional Plug-ins Folder Zusätzlicher Plug-in-Ordner Additional Fonts Folder Zusätzlicher Schriftenordner Adjust Adjoining Width Points Angrenzende Breitenpunkte anpassen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a1a203a257..4586bc55d5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -118,6 +118,10 @@ Add to Selection Προσθήκη στην επιλογή Add to Swatches Προσθήκη στα δείγματα χρωμάτων Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων + Show Document Colors Εμφάνιση χρωμάτων εγγράφου + Document Colors Χρώματα εγγράφου + Selection Colors Χρώματα επιλογής +@plural Used {n} time|Used {n} times Χρησιμοποιείται {n} φορά|Χρησιμοποιείται {n} φορές Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών Adjust Adjoining Width Points Ρύθμιση γειτονικών σημείων πλάτους diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 45fd0d8235..71303625d0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -138,6 +138,10 @@ Add to Selection Agregar a la selección Add to Swatches Agregar a muestras Add Used Colors Agregar colores usados + Show Document Colors Mostrar colores del documento + Document Colors Colores del documento + Selection Colors Colores de la selección +@plural Used {n} time|Used {n} times Usado {n} vez|Usado {n} veces Additional Plug-ins Folder Carpeta de plugins adicionales Additional Fonts Folder Carpeta de fuentes adicionales Adjust Adjoining Width Points Ajustar puntos de anchura contiguos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f6db5b8ee1..73be8592dc 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3976,6 +3976,10 @@ theme Appearance Ulkoasu Add to Graphic Styles Lisää grafiikkatyyleihin Graphic Style Library Grafiikkatyylikirjasto Add Used Colors Lisää käytetyt värit + Show Document Colors Näytä asiakirjan värit + Document Colors Asiakirjan värit + Selection Colors Valinnan värit +@plural Used {n} time|Used {n} times Käytetty {n} kerran|Käytetty {n} kertaa Delete Swatch Poista värimalli Duplicate Swatch Monista värimalli Merge Swatches Yhdistä värimallit diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index ae0bf3b436..b820a18e31 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -139,6 +139,10 @@ Add to Selection Ajouter à la sélection Add to Swatches Ajouter au nuancier Add Used Colors Ajouter les couleurs utilisées + Show Document Colors Afficher les couleurs du document + Document Colors Couleurs du document + Selection Colors Couleurs de la sélection +@plural Used {n} time|Used {n} times Utilisée {n} fois|Utilisée {n} fois Additional Plug-ins Folder Dossier de modules externes supplémentaires Additional Fonts Folder Dossier de polices supplémentaires Adjust Adjoining Width Points Ajuster les points de largeur adjacents diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index f38612601c..082c6ed11b 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -148,6 +148,10 @@ Add Selected Artwork as One Asset પસંદ કરેલી આર્ટવર્ક એક સંપત્તિ તરીકે ઉમેરો Add Spine Point સ્પાઇન બિંદુ ઉમેરો Add Used Colors વપરાયેલા રંગ ઉમેરો + Show Document Colors દસ્તાવેજના રંગો બતાવો + Document Colors દસ્તાવેજના રંગો + Selection Colors પસંદગીના રંગો +@plural Used {n} time|Used {n} times {n} વાર વપરાયો|{n} વાર વપરાયો Add as Effect ઇફેક્ટ તરીકે ઉમેરો Add space to fit ફિટ કરવા જગ્યા ઉમેરો Add to Brushes બ્રશમાં ઉમેરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 624671acca..85875a3ec7 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -254,6 +254,10 @@ Add to Symbols सिंबल्स में जोड़ें Add to the Current Shortcuts वर्तमान शॉर्टकट में जोड़ें Add Used Colors उपयोग किए रंग जोड़ें + Show Document Colors डॉक्यूमेंट के रंग दिखाएँ + Document Colors डॉक्यूमेंट के रंग + Selection Colors चयन के रंग +@plural Used {n} time|Used {n} times {n} बार उपयोग किया गया|{n} बार उपयोग किया गया Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3e8a200697..c43b3aaaf9 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -208,6 +208,10 @@ Add to Selection Hozzáadás a kijelöléshez Add to Swatches Hozzáadás a színmintákhoz Add Used Colors Használt színek hozzáadása + Show Document Colors Dokumentumszínek megjelenítése + Document Colors Dokumentumszínek + Selection Colors A kijelölés színei +@plural Used {n} time|Used {n} times {n} alkalommal használva Additional Fonts Folder További betűtípusok mappája Additional Plug-ins Folder További bővítmények mappája Adjust Adjoining Width Points Szomszédos szélességi pontok igazítása diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 2107a23bf0..5925757556 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3769,6 +3769,10 @@ theme Appearance Tampilan Add to Graphic Styles Tambahkan ke gaya grafis Graphic Style Library Pustaka gaya grafis Add Used Colors Tambahkan warna yang digunakan + Show Document Colors Tampilkan warna dokumen + Document Colors Warna dokumen + Selection Colors Warna pilihan +@plural Used {n} time|Used {n} times Dipakai {n} kali Delete Swatch Hapus sampel Duplicate Swatch Duplikatkan sampel Merge Swatches Gabungkan sampel diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f75dc629db..308ca4f98a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -138,6 +138,10 @@ Add to Selection Aggiungi alla selezione Add to Swatches Aggiungi ai campioni Add Used Colors Aggiungi colori usati + Show Document Colors Mostra colori del documento + Document Colors Colori del documento + Selection Colors Colori della selezione +@plural Used {n} time|Used {n} times Usato {n} volta|Usato {n} volte Additional Plug-ins Folder Cartella plug-in aggiuntivi Additional Fonts Folder Cartella font aggiuntivi Adjust Adjoining Width Points Regola punti di larghezza adiacenti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 67072cc8b3..26ba2dd4a8 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1046,6 +1046,10 @@ digits Malayalam マラヤーラム数字 Add Selected Artwork as One Asset 選択したアートワークを 1 つのアセットとして追加 Add Spine Point スパインポイントを追加 Add Used Colors 使用中のカラーを追加 + Show Document Colors ドキュメントのカラーを表示 + Document Colors ドキュメントのカラー + Selection Colors 選択範囲のカラー +@plural Used {n} time|Used {n} times {n} 回使用 Add to Graphic Styles グラフィックスタイルに追加 Add to Profiles プロファイルに追加 Add to Profiles… プロファイルに追加… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index c8513b84c3..88883691d5 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3608,6 +3608,10 @@ theme Appearance იერსახე Add to Graphic Styles გრაფიკულ სტილებში დამატება Graphic Style Library გრაფიკული სტილების ბიბლიოთეკა Add Used Colors გამოყენებული ფერების დამატება + Show Document Colors დოკუმენტის ფერების ჩვენება + Document Colors დოკუმენტის ფერები + Selection Colors მონიშნულის ფერები +@plural Used {n} time|Used {n} times გამოყენებულია {n}-ჯერ Delete Swatch ფერის ნიმუშის წაშლა Duplicate Swatch ფერის ნიმუშის დუბლირება Merge Swatches ფერის ნიმუშების შერწყმა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 8aa0bc41ca..adafabceee 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1036,6 +1036,10 @@ digits Malayalam 말라얄람어 Add Selected Artwork as One Asset 선택한 아트워크를 하나의 에셋으로 추가 Add Spine Point 스파인 포인트 추가 Add Used Colors 사용한 색상 추가 + Show Document Colors 문서 색상 표시 + Document Colors 문서 색상 + Selection Colors 선택 영역 색상 +@plural Used {n} time|Used {n} times {n}회 사용 Add to Graphic Styles 그래픽 스타일에 추가 Add to Profiles 프로필에 추가 Add to Profiles… 프로필에 추가… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index de5b7a3cf6..fbc59dbbea 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4287,6 +4287,10 @@ theme Appearance Vormgeving Add to Graphic Styles Aan grafische stijlen toevoegen Graphic Style Library Bibliotheek met grafische stijlen Add Used Colors Gebruikte kleuren toevoegen + Show Document Colors Documentkleuren tonen + Document Colors Documentkleuren + Selection Colors Kleuren van de selectie +@plural Used {n} time|Used {n} times {n} keer gebruikt|{n} keer gebruikt Delete Swatch Kleurstaal verwijderen Duplicate Swatch Kleurstaal dupliceren Merge Swatches Kleurstalen samenvoegen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f9bdc664f1..a1b3192735 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3911,6 +3911,10 @@ theme Appearance Wygląd Add to Graphic Styles Dodaj do stylów graficznych Graphic Style Library Biblioteka stylów graficznych Add Used Colors Dodaj użyte kolory + Show Document Colors Pokaż kolory dokumentu + Document Colors Kolory dokumentu + Selection Colors Kolory zaznaczenia +@plural Used {n} time|Used {n} times Użyty {n} raz|Użyty {n} razy|Użyty {n} razy Delete Swatch Usuń próbkę Duplicate Swatch Powiel próbkę Merge Swatches Scal próbki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 07cd9c6fd6..4763e73dbc 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -140,6 +140,10 @@ Add Selected Artwork as One Asset Adicionar Arte Selecionada como Um Ativo Add Spine Point Adicionar Ponto de Coluna Add Used Colors Adicionar Cores Usadas + Show Document Colors Mostrar Cores do Documento + Document Colors Cores do Documento + Selection Colors Cores da Seleção +@plural Used {n} time|Used {n} times Usada {n} vez|Usada {n} vezes Add to Graphic Styles Adicionar aos Estilos Gráficos Add to Profiles Adicionar aos Perfis Add to Profiles… Adicionar aos Perfis… diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index fcf44192cd..15bf324a05 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -136,6 +136,10 @@ Add to Selection Добавить к выделению Add to Swatches Добавить в образцы Add Used Colors Добавить использованные цвета + Show Document Colors Показать цвета документа + Document Colors Цвета документа + Selection Colors Цвета выделения +@plural Used {n} time|Used {n} times Используется {n} раз|Используется {n} раза|Используется {n} раз Additional Plug-ins Folder Папка дополнительных модулей Additional Fonts Folder Папка дополнительных шрифтов Adjust Adjoining Width Points Настроить смежные точки ширины diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index d68878734e..07131dc54a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -126,6 +126,10 @@ Add to Selection Lägg till i markering Add to Swatches Lägg till i färgrutor Add Used Colors Lägg till använda färger + Show Document Colors Visa dokumentfärger + Document Colors Dokumentfärger + Selection Colors Markeringens färger +@plural Used {n} time|Used {n} times Används {n} gång|Används {n} gånger Additional Plug-ins Folder Mapp för ytterligare plugins Additional Fonts Folder Mapp för ytterligare typsnitt Adjust Adjoining Width Points Justera angränsande breddpunkter diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index b3c88cc563..fd5bcf86b3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -123,6 +123,10 @@ Add to Selection Seçime Ekle Add to Swatches Renk Örneklerine Ekle Add Used Colors Kullanılan Renkleri Ekle + Show Document Colors Belge Renklerini Göster + Document Colors Belge Renkleri + Selection Colors Seçim Renkleri +@plural Used {n} time|Used {n} times {n} kez kullanıldı Additional Plug-ins Folder Ek Eklentiler Klasörü Additional Fonts Folder Ek Yazı Tipleri Klasörü Adjust Adjoining Width Points Bitişik Genişlik Noktalarını Ayarlayın diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0ab6257df4..90b4427f4c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -132,6 +132,10 @@ Add to Selection Додати до виділення Add to Swatches Додати до зразків Add Used Colors Додати використані кольори + Show Document Colors Показати кольори документа + Document Colors Кольори документа + Selection Colors Кольори виділення +@plural Used {n} time|Used {n} times Використано {n} раз|Використано {n} рази|Використано {n} разів Additional Plug-ins Folder Папка додаткових модулів Additional Fonts Folder Папка додаткових шрифтів Adjust Adjoining Width Points Налаштувати суміжні точки ширини diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 80cc4951cf..799a300b68 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -154,6 +154,10 @@ Add to Selection Thêm vào vùng chọn Add to Swatches Thêm vào mẫu màu Add Used Colors Thêm các màu đã dùng + Show Document Colors Hiện màu của tài liệu + Document Colors Màu của tài liệu + Selection Colors Màu của vùng chọn +@plural Used {n} time|Used {n} times Dùng {n} lần Additional Fonts Folder Thư mục phông bổ sung Additional Plug-ins Folder Thư mục plug-in bổ sung Adjust Adjoining Width Points Điều chỉnh các điểm chiều rộng kề nhau diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9561a51baf..ce34bdd1ec 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -88,6 +88,10 @@ Add to Selection 添加到选区 Add to Swatches 添加到色板 Add Used Colors 添加已用颜色 + Show Document Colors 显示文档颜色 + Document Colors 文档颜色 + Selection Colors 所选对象的颜色 +@plural Used {n} time|Used {n} times 使用 {n} 次 Additional Plug-ins Folder 附加增效工具文件夹 Additional Fonts Folder 附加字体文件夹 Adjust Adjoining Width Points 调整相邻宽度点 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 7489e3d4d9..c6b9974da3 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -97,6 +97,10 @@ Add to Selection 加入選取範圍 Add to Swatches 新增至色票 Add Used Colors 新增使用中的顏色 + Show Document Colors 顯示文件顏色 + Document Colors 文件顏色 + Selection Colors 所選物件的顏色 +@plural Used {n} time|Used {n} times 使用 {n} 次 Additional Plug-ins Folder 額外的增效模組資料夾 Additional Fonts Folder 額外的字體資料夾 Adjust Adjoining Width Points 調整相鄰寬度點 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d36ecae60f..9b7a742d02 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1325,7 +1325,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, all three are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, documentColors}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index d12c89d2af..003b353f4c 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -698,6 +698,8 @@ mod tests_color_wheel; #[cfg(test)] mod tests_color_wheel_box; #[cfg(test)] +mod tests_color_wheel_document_colors; +#[cfg(test)] mod tests_constrain; #[cfg(test)] mod tests_css_properties; diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 31522578e5..8e4beda794 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -11,8 +11,16 @@ //! channel strip at its right, for the channel picked under Box Channel (Hue, Saturation, //! Brightness, Red, Green or Blue). The field shows the other two components on the Color //! Picker's axes. The view and the channel are kept with the preferences (`ui.colorWheel`). +//! +//! The panel menu's Show Document Colors adds a row under the wheel or the box with the colors +//! of the selection, or with nothing selected of the art Select All takes, most used first +//! (`color.used`). A click on one applies it as a pick does. The active proxy and a selected +//! gradient stop keep its swatch link; a freeform point takes the color alone. -use egui::{Ui, UiBuilder, vec2}; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use egui::{Rect, Sense, Ui, UiBuilder, vec2}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Cms}; @@ -23,6 +31,7 @@ use super::color::{Target, apply, wheel_target}; use super::{pstate, set_pstate}; use crate::VectorcraftApp; use crate::dialogs::color_picker::Channel; +use crate::theme::Tokens; use crate::widgets::{self, FieldAxis, Live, SliderValue, menu_item}; pub const ID: &str = "colorWheel"; @@ -67,6 +76,13 @@ pub struct Settings { pub view: View, #[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")] pub channel: Channel, + /// Show Document Colors: the row of the colors the art uses, under the wheel or the box. + #[serde(deserialize_with = "deserialize_flag")] + pub document_colors: bool, +} + +fn deserialize_flag<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(::deserialize(d)?.as_bool().unwrap_or_default()) } fn deserialize_view<'de, D: serde::Deserializer<'de>>(d: D) -> Result { @@ -90,11 +106,12 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { - const KEYS: [&str; 2] = ["view", "channel"]; + const KEYS: [&str; 3] = ["view", "channel", "documentColors"]; match p { Value::Null => {} Value::Object(o) => { @@ -113,6 +130,9 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result {} Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?, } + if let Some(on) = crate::menus::opt_bool(p, "documentColors")? { + set.document_colors = on; + } app.ui.color_wheel = set; Ok(json!(app.ui.color_wheel)) } @@ -134,6 +154,151 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); }); + ui.separator(); + if menu_item(ui, tl!("Show Document Colors"), true, set.document_colors) { + command(app, &json!({ "documentColors": !set.document_colors })).ok(); + } +} + +/// Panel state: the Show Document Colors row's colors, with the [`UsedKey`] they were read for. +const USED: &str = "color-wheel-used"; +/// The most chips the row asks `color.used` for. +const MAX_CHIPS: usize = 128; +/// Above this many color uses, an edit makes the row read the colors again at most once every +/// [`LARGE_EVERY`] seconds; a change of document or selection still reads them at once. +const LARGE_USES: u64 = 5_000; +const LARGE_EVERY: f64 = 0.5; + +/// What the Show Document Colors row depends on: the document, its revision, and the number of +/// selected objects with a hash of their ids. +type UsedKey = Option<(u64, u64, usize, u64)>; + +/// The row's colors as last read, kept in the panel state behind an `Arc`, so a frame that reads +/// them back copies no list. +#[derive(Debug, PartialEq)] +struct UsedCache { + key: UsedKey, + /// The frame time the colors were read at. + at: f64, + /// The uses of every color (`color.used`'s `uses`). + uses: u64, + /// Whether the colors are the selection's. + selected: bool, + colors: Vec, +} + +/// A color of the row: the color, its hex value, how many times the art uses it, and the global +/// swatch it is linked to with the tint (0..1) of that swatch it is. +#[derive(Clone, Debug, PartialEq)] +struct Used { + color: Color, + hex: String, + count: u64, + link: Option<(String, f32)>, +} + +impl Used { + /// The paint the color applies and drags: linked to its swatch at its tint when it has one. + fn paint(&self) -> Paint { + match &self.link { + Some((name, tint)) => Paint::Solid { color: self.color, swatch: Some(name.clone()), tint: *tint }, + None => Paint::solid(self.color), + } + } +} + +/// The colors the row shows and whether they are the selection's, read with `color.used` once per +/// document revision and selection and kept as they are while an interaction is in progress (a +/// preview raises the revision on every frame of a drag). In art with more than [`LARGE_USES`] +/// color uses, an edit reads them again only after [`LARGE_EVERY`] seconds. +fn used_colors(app: &mut VectorcraftApp, ui: &Ui) -> Arc { + let key: UsedKey = app.session.active().map(|d| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + d.selection.objects.hash(&mut h); + (d.uid, d.revision, d.selection.objects.len(), h.finish()) + }); + let now = ui.input(|i| i.time); + if let Some(cache) = pstate::>>(ui.ctx(), USED) { + if cache.key == key || app.session.in_interaction() { + return cache; + } + let scope = |k: &UsedKey| k.map(|(doc, _, n, h)| (doc, n, h)); + let wait = LARGE_EVERY - (now - cache.at); + if cache.uses > LARGE_USES && scope(&cache.key) == scope(&key) && wait > 0.0 { + ui.ctx().request_repaint_after_secs(wait as f32); + return cache; + } + } + let r = key.as_ref().and_then(|_| app.session.execute("color.used", &json!({ "limit": MAX_CHIPS })).ok()); + let colors: Vec = r + .as_ref() + .and_then(|r| r["colors"].as_array()) + .map(|a| { + a.iter() + .filter_map(|c| { + let color = serde_json::from_value::(c["color"].clone()).ok()?; + let hex = c["hex"].as_str().map_or_else(|| color.to_hex(), str::to_string); + let link = c["swatch"].as_str().zip(c["tint"].as_f64()).map(|(n, t)| (n.to_string(), (t / 100.0).clamp(0.0, 1.0) as f32)); + Some(Used { color, hex, count: c["count"].as_u64().unwrap_or(0), link }) + }) + .collect() + }) + .unwrap_or_default(); + let selected = r.as_ref().is_some_and(|r| r["selection"] == true); + let uses = r.as_ref().and_then(|r| r["uses"].as_u64()).unwrap_or(0); + let cache = Arc::new(UsedCache { key, at: now, uses, selected, colors }); + set_pstate(ui.ctx(), USED, Some(Arc::clone(&cache))); + cache +} + +/// The Show Document Colors row: a heading (Selection Colors or Document Colors) and the colors, +/// most used first, as many as fit in one row. Returns the color clicked. +fn document_colors_row(app: &mut VectorcraftApp, ui: &mut Ui) -> Option { + let cache = used_colors(app, ui); + widgets::subheader(ui, if cache.selected { tl!("Selection Colors") } else { tl!("Document Colors") }); + let t = Tokens::get(ui.ctx()); + let width = ui.available_width(); + // Chips are 16 px on a 19 px pitch, inset 3 px, with 2 px kept clear of the right edge, as + // in the Recent Colors row. + let per_row = (((width - 21.0) / 19.0).floor().max(0.0) as usize + 1).max(1); + let (r, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover()); + ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); + let mut chosen = None; + for (i, u) in cache.colors.iter().take(per_row).enumerate() { + let cell = Rect::from_min_size(r.min + vec2(3.0 + i as f32 * 19.0, 3.0), vec2(16.0, 16.0)); + let resp = ui.interact(cell, ui.scope_id().with(("document-color", i)), Sense::click_and_drag()); + let paint = u.paint(); + widgets::drag_source(ui, &resp, || widgets::PanelDrag::paint(paint.clone())); + widgets::swatch_tile(ui, cell, &paint, false, resp.hovered()); + let tip = format!("{}\n{}", u.hex, crate::i18n::tn(u.count, "Used {n} time", "Used {n} times")); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &tip)); + if resp.on_hover_text(&tip).clicked() { + chosen = Some(u.clone()); + } + } + chosen +} + +/// Apply a color of the Show Document Colors row as a pick does, to the inactive proxy when +/// `behind`. A color linked to a swatch stays linked at its tint, except at a freeform gradient's +/// point, which takes the color alone. +fn apply_used(app: &mut VectorcraftApp, tgt: &Target, u: &Used, behind: bool) { + let Some((name, tint)) = &u.link else { return apply(app, tgt, u.color, Live::Released, behind) }; + match tgt { + Target::Stop { paint: Paint::Gradient(g), index, .. } if !behind => { + let mut stops = g.gradient.stops.clone(); + if let Some(s) = stops.get_mut(*index) { + s.set_color(u.color, Some((name.clone(), *tint))); + } + super::gradient::set_stops(app, &stops, None, Live::Released); + } + Target::Point { .. } if !behind => apply(app, tgt, u.color, Live::Released, behind), + _ => { + let mut p = super::paint_params(&u.paint()); + p["focus"] = json!(!behind); + super::live_run(app, "Color", super::proxy_cmd(app, behind), p, Live::Released); + } + } } /// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness, @@ -344,8 +509,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { pick = Some(([hsb[0], x, 1.0 - y], field_phase)); } }); - let Some((hsb, phase)) = pick else { return }; let behind = super::alt_held(ui); + if app.ui.color_wheel.document_colors + && let Some(u) = document_colors_row(app, ui) + { + apply_used(app, &tgt, &u, behind); + return; + } + let Some((hsb, phase)) = pick else { return }; let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index d3866fd5d9..8eb0c87bc3 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -167,16 +167,16 @@ fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() { #[test] fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue"})); - assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue"})); - assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green"})); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue", "documentColors": false})); + assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue", "documentColors": false})); + assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green", "documentColors": false})); let e = app.run("ui.colorWheel", json!({"view": "triangle"})).unwrap_err(); assert_eq!(e, "`view` must be wheel or box"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "channel": 7})).unwrap_err(); assert_eq!(e, "`channel` must be hue, saturation, brightness, red, green or blue"); - assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green }, "an error changes nothing"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green, ..Default::default() }, "an error changes nothing"); let ui = crate::control::inspect(&app, &egui::Context::default()); - assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green"})); + assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green", "documentColors": false})); } /// The command's errors are translated in the catalogs that translate status and error messages, @@ -211,10 +211,10 @@ fn ui_color_wheel_rejects_other_params() { let e = app.run("ui.colorWheel", json!([1])).unwrap_err(); assert_eq!(e, "the params must be an object, not [1]"); let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err(); - assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel"); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, documentColors"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); - assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel"); - assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red }, "an error changes nothing"); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, documentColors"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } /// With None there is no color to edit: the strip reads 0 to screen readers, as the hue ring does, @@ -249,7 +249,11 @@ fn ui_color_wheel_answers_junk_params_without_a_panic() { /// not know reads as the key's default without losing the other preferences. #[test] fn the_settings_are_kept_and_read_leniently() { - let ui = crate::UiState { color_wheel: Settings { view: View::Box, channel: Channel::Blue }, color_rgb_percent: true, ..Default::default() }; + let ui = crate::UiState { + color_wheel: Settings { view: View::Box, channel: Channel::Blue, ..Default::default() }, + color_rgb_percent: true, + ..Default::default() + }; let saved = serde_json::to_value(&ui).unwrap(); let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); assert_eq!(back.color_wheel, ui.color_wheel); @@ -262,11 +266,11 @@ fn the_settings_are_kept_and_read_leniently() { let mut odd = saved.clone(); odd["color_wheel"] = json!({"view": "box", "channel": 7}); let back: crate::UiState = serde_json::from_value(odd).unwrap(); - assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default() }); + assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default(), ..Default::default() }); let mut odd = saved.clone(); odd["color_wheel"] = json!({"view": "triangle", "channel": "blue"}); let back: crate::UiState = serde_json::from_value(odd).unwrap(); - assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue }); + assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue, ..Default::default() }); let mut odd = saved; odd["color_wheel"] = json!("box"); let back: crate::UiState = serde_json::from_value(odd).unwrap(); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs new file mode 100644 index 0000000000..a53e4e44db --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs @@ -0,0 +1,323 @@ +//! The Color Wheel panel's Show Document Colors row drawn headless: its colors and their order, +//! the heading that follows the selection, the colors that fit in one row, a click and an Alt+click +//! on a color, swatch links, gradient stops, the colors kept during a drag, the panel menu, +//! `ui.colorWheel {documentColors}` and the saved setting. + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_engine::Session; + +use super::color_wheel::show; +use crate::VectorcraftApp; + +/// A rectangle filled with `fill` (any paint `paint.setFill` takes), without a stroke, which +/// becomes the selection. → its id. +fn rect(app: &mut VectorcraftApp, x: f64, fill: Value) -> Value { + let id = app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 30})).unwrap()["id"].clone(); + app.run("paint.setFill", fill).unwrap(); + app.run("paint.setStroke", json!({"none": true, "focus": false})).unwrap(); + id +} + +/// A document with three red rectangles and one blue one (selected), with Show Document Colors on. +/// → the app, the ids of the red rectangles and the id of the blue one. +fn app() -> (VectorcraftApp, Vec, Value) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let reds = (0..3).map(|i| rect(&mut app, 10.0 + 40.0 * i as f64, json!({"color": "#ff0000"}))).collect(); + let blue = rect(&mut app, 130.0, json!({"color": "#0000ff"})); + app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + (app, reds, blue) +} + +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(2); + h +} + +fn label(hex: &str, n: u64) -> String { + format!("{hex}\n{}", if n == 1 { "Used 1 time".to_string() } else { format!("Used {n} times") }) +} + +fn has(h: &Harness<'static, VectorcraftApp>, label: &str) -> bool { + h.query_by_label(label).is_some() +} + +fn press(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, pressed: bool, modifiers: Modifiers) { + h.event(Event::ModifiersChanged(modifiers)); + h.event(Event::PointerMoved(pos)); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers }); + h.run_steps(1); +} + +fn click(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, modifiers: Modifiers) { + press(h, pos, true, modifiers); + press(h, pos, false, modifiers); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(1); +} + +/// The hex value of the one color object `id` uses (its fill: it has no stroke). +fn fill_of(app: &mut VectorcraftApp, id: &Value) -> String { + let r = app.session.execute("recolor.colors", &json!({"ids": [id]})).unwrap(); + assert_eq!(r["colors"].as_array().map(Vec::len), Some(1), "{r}"); + r["colors"][0]["hex"].as_str().unwrap().to_string() +} + +/// With nothing selected, the row is headed Document Colors and lists the art's colors, the red +/// that three rectangles use before the blue that one uses. +#[test] +fn show_document_colors_lists_the_art_colors_most_used_first() { + let (mut app, _, _) = app(); + app.run("select.none", json!({})).unwrap(); + let h = harness(app); + assert!(has(&h, "Document Colors")); + let red = h.get_by_label(&label("#ff0000", 3)).rect(); + let blue = h.get_by_label(&label("#0000ff", 1)).rect(); + assert!(red.left() < blue.left(), "red {red:?} comes before blue {blue:?}"); +} + +/// With something selected the row is headed Selection Colors and lists the selection's colors. +#[test] +fn the_heading_and_the_colors_follow_the_selection() { + let (app, _, _) = app(); + let mut h = harness(app); + assert!(has(&h, "Selection Colors")); + assert!(has(&h, &label("#0000ff", 1))); + assert!(!has(&h, &label("#ff0000", 3))); + h.state_mut().run("select.none", json!({})).unwrap(); + h.run_steps(2); + assert!(has(&h, "Document Colors") && !has(&h, "Selection Colors")); + assert!(has(&h, &label("#ff0000", 3))); +} + +/// The row shows the most used colors that fit in one row and leaves out the rest. +#[test] +fn the_row_shows_only_the_colors_that_fit() { + let (mut app, _, _) = app(); + for i in 0..30 { + rect(&mut app, 170.0 + i as f64, json!({"color": format!("#00{:02x}00", 40 + 6 * i)})); + } + app.run("select.none", json!({})).unwrap(); + let h = harness(app); + let red = h.get_by_label(&label("#ff0000", 3)).rect(); + let shown: Vec<_> = (0..30).filter_map(|i| h.query_by_label(&label(&format!("#00{:02x}00", 40 + 6 * i), 1)).map(|n| n.rect())).collect(); + assert!(!shown.is_empty() && shown.len() < 30, "{} of the 30 greens show", shown.len()); + assert!(shown.iter().all(|r| (r.top() - red.top()).abs() < 0.5 && r.right() <= 260.0), "one row inside the panel: {shown:?}"); +} + +/// A click on a color fills the selection with it, as one undo step. +#[test] +fn a_click_on_a_color_sets_the_fill() { + let (mut app, reds, blue) = app(); + app.run("select.set", json!({"ids": [reds[0], blue]})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + let mut h = harness(app); + let at = h.get_by_label(&label("#0000ff", 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let app = h.state_mut(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(fill_of(app, &reds[0]), "#0000ff"); + assert_eq!(fill_of(app, &blue), "#0000ff"); + assert_eq!(fill_of(app, &reds[1]), "#ff0000"); +} + +/// Alt+click applies the color to the inactive proxy (the stroke) and leaves the fill in front. +#[test] +fn alt_click_on_a_color_sets_the_stroke() { + let (mut app, reds, blue) = app(); + app.run("select.set", json!({"ids": [reds[0], blue]})).unwrap(); + let mut h = harness(app); + let at = h.get_by_label(&label("#ff0000", 1)).rect().center(); + click(&mut h, at, Modifiers::ALT); + let app = h.state_mut(); + assert!(app.session.fill_active, "the fill stays in front"); + let st = app.session.doc().unwrap(); + let paints = |id: &Value| { + let n = st.doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap(); + (n.appearance.fill_paint().color().map(|c| c.to_hex()), n.appearance.stroke_paint().color().map(|c| c.to_hex())) + }; + assert_eq!(paints(&blue), (Some("#0000ff".into()), Some("#ff0000".into()))); +} + +/// A color linked to a spot swatch stays linked at its tint when a click applies it. +#[test] +fn a_click_keeps_a_swatch_link_and_its_tint() { + let (mut app, _, blue) = app(); + app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap(); + let ink = rect(&mut app, 170.0, json!({"swatch": "Ink", "tint": 40})); + app.run("select.set", json!({"ids": [ink, blue]})).unwrap(); + let hex = app.session.execute("color.used", &json!({})).unwrap()["colors"] + .as_array() + .unwrap() + .iter() + .find(|c| c["swatch"] == "Ink") + .expect("the tint is listed")["hex"] + .as_str() + .unwrap() + .to_string(); + let mut h = harness(app); + let at = h.get_by_label(&label(&hex, 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let st = h.state().session.doc().unwrap(); + let fill = st.doc.node(vectorcraft_doc::NodeId(blue.as_u64().unwrap())).unwrap().appearance.fill_paint().clone(); + let Paint::Solid { swatch, tint, .. } = fill else { panic!("a solid fill, not {fill:?}") }; + assert_eq!(swatch.as_deref(), Some("Ink")); + assert!((tint - 0.4).abs() < 1e-3, "tint {tint}"); +} + +/// A click recolors the selected gradient stop, linking it to a color's swatch. +#[test] +fn a_click_recolors_the_selected_gradient_stop() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap(); + let stops = json!([{"offset": 0, "color": "#000000", "swatch": "Ink"}, {"offset": 1, "color": "#0000ff"}]); + rect(&mut app, 10.0, json!({"gradient": {"stops": stops, "start": [10, 25], "end": [40, 25]}})); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + let hex = app.session.execute("color.used", &json!({})).unwrap()["colors"] + .as_array() + .unwrap() + .iter() + .find(|c| c["swatch"] == "Ink") + .expect("the stop's color is listed")["hex"] + .as_str() + .unwrap() + .to_string(); + let mut h = harness(app); + let at = h.get_by_label(&label(&hex, 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[1]; + assert_eq!((stop.color.to_hex(), stop.swatch.as_deref()), (hex, Some("Ink"))); +} + +/// While a drag on the wheel recolors the selection, the row keeps the colors from before the +/// drag; once it ends, it lists the new color. +#[test] +fn a_drag_on_the_wheel_does_not_read_the_colors_again_until_it_ends() { + let (app, _, blue) = app(); + let revision = app.session.active().unwrap().revision; + let mut h = harness(app); + let ring = h.get_by_label("Hue ring").rect(); + // The left of the ring (cyan), then its bottom, in the middle of the band. + let r = ring.width() / 2.0 - 11.0; + let (a, b) = (ring.center() - vec2(r, 0.0), ring.center() + vec2(0.0, r)); + press(&mut h, a, true, Modifiers::NONE); + for p in [a, b, b] { + h.event(Event::PointerMoved(p)); + h.run_steps(1); + } + assert!(h.state().session.in_interaction(), "the drag is in progress"); + assert_ne!(h.state().session.active().unwrap().revision, revision, "the drag changed the document"); + assert!(has(&h, &label("#0000ff", 1)), "the row keeps the colors from before the drag"); + press(&mut h, b, false, Modifiers::NONE); + h.run_steps(2); + let now = fill_of(h.state_mut(), &blue); + assert_ne!(now, "#0000ff"); + assert!(!has(&h, &label("#0000ff", 1))); + assert!(has(&h, &label(&now, 1)), "the row lists {now} after the drag"); +} + +/// In art with more than 5,000 color uses, the row reads the colors again after an edit at most +/// once every half second of frames, and a change of selection reads them at once. +#[test] +fn in_large_art_an_edit_reads_the_colors_again_after_half_a_second() { + let (mut app, reds, _) = app(); + app.run("select.set", json!({"ids": [reds[0]]})).unwrap(); + for _ in 0..11 { + app.run("select.all", json!({})).unwrap(); + app.run("edit.duplicate", json!({})).unwrap(); + } + app.run("select.none", json!({})).unwrap(); + let uses = app.session.execute("color.used", &json!({})).unwrap()["uses"].as_u64().unwrap(); + assert!(uses > 5_000, "{uses} uses"); + let reds_used = app.session.execute("color.used", &json!({})).unwrap()["colors"][0]["count"].as_u64().unwrap(); + let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).with_step_dt(0.1).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(6); + assert!(has(&h, &label("#ff0000", reds_used))); + // Half a second after the last read, an edit is read at once. + h.state_mut().run("paint.setFill", json!({"ids": [reds[0]], "color": "#00ff00"})).unwrap(); + h.run_steps(1); + assert!(has(&h, &label("#ff0000", reds_used - 1)) && has(&h, &label("#00ff00", 1)), "the first edit is read at once"); + // The next edit within half a second waits. + h.state_mut().run("paint.setFill", json!({"ids": [reds[1]], "color": "#00ff00"})).unwrap(); + h.run_steps(1); + assert!(has(&h, &label("#00ff00", 1)), "the row waits after the second edit"); + h.run_steps(5); + assert!(has(&h, &label("#ff0000", reds_used - 2)) && has(&h, &label("#00ff00", 2)), "the row reads the colors again"); + h.state_mut().run("paint.setFill", json!({"ids": [reds[2]], "color": "#00ff00"})).unwrap(); + h.state_mut().run("select.set", json!({"ids": [reds[2]]})).unwrap(); + h.run_steps(1); + assert!(has(&h, "Selection Colors") && has(&h, &label("#00ff00", 1)), "a new selection reads the colors at once"); + assert!(!has(&h, &label("#00ff00", 3))); +} + +/// Without the setting the row is not drawn, and the panel menu's Show Document Colors turns it on. +#[test] +fn the_panel_menu_turns_the_row_on_and_off() { + let off = || { + let (mut a, _, _) = app(); + a.run("ui.colorWheel", json!({"documentColors": false})).unwrap(); + a + }; + let mut h = harness(off()); + assert!(!has(&h, "Selection Colors")); + // The menu in a context of its own, as the other panel menu tests draw it. + let mut app = off(); + let ctx = egui::Context::default(); + let raw = |events| egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(240.0, 200.0))), ..Default::default() }; + let click_item = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(raw(vec![]), |ui| super::color_wheel::menu(app, ui)); + out.textures_delta.clear(); + let item = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().ends_with("Show Document Colors") => Some(t.visual_bounding_rect().center()), + _ => None, + }) + .expect("the menu shows Show Document Colors"); + let button = |pressed| Event::PointerButton { pos: item, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + ctx.run_ui(raw(vec![Event::PointerMoved(item), button(true), button(false)]), |ui| super::color_wheel::menu(app, ui)).textures_delta.clear(); + }; + click_item(&mut app); + assert!(app.ui.color_wheel.document_colors); + click_item(&mut app); + assert!(!app.ui.color_wheel.document_colors); + h.state_mut().run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + h.run_steps(2); + assert!(has(&h, "Selection Colors")); +} + +/// `ui.colorWheel {documentColors}` sets the row's setting, keeps the others, and refuses a value +/// that is not a bool, changing nothing. +#[test] +fn ui_color_wheel_sets_document_colors() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["documentColors"], json!(false)); + app.run("ui.colorWheel", json!({"view": "box"})).unwrap(); + let r = app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + assert_eq!((r["documentColors"].clone(), r["view"].clone()), (json!(true), json!("box"))); + assert_eq!(app.run("ui.colorWheel", json!({"documentColors": "no"})).unwrap_err(), "`documentColors` must be true or false"); + assert!(app.ui.color_wheel.document_colors); + assert_eq!(app.run("ui.colorWheel", json!({"documentColors": null})).unwrap()["documentColors"], json!(true)); +} + +/// The saved setting reads leniently: a value this build does not know reads as off, and the other +/// settings and preferences are kept. +#[test] +fn the_saved_setting_reads_leniently() { + let read = |v: Value| serde_json::from_value::(v).expect("the preferences read"); + let s = read(json!({"color_wheel": {"documentColors": true, "view": "box"}, "color_rgb_percent": true})); + assert!(s.color_wheel.document_colors && s.color_rgb_percent); + let s = read(json!({"color_wheel": {"documentColors": "yes", "view": "box"}, "color_rgb_percent": true})); + assert!(!s.color_wheel.document_colors && s.color_rgb_percent); + assert_eq!(s.color_wheel.view, super::color_wheel::View::Box); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bb13e0d5f5..fea192e374 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -298,6 +298,16 @@ selects its row for the sliders and a drag moves the row without changing a colo step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder, or the options button while a group is selected, opens it. +`color.used {selection?, limit?}` lists the colors of the selection, or with nothing selected the colors of the art +`select.all` takes, most used first, as `recolor.colors {}` counts them. Each entry adds `color`, the color in its own +model as the paint commands take it, and `tint`, the percent of its global `swatch` it is, to three decimals. The +swatch and tint come from the color's first linked use in paint order; a plain use goes before a gradient stop that +mixes a spot ink with process inks, and a color only such stops link has no `swatch` here. `selection: false` reads +the art `select.all` takes while something is selected, and the answer's `selection` says whether the colors are +the selection's. `limit` keeps only the most used entries, and the answer's `uses` counts the uses of every color. +The selection does not change. The Color Wheel panel's Show Document Colors row (`ui.colorWheel {documentColors: +true}`) shows these colors. + Library panel: `engine.execute {command: "window.swatchLibrary", params: {library}}` opens the read-only library panel on a swatch library (`ui.inspect` shows it as `library_panel: {kind, id}`; `library: null` closes it). Clicking a swatch there runs `swatch.library.add {library, names: [name], apply}` (the active proxy, or the other diff --git a/docs/mcp.md b/docs/mcp.md index 12c1f38184..30db1718d5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -625,6 +625,10 @@ strip at its right) in place of the wheel, as the panel menu's Box View and Box shows the wheel again. Keys left out keep their values. Params that are not an object, another key or a value off the list return an error and change nothing. The command returns `{view, channel}`, and both settings are kept with the preferences. +`ui.colorWheel {"documentColors": true}` shows the Color Wheel panel's row of the colors the selection uses, or with +nothing selected the colors of the art `select.all` takes, in the order `color.used {}` lists them. A click on a color +applies it to the active proxy, keeping its link to a global swatch. The answer includes `documentColors` +with the other settings, and the setting is kept with the preferences. In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e34f814534..959da8ed1a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1503,6 +1503,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged. + - **Color Wheel document colors (part of #978):** the Color Wheel panel menu's Show Document Colors adds a row under the wheel or the box with the colors of the selection, headed Selection Colors, or with nothing selected of the art Select All takes, headed Document Colors, most used first and as many as fit in one row (`color.used`, `ui.colorWheel {documentColors}`). A color's tooltip gives its hex value and how many times the art uses it, and a click applies it as a pick does, keeping its color model; the active proxy and a selected gradient stop also keep its link to a global swatch. Tests: `crates/engine/src/tests/recolor.rs`, `crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs`. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`. From 276d493e46dd9537bddf5b28c38c4e603e0c39f1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:00:27 -0800 Subject: [PATCH 04/69] Color Wheel: recolor.colors keeps its swatch rule, and a wide row shows every color that fits - `recolor.colors`, `recolor.reduce` and the recolor groups name the swatch of a color's first linked use again. Only `color.used` takes its swatch and tint from the first linked use that is not a gradient stop mixing a spot ink with process inks. - A row wider than 128 chips asks `color.used` for as many colors as it holds. - The new catalog rows sit with the other Color Wheel rows. - Tests cover a click on a selected freeform point, the tint a click gives a selected gradient stop, a row wider than 128 chips, and `recolor.colors` with a mixed stop painted before a plain use linked to another swatch. --- crates/engine/src/cmd/recolor.rs | 43 ++++++++------- crates/engine/src/tests/recolor.rs | 26 ++++++++++ crates/ui-egui/src/i18n/bg.tsv | 8 +-- crates/ui-egui/src/i18n/bs.tsv | 8 +-- crates/ui-egui/src/i18n/ca.tsv | 8 +-- crates/ui-egui/src/i18n/cs.tsv | 8 +-- crates/ui-egui/src/i18n/da.tsv | 8 +-- crates/ui-egui/src/i18n/de.tsv | 8 +-- crates/ui-egui/src/i18n/el.tsv | 8 +-- crates/ui-egui/src/i18n/es.tsv | 8 +-- crates/ui-egui/src/i18n/fi.tsv | 8 +-- crates/ui-egui/src/i18n/fr.tsv | 8 +-- crates/ui-egui/src/i18n/gu.tsv | 8 +-- crates/ui-egui/src/i18n/hi.tsv | 8 +-- crates/ui-egui/src/i18n/hu.tsv | 8 +-- crates/ui-egui/src/i18n/id.tsv | 8 +-- crates/ui-egui/src/i18n/it.tsv | 8 +-- crates/ui-egui/src/i18n/ja.tsv | 8 +-- crates/ui-egui/src/i18n/ka.tsv | 8 +-- crates/ui-egui/src/i18n/ko.tsv | 8 +-- crates/ui-egui/src/i18n/nl.tsv | 8 +-- crates/ui-egui/src/i18n/pl.tsv | 8 +-- crates/ui-egui/src/i18n/pt-br.tsv | 8 +-- crates/ui-egui/src/i18n/ru.tsv | 8 +-- crates/ui-egui/src/i18n/sv.tsv | 8 +-- crates/ui-egui/src/i18n/tr.tsv | 8 +-- crates/ui-egui/src/i18n/uk.tsv | 8 +-- crates/ui-egui/src/i18n/vi.tsv | 8 +-- crates/ui-egui/src/i18n/zh-hans.tsv | 8 +-- crates/ui-egui/src/i18n/zh-hant.tsv | 8 +-- crates/ui-egui/src/panels/color_wheel.rs | 25 +++++---- .../tests_color_wheel_document_colors.rs | 52 +++++++++++++++++-- 32 files changed, 226 insertions(+), 144 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 08e8c48657..c34db53f65 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -954,15 +954,14 @@ fn pick_theme(s: &mut Session, p: &Value) -> Result { Ok(json!({"colors": colors.iter().map(key_str).collect::>(), "objects": theme.objects})) } -/// A color the art uses: how often, and the global swatch it is linked to with the tint (0..1) of -/// the swatch its paint stores, when the paint gives one. +/// A color the art uses: how often, and the global swatch of its first linked use in paint order. struct Used { color: Color, count: usize, swatch: Option, - tint: Option, - /// The link comes from a gradient stop that mixes the swatch's ink with process inks. - mixed: bool, + /// The global swatch of the first linked use that is not a gradient stop mixing the swatch's + /// ink with process inks, with the tint (0..1) its paint stores when the paint gives one. + plain: Option<(String, Option)>, } /// The unique colours of the objects `ids` and the objects inside them, most used first (ties by @@ -983,19 +982,20 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> let mut count_tint = |c: &Color, link: Option<&str>, tint: Option, mixed: bool| { let k = ColorKey::of(c); let i = *index.entry(k).or_insert_with(|| { - used.push((k, Used { color: *c, count: 0, swatch: None, tint: None, mixed: false })); + used.push((k, Used { color: *c, count: 0, swatch: None, plain: None })); used.len() - 1 }); let u = &mut used[i].1; u.count += 1; - // The first linked use in paint order gives the swatch and tint; a plain linked use - // replaces one from a stop that mixes the swatch's ink with process inks. - if u.swatch.is_none() || (u.mixed && !mixed) { - let linked = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())); - if let Some(l) = linked { + if u.swatch.is_some() && (u.plain.is_some() || mixed) { + return; + } + if let Some(l) = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())) { + if u.swatch.is_none() { u.swatch = Some(l.to_string()); - u.tint = tint; - u.mixed = mixed; + } + if u.plain.is_none() && !mixed { + u.plain = Some((l.to_string(), tint)); } } }; @@ -1089,20 +1089,23 @@ fn all_art(st: &crate::DocState) -> (Vec, Option>) { } /// The `colors` list of `recolor.colors` and `color.used` for the objects `ids` (see -/// [`used_colors`]). With `with_color`, each has its color in its own model and the tint of its -/// swatch, and a gradient stop's color that mixes the swatch's ink with process inks has no swatch. +/// [`used_colors`]). Each names the swatch of its first linked use. With `with_color`, each has its +/// color in its own model, and the swatch and tint come from its first linked use that is not a +/// gradient stop mixing the swatch's ink with process inks (none when every linked use is one). fn colors_json(used: &[Used], with_color: bool) -> Vec { used.iter() .map(|u| { let mut v = json!({"key": key_str(&u.color), "hex": u.color.to_hex(), "count": u.count}); if with_color { v["color"] = json!(u.color); - } - if let Some(w) = u.swatch.as_ref().filter(|_| !(with_color && u.mixed)) { - v["swatch"] = json!(w); - if let Some(t) = u.tint.filter(|_| with_color) { - v["tint"] = json!((f64::from(t) * 100_000.0).round() / 1000.0); + if let Some((w, tint)) = &u.plain { + v["swatch"] = json!(w); + if let Some(t) = tint { + v["tint"] = json!((f64::from(*t) * 100_000.0).round() / 1000.0); + } } + } else if let Some(w) = &u.swatch { + v["swatch"] = json!(w); } v }) diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index e402956a1c..a6e8c56b1b 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -249,6 +249,32 @@ fn used_colors_take_the_swatch_of_a_plain_use_painted_after_a_mixed_stop_of_the_ assert_eq!((c["swatch"].as_str(), c["tint"].as_f64()), (Some("Ink"), Some(50.0)), "{r}"); } +#[test] +fn recolor_colors_keeps_the_swatch_of_the_first_linked_use_when_a_mixed_stop_comes_first() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let shape = rect(&mut s, json!("#000000")); + let plain = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Other", "tint": 50})); + let ink = fill(&s, plain); + // The stop below the plain fill has the same color, linked to another swatch, with process + // plates that add nothing. + let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) }; + let mut end = stop.clone(); + end.offset = 1.0; + let g = Gradient::new(GradientKind::Linear, vec![stop, end]); + let st = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g)))); + run(&mut s, "select.set", json!({"ids": []})); + let three = |r: &Value| r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap(); + let used = run(&mut s, "color.used", json!({})); + assert_eq!(three(&used)["swatch"], "Other", "{used}"); + let listed = run(&mut s, "recolor.colors", json!({})); + assert_eq!(three(&listed)["swatch"], "Ink", "recolor.colors names the first linked use: {listed}"); +} + #[test] fn colors_with_nothing_selected_leave_out_hidden_and_locked_objects_in_groups() { let mut s = session(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index df1edd2590..81dda92a97 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -124,10 +124,6 @@ Add to Selection Добавяне към селекцията Add to Swatches Добавяне към образци Add Used Colors Добавяне на използваните цветове - Show Document Colors Показване на цветовете на документа - Document Colors Цветове на документа - Selection Colors Цветове на селекцията -@plural Used {n} time|Used {n} times Използван {n} път|Използван {n} пъти Additional Plug-ins Folder Допълнителна папка за плъгини Additional Fonts Folder Допълнителна папка за шрифтове Adjust Adjoining Width Points Регулиране на прилежащите точки за ширина @@ -566,6 +562,10 @@ font-technology Variable Променливи Box Channel Канал на квадрата Color box Цветови квадрат Color Wheel Options Опции на цветното колело + Show Document Colors Показване на цветовете на документа + Document Colors Цветове на документа + Selection Colors Цветове на селекцията +@plural Used {n} time|Used {n} times Използван {n} път|Използван {n} пъти Color Type: Цветен тип: Color: Цвят: Colorize Оцветяване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f82871372a..52340f1666 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -740,6 +740,10 @@ Box Channel Kanal kvadrata Color box Kvadrat boje Color Wheel Options Opcije kotača boja + Show Document Colors Prikaži boje dokumenta + Document Colors Boje dokumenta + Selection Colors Boje odabira +@plural Used {n} time|Used {n} times Korišteno {n} put|Korišteno {n} puta|Korišteno {n} puta CSS Properties CSS svojstva Document Info Informacije o dokumentu Flattener Preview Pregled spljoštavanja @@ -3996,10 +4000,6 @@ theme Appearance Izgled Add to Graphic Styles Dodaj u grafičke stilove Graphic Style Library Biblioteka grafičkih stilova Add Used Colors Dodaj korištene boje - Show Document Colors Prikaži boje dokumenta - Document Colors Boje dokumenta - Selection Colors Boje odabira -@plural Used {n} time|Used {n} times Korišteno {n} put|Korišteno {n} puta|Korišteno {n} puta Delete Swatch Izbriši uzorak boje Duplicate Swatch Dupliciraj uzorak boje Merge Swatches Spoji uzorke boja diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 29e1ee4c7b..c8f17a68d1 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -220,10 +220,6 @@ Add to Symbols Afegeix als símbols Add to the Current Shortcuts Afegeix a les dreceres actuals Add Used Colors Afegeix els colors utilitzats - Show Document Colors Mostra els colors del document - Document Colors Colors del document - Selection Colors Colors de la selecció -@plural Used {n} time|Used {n} times Utilitzat {n} vegada|Utilitzat {n} vegades Additional Fonts Folder Carpeta addicional de tipus de lletra Additional Plug-ins Folder Carpeta addicional de complements Adjust Adjoining Width Points Ajusta els punts d’amplada contigus @@ -828,6 +824,10 @@ antiAlias Sharp Nítid Box Channel Canal del quadre Color box Quadre de color Color Wheel Options Opcions de la roda de colors + Show Document Colors Mostra els colors del document + Document Colors Colors del document + Selection Colors Colors de la selecció +@plural Used {n} time|Used {n} times Utilitzat {n} vegada|Utilitzat {n} vegades Color Type: Tipus de color: Color wheel Roda de color Color: Color: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 022f7a27c6..4eb1280dd2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -753,6 +753,10 @@ Box Channel Kanál čtverce Color box Barevný čtverec Color Wheel Options Možnosti barevného kola + Show Document Colors Zobrazit barvy dokumentu + Document Colors Barvy dokumentu + Selection Colors Barvy výběru +@plural Used {n} time|Used {n} times Použito {n}krát|Použito {n}krát|Použito {n}krát CSS Properties Vlastnosti CSS Document Info Informace o dokumentu Flattener Preview Náhled sloučení @@ -4052,10 +4056,6 @@ theme Appearance Motiv Add to Graphic Styles Přidat do grafických stylů Graphic Style Library Knihovna grafických stylů Add Used Colors Přidat použité barvy - Show Document Colors Zobrazit barvy dokumentu - Document Colors Barvy dokumentu - Selection Colors Barvy výběru -@plural Used {n} time|Used {n} times Použito {n}krát|Použito {n}krát|Použito {n}krát Delete Swatch Odstranit položku vzorníku Duplicate Swatch Duplikovat položku vzorníku Merge Swatches Sloučit položky vzorníku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 867e270455..db8c15cdd0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -698,6 +698,10 @@ Box Channel Kvadratets kanal Color box Farvekvadrat Color Wheel Options Indstillinger for farvehjul + Show Document Colors Vis dokumentfarver + Document Colors Dokumentfarver + Selection Colors Markeringens farver +@plural Used {n} time|Used {n} times Brugt {n} gang|Brugt {n} gange CSS Properties CSS-egenskaber Document Info Dokumentoplysninger Flattener Preview Udjævningsforhåndsvisning @@ -3769,10 +3773,6 @@ theme Appearance Udseende Add to Graphic Styles Føj til grafikstile Graphic Style Library Grafikstilbibliotek Add Used Colors Tilføj anvendte farver - Show Document Colors Vis dokumentfarver - Document Colors Dokumentfarver - Selection Colors Markeringens farver -@plural Used {n} time|Used {n} times Brugt {n} gang|Brugt {n} gange Delete Swatch Slet farveprøve Duplicate Swatch Duplikér farveprøve Merge Swatches Flet farveprøver diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1dea2713e5..fcf358a45e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -113,10 +113,6 @@ Add to Selection Zur Auswahl hinzufügen Add to Swatches Zu Farbfeldern hinzufügen Add Used Colors Verwendete Farben hinzufügen - Show Document Colors Dokumentfarben einblenden - Document Colors Dokumentfarben - Selection Colors Farben der Auswahl -@plural Used {n} time|Used {n} times {n}-mal verwendet|{n}-mal verwendet Additional Plug-ins Folder Zusätzlicher Plug-in-Ordner Additional Fonts Folder Zusätzlicher Schriftenordner Adjust Adjoining Width Points Angrenzende Breitenpunkte anpassen @@ -559,6 +555,10 @@ font-technology Variable Variabel Box Channel Kanal des Quadrats Color box Farbquadrat Color Wheel Options Optionen für den Farbkreis + Show Document Colors Dokumentfarben einblenden + Document Colors Dokumentfarben + Selection Colors Farben der Auswahl +@plural Used {n} time|Used {n} times {n}-mal verwendet|{n}-mal verwendet Color Type: Farbart: Color: Farbe: Colorize Einfärben diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4586bc55d5..49699ea928 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -118,10 +118,6 @@ Add to Selection Προσθήκη στην επιλογή Add to Swatches Προσθήκη στα δείγματα χρωμάτων Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων - Show Document Colors Εμφάνιση χρωμάτων εγγράφου - Document Colors Χρώματα εγγράφου - Selection Colors Χρώματα επιλογής -@plural Used {n} time|Used {n} times Χρησιμοποιείται {n} φορά|Χρησιμοποιείται {n} φορές Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών Adjust Adjoining Width Points Ρύθμιση γειτονικών σημείων πλάτους @@ -541,6 +537,10 @@ font-technology Variable Μεταβλητές Box Channel Κανάλι τετραγώνου Color box Τετράγωνο χρώματος Color Wheel Options Επιλογές χρωματικού τροχού + Show Document Colors Εμφάνιση χρωμάτων εγγράφου + Document Colors Χρώματα εγγράφου + Selection Colors Χρώματα επιλογής +@plural Used {n} time|Used {n} times Χρησιμοποιείται {n} φορά|Χρησιμοποιείται {n} φορές Color Type: Τύπος χρώματος: Color: Χρώμα: Colorize Χρωματισμός diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 71303625d0..5ae96f6c14 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -138,10 +138,6 @@ Add to Selection Agregar a la selección Add to Swatches Agregar a muestras Add Used Colors Agregar colores usados - Show Document Colors Mostrar colores del documento - Document Colors Colores del documento - Selection Colors Colores de la selección -@plural Used {n} time|Used {n} times Usado {n} vez|Usado {n} veces Additional Plug-ins Folder Carpeta de plugins adicionales Additional Fonts Folder Carpeta de fuentes adicionales Adjust Adjoining Width Points Ajustar puntos de anchura contiguos @@ -581,6 +577,10 @@ font-technology Variable Variables Box Channel Canal del cuadro Color box Cuadro de color Color Wheel Options Opciones de la rueda de color + Show Document Colors Mostrar colores del documento + Document Colors Colores del documento + Selection Colors Colores de la selección +@plural Used {n} time|Used {n} times Usado {n} vez|Usado {n} veces Color Type: Tipo de color: Color: Color: Colorize Colorear diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 73be8592dc..07a4666928 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -744,6 +744,10 @@ Box Channel Ruudun kanava Color box Väriruutu Color Wheel Options Väriympyrän asetukset + Show Document Colors Näytä asiakirjan värit + Document Colors Asiakirjan värit + Selection Colors Valinnan värit +@plural Used {n} time|Used {n} times Käytetty {n} kerran|Käytetty {n} kertaa CSS Properties CSS-ominaisuudet Document Info Asiakirjan tiedot Flattener Preview Litistyksen esikatselu @@ -3976,10 +3980,6 @@ theme Appearance Ulkoasu Add to Graphic Styles Lisää grafiikkatyyleihin Graphic Style Library Grafiikkatyylikirjasto Add Used Colors Lisää käytetyt värit - Show Document Colors Näytä asiakirjan värit - Document Colors Asiakirjan värit - Selection Colors Valinnan värit -@plural Used {n} time|Used {n} times Käytetty {n} kerran|Käytetty {n} kertaa Delete Swatch Poista värimalli Duplicate Swatch Monista värimalli Merge Swatches Yhdistä värimallit diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b820a18e31..85852964cd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -139,10 +139,6 @@ Add to Selection Ajouter à la sélection Add to Swatches Ajouter au nuancier Add Used Colors Ajouter les couleurs utilisées - Show Document Colors Afficher les couleurs du document - Document Colors Couleurs du document - Selection Colors Couleurs de la sélection -@plural Used {n} time|Used {n} times Utilisée {n} fois|Utilisée {n} fois Additional Plug-ins Folder Dossier de modules externes supplémentaires Additional Fonts Folder Dossier de polices supplémentaires Adjust Adjoining Width Points Ajuster les points de largeur adjacents @@ -582,6 +578,10 @@ font-technology Variable Variables Box Channel Couche du carré Color box Carré de couleur Color Wheel Options Options de la roue chromatique + Show Document Colors Afficher les couleurs du document + Document Colors Couleurs du document + Selection Colors Couleurs de la sélection +@plural Used {n} time|Used {n} times Utilisée {n} fois|Utilisée {n} fois Color Type: Type de couleur : Color: Couleur : Colorize Coloriser diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 082c6ed11b..39f95397b6 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -148,10 +148,6 @@ Add Selected Artwork as One Asset પસંદ કરેલી આર્ટવર્ક એક સંપત્તિ તરીકે ઉમેરો Add Spine Point સ્પાઇન બિંદુ ઉમેરો Add Used Colors વપરાયેલા રંગ ઉમેરો - Show Document Colors દસ્તાવેજના રંગો બતાવો - Document Colors દસ્તાવેજના રંગો - Selection Colors પસંદગીના રંગો -@plural Used {n} time|Used {n} times {n} વાર વપરાયો|{n} વાર વપરાયો Add as Effect ઇફેક્ટ તરીકે ઉમેરો Add space to fit ફિટ કરવા જગ્યા ઉમેરો Add to Brushes બ્રશમાં ઉમેરો @@ -4233,6 +4229,10 @@ Box Channel બૉક્સ ચેનલ Color box રંગ બૉક્સ Color Wheel Options રંગ વ્હીલ વિકલ્પો + Show Document Colors દસ્તાવેજના રંગો બતાવો + Document Colors દસ્તાવેજના રંગો + Selection Colors પસંદગીના રંગો +@plural Used {n} time|Used {n} times {n} વાર વપરાયો|{n} વાર વપરાયો {name} (spot) {name} (સ્પૉટ) {pages} in all, {count} per copy કુલ {pages}, પ્રતિ નકલ {count} {page} of {count} {count} માંથી {page} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 85875a3ec7..fae6c7b982 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -254,10 +254,6 @@ Add to Symbols सिंबल्स में जोड़ें Add to the Current Shortcuts वर्तमान शॉर्टकट में जोड़ें Add Used Colors उपयोग किए रंग जोड़ें - Show Document Colors डॉक्यूमेंट के रंग दिखाएँ - Document Colors डॉक्यूमेंट के रंग - Selection Colors चयन के रंग -@plural Used {n} time|Used {n} times {n} बार उपयोग किया गया|{n} बार उपयोग किया गया Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें @@ -952,6 +948,10 @@ antiAlias Sharp शार्प Box Channel बॉक्स चैनल Color box कलर बॉक्स Color Wheel Options कलर व्हील ऑप्शन्स + Show Document Colors डॉक्यूमेंट के रंग दिखाएँ + Document Colors डॉक्यूमेंट के रंग + Selection Colors चयन के रंग +@plural Used {n} time|Used {n} times {n} बार उपयोग किया गया|{n} बार उपयोग किया गया Color Type: रंग का प्रकार: Color wheel कलर व्हील Color: रंग: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c43b3aaaf9..c44edf9ae9 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -208,10 +208,6 @@ Add to Selection Hozzáadás a kijelöléshez Add to Swatches Hozzáadás a színmintákhoz Add Used Colors Használt színek hozzáadása - Show Document Colors Dokumentumszínek megjelenítése - Document Colors Dokumentumszínek - Selection Colors A kijelölés színei -@plural Used {n} time|Used {n} times {n} alkalommal használva Additional Fonts Folder További betűtípusok mappája Additional Plug-ins Folder További bővítmények mappája Adjust Adjoining Width Points Szomszédos szélességi pontok igazítása @@ -757,6 +753,10 @@ font-technology Variable Változó Box Channel Négyzet csatornája Color box Színnégyzet Color Wheel Options Színkör beállításai + Show Document Colors Dokumentumszínek megjelenítése + Document Colors Dokumentumszínek + Selection Colors A kijelölés színei +@plural Used {n} time|Used {n} times {n} alkalommal használva Color Type: Színtípus: Color: Szín: Colorization Színezés diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 5925757556..dea35cf846 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -698,6 +698,10 @@ Box Channel Saluran kotak Color box Kotak warna Color Wheel Options Opsi roda warna + Show Document Colors Tampilkan warna dokumen + Document Colors Warna dokumen + Selection Colors Warna pilihan +@plural Used {n} time|Used {n} times Dipakai {n} kali CSS Properties Properti CSS Document Info Info dokumen Flattener Preview Pratinjau perata @@ -3769,10 +3773,6 @@ theme Appearance Tampilan Add to Graphic Styles Tambahkan ke gaya grafis Graphic Style Library Pustaka gaya grafis Add Used Colors Tambahkan warna yang digunakan - Show Document Colors Tampilkan warna dokumen - Document Colors Warna dokumen - Selection Colors Warna pilihan -@plural Used {n} time|Used {n} times Dipakai {n} kali Delete Swatch Hapus sampel Duplicate Swatch Duplikatkan sampel Merge Swatches Gabungkan sampel diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 308ca4f98a..1c01da1945 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -138,10 +138,6 @@ Add to Selection Aggiungi alla selezione Add to Swatches Aggiungi ai campioni Add Used Colors Aggiungi colori usati - Show Document Colors Mostra colori del documento - Document Colors Colori del documento - Selection Colors Colori della selezione -@plural Used {n} time|Used {n} times Usato {n} volta|Usato {n} volte Additional Plug-ins Folder Cartella plug-in aggiuntivi Additional Fonts Folder Cartella font aggiuntivi Adjust Adjoining Width Points Regola punti di larghezza adiacenti @@ -581,6 +577,10 @@ font-technology Variable Variabili Box Channel Canale del riquadro Color box Riquadro colore Color Wheel Options Opzioni ruota dei colori + Show Document Colors Mostra colori del documento + Document Colors Colori del documento + Selection Colors Colori della selezione +@plural Used {n} time|Used {n} times Usato {n} volta|Usato {n} volte Color Type: Tipo di colore: Color: Colore: Colorize Colora diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 26ba2dd4a8..d872e733fa 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -768,6 +768,10 @@ digits Malayalam マラヤーラム数字 Box Channel ボックスのチャンネル Color box カラーボックス Color Wheel Options カラーホイールオプション + Show Document Colors ドキュメントのカラーを表示 + Document Colors ドキュメントのカラー + Selection Colors 選択範囲のカラー +@plural Used {n} time|Used {n} times {n} 回使用 CSS Properties CSS プロパティ Document Info ドキュメント情報 Flattener Preview 分割・統合プレビュー @@ -1046,10 +1050,6 @@ digits Malayalam マラヤーラム数字 Add Selected Artwork as One Asset 選択したアートワークを 1 つのアセットとして追加 Add Spine Point スパインポイントを追加 Add Used Colors 使用中のカラーを追加 - Show Document Colors ドキュメントのカラーを表示 - Document Colors ドキュメントのカラー - Selection Colors 選択範囲のカラー -@plural Used {n} time|Used {n} times {n} 回使用 Add to Graphic Styles グラフィックスタイルに追加 Add to Profiles プロファイルに追加 Add to Profiles… プロファイルに追加… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 88883691d5..4792dcb8e8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -664,6 +664,10 @@ Box Channel კვადრატის არხი Color box ფერის კვადრატი Color Wheel Options ფერთა წრის პარამეტრები + Show Document Colors დოკუმენტის ფერების ჩვენება + Document Colors დოკუმენტის ფერები + Selection Colors მონიშნულის ფერები +@plural Used {n} time|Used {n} times გამოყენებულია {n}-ჯერ CSS Properties CSS თვისებები Document Info დოკუმენტის ინფორმაცია Flattener Preview გაბრტყელების წინასწარი ნახვა @@ -3608,10 +3612,6 @@ theme Appearance იერსახე Add to Graphic Styles გრაფიკულ სტილებში დამატება Graphic Style Library გრაფიკული სტილების ბიბლიოთეკა Add Used Colors გამოყენებული ფერების დამატება - Show Document Colors დოკუმენტის ფერების ჩვენება - Document Colors დოკუმენტის ფერები - Selection Colors მონიშნულის ფერები -@plural Used {n} time|Used {n} times გამოყენებულია {n}-ჯერ Delete Swatch ფერის ნიმუშის წაშლა Duplicate Swatch ფერის ნიმუშის დუბლირება Merge Swatches ფერის ნიმუშების შერწყმა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index adafabceee..e444d5b0d4 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -761,6 +761,10 @@ digits Malayalam 말라얄람어 Box Channel 상자 채널 Color box 색상 상자 Color Wheel Options 색상환 옵션 + Show Document Colors 문서 색상 표시 + Document Colors 문서 색상 + Selection Colors 선택 영역 색상 +@plural Used {n} time|Used {n} times {n}회 사용 CSS Properties CSS 속성 Document Info 문서 정보 Flattener Preview 병합 미리 보기 @@ -1036,10 +1040,6 @@ digits Malayalam 말라얄람어 Add Selected Artwork as One Asset 선택한 아트워크를 하나의 에셋으로 추가 Add Spine Point 스파인 포인트 추가 Add Used Colors 사용한 색상 추가 - Show Document Colors 문서 색상 표시 - Document Colors 문서 색상 - Selection Colors 선택 영역 색상 -@plural Used {n} time|Used {n} times {n}회 사용 Add to Graphic Styles 그래픽 스타일에 추가 Add to Profiles 프로필에 추가 Add to Profiles… 프로필에 추가… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index fbc59dbbea..e800ff129b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1216,6 +1216,10 @@ Box Channel Kanaal van het vak Color box Kleurvak Color Wheel Options Opties voor kleurenwiel + Show Document Colors Documentkleuren tonen + Document Colors Documentkleuren + Selection Colors Kleuren van de selectie +@plural Used {n} time|Used {n} times {n} keer gebruikt|{n} keer gebruikt CSS Properties CSS-eigenschappen Document Info Documentinfo Flattener Preview Afvlakvoorbeeld @@ -4287,10 +4291,6 @@ theme Appearance Vormgeving Add to Graphic Styles Aan grafische stijlen toevoegen Graphic Style Library Bibliotheek met grafische stijlen Add Used Colors Gebruikte kleuren toevoegen - Show Document Colors Documentkleuren tonen - Document Colors Documentkleuren - Selection Colors Kleuren van de selectie -@plural Used {n} time|Used {n} times {n} keer gebruikt|{n} keer gebruikt Delete Swatch Kleurstaal verwijderen Duplicate Swatch Kleurstaal dupliceren Merge Swatches Kleurstalen samenvoegen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a1b3192735..12eed4d623 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -702,6 +702,10 @@ Box Channel Kanał kwadratu Color box Kwadrat koloru Color Wheel Options Opcje koła kolorów + Show Document Colors Pokaż kolory dokumentu + Document Colors Kolory dokumentu + Selection Colors Kolory zaznaczenia +@plural Used {n} time|Used {n} times Użyty {n} raz|Użyty {n} razy|Użyty {n} razy CSS Properties Właściwości CSS Document Info Informacje o dokumencie Flattener Preview Podgląd spłaszczania @@ -3911,10 +3915,6 @@ theme Appearance Wygląd Add to Graphic Styles Dodaj do stylów graficznych Graphic Style Library Biblioteka stylów graficznych Add Used Colors Dodaj użyte kolory - Show Document Colors Pokaż kolory dokumentu - Document Colors Kolory dokumentu - Selection Colors Kolory zaznaczenia -@plural Used {n} time|Used {n} times Użyty {n} raz|Użyty {n} razy|Użyty {n} razy Delete Swatch Usuń próbkę Duplicate Swatch Powiel próbkę Merge Swatches Scal próbki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4763e73dbc..fc5bc3327a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -140,10 +140,6 @@ Add Selected Artwork as One Asset Adicionar Arte Selecionada como Um Ativo Add Spine Point Adicionar Ponto de Coluna Add Used Colors Adicionar Cores Usadas - Show Document Colors Mostrar Cores do Documento - Document Colors Cores do Documento - Selection Colors Cores da Seleção -@plural Used {n} time|Used {n} times Usada {n} vez|Usada {n} vezes Add to Graphic Styles Adicionar aos Estilos Gráficos Add to Profiles Adicionar aos Perfis Add to Profiles… Adicionar aos Perfis… @@ -526,6 +522,10 @@ antiAlias Sharp Nítido Box Channel Canal da Caixa Color box Caixa de cor Color Wheel Options Opções da Roda de Cores + Show Document Colors Mostrar Cores do Documento + Document Colors Cores do Documento + Selection Colors Cores da Seleção +@plural Used {n} time|Used {n} times Usada {n} vez|Usada {n} vezes Color Type: Tipo de Cor: Color blindness – Deuteranopia-type Daltonismo – tipo deuteranopia Color blindness – Protanopia-type Daltonismo – tipo protanopia diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 15bf324a05..58a46b98f4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -136,10 +136,6 @@ Add to Selection Добавить к выделению Add to Swatches Добавить в образцы Add Used Colors Добавить использованные цвета - Show Document Colors Показать цвета документа - Document Colors Цвета документа - Selection Colors Цвета выделения -@plural Used {n} time|Used {n} times Используется {n} раз|Используется {n} раза|Используется {n} раз Additional Plug-ins Folder Папка дополнительных модулей Additional Fonts Folder Папка дополнительных шрифтов Adjust Adjoining Width Points Настроить смежные точки ширины @@ -579,6 +575,10 @@ font-technology Variable Вариативные Box Channel Канал квадрата Color box Цветовой квадрат Color Wheel Options Параметры цветового круга + Show Document Colors Показать цвета документа + Document Colors Цвета документа + Selection Colors Цвета выделения +@plural Used {n} time|Used {n} times Используется {n} раз|Используется {n} раза|Используется {n} раз Color Type: Тип цвета: Color: Цвет: Colorize Тонировать diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 07131dc54a..d65a48a79f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -126,10 +126,6 @@ Add to Selection Lägg till i markering Add to Swatches Lägg till i färgrutor Add Used Colors Lägg till använda färger - Show Document Colors Visa dokumentfärger - Document Colors Dokumentfärger - Selection Colors Markeringens färger -@plural Used {n} time|Used {n} times Används {n} gång|Används {n} gånger Additional Plug-ins Folder Mapp för ytterligare plugins Additional Fonts Folder Mapp för ytterligare typsnitt Adjust Adjoining Width Points Justera angränsande breddpunkter @@ -568,6 +564,10 @@ font-technology Variable Variabla Box Channel Rutans kanal Color box Färgruta Color Wheel Options Alternativ för färghjulet + Show Document Colors Visa dokumentfärger + Document Colors Dokumentfärger + Selection Colors Markeringens färger +@plural Used {n} time|Used {n} times Används {n} gång|Används {n} gånger Color Type: Färgtyp: Color: Färg: Colorize Färglägg diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index fd5bcf86b3..536575ed8e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -123,10 +123,6 @@ Add to Selection Seçime Ekle Add to Swatches Renk Örneklerine Ekle Add Used Colors Kullanılan Renkleri Ekle - Show Document Colors Belge Renklerini Göster - Document Colors Belge Renkleri - Selection Colors Seçim Renkleri -@plural Used {n} time|Used {n} times {n} kez kullanıldı Additional Plug-ins Folder Ek Eklentiler Klasörü Additional Fonts Folder Ek Yazı Tipleri Klasörü Adjust Adjoining Width Points Bitişik Genişlik Noktalarını Ayarlayın @@ -562,6 +558,10 @@ font-technology Variable Değişken Box Channel Kutu Kanalı Color box Renk kutusu Color Wheel Options Renk Tekerleği Seçenekleri + Show Document Colors Belge Renklerini Göster + Document Colors Belge Renkleri + Selection Colors Seçim Renkleri +@plural Used {n} time|Used {n} times {n} kez kullanıldı Color Type: Renk Türü: Color: Renk: Colorize Renklendir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 90b4427f4c..cf3c7e3eee 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -132,10 +132,6 @@ Add to Selection Додати до виділення Add to Swatches Додати до зразків Add Used Colors Додати використані кольори - Show Document Colors Показати кольори документа - Document Colors Кольори документа - Selection Colors Кольори виділення -@plural Used {n} time|Used {n} times Використано {n} раз|Використано {n} рази|Використано {n} разів Additional Plug-ins Folder Папка додаткових модулів Additional Fonts Folder Папка додаткових шрифтів Adjust Adjoining Width Points Налаштувати суміжні точки ширини @@ -575,6 +571,10 @@ font-technology Variable Варіативні Box Channel Канал квадрата Color box Колірний квадрат Color Wheel Options Параметри колірного кола + Show Document Colors Показати кольори документа + Document Colors Кольори документа + Selection Colors Кольори виділення +@plural Used {n} time|Used {n} times Використано {n} раз|Використано {n} рази|Використано {n} разів Color Type: Тип кольору: Color: Колір: Colorize Тонувати diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 799a300b68..4468ba2f14 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -154,10 +154,6 @@ Add to Selection Thêm vào vùng chọn Add to Swatches Thêm vào mẫu màu Add Used Colors Thêm các màu đã dùng - Show Document Colors Hiện màu của tài liệu - Document Colors Màu của tài liệu - Selection Colors Màu của vùng chọn -@plural Used {n} time|Used {n} times Dùng {n} lần Additional Fonts Folder Thư mục phông bổ sung Additional Plug-ins Folder Thư mục plug-in bổ sung Adjust Adjoining Width Points Điều chỉnh các điểm chiều rộng kề nhau @@ -668,6 +664,10 @@ font-technology Variable Biến thiên Box Channel Kênh của hộp Color box Hộp màu Color Wheel Options Tùy chọn bánh xe màu + Show Document Colors Hiện màu của tài liệu + Document Colors Màu của tài liệu + Selection Colors Màu của vùng chọn +@plural Used {n} time|Used {n} times Dùng {n} lần Color Type: Loại màu: Color: Màu: Colorization Tô màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ce34bdd1ec..0ba389ed96 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -88,10 +88,6 @@ Add to Selection 添加到选区 Add to Swatches 添加到色板 Add Used Colors 添加已用颜色 - Show Document Colors 显示文档颜色 - Document Colors 文档颜色 - Selection Colors 所选对象的颜色 -@plural Used {n} time|Used {n} times 使用 {n} 次 Additional Plug-ins Folder 附加增效工具文件夹 Additional Fonts Folder 附加字体文件夹 Adjust Adjoining Width Points 调整相邻宽度点 @@ -527,6 +523,10 @@ antiAlias Sharp 锐利 Box Channel 方块色版 Color box 颜色方块 Color Wheel Options 色轮选项 + Show Document Colors 显示文档颜色 + Document Colors 文档颜色 + Selection Colors 所选对象的颜色 +@plural Used {n} time|Used {n} times 使用 {n} 次 Color Type: 颜色类型: Color: 颜色: Colorize 上色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index c6b9974da3..7e7af2995b 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -97,10 +97,6 @@ Add to Selection 加入選取範圍 Add to Swatches 新增至色票 Add Used Colors 新增使用中的顏色 - Show Document Colors 顯示文件顏色 - Document Colors 文件顏色 - Selection Colors 所選物件的顏色 -@plural Used {n} time|Used {n} times 使用 {n} 次 Additional Plug-ins Folder 額外的增效模組資料夾 Additional Fonts Folder 額外的字體資料夾 Adjust Adjoining Width Points 調整相鄰寬度點 @@ -544,6 +540,10 @@ font-technology Variable 可變 Box Channel 方塊色版 Color box 顏色方塊 Color Wheel Options 色輪選項 + Show Document Colors 顯示文件顏色 + Document Colors 文件顏色 + Selection Colors 所選物件的顏色 +@plural Used {n} time|Used {n} times 使用 {n} 次 Color Type: 顏色類型: Color: 顏色: Colorize 上色 diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 8e4beda794..eae319008b 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -162,7 +162,8 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { /// Panel state: the Show Document Colors row's colors, with the [`UsedKey`] they were read for. const USED: &str = "color-wheel-used"; -/// The most chips the row asks `color.used` for. +/// The fewest chips the row asks `color.used` for; a row wider than this many chips asks for as +/// many as it holds. const MAX_CHIPS: usize = 128; /// Above this many color uses, an edit makes the row read the colors again at most once every /// [`LARGE_EVERY`] seconds; a change of document or selection still reads them at once. @@ -184,6 +185,8 @@ struct UsedCache { uses: u64, /// Whether the colors are the selection's. selected: bool, + /// The most colors asked for. + limit: usize, colors: Vec, } @@ -210,15 +213,19 @@ impl Used { /// The colors the row shows and whether they are the selection's, read with `color.used` once per /// document revision and selection and kept as they are while an interaction is in progress (a /// preview raises the revision on every frame of a drag). In art with more than [`LARGE_USES`] -/// color uses, an edit reads them again only after [`LARGE_EVERY`] seconds. -fn used_colors(app: &mut VectorcraftApp, ui: &Ui) -> Arc { +/// color uses, an edit reads them again only after [`LARGE_EVERY`] seconds. A row that holds more +/// than the colors last asked for reads them again. +fn used_colors(app: &mut VectorcraftApp, ui: &Ui, per_row: usize) -> Arc { + let limit = per_row.max(MAX_CHIPS); let key: UsedKey = app.session.active().map(|d| { let mut h = std::collections::hash_map::DefaultHasher::new(); d.selection.objects.hash(&mut h); (d.uid, d.revision, d.selection.objects.len(), h.finish()) }); let now = ui.input(|i| i.time); - if let Some(cache) = pstate::>>(ui.ctx(), USED) { + if let Some(cache) = pstate::>>(ui.ctx(), USED) + && (cache.limit >= per_row || cache.colors.len() < cache.limit) + { if cache.key == key || app.session.in_interaction() { return cache; } @@ -229,7 +236,7 @@ fn used_colors(app: &mut VectorcraftApp, ui: &Ui) -> Arc { return cache; } } - let r = key.as_ref().and_then(|_| app.session.execute("color.used", &json!({ "limit": MAX_CHIPS })).ok()); + let r = key.as_ref().and_then(|_| app.session.execute("color.used", &json!({ "limit": limit })).ok()); let colors: Vec = r .as_ref() .and_then(|r| r["colors"].as_array()) @@ -246,7 +253,7 @@ fn used_colors(app: &mut VectorcraftApp, ui: &Ui) -> Arc { .unwrap_or_default(); let selected = r.as_ref().is_some_and(|r| r["selection"] == true); let uses = r.as_ref().and_then(|r| r["uses"].as_u64()).unwrap_or(0); - let cache = Arc::new(UsedCache { key, at: now, uses, selected, colors }); + let cache = Arc::new(UsedCache { key, at: now, uses, selected, limit, colors }); set_pstate(ui.ctx(), USED, Some(Arc::clone(&cache))); cache } @@ -254,13 +261,13 @@ fn used_colors(app: &mut VectorcraftApp, ui: &Ui) -> Arc { /// The Show Document Colors row: a heading (Selection Colors or Document Colors) and the colors, /// most used first, as many as fit in one row. Returns the color clicked. fn document_colors_row(app: &mut VectorcraftApp, ui: &mut Ui) -> Option { - let cache = used_colors(app, ui); - widgets::subheader(ui, if cache.selected { tl!("Selection Colors") } else { tl!("Document Colors") }); - let t = Tokens::get(ui.ctx()); let width = ui.available_width(); // Chips are 16 px on a 19 px pitch, inset 3 px, with 2 px kept clear of the right edge, as // in the Recent Colors row. let per_row = (((width - 21.0) / 19.0).floor().max(0.0) as usize + 1).max(1); + let cache = used_colors(app, ui, per_row); + widgets::subheader(ui, if cache.selected { tl!("Selection Colors") } else { tl!("Document Colors") }); + let t = Tokens::get(ui.ctx()); let (r, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover()); ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); let mut chosen = None; diff --git a/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs index a53e4e44db..e8db930a4a 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs @@ -1,6 +1,6 @@ //! The Color Wheel panel's Show Document Colors row drawn headless: its colors and their order, //! the heading that follows the selection, the colors that fit in one row, a click and an Alt+click -//! on a color, swatch links, gradient stops, the colors kept during a drag, the panel menu, +//! on a color, swatch links, gradient stops and freeform points, the colors kept during a drag, the panel menu, //! `ui.colorWheel {documentColors}` and the saved setting. use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; @@ -110,6 +110,21 @@ fn the_row_shows_only_the_colors_that_fit() { assert!(shown.iter().all(|r| (r.top() - red.top()).abs() < 0.5 && r.right() <= 260.0), "one row inside the panel: {shown:?}"); } +/// A row wide enough for more than 128 chips shows as many colors as fit. +#[test] +fn a_wide_row_shows_more_than_128_colors() { + let (mut app, _, _) = app(); + let hex = |i: usize| format!("#{:02x}{:02x}80", i % 256, i / 256 + 1); + for i in 0..160 { + rect(&mut app, 170.0, json!({"color": hex(i)})); + } + app.run("select.none", json!({})).unwrap(); + let mut h = Harness::builder().with_size(vec2(3400.0, 360.0)).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(2); + let shown = (0..160).filter(|i| has(&h, &label(&hex(*i), 1))).count(); + assert!(shown > 128, "{shown} of the 160 colors show"); +} + /// A click on a color fills the selection with it, as one undo step. #[test] fn a_click_on_a_color_sets_the_fill() { @@ -170,13 +185,13 @@ fn a_click_keeps_a_swatch_link_and_its_tint() { assert!((tint - 0.4).abs() < 1e-3, "tint {tint}"); } -/// A click recolors the selected gradient stop, linking it to a color's swatch. +/// A click recolors the selected gradient stop, linking it to a color's swatch at its tint. #[test] fn a_click_recolors_the_selected_gradient_stop() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap(); - let stops = json!([{"offset": 0, "color": "#000000", "swatch": "Ink"}, {"offset": 1, "color": "#0000ff"}]); + let stops = json!([{"offset": 0, "color": "#000000", "swatch": "Ink", "tint": 40}, {"offset": 1, "color": "#0000ff"}]); rect(&mut app, 10.0, json!({"gradient": {"stops": stops, "start": [10, 25], "end": [40, 25]}})); app.select_tool("gradient"); app.run("gradient.selectStop", json!({"index": 1})).unwrap(); @@ -196,6 +211,37 @@ fn a_click_recolors_the_selected_gradient_stop() { let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; let stop = &g.gradient.stops[1]; assert_eq!((stop.color.to_hex(), stop.swatch.as_deref()), (hex, Some("Ink"))); + assert!((stop.tint - 0.4).abs() < 1e-3, "tint {}", stop.tint); +} + +/// A click on a color linked to a swatch gives a selected freeform point the color alone and keeps +/// the freeform fill. +#[test] +fn a_click_gives_a_freeform_point_the_color_alone() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 100, "height": 100})).unwrap(); + app.run("paint.editGradient", json!({"kind": "freeform"})).unwrap(); + app.run("paint.setStroke", json!({"swatch": "Ink", "tint": 40, "focus": false})).unwrap(); + app.select_tool("gradient"); + app.run("paint.freeform.selectPoint", json!({"index": 1})).unwrap(); + app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + let hex = app.session.execute("color.used", &json!({})).unwrap()["colors"] + .as_array() + .unwrap() + .iter() + .find(|c| c["swatch"] == "Ink") + .expect("the stroke's color is listed")["hex"] + .as_str() + .unwrap() + .to_string(); + let mut h = harness(app); + let at = h.get_by_label(&label(&hex, 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let points = g.freeform.expect("still freeform").points; + assert_eq!(points[1].color.to_hex(), hex); } /// While a drag on the wheel recolors the selection, the row keeps the colors from before the From 18ffda75dcc6d3b67257074ab704d957a4eb3ca1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:17:32 -0800 Subject: [PATCH 05/69] Graphs: graph designs come in from another document A document opened with Window > Swatch Libraries > Other Library... now adds its graph designs to the Column and Marker dialogs, listed under the library's name after the document's own designs. OK on one of them copies the design into the document with the swatches, patterns, symbols, styles, brushes and images its art uses, in the same undo step as the graph change. graph.column and graph.marker take `library`, graph.design takes `library` with `add`, and swatch.library.load reports `graphDesigns` and refuses a file larger than 256 MB before reading it. The clipboard carries the graph designs that copied graphs draw with, so a graph pasted into another document brings its designs. A design the document already has under the same name stays as it is, and a pasted graph is drawn again with it when it would draw the graph otherwise. --- crates/engine/src/cmd/clipboard.rs | 8 +- crates/engine/src/cmd/clipboard/resources.rs | 123 ++++++++- crates/engine/src/cmd/edit.rs | 4 + crates/engine/src/cmd/graph.rs | 1 + crates/engine/src/cmd/graph/columns.rs | 21 +- crates/engine/src/cmd/graph/commands.rs | 6 +- crates/engine/src/cmd/graph/designs.rs | 105 +++++++- crates/engine/src/cmd/graph/markers.rs | 26 +- crates/engine/src/cmd/graph/tests.rs | 267 +++++++++++++++++++ crates/engine/src/cmd/swatchlib.rs | 57 +++- crates/engine/src/lib.rs | 3 + crates/engine/src/session/documents.rs | 1 + crates/ui-egui/src/dialogs/graph_design.rs | 122 +++++++-- docs/mcp.md | 13 +- docs/target-app-parity.md | 1 + 15 files changed, 718 insertions(+), 40 deletions(-) diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 446634d21c..944c615fc0 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::Swatch; -use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef}; +use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef}; use vectorcraft_geom::{PathData, Rect}; pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; @@ -85,6 +85,9 @@ pub struct Clipboard { pub para_styles: Vec, /// Brushes the objects' strokes use. pub brushes: Vec, + /// Graph designs the copied graphs draw their columns, bars or markers with. Pasting adds the + /// ones the document lacks; a design the document has under the same name stays as it is. + pub graph_designs: Vec, /// The artboard the objects were copied from (none when they lie on no artboard; the first of /// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it. pub source_artboard: Option, @@ -372,7 +375,7 @@ impl Clipboard { if self.source_doc == Some(st.uid) { return vec![]; } - self.conflicts(&st.doc, &self.used()) + self.conflicts(&st.doc, &self.used(&st.doc)) } /// A standalone document holding the objects and their resources (SVG export). @@ -385,6 +388,7 @@ impl Clipboard { d.graphic_styles.extend(self.graphic_styles.iter().cloned()); d.char_styles = self.char_styles.clone().into(); d.para_styles = self.para_styles.clone().into(); + d.graph_designs = self.graph_designs.clone(); if !self.brushes.is_empty() { let mut lib = vectorcraft_brush::library(&d); // Each brush's place in the library by name: finding it by scanning the growing list diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f457712415..bc1c9e54e5 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1,8 +1,9 @@ //! The document resources copied objects use, and adding them to the document they're pasted into. //! //! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and -//! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also -//! through the symbols, patterns, styles and brush art it finds, and keeps what they lead to. +//! paragraph styles, brushes, graph designs) and to graphic styles by id. Copy follows those +//! references, also through the symbols, patterns, styles, brush art and graph design art it finds, +//! and keeps what they lead to. //! //! Pasting matches each resource by name: an identical one in the document is used, a missing one //! is added, and a different one of the same name is added under a free name, which the pasted @@ -21,7 +22,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::{ - Appearance, AppearanceItem, Document, Effect, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, + Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, TextStyleDef, }; @@ -42,6 +43,7 @@ enum Res { ParaStyle, Brush, GraphicStyle, + GraphDesign, } impl Res { @@ -55,6 +57,7 @@ impl Res { Res::ParaStyle => "paraStyle", Res::Brush => "brush", Res::GraphicStyle => "graphicStyle", + Res::GraphDesign => "graphDesign", } } } @@ -137,6 +140,10 @@ fn node_refs(n: &Node, f: Visit) { for s in [&l.values_para, &l.categories_para, &l.legend_para].into_iter().flatten().filter_map(|pa| pa.style_name.as_ref()) { f(Ref::Name(Res::ParaStyle, s)); } + // The designs its series draw their markers, columns or bars with. + for d in g.series_markers.iter().flatten().chain(g.series_columns.iter().flatten().map(|c| &c.design)) { + f(Ref::Name(Res::GraphDesign, d)); + } } match &m.kind { NodeKind::Text(t) => { @@ -215,6 +222,7 @@ struct Defs<'a> { char_styles: &'a [TextStyleDef], para_styles: &'a [TextStyleDef], brushes: Brushes<'a>, + graph_designs: &'a [GraphDesign], /// Where each name is defined, built the first time a kind is followed. index: DefIndex, } @@ -234,6 +242,7 @@ struct DefIndex { char_styles: OnceCell, para_styles: OnceCell, brushes: OnceCell, + graph_designs: OnceCell, } /// The items of `list` named `name`, in order, `index` holding their positions (built from @@ -277,6 +286,7 @@ impl<'a> Defs<'a> { char_styles: &d.char_styles, para_styles: &d.para_styles, brushes: Brushes::Lazy(d, brushes), + graph_designs: &d.graph_designs, index: DefIndex::default(), } } @@ -374,6 +384,7 @@ impl Used { Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))), // A scatter or art brush's art, a pattern brush's tiles. Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))), + Res::GraphDesign => todo.extend(named(&ix.graph_designs, defs.graph_designs, |g| &g.name, name).map(|g| Source::Node(&g.art))), _ => {} } } @@ -404,7 +415,7 @@ pub struct ArtResources { /// The resources `art` uses in `doc`, through the definitions they lead to as Copy follows them /// ([`Used`]): images, symbols, patterns (tile type, overlap and spacing too), swatches (linked /// colours, tints, gradient swatches; colour groups' included), character and paragraph styles, -/// brushes and graphic styles, and the document's Spot Colors option. Art and image bytes count +/// brushes, graph designs and graphic styles, and the document's Spot Colors option. Art and image bytes count /// by identity, the other definitions by their saved form: working the key out walks `art` and /// the definitions it leads to, and never reads an image's bytes. pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator) -> ArtResources { @@ -449,6 +460,7 @@ pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator doc.char_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)), Res::ParaStyle => doc.para_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)), Res::Brush => defs.brushes.get().iter().filter(|b| b.name == *name).for_each(|b| saved(&mut h, b)), + Res::GraphDesign => doc.graph_designs.iter().filter(|g| g.name == *name).for_each(|g| node(&mut h, &mut kept.0, &g.art)), // Swatches below (tints count too); graphic styles go by id. Res::Swatch | Res::GraphicStyle => {} } @@ -1019,6 +1031,10 @@ pub(crate) struct Imported { /// `{kind, from, to}` for every resource the pasted objects now know under another name: added /// renamed, or a copy added renamed by an earlier paste. pub renamed: Vec, + /// The graph designs the pasted graphs draw with that the document has under the same name + /// and that would draw them otherwise than the art they were pasted with: the document keeps + /// its own, and the pasted graphs are drawn again with it. + pub kept_designs: BTreeSet, } impl Imported { @@ -1071,13 +1087,17 @@ impl Clipboard { char_styles: pick(Res::CharStyle, &src.char_styles), para_styles: pick(Res::ParaStyle, &src.para_styles), brushes, + graph_designs: src.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)).cloned().collect(), nodes, ..Default::default() } } - /// The resources the objects use now (Paste without Formatting leaves text styles behind). - pub(super) fn used(&self) -> Used { + /// The resources the objects use now (Paste without Formatting leaves text styles behind), + /// pasted into `d`: the art of a graph design `d` has under the same name is not followed, as + /// `d` keeps its own design. + pub(super) fn used(&self, d: &Document) -> Used { + let designs: Vec = self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)).cloned().collect(); let defs = Defs { swatches: self.swatches.iter().collect(), symbols: &self.symbols, @@ -1086,6 +1106,7 @@ impl Clipboard { char_styles: &self.char_styles, para_styles: &self.para_styles, brushes: Brushes::Ready(&self.brushes), + graph_designs: &designs, index: DefIndex::default(), }; Used::of(&defs, &self.nodes) @@ -1106,7 +1127,8 @@ impl Clipboard { /// under a free name ("Dots 2") is compared and added with that name. An error, with `d` /// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]). pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result { - self.import_used(d, &self.used(), choices, same_doc) + let used = self.used(d); + self.import_used(d, &used, choices, same_doc) } /// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush @@ -1117,6 +1139,11 @@ impl Clipboard { fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result { let mut out = Imported::default(); out.relink.filters = self.filter_links(d, same_doc)?; + let held = |name: &str| d.graph_designs.iter().any(|x| x.name == name); + let new_designs = self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name) && !held(&g.name)).count(); + if new_designs > 0 && d.graph_designs.len().saturating_add(new_designs) > GraphDesign::MAX { + return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX))); + } self.import_images(d, used, same_doc, &mut out); self.import_swatches(d, used, choices, same_doc, &mut out); let mut defs: Vec> = vec![]; @@ -1239,6 +1266,7 @@ impl Clipboard { } } self.import_graphic_styles(d, used, same_doc, &mut out); + self.import_graph_designs(d, used, same_doc, &mut out)?; for (r, name, def) in added_styles { let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles }; if let Some(s) = theirs.iter_mut().find(|s| s.name == name) { @@ -1289,6 +1317,9 @@ impl Clipboard { for a in self.brushes.iter().flat_map(Brush::art) { node_filters(a, &mut found); } + for g in &self.graph_designs { + node_filters(&g.art, &mut found); + } for g in &self.graphic_styles { appearance_filters(&g.appearance, &mut found); } @@ -1416,6 +1447,39 @@ impl Clipboard { out.relink.styles.insert(g.id, d.graphic_style_id(i)); } } + + /// Graph designs: the document's design of a name stays as it is and the pasted graphs draw + /// with it ([`Imported::kept_designs`]); a design the document lacks is added under its name, its art following the + /// resources placed above, with fresh ids. Called once every other resource is placed. + fn import_graph_designs(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) -> Result<()> { + // Every name the pasted graphs draw with whose design in the document would draw them + // otherwise: another design of that name, one the clipboard holds no design for (deleted + // and made again), or, from another document, the same art when a resource came in renamed + // or a swatch took the document's color (the art may draw it). + let moved = !same_doc && (!out.relink.renames.is_empty() || out.merged > 0); + let differs = |n: &str| { + let ours = d.graph_designs.iter().find(|x| x.name == n); + let theirs = self.graph_designs.iter().find(|g| g.name == n); + ours.is_some_and(|x| moved || theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art)) + }; + let named = used.names.get(&Res::GraphDesign).into_iter().flatten(); + out.kept_designs.extend(named.filter(|n| differs(n)).cloned()); + for g in self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)) { + if d.graph_designs.iter().any(|x| x.name == g.name) { + out.placed(Res::GraphDesign, &g.name, &Placed::Existing); + continue; + } + if d.graph_designs.len() >= GraphDesign::MAX { + return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX))); + } + let mut art = (*g.art).clone(); + out.relink.node(&mut art); + let art = d.reid(&art); + d.graph_designs.push(GraphDesign { name: g.name.clone(), art: Arc::new(art) }); + out.placed(Res::GraphDesign, &g.name, &Placed::Added); + } + Ok(()) + } } /// Where a loaded text style is in the document ([`import_text_styles`]). @@ -1455,6 +1519,51 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, Ok(placed) } +/// The resources graph designs `names` of `src` use, through the definitions they lead to. +fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used { + let mut used = Used::default(); + let mut todo = vec![]; + for n in names { + used.note(defs, Ref::Name(Res::GraphDesign, n), &mut todo); + } + used.follow(defs, todo); + used +} + +/// A document holding `src`'s graph designs and the swatches, patterns, symbols, styles, brushes +/// and images their art uses, and nothing else: what a document opened as a library keeps for the +/// Graph Column and Graph Marker dialogs. `None` when `src` has no graph designs. +pub(crate) fn graph_design_library(src: &Document) -> Option { + if src.graph_designs.is_empty() { + return None; + } + let names: Vec = src.graph_designs.iter().map(|g| g.name.clone()).collect(); + let library = OnceCell::new(); + let used = designs_used(&Defs::of(src, &library), &names); + let clip = Clipboard::with_used(src, &used, &library, vec![]); + let mut d = clip.to_document(); + // The symbols keep their Symbol Options, which the document keeps by name. + for (name, options) in &clip.symbol_options { + options.give(&mut d, name); + } + d.title = src.title.clone(); + Some(d) +} + +/// Add graph designs `names` of `src` to `d`, with the swatches, patterns, symbols, styles, +/// brushes and images their art uses, placed as Paste places them ([`Clipboard::import_into`]; a +/// global or spot color whose name `d` gives another color is `d`'s). A design `d` has under the +/// same name stays as it is. → each name, and whether its design was added. An error, with `d` +/// unchanged, when `d` would hold more than [`GraphDesign::MAX`] designs. +pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result> { + let library = OnceCell::new(); + let used = designs_used(&Defs::of(src, &library), names); + let clip = Clipboard::with_used(src, &used, &library, vec![]); + let before: HashSet = d.graph_designs.iter().map(|g| g.name.clone()).collect(); + clip.import_used(d, &used, &SwatchChoices::default(), false)?; + Ok(names.iter().map(|n| (n.clone(), !before.contains(n))).collect()) +} + /// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups /// share one namespace). fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 00b6a338f2..53fc5c2d83 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1536,6 +1536,10 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho for id in &new_ids { super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default()); } + // A pasted graph whose design the document has under the same name draws with the document's. + if !imported.kept_designs.is_empty() { + super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?; + } sel.set(new_ids.iter().copied()); // Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a // paste of guides alone keeps them where they were, but onto another artboard or every diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 9af36db9aa..3f8051c8b5 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -40,6 +40,7 @@ pub use commands::specs; pub(crate) use data::apply_csv; #[cfg(test)] use data::{fmt_value, parse_csv, to_csv}; +pub(crate) use designs::redraw_with_designs; pub(crate) use edit::{graphs_holding, keep_placed}; #[cfg(test)] use generate::generate; diff --git a/crates/engine/src/cmd/graph/columns.rs b/crates/engine/src/cmd/graph/columns.rs index 34addd90bd..4e56338849 100644 --- a/crates/engine/src/cmd/graph/columns.rs +++ b/crates/engine/src/cmd/graph/columns.rs @@ -1,5 +1,5 @@ use super::data::fmt_value; -use super::designs::design_names; +use super::designs::{bring_in, design_names, from_library, libraries_json}; use super::edit::{regenerate, spec_of, target}; use super::generate::generate_with; use super::markers::{design_frame, fit_affine}; @@ -437,7 +437,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { let mut spec = spec_of(s, id)?; let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES); let picked = picked_series(s, p, id, count, C)?; - let names = design_names(&s.doc()?.doc); + let mut names = design_names(&s.doc()?.doc); let all: Vec = if picked.is_empty() { (0..count).collect() } else { picked.clone() }; // The column design the picked series (all of them with none picked) share; a design deleted since doesn't count, // as those series draw plain columns. @@ -446,14 +446,21 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { let shared = used.first().copied().flatten().filter(|c| used.iter().all(|x| *x == Some(*c))).cloned(); let Some(v) = p.get("design") else { let options = shared.clone().unwrap_or_default(); - return Ok(json!({ + let mut out = json!({ "designs": names, "design": shared.map(|c| c.design), "columnType": options.column_type.id(), "each": options.each, "fractions": options.fractions.id(), - })); + }); + if let Some(libs) = libraries_json(s) { + out["libraries"] = libs; + } + return Ok(out); }; + // A design of a loaded library comes into the document in the same undo step. + let library = from_library(s, p, C)?; + names.extend(library.as_ref().map(|(_, n)| n.clone())); let design = match v { Value::Null => None, Value::String(n) if names.contains(n) => Some(n.clone()), @@ -485,11 +492,17 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { } // Drawn once on a copy of the document, to refuse designs past the budget before the edit. let mut probe = (*s.doc()?.doc).clone(); + if let Some((lib, name)) = &library { + bring_in(&mut probe, lib, std::slice::from_ref(name))?; + } let looks = column_designs(&probe, &spec); if generate_with(&mut probe, &spec, &looks).is_none() { return Err(bad(C, "the design is too big to draw in every column of this graph")); } s.edit("Graph Column", |d, sel| { + if let Some((lib, name)) = &library { + bring_in(d, lib, std::slice::from_ref(name))?; + } regenerate(d, id, spec)?; if !reselect.is_empty() { reselect_series(d, sel, id, &reselect); diff --git a/crates/engine/src/cmd/graph/commands.rs b/crates/engine/src/cmd/graph/commands.rs index 7084fe19f6..b88b4f8c7e 100644 --- a/crates/engine/src/cmd/graph/commands.rs +++ b/crates/engine/src/cmd/graph/commands.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Design…", ["Object", "Graph"], None, - "{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list)}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with]}", + "{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list), library?: the id or name of a document loaded with swatch.library.load (Other Library…) that holds graph designs, add?: name|[names] of that library's designs (copy them into the document as one undo step, with the swatches, patterns, symbols, styles, brushes and images their art uses, as pasting brings them; a design the document already has under the same name stays as it is) → {added: [names], existing: [names the document already had]}}; library alone → {designs: [the library's names]}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with], libraries?: [{library, name, designs}] (the loaded libraries that hold graph designs)}", has_doc, design ), @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Column…", ["Object", "Graph"], None, - "{id?, seriesIndexes?: [index], design?: name|null, columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions}", + "{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used), columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions, libraries?: [{library, name, designs}]}", has_selection, set_column ), @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Marker…", ["Object", "Graph"], None, - "{id?, seriesIndexes?: [index], design?: name|null} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null}", + "{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used)} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null, libraries?: [{library, name, designs}]}", has_selection, set_marker ), diff --git a/crates/engine/src/cmd/graph/designs.rs b/crates/engine/src/cmd/graph/designs.rs index 6ab79bac77..4d272d7bc3 100644 --- a/crates/engine/src/cmd/graph/designs.rs +++ b/crates/engine/src/cmd/graph/designs.rs @@ -1,11 +1,71 @@ use super::edit::regenerate; use super::{Arc, Document, GraphDesign, GraphSpec, Result, Session, Value, bad, json, ok, str_param}; +use crate::cmd::clipboard::resources::import_graph_designs; +use crate::cmd::swatchlib::{concealed_library_id, shown_library_id}; /// The document's graph design names, in order. pub(super) fn design_names(d: &Document) -> Vec { d.graph_designs.iter().map(|x| x.name.clone()).collect() } +/// The library param `library` names: a document Other Library… loaded (`swatch.library.load`) +/// that holds graph designs, by its id, the id a reply showed for it, or its name. `None` without +/// `library`. +fn library_param(s: &Session, p: &Value, cmd: &str) -> Result>> { + let key = match p.get("library") { + None | Some(Value::Null) => return Ok(None), + Some(Value::String(k)) => k.as_str(), + Some(_) => { + let list = "graph.design"; + return Err(bad(cmd, format!("`library` is a library id or name (see {list})"))); + } + }; + let libs = &s.graph_design_libraries; + let own = concealed_library_id(s, key); + libs.get(key) + .or_else(|| own.as_deref().and_then(|id| libs.get(id))) + .or_else(|| libs.iter().find(|l| l.name == key)) + .map(|l| Some(l.doc.clone())) + .ok_or_else(|| bad(cmd, format!("no library `{key}`"))) +} + +/// The loaded libraries' designs, as lists show them: `[{library, name, designs}]`; `None` when no +/// loaded library holds graph designs. +pub(super) fn libraries_json(s: &Session) -> Option { + let libs: Vec = s + .graph_design_libraries + .iter() + .map(|l| json!({ "library": shown_library_id(s, &l.id), "name": l.name, "designs": design_names(&l.doc) })) + .collect(); + (!libs.is_empty()).then(|| json!(libs)) +} + +/// The library design `p`'s `design` names, with the library to bring it in from, when `p` gives a +/// `library` and the document has no design of that name: the document's own design of a name is +/// the one a graph draws with. +pub(super) fn from_library(s: &Session, p: &Value, cmd: &str) -> Result, String)>> { + let Some(lib) = library_param(s, p, cmd)? else { return Ok(None) }; + let Some(Value::String(n)) = p.get("design") else { return Ok(None) }; + if s.doc()?.doc.graph_designs.iter().any(|x| x.name == *n) { + return Ok(None); + } + if !lib.graph_designs.iter().any(|x| x.name == *n) { + return Err(bad(cmd, format!("no design named `{n}`"))); + } + Ok(Some((lib, n.clone()))) +} + +/// Add designs `names` of library `lib` to `d` with the resources their art uses, and redraw the +/// graphs that already name one the document lacked. +pub(super) fn bring_in(d: &mut Document, lib: &Document, names: &[String]) -> Result<()> { + for (name, added) in import_graph_designs(lib, d, names)? { + if added { + refresh_graphs_using(d, &name)?; + } + } + Ok(()) +} + /// Whether graph `g` draws a series with design `name`, as its marker or its columns. fn draws_with(g: &GraphSpec, name: &str) -> bool { g.series_markers.iter().flatten().any(|m| m == name) || g.series_columns.iter().flatten().any(|c| c.design == name) @@ -27,6 +87,27 @@ fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> { Ok(()) } +/// Draw the graphs in the subtrees of `ids` again that draw a series with one of the designs +/// `names`: pasted graphs, after the paste kept the document's own designs of those names. +pub(crate) fn redraw_with_designs(d: &mut Document, ids: &[super::NodeId], names: &std::collections::BTreeSet) -> Result<()> { + let mut graphs = vec![]; + for id in ids { + if let Some(n) = d.node(*id) { + n.walk(&mut |m| { + if m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) { + graphs.push(m.id); + } + }); + } + } + for id in graphs { + if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) { + regenerate(d, id, spec)?; + } + } + Ok(()) +} + /// The designs no graph's series draw with (Select Unused). fn unused_designs(d: &Document) -> Vec { let mut used = std::collections::HashSet::new(); @@ -159,7 +240,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result { })?; return ok(); } + // Designs from a document loaded as a library: those the document has under the same name stay + // as they are. + if let Some(mut wanted) = names_param(p, "add", C)? { + let lib = library_param(s, p, C)?.ok_or_else(|| bad(C, "missing `library`"))?; + if let Some(n) = wanted.iter().find(|n| !lib.graph_designs.iter().any(|x| x.name == **n)) { + return Err(bad(C, format!("no design named `{n}`"))); + } + let mut seen = std::collections::HashSet::new(); + wanted.retain(|n| seen.insert(n.clone())); + let (existing, added): (Vec, Vec) = wanted.into_iter().partition(|n| taken(s, n)); + if !added.is_empty() { + s.edit("New Design", |d, _| bring_in(d, &lib, &added))?; + } + return Ok(json!({ "added": added, "existing": existing })); + } + if let Some(lib) = library_param(s, p, C)? { + return Ok(json!({ "designs": design_names(&lib) })); + } // The list, with the designs no graph draws with (Select Unused picks those). let d = &s.doc()?.doc; - Ok(json!({ "designs": design_names(d), "unused": unused_designs(d) })) + let mut out = json!({ "designs": design_names(d), "unused": unused_designs(d) }); + if let Some(libs) = libraries_json(s) { + out["libraries"] = libs; + } + Ok(out) } diff --git a/crates/engine/src/cmd/graph/markers.rs b/crates/engine/src/cmd/graph/markers.rs index 95a738ff7e..7045fee638 100644 --- a/crates/engine/src/cmd/graph/markers.rs +++ b/crates/engine/src/cmd/graph/markers.rs @@ -1,4 +1,4 @@ -use super::designs::design_names; +use super::designs::{bring_in, design_names, from_library, libraries_json}; use super::edit::{regenerate, spec_of, target}; use super::series::{picked_series, reselect_series}; use super::{Affine, Arc, Document, GraphSpec, Node, NodeKind, Rect, Result, Session, Value, bad, json}; @@ -55,7 +55,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { let mut spec = spec_of(s, id)?; let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES); let picked = picked_series(s, p, id, count, C)?; - let names = design_names(&s.doc()?.doc); + let mut names = design_names(&s.doc()?.doc); let Some(v) = p.get("design") else { // The design the picked series (all of them with none picked) share, or null. let all: Vec = if picked.is_empty() { (0..count).collect() } else { picked }; @@ -63,8 +63,15 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { let used: Vec> = all.iter().map(|i| spec.series_markers.get(*i).and_then(Option::as_ref).filter(|n| names.contains(n))).collect(); let shared = used.first().copied().flatten().filter(|d| used.iter().all(|x| *x == Some(*d))); - return Ok(json!({ "designs": names, "design": shared })); + let mut out = json!({ "designs": names, "design": shared }); + if let Some(libs) = libraries_json(s) { + out["libraries"] = libs; + } + return Ok(out); }; + // A design of a loaded library comes into the document in the same undo step. + let library = from_library(s, p, C)?; + names.extend(library.as_ref().map(|(_, n)| n.clone())); let design = match v { Value::Null => None, Value::String(n) if names.contains(n) => Some(n.clone()), @@ -83,10 +90,21 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { while spec.series_markers.last().is_some_and(Option::is_none) { spec.series_markers.pop(); } - if marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)) > MARKER_BUDGET { + let cost = match &library { + Some((lib, name)) => { + let mut probe = (*s.doc()?.doc).clone(); + bring_in(&mut probe, lib, std::slice::from_ref(name))?; + marker_cost(&spec, &marker_designs(&probe, &spec)) + } + None => marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)), + }; + if cost > MARKER_BUDGET { return Err(bad(C, "the design is too big to draw at every data point of this graph")); } s.edit("Graph Marker", |d, sel| { + if let Some((lib, name)) = &library { + bring_in(d, lib, std::slice::from_ref(name))?; + } regenerate(d, id, spec)?; if !reselect.is_empty() { reselect_series(d, sel, id, &reselect); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index c160a78833..a2a7d63002 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -4320,6 +4320,273 @@ fn graph_designs_are_saved_pasted_and_deleted() { assert!(series_parts(&s, id, 0).iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); } +/// Graph design "Coin" in the active document: a 10 × 10 rectangle filled with global swatch "Gold". +fn save_coin_design(s: &mut Session) { + s.execute("swatch.new", &json!({"name": "Gold", "color": "#d4a017", "global": true})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Gold", "ids": [r]})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Coin"})).unwrap(); +} + +/// Load a saved document holding [`save_coin_design`]'s design as a swatch library (Other +/// Library…) → its id. +fn load_coin_library(s: &mut Session) -> String { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut src); + let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Coins.vectorcraft"}); + let r = s.execute("swatch.library.load", &p).unwrap(); + assert_eq!(r["graphDesigns"], 1); + r["library"].as_str().unwrap().to_string() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Whether some object of `n` is filled with a colour linked to swatch `name`. +fn paints_with_swatch(n: &vectorcraft_doc::Node, name: &str) -> bool { + let mut found = false; + n.walk(&mut |m| found |= m.appearance.items.iter().any(|it| matches!(it.paint(), Paint::Solid { swatch: Some(w), .. } if w == name))); + found +} + +#[test] +fn designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + // The Column dialog's list: none of the document's, Coin from the library. + let q = s.execute("graph.column", &json!({})).unwrap(); + assert_eq!((q["designs"].clone(), q["libraries"][0]["library"].clone()), (json!([]), json!(lib))); + assert_eq!(q["libraries"][0]["designs"], json!(["Coin"])); + assert!(s.execute("graph.column", &json!({"design": "Coin"})).is_err(), "not the document's"); + let steps = undo_len(&s); + s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap(); + assert_eq!(undo_len(&s), steps + 1, "one undo step"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::>(), ["Coin"]); + assert!(d.swatch("Gold").is_some_and(|w| w.global), "the swatch the design's art uses comes along"); + assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold")); + assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "the columns draw the design"); + // Undo takes the design, its swatch and the columns' design out together. + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.is_empty() && d.swatch("Gold").is_none() && spec(&s, id).series_columns.is_empty()); + // Marker takes them too. + let line = graph(&mut s, "line"); + s.execute("select.set", &json!({"ids": [line.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin", "library": lib})).unwrap(); + assert_eq!(spec(&s, line).series_markers, [Some("Coin".to_string()), Some("Coin".to_string())]); + assert!(s.doc().unwrap().doc.swatch("Gold").is_some()); + // An unknown library or design, and a library that is not a string, are refused. + for p in [json!({"design": "Coin", "library": "Nope"}), json!({"design": "Nope", "library": lib}), json!({"design": "Coin", "library": 3})] { + assert!(s.execute("graph.column", &p).is_err(), "{p}"); + } +} + +#[test] +fn a_design_the_document_has_under_the_same_name_stays_as_it_is() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let own = s.doc().unwrap().doc.graph_designs[0].art.clone(); + assert_eq!(s.execute("graph.design", &json!({"library": lib})).unwrap(), json!({"designs": ["Coin"]})); + let steps = undo_len(&s); + let r = s.execute("graph.design", &json!({"library": lib, "add": ["Coin", "Coin"]})).unwrap(); + assert_eq!(r, json!({"added": [], "existing": ["Coin"]})); + assert_eq!(undo_len(&s), steps, "nothing changed: no undo step"); + // Applying it with the library draws with the document's own design. + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own)); + assert!(d.swatch("Gold").is_none()); + assert!(s.execute("graph.design", &json!({"add": "Coin"})).is_err(), "no library"); + assert!(s.execute("graph.design", &json!({"library": lib, "add": "Nope"})).is_err()); + assert!(s.execute("graph.design", &json!({"library": lib, "add": 4})).is_err()); + // The document without it takes it as one undo step. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let r = s.execute("graph.design", &json!({"library": "Coins", "add": "Coin"})).unwrap(); + assert_eq!(r, json!({"added": ["Coin"], "existing": []})); + assert!(s.doc().unwrap().doc.swatch("Gold").is_some()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.graph_designs.is_empty()); +} + +#[test] +fn a_pasted_graph_brings_the_designs_its_series_draw_with() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::>(), ["Coin"]); + assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold") && d.swatch("Gold").is_some()); + // A data edit redraws the pasted graph with the design. + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + s.execute("graph.setData", &json!({"id": pasted.0, "csv": ",A\nQ1,4\nQ2,6"})).unwrap(); + assert!(paints_with_swatch(series(s.doc().unwrap().doc.node(pasted).unwrap(), 0), "Gold")); + // A document with its own design of that name keeps it. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let own = s.doc().unwrap().doc.graph_designs[0].art.clone(); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own)); + // The pasted graph is drawn with that design straight away. + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + // The document's design is a rectangle and an ellipse, the pasted one a rectangle alone: each + // column and the legend swatch hold two paths. + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns: Vec = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); +} + +#[test] +fn a_design_the_document_keeps_brings_none_of_the_pasted_designs_resources() { + // A column graph whose spec names marker design "Coin", which only line series draw: the + // graph's own art does not use the design's swatch. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin"})).unwrap(); + assert!(spec(&s, id).series_markers.iter().any(|m| m.as_deref() == Some("Coin"))); + assert!(!paints_with_swatch(s.doc().unwrap().doc.node(id).unwrap(), "Gold")); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document with its own "Coin" keeps it and takes nothing the pasted design's art uses. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Gold").is_none()); + // A document without one takes the design and its swatch. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Gold").is_some()); +} + +#[test] +fn a_pasted_graph_naming_a_deleted_design_draws_with_the_documents_design_of_that_name() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + assert!(spec(&s, id).series_columns.iter().flatten().any(|c| c.design == "Coin"), "the graph still names it"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let d = &s.doc().unwrap().doc; + let columns: Vec = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); +} + +#[test] +fn a_graph_pasted_back_after_its_design_was_made_again_draws_with_the_new_design() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // Made again under the same name as a rectangle and an ellipse. + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let d = &s.doc().unwrap().doc; + let columns: Vec = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the design the document has now"); +} + +#[test] +fn a_library_copied_to_user_defined_keeps_its_graph_designs_under_the_loaded_id() { + let dir = vectorcraft_testkit::TempDir::new("graph-design-library-user"); + let mut s = Session::new(); + s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string())); + let loaded = load_coin_library(&mut s); + // The User Defined copy is a swatch file: it holds the swatches alone. + let copy = s.execute("swatch.library.copyToUser", &json!({"library": loaded})).unwrap()["library"].as_str().unwrap().to_string(); + assert_ne!(copy, loaded); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let libraries = s.execute("graph.design", &json!({})).unwrap()["libraries"].clone(); + assert_eq!(libraries, json!([{"library": loaded, "name": libraries[0]["name"], "designs": ["Coin"]}])); + assert_eq!(s.execute("graph.design", &json!({"library": loaded})).unwrap(), json!({"designs": ["Coin"]})); + assert!(s.execute("graph.design", &json!({"library": copy})).is_err()); +} + +#[test] +fn a_swatch_library_file_over_the_size_limit_is_refused_before_it_is_read() { + let dir = vectorcraft_testkit::TempDir::new("graph-design-library-size"); + let path = dir.join("big.vectorcraft"); + let f = std::fs::File::create(&path).unwrap(); + f.set_len(((256 << 20) + 1) as u64).unwrap(); + let mut s = Session::new(); + let e = s.execute("swatch.library.load", &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains("larger than 256 MB"), "{e}"); +} + +#[test] +fn a_library_design_brings_its_symbols_with_their_symbol_options() { + // The source design is an instance of symbol "Corner" with 9-slice scaling, a top-left + // registration point and the Graphic export type. + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap(); + src.execute("select.all", &json!({})).unwrap(); + let opts = json!({"name": "Corner", "nineSlice": true, "registration": 0, "exportType": "graphic"}); + let inst = src.execute("symbol.new", &opts).unwrap()["id"].as_u64().unwrap(); + src.execute("select.set", &json!({"ids": [inst]})).unwrap(); + src.execute("graph.design", &json!({"new": "Corner Mark"})).unwrap(); + let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc); + let mut s = Session::new(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Corners.vectorcraft"}); + let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Corner Mark"})).unwrap(); + let (from, to) = (&src.doc().unwrap().doc, &s.doc().unwrap().doc); + assert!(from.symbol_nine_slice("Corner").is_some()); + assert_eq!(to.symbol_nine_slice("Corner"), from.symbol_nine_slice("Corner")); + assert_eq!(to.symbol_registration("Corner"), from.symbol_registration("Corner")); + assert_eq!(to.symbol_export_type("Corner"), from.symbol_export_type("Corner")); +} + #[test] fn designs_and_markers_survive_save_and_open() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index ed712d8509..a8b3dee0d4 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Other Library…", ["Window", "Swatch Libraries"], None, - "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library) → {library: id, name, count}", + "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's graph designs are offered by Object › Graph › Column… and Marker… (graph.column, graph.marker and graph.design take the library's id) until the app quits. A file larger than 256 MB is refused before it is read → {library: id, name, count, graphDesigns: the document's graph designs (0 for a library file)}", always, load ), @@ -92,6 +92,45 @@ pub fn specs() -> Vec { ] } +/// The graph designs of the documents Other Library… loaded (`swatch.library.load`), which the +/// Graph Column and Graph Marker dialogs offer besides the document's own; not saved. +#[derive(Clone, Debug, Default)] +pub struct DesignLibraries { + libs: Vec, +} + +/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]). +#[derive(Clone, Debug)] +pub struct DesignLibrary { + /// The id `swatch.library.load` gave the swatch library. A User Defined copy of it + /// (`swatch.library.copyToUser`) holds the swatches alone, so the designs stay under this id. + pub id: String, + pub name: String, + /// The designs and the resources their art uses. + pub doc: Arc, +} + +impl DesignLibraries { + /// The libraries, in the order they were loaded. + pub fn iter(&self) -> impl Iterator { + self.libs.iter() + } + + /// The library loaded as swatch library `id`. + pub fn get(&self, id: &str) -> Option<&DesignLibrary> { + self.libs.iter().find(|l| l.id == id) + } + + /// Keep `doc`'s graph designs as library `id` named `name`, in place of the ones loaded as `id` + /// before; with no designs, `id` no longer has any. + fn set(&mut self, id: &str, name: &str, doc: Option) { + self.libs.retain(|l| l.id != id); + if let Some(doc) = doc { + self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) }); + } + } +} + /// The libraries beyond the built-in ones: User Defined (the library files in the user library /// folder, as last scanned) and loaded ones (`swatch.library.load`). Graphic style libraries use /// the same with [`vectorcraft_doc::StyleLibrary`] ([`super::stylelib`]). @@ -734,8 +773,17 @@ fn save(s: &mut Session, p: &Value) -> Result { fn load(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.load"; + // The size is checked before the file is read. + let max = super::place::document::MAX_FILE; + if let Some(path) = text_param(p, "path", C)? + && super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64) + { + return Err(bad(C, format!("the file is larger than {} MB", max >> 20))); + } + let mut designs = None; let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| { - // A library file, or a document whose swatches become the library. + // A library file, or a document whose swatches become the library and whose graph + // designs the Graph Column and Graph Marker dialogs offer. if palette_io::sniff_bytes(bytes) { palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e)) } else { @@ -743,10 +791,13 @@ fn load(s: &mut Session, p: &Value) -> Result { if loaded.preview_only { return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning")); } + designs = super::clipboard::resources::graph_design_library(&loaded.doc); document_library(&loaded.doc, &[], stem(file).to_string(), C) } })?; - Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()})) + let count = designs.as_ref().map_or(0, |d| d.graph_designs.len()); + s.graph_design_libraries.set(&info.id, &info.name, designs); + Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len(), "graphDesigns": count})) } fn get(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4b47966463..81d67a9b55 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -144,6 +144,9 @@ pub struct Session { pub(crate) pending_paint: Option, /// User Defined and loaded swatch libraries (Window → Swatch Libraries); not saved. pub swatch_libraries: cmd::swatchlib::Libraries, + /// The graph designs of the documents loaded as swatch libraries (Window → Swatch Libraries → + /// Other Library…), for the Graph Column and Graph Marker dialogs; not saved. + pub graph_design_libraries: cmd::swatchlib::DesignLibraries, /// The selected freeform gradient point (`paint.freeform.selectPoint`) and whose gradient it /// was selected on: read it with [`Session::selected_freeform_point`]. pub(crate) freeform_point: Option<(usize, cmd::gradient::StopOwner)>, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 83e6368f8b..a641bf255c 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -78,6 +78,7 @@ impl Session { recent_colors: vec![], pending_paint: None, swatch_libraries: Default::default(), + graph_design_libraries: Default::default(), freeform_point: None, style_libraries: Default::default(), symbol_libraries: Default::default(), diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 75659920e5..8c0c536542 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -9,8 +9,12 @@ //! For Fractions; OK runs `graph.column`. //! Marker: the design the selected graph series draw their data points with, or None (the default //! square marker); OK runs `graph.marker`. +//! Column and Marker also list, under each library's name, the graph designs of the documents +//! Window › Swatch Libraries › Other Library… loaded that the document lacks; OK on one copies it +//! into the document with the resources its art uses. //! //! Fields: `selected` (the selected designs' names; Column and Marker: one name, null for None), +//! in Column and Marker `library` (the library of the selected design, null for the document's), //! in Graph Design `name` (the name Rename gives), and in Column `columnType`, `each` and //! `fractions`. @@ -46,6 +50,7 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec { confirm: |app, d| { let p = json!({ "design": d.fields.get("selected").and_then(Value::as_str), + "library": library_of(d), "columnType": d.str("columnType"), "each": d.f64("each", vectorcraft_doc::ColumnDesign::EACH), "fractions": d.str("fractions"), @@ -59,7 +64,9 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec { pub(super) const MARKER_SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Graph Marker").into(), body: marker_body, - confirm: |app, d| run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str) })), + confirm: |app, d| { + run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str), "library": library_of(d) })) + }, min_width: 300.0, ..DialogSpec::FORM }; @@ -95,6 +102,24 @@ fn names(app: &VectorcraftApp) -> Result, String> { Ok(st.doc.graph_designs.iter().map(|d| d.name.clone()).collect()) } +/// The designs of the loaded libraries that the document lacks (the document's own design of a name +/// is the one used), by library: its id, its name and the design names, libraries with none left +/// out. +fn library_designs(app: &VectorcraftApp) -> Vec<(String, String, Vec)> { + let own = names(app).unwrap_or_default(); + app.session + .graph_design_libraries + .iter() + .map(|l| (l.id.clone(), l.name.clone(), l.doc.graph_designs.iter().map(|g| g.name.clone()).filter(|n| !own.contains(n)).collect::>())) + .filter(|(.., names)| !names.is_empty()) + .collect() +} + +/// Column and Marker's `library`: the library of the selected design, `None` for the document's. +fn library_of(d: &Dialog) -> Option<&str> { + d.fields.get("library").and_then(Value::as_str) +} + /// Graph Design's selected designs. fn selected(d: &Dialog) -> Vec { d.fields.get("selected").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default() @@ -105,8 +130,9 @@ fn select(d: &mut Dialog, names: Vec) { d.fields.insert("selected".into(), json!(names)); } -/// A design's art drawn in `r` (cached by the art's identity). -fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) { +/// A design's art drawn in `r` (cached by the art's identity): the document's design `name`, or +/// with `library` that loaded library's. +fn preview(ui: &egui::Ui, app: &VectorcraftApp, library: Option<&str>, name: &str, r: egui::Rect) { use std::cell::RefCell; use std::collections::HashMap; thread_local! { @@ -114,11 +140,18 @@ fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) { static CACHE: crate::graphics::TexCache> = crate::graphics::TexCache::default(); } let Some(st) = app.session.active() else { return }; - let Some(art) = st.doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return }; + let doc = match library { + Some(id) => match app.session.graph_design_libraries.get(id) { + Some(l) => &l.doc, + None => return, + }, + None => &st.doc, + }; + let Some(art) = doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return }; let key = std::sync::Arc::as_ptr(&art) as usize; let px = (r.width() * ui.ctx().pixels_per_point()).round() as u32; let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).or_else(|| { - let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(&st.doc, &art, px.max(16), Some([255, 255, 255, 255])))?; + let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(doc, &art, px.max(16), Some([255, 255, 255, 255])))?; let color = crate::canvas::color_image(&img); let tex = ui.ctx().load_texture(format!("graph-design-{key}"), color, egui::TextureOptions::LINEAR); CACHE.with(|c| { @@ -177,7 +210,7 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover()); ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside); if let Some(n) = &one { - preview(ui, app, n, r.shrink(4.0)); + preview(ui, app, None, n, r.shrink(4.0)); } ui.add_space(6.0); let button = @@ -220,37 +253,66 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b false } -/// The list of Column and Marker: None, then the designs `names`; a click picks one into `selected` (null for None). -fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], salt: &str) { +/// The list of Column and Marker: None, the document's designs `names`, then each loaded library's +/// name and the designs of it in `libraries` ([`library_designs`]); a click picks one into +/// `selected` (null for None) and its library into `library` (null for the document's). +fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], libraries: &[(String, String, Vec)], salt: &str) { widgets::list_box(ui, |ui| { egui::ScrollArea::vertical().id_salt(salt).min_scrolled_height(160.0).max_height(160.0).show(ui, |ui| { ui.set_width(ui.available_width()); ui.set_min_height(160.0); let current = d.fields.get("selected").and_then(Value::as_str).map(str::to_string); + let from = library_of(d).map(str::to_string); + let pick = |d: &mut Dialog, name: Option<&str>, library: Option<&str>| { + d.fields.insert("selected".into(), json!(name)); + d.fields.insert("library".into(), json!(library)); + }; if ui.selectable_label(current.is_none(), tl!("None")).clicked() { - d.fields.insert("selected".into(), Value::Null); + pick(d, None, None); } for n in names { - if ui.selectable_label(current.as_deref() == Some(n.as_str()), n.as_str()).clicked() { - d.fields.insert("selected".into(), json!(n)); + if ui.selectable_label(from.is_none() && current.as_deref() == Some(n.as_str()), n.as_str()).clicked() { + pick(d, Some(n), None); + } + } + for (id, library, designs) in libraries { + ui.add_space(4.0); + // The library's own name, not interface text. + widgets::dim_name(ui, library); + for n in designs { + let on = from.as_deref() == Some(id.as_str()) && current.as_deref() == Some(n.as_str()); + if ui.selectable_label(on, n.as_str()).clicked() { + pick(d, Some(n), Some(id)); + } } } }); }); } +/// The design Column or Marker has selected, with its library (`None`: the document's), when the +/// document or that library still has it. +fn shown_design(d: &Dialog, names: &[String], libraries: &[(String, String, Vec)]) -> Option<(Option, String)> { + let n = d.fields.get("selected").and_then(Value::as_str)?; + match library_of(d) { + None => names.iter().any(|x| x == n).then(|| (None, n.to_string())), + Some(id) => libraries.iter().any(|(l, _, designs)| l == id && designs.iter().any(|x| x == n)).then(|| (Some(id.to_string()), n.to_string())), + } +} + fn column_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let names = names(app).unwrap_or_default(); + let libraries = library_designs(app); ui.horizontal_top(|ui| { ui.vertical(|ui| { ui.set_width(220.0); - one_design_list(ui, d, &names, "graph-columns"); + one_design_list(ui, d, &names, &libraries, "graph-columns"); }); ui.add_space(10.0); let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover()); ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside); - if let Some(n) = d.fields.get("selected").and_then(Value::as_str).filter(|n| names.iter().any(|x| x == n)) { - preview(ui, app, n, r.shrink(4.0)); + if let Some((library, n)) = shown_design(d, &names, &libraries) { + preview(ui, app, library.as_deref(), &n, r.shrink(4.0)); } }); ui.add_space(8.0); @@ -277,9 +339,10 @@ const EACH_RANGE: std::ops::RangeInclusive = 0.0001..=1_000_000_000.0; fn marker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let names = names(app).unwrap_or_default(); + let libraries = library_designs(app); // A list as wide as Graph Design's, not the whole window. ui.set_width(220.0); - one_design_list(ui, d, &names, "graph-markers"); + one_design_list(ui, d, &names, &libraries, "graph-markers"); false } @@ -377,4 +440,33 @@ mod tests { (super::COLUMN_SPEC.confirm)(&mut app, &d).unwrap(); assert_eq!(app.session.execute("graph.column", &json!({})).unwrap()["design"], json!(null)); } + + #[test] + fn marker_lists_a_loaded_documents_designs_and_ok_copies_the_one_picked_in() { + // A document with design "New Design", loaded as a swatch library (Other Library…). + let src = app_with_design(); + let bytes = vectorcraft_format::save_file(&src.session.active().unwrap().doc); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Dots.vectorcraft"}); + app.run("swatch.library.load", p).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let g = app.run("graph.create", json!({"type": "line", "x": 100, "y": 100, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [g]})).unwrap(); + let libraries = super::library_designs(&app); + assert_eq!(libraries.len(), 1); + let (id, _, designs) = &libraries[0]; + assert_eq!(designs, &["New Design".to_string()]); + crate::menus::invoke(&mut app, "graph.marker", json!({})); + frame(&mut app); + let mut d: Dialog = app.ui.dialog.take().unwrap(); + d.fields.insert("selected".into(), json!("New Design")); + d.fields.insert("library".into(), json!(id)); + app.ui.dialog = Some(d.clone()); + frame(&mut app); + (super::MARKER_SPEC.confirm)(&mut app, &d).unwrap(); + assert_eq!(app.session.execute("graph.marker", &json!({})).unwrap()["design"], "New Design"); + assert_eq!(super::names(&app).unwrap(), ["New Design"]); + // The document has it now, so the library lists it no more. + assert!(super::library_designs(&app).is_empty()); + } } diff --git a/docs/mcp.md b/docs/mcp.md index fc4430a08f..e580eb51be 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4413,7 +4413,18 @@ document's swatches, as a library to add from. From an `.ase` file it reads RGB, spot or process swatches and keeps their color groups. A color book (such as a Pantone book you own) gives its RGB, CMYK or Lab colors named with the book's prefix and suffix ("PANTONE 185 C"), as spot colors unless the book marks them as process colors; `.acb` files are read, never written. A file in the user library folder, or a file with the -same extension and bytes as one there, loads as that User Defined library (category `user`). +same extension and bytes as one there, loads as that User Defined library (category `user`). A file larger than 256 MB +is refused before it is read. A document's graph designs come with it: the reply's `graphDesigns` counts them, and +`graph.column`, `graph.marker` and `graph.design` take the library's id as `library` until the app quits (a User +Defined copy made with `swatch.library.copyToUser` holds the swatches alone, so the designs stay under the loaded id). +`graph.column {design, library}` and `graph.marker {design, library}` copy a design the document lacks into it, with the +swatches, patterns, symbols, styles, brushes and images its art uses, in the same undo step as the graph change. +`graph.design {library, add: name | [names]}` copies designs without applying them and returns `{added, existing}`, and +`graph.design {library}` lists the library's designs. A design the document already has under the same name stays as it +is. With no `design`, `graph.column`, `graph.marker` and `graph.design` list the loaded libraries that hold designs as +`libraries: [{library, name, designs}]`. Copying a graph and pasting it into another document brings the designs its series +draw with in the same way; a pasted graph is drawn again with the document's design of that name when that design +would draw it otherwise. `swatch.library.copyToUser {library}` copies a loaded library into the user library folder of the desktop app (a library file as it is; a document's swatches or a library loaded from `data` or `dataBase64` as `.vcswatches`) under a name no file there has, and lists it as User Defined from then on; until the app diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ae0a2f2b92..5383de7f48 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1164,6 +1164,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur What Global Edit gives a mark from another match (in an isolated graph) is kept on the graph the same way, and so is the object opacity, with its blend mode, that Randomize Opacity and Sort Objects change on marks. - **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete. Type in a column design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits: the first digit is the least number of places before the decimal point (zeros are added in front; 0 gives as many as the value needs), and the second digit sets the places after it, rounded. Unless it is inside a group that clips or has its own opacity or appearance, or inside a blend, compound shape, envelope, repeat or intertwined objects, the type keeps its size and is drawn once per column in a repeating design. The legend swatch leaves it out. + - **Graph designs from another document** ([Import a column or marker design](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=486)): a document opened with Window › Swatch Libraries › Other Library… adds its graph designs to the Column and Marker dialogs, listed under the library's name after the document's own. OK on one of them copies the design into the document with the swatches, patterns, symbols and styles its art uses, in the same undo step as the graph change (`graph.column` and `graph.marker` with `library`; `graph.design {library, add}` copies designs without applying them). A graph that is copied and pasted into another document brings the designs its series draw with. A design the document already has under the same name stays as it is, and a pasted graph is drawn again with that design when it would draw the graph otherwise, a VectorCraft rule. Tests: `designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied`, `a_design_the_document_has_under_the_same_name_stays_as_it_is`, `a_pasted_graph_brings_the_designs_its_series_draw_with` in `crates/engine/src/cmd/graph/tests.rs`. - **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681; Scale Artwork with Artboard, in the Control bar and Properties beside Move Artwork with Artboard, resizes the artboard proportionally with the art fully inside it and its guides, strokes and corners per the Scale preferences, #602), Measure, Type, Hand, Zoom, Rotate View. While a drag rotates the view, a dial at the center of the canvas shows the angle. - **Editing type:** double-clicking type with a selection tool (Selection or Direct Selection) switches to the Type tool with the caret where it was clicked; pressing Escape finishes editing and switches back to the selection tool used before double-clicking it (when in isolation mode, the first Escape exits text editing while preserving isolation mode, and a second Escape exits isolation). From 60fe72537d04a0b44cc0834766c6b9fea16272fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 21:37:28 -0800 Subject: [PATCH 06/69] Image Trace: opened preset files stop at the size limit and long name lists scroll File > Open and a drop read a .vctracepresets file no further than one byte past the 4 MiB limit, as Import... does, instead of reading the whole file before the check. The question about replacing saved presets scrolls its list of names, so Replace and Cancel stay on screen. --- crates/ui-egui/src/dialogs/tracing_presets.rs | 18 +++++- .../src/dialogs/tracing_presets/tests.rs | 58 +++++++++++++++++++ crates/ui-egui/src/io/open.rs | 6 ++ 3 files changed, 80 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tracing_presets.rs b/crates/ui-egui/src/dialogs/tracing_presets.rs index 4fe9cedd58..57abc052b3 100644 --- a/crates/ui-egui/src/dialogs/tracing_presets.rs +++ b/crates/ui-egui/src/dialogs/tracing_presets.rs @@ -61,7 +61,10 @@ pub(super) const REPLACE_SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Replace the saved presets that have these names?").into(), body: |_, ui, d| { let names: Vec<&str> = d.fields.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); - ui.label(egui::RichText::new(names.join("\n")).color(Tokens::get(ui.ctx()).text_dim)); + // A long list scrolls, so Replace and Cancel stay on screen. + super::modal::scrolled_rows(ui, "tracing-replace-names", |ui| { + ui.label(egui::RichText::new(names.join("\n")).color(Tokens::get(ui.ctx()).text_dim)); + }); false }, confirm: confirm_replace, @@ -267,7 +270,18 @@ pub(crate) fn open_file(app: &mut VectorcraftApp, bytes: &[u8]) -> Result<(), St if bytes.len() > TRACE_PRESET_MAX_BYTES { return Err(too_big()); } - let file = json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }); + open_import(app, json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) })) +} + +/// [`open_file`] for the tracing presets file at `path` (File › Open, a drop): the file is read no +/// further than one byte past the size limit, as Import… reads it. +pub(crate) fn open_path(app: &mut VectorcraftApp, path: &str) -> Result<(), String> { + let file = file_contents(app, json!({ "path": path }))?; + open_import(app, file) +} + +/// The import of an opened tracing presets file `file` (`{dataBase64}`), over the dialog open now. +fn open_import(app: &mut VectorcraftApp, file: Value) -> Result<(), String> { let (imported, skipped) = import_file(app, &file)?; let mut under = app.ui.dialog.take(); if let (Some(d), Some(first)) = (under.as_mut().filter(|d| d.kind == KIND), imported.get(0).and_then(Value::as_str)) { diff --git a/crates/ui-egui/src/dialogs/tracing_presets/tests.rs b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs index 4ef5217420..5f0cc5e385 100644 --- a/crates/ui-egui/src/dialogs/tracing_presets/tests.rs +++ b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs @@ -327,3 +327,61 @@ fn a_file_with_a_fault_changes_nothing() { assert!(app.session.prefs.trace_presets.is_empty()); let _ = std::fs::remove_dir_all(dir); } + +/// File › Open reads a tracing presets file no further than one byte past the size limit, and +/// refuses a larger one, without the whole-file reader. +#[test] +fn an_opened_file_is_read_no_further_than_the_limit() { + let dir = std::env::temp_dir().join(format!("vc-tracing-presets-open-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let fine = dir.join("fine.vctracepresets"); + std::fs::write(&fine, r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Fine", "params": {}}]}"#).unwrap(); + let big = dir.join("big.vctracepresets"); + std::fs::write(&big, vec![b' '; TRACE_PRESET_MAX_BYTES + 1]).unwrap(); + let read_head = |p: &str, max: usize| { + use std::io::Read as _; + assert_eq!(max, TRACE_PRESET_MAX_BYTES + 1); + let mut bytes = vec![]; + std::fs::File::open(p).and_then(|f| f.take(max as u64).read_to_end(&mut bytes)).map_err(|e| e.to_string())?; + Ok(bytes) + }; + let read = |p: &str| -> Result, String> { Err(format!("`{p}` was read in full")) }; + let services = crate::Services { read_head: Some(Box::new(read_head)), read: Some(Box::new(read)), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + crate::io::open_path(&mut app, &fine.to_string_lossy()).unwrap(); + assert_eq!(saved_names(&app), ["Fine"]); + let e = crate::io::open_path(&mut app, &big.to_string_lossy()).unwrap_err(); + assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}"); + assert_eq!(saved_names(&app), ["Fine"]); + let _ = std::fs::remove_dir_all(dir); +} + +/// The question's list of names scrolls, so a long one keeps Replace and Cancel on a small screen. +#[test] +fn a_long_list_of_names_keeps_replace_on_screen() { + fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let names: Vec = (0..200).map(|i| json!(format!("Tracing Preset {i}"))).collect(); + app.ui.dialog = Some(ask_replace(None, names, json!({ "dataBase64": "" }))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 600.0)); + let mut texts = vec![]; + for k in 0..6 { + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + texts.clear(); + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + } + for button in ["Replace", "Cancel"] { + let rect = texts.iter().find(|(t, _)| t == button).map(|(_, r)| *r); + assert!(rect.is_some_and(|r| screen.contains_rect(r)), "{button} is drawn on screen: {rect:?}"); + } +} diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 632cdc5f94..5732b87139 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -552,6 +552,12 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va note_recent(app, path); return Ok(Value::Null); } + // A tracing presets file is read up to its size limit, as Import… reads it. + if let Some(OpensAs::Presets { import: "imageTrace.presets.import", .. }) = opens_as(path) { + dialogs::tracing_presets::open_path(app, path)?; + note_recent(app, path); + return Ok(Value::Null); + } // A file only an importer plug-in reads is not read past the importer's input limit. check_import_size(path, false)?; let mut bytes = read(app, path)?; From 2ffaa673fedab7f562a0c4477ada46256396b657 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 22:12:33 -0800 Subject: [PATCH 07/69] 3D and Materials: graphics map onto Inflate objects A Materials-tab graphic now lies on Inflate's puffed front, and on its puffed back when Both sides and Cap are on. The graphic is placed in the art's plane with the same X, Y, Scale and Rotation as on a cap and is carried straight out onto the puff, so it follows the membrane; Twist and Taper turn and shrink the back's graphics with it. The membrane is cut into triangles that draw their part of the graphic shaded with them and only where the outside faces the viewer, in Revolve's side order with its seams and limits. The blue handle sits on the puffed face. threeD.mapGraphic refuses a back graphic on Inflate without Both sides and Cap, and changing the type to Inflate keeps the graphics. The panel note, the params text and docs/three-d.md, docs/mcp.md and docs/effects-parity.md list Inflate. --- crates/effects/src/catalog.rs | 4 +- crates/effects/src/revolve.rs | 10 +- crates/effects/src/revolve/tests_graphics.rs | 6 +- crates/effects/src/solids.rs | 155 ++++++++++- crates/effects/src/solids/graphics.rs | 243 ++++++++++++++---- crates/effects/src/solids/tests.rs | 2 + crates/effects/src/solids/tests_graphics.rs | 85 +++++- crates/engine/src/cmd/effectcmd/graphics.rs | 12 +- .../src/cmd/effectcmd/graphics_tests.rs | 33 ++- crates/three-d/src/solid.rs | 16 +- crates/three-d/src/solid/build.rs | 2 + crates/three-d/src/solid/inflate.rs | 65 ++++- crates/three-d/src/solid/tests.rs | 43 +++- .../ui-egui/src/dialogs/three_d_materials.rs | 6 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 4 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/gu.tsv | 2 +- crates/ui-egui/src/i18n/hi.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 4 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 4 +- crates/ui-egui/src/i18n/zh-hant.tsv | 4 +- crates/ui-egui/src/panels/tests_three_d.rs | 8 +- docs/effects-parity.md | 2 +- docs/mcp.md | 8 +- docs/three-d.md | 29 ++- 43 files changed, 656 insertions(+), 131 deletions(-) diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 1c1ca96d9f..06db1cb2b3 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -196,8 +196,8 @@ pub fn effect_catalog() -> Vec { INFLATE, "Inflate…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. Painted with the top fill (else the top stroke).", - json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}), + "{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer)}. Painted with the top fill (else the top stroke).", + json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}), ), g( ROTATE, diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index a9c9482d1d..7c2ac3ff56 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -6,7 +6,7 @@ use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind}; use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2}; -use vectorcraft_three_d::{Edge, Revolve, SolidFaces}; +use vectorcraft_three_d::{Edge, PlanarFace, Revolve, SolidFaces}; use crate::solids::wireframe::WireFace; use crate::solids::{ @@ -162,7 +162,7 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) // With no member to carry them, the graphics' art must still fit its limits. None => { crate::solids::graphics::validate_symbols(doc, p)?; - crate::solids::graphics::validate_surface_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?; } } } @@ -191,10 +191,10 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op let graphics = crate::solids::mapped_graphics(p); let Some(doc) = doc.filter(|_| id == REVOLVE && !graphics.is_empty()) else { return Ok(()) }; crate::solids::graphics::validate_symbols(doc, p)?; - crate::solids::graphics::validate_surface_symbols(doc, p)?; + crate::solids::graphics::validate_surface_symbols(doc, p, PlanarFace::Front)?; let faces = vectorcraft_three_d::revolve(path, b, options)?; let mut used = *copies; - match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), &mut used) { + match crate::solids::graphics::surface_parts(Some(doc), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), &mut used) { Some(_) => { *copies = used; Ok(()) @@ -481,7 +481,7 @@ fn surface( let mut parts = if graphics.is_empty() { vec![] } else { - match crate::solids::graphics::surface_parts(doc, n.id, &graphics, &faces, &shade, &mut used) { + match crate::solids::graphics::surface_parts(doc, n.id, (&graphics, PlanarFace::Front), &faces, &shade, &mut used) { Some(parts) => { copies.graphics = used; parts diff --git a/crates/effects/src/revolve/tests_graphics.rs b/crates/effects/src/revolve/tests_graphics.rs index 5d9500628b..0d39d6dfe1 100644 --- a/crates/effects/src/revolve/tests_graphics.rs +++ b/crates/effects/src/revolve/tests_graphics.rs @@ -365,7 +365,8 @@ fn revolve_takes_graphics_on_its_side_only() { let kept = three_d_params_as(crate::EXTRUDE, &both, REVOLVE); assert_eq!(kept["graphics"].as_array().map(Vec::len), Some(1)); assert_eq!(kept["graphics"][0]["symbol"], "Red"); - assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE).get("graphics"), None); + // Inflate keeps them, and its front takes them. + assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE)["graphics"], front["graphics"]); } #[test] @@ -503,7 +504,8 @@ fn the_copies_of_a_graphics_paint_have_a_budget_of_their_own() { let faces = vectorcraft_three_d::revolve(path, path.bounds().unwrap(), options_of(REVOLVE, &p)).unwrap(); let parts_of = |symbol: &str, copies: &mut usize| { let graphics = crate::solids::mapped_graphics(&json!({"graphics": [{"symbol": symbol}]})); - crate::solids::graphics::surface_parts(Some(&d), NodeId(0), &graphics, &faces, &|_, c| Paint::solid(c), copies).map(|p| p.concat().len()) + crate::solids::graphics::surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Front), &faces, &|_, c| Paint::solid(c), copies) + .map(|p| p.concat().len()) }; // Each opaque part copies the paint into its fill and its seam stroke; a part with // transparent stops takes no seam stroke and copies it once. diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index c0d44947d7..b8323084f8 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -173,6 +173,7 @@ pub fn inflate_options(p: &Value) -> Inflate { twist: num(p, "twist", 0.0), taper: num(p, "taper", 100.0) / 100.0, cap: flag(p, "cap", true), + map_surface: false, } } @@ -324,6 +325,7 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; check_profiles(id, p, &shapes, b)?; check_solids(id, p, &shapes)?; + check_membrane_graphics(doc, n, id, p, &shapes)?; return cast_shadow(id, p, &shapes).map(|_| ()); } let (path, rule) = object_profile(n, label)?; @@ -342,9 +344,33 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; check_profiles(id, p, &shapes, b)?; check_solids(id, p, &shapes)?; + check_membrane_graphics(doc, n, id, p, &shapes)?; cast_shadow(id, p, &shapes).map(|_| ()) } +/// An error when the graphics of Inflate `id` with parameters `p`, with the symbols of `doc`, are +/// past their limits on the front and puffed back of the solids of `shapes`: their art, or the +/// parts they draw on its pieces ([`graphics::surface_parts`]), or when the solids can't be built +/// with their pieces carrying the graphics. They are built as the art builds them +/// ([`surfaces_with`]). Without `doc` nothing is drawn, and nothing is checked. +fn check_membrane_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { + let Some(doc) = doc else { return Ok(()) }; + if id != INFLATE || mapped_graphics(p).is_empty() { + return Ok(()); + } + for face in PlanarFace::ALL { + graphics::validate_surface_symbols(doc, p, face)?; + } + let fx = Effect { id: id.into(), params: p.clone(), visible: true }; + let mut dropped = false; + // Art that can't be built with the graphics draws without them. + let built = surfaces_with(Some(doc), n, &fx, shapes, false, true, &mut dropped); + if dropped || built.is_none() { + return Err("The graphics are too complex: simplify the symbols' art".into()); + } + Ok(()) +} + /// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b` /// build? Only the profiles no solid of [`check_solids`] is built from are built here: every /// shape's for Rotate, and for Extrude & Bevel and Inflate the profile of a shape with no fill, @@ -632,6 +658,55 @@ fn surface(n: &Node, facets: Vec, paint: &Paint, opacity: f32, blend: Ble group } +/// The parts of `graphics` that fall on each of `facets`, the facets of one of Inflate's solids in +/// drawing order, built with their front and puffed back carrying the graphics +/// ([`vectorcraft_three_d::Inflate::map_surface`]): for each facet, the parts of the graphics on +/// its face to draw right after it ([`graphics::surface_parts`]), shaded as a solid color is on +/// that facet. `copies` counts the bytes of the paint copies of the object's graphics. `None` past +/// the graphics' limits. +fn membrane_parts( + doc: Option<&Document>, + id: NodeId, + graphics: &[MappedGraphic], + facets: &[Facet], + copies: &mut usize, +) -> Option>>> { + let shade = |f: &graphics::OnFace<'_>, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.facet.illumination)); + let mut out: Vec>> = vec![vec![]; facets.len()]; + for face in PlanarFace::ALL.into_iter().filter(|face| graphics.iter().any(|g| g.face == *face)) { + let on: Vec> = facets.iter().map(|facet| graphics::OnFace { facet, face }).collect(); + let parts = graphics::surface_parts(doc, id, (graphics, face), &on, &shade, copies)?; + for (slot, extra) in out.iter_mut().zip(parts) { + slot.extend(extra); + } + } + Some(out) +} + +/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by +/// the parts of the graphics that `parts` holds for its facet ([`membrane_parts`]): a face with +/// parts becomes a group of the face and its parts, so nearer faces drawn after it cover them too. +/// `surface` is returned as it is when no facet has a part or it is not such a group. +fn with_surface_parts(id: NodeId, mut surface: Node, parts: Vec>>) -> Node { + if parts.iter().all(Vec::is_empty) { + return surface; + } + let NodeKind::Group { children, clip: false } = &mut surface.kind else { return surface }; + if children.len() != parts.len() { + return surface; + } + for (child, extra) in children.iter_mut().zip(parts) { + if extra.is_empty() { + continue; + } + let mut list = Vec::with_capacity(extra.len() + 1); + list.push(child.clone()); + list.extend(extra); + *child = Arc::new(Node::group(id, list)); + } + surface +} + /// The width of the stroke of a facet's own paint that closes the seams between `face` and its /// neighbors. No wider than the facet is thick: seen at a grazing angle a facet can be thinner than /// the stroke, and its stroke would then paint over its neighbors. @@ -740,7 +815,7 @@ fn built_solids<'a>( bounds: Rect, limit: usize, ) -> impl Iterator>, String>> + 'a { - built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f))) + built_solids_cast(id, p, parts, bounds, limit, false, false).map(|r| r.map(|s| s.map(|(f, _)| f))) } /// One solid's facets and, when its shadow is cast, the faces it is cast from. @@ -751,7 +826,9 @@ type CastingSolid = (Vec, Option); type SurfacesAndFaces = (Vec>, Vec>); /// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow -/// is cast from, from the same build ([`SolidFaces`]). +/// is cast from, from the same build ([`SolidFaces`]). With `membrane`, Inflate's solids are built +/// with the pieces of their front and puffed back carrying where they lie in the art's plane, for +/// the graphics drawn on them ([`vectorcraft_three_d::Inflate::map_surface`]). fn built_solids_cast<'a>( id: &'a str, p: &'a Value, @@ -759,11 +836,12 @@ fn built_solids_cast<'a>( bounds: Rect, limit: usize, cast: bool, + membrane: bool, ) -> impl Iterator, String>> + 'a { // Inflate's eye is placed for every puff together, as far away as the highest needs. let mut inflated = (id == INFLATE).then(|| -> Box>> { let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect(); - let (o, view) = (inflate_options(p), view_options(p)); + let (o, view) = (Inflate { map_surface: membrane, ..inflate_options(p) }, view_options(p)); if cast { Box::new(vectorcraft_three_d::inflate_shadowed(&shapes, bounds, o, view).map(|r| r.map(|(f, faces)| (f, Some(faces))))) } else { @@ -1720,8 +1798,32 @@ fn seen_ends(f: &[Facet]) -> impl Iterator { /// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar /// faces drawn right after the last of the solids' surfaces that holds that face. With `cast`, each /// solid built also keeps the faces its shadow is cast from, from the same build, in the order the -/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. +/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. Inflate's +/// graphics are drawn on the pieces of its front and puffed back; when its solids can't be built +/// with those pieces, or the graphics are past their limits on them, the solids draw without them. fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option { + let p = crate::merged_params(&fx.id, &fx.params); + if fx.id == INFLATE && doc.is_some() && !mapped_graphics(&p).is_empty() { + let mut dropped = false; + if let Some(built) = surfaces_with(doc, n, fx, shapes, cast, true, &mut dropped).filter(|_| !dropped) { + return Some(built); + } + } + surfaces_with(doc, n, fx, shapes, cast, false, &mut false) +} + +/// [`surfaces_for`], with `membrane` building Inflate's solids with their front and puffed back +/// carrying the graphics ([`built_solids_cast`]), and setting `dropped` when those graphics are past +/// their limits on the pieces drawn and the solids draw without them. +fn surfaces_with( + doc: Option<&Document>, + n: &Node, + fx: &Effect, + shapes: &[Profile], + cast: bool, + membrane: bool, + dropped: &mut bool, +) -> Option { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; @@ -1766,7 +1868,8 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile let (parts, bounds) = solid_parts(shapes, b); let mut solids = vec![]; let mut built = vec![]; - for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) { + let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane); + for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(made) { let item: &AppearanceItem = item; match f { Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { @@ -1776,8 +1879,12 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile solids.push((item, *opacity, *scopes, f, *member)); built.push(faces); } - // A stroke's outline past the limits is left out; the fill's solid still draws. - Ok(None) => built.push(None), + // A stroke's outline past the limits is left out; the fill's solid still draws. Built + // with the graphics' pieces, a stroke past the limits draws without the graphics. + Ok(None) => { + built.push(None); + *dropped |= membrane; + } // A loaded file or a shape edited past the limits (its own, or those of the object's // solids together) keeps drawing its source path instead of failing the frame; // commands validate the same evaluator and report its errors. @@ -1861,6 +1968,9 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile // ([`in_one_order`], [`underlaid_surface`]). let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); let seal = |range: std::ops::Range| seals.get(range).is_some_and(|s| s.iter().any(|s| *s)); + let membrane_graphics = if membrane && graphics_on { mapped_graphics(&p) } else { vec![] }; + // The paint copies of Inflate's graphics, apart from those of the surfaces, as on Revolve. + let mut graphic_copies = 0usize; let surfaces: Vec = solids .into_iter() .map(|(item, member, scopes, f, shape)| { @@ -1868,10 +1978,21 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile let depths: Vec = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); let (paint, opacity, blend) = paint_of(item, member); + // The pieces of Inflate's front and back draw the parts of the graphics that fall on + // them; past the graphics' limits the solid draws without them. + let parts = if membrane_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) { + vec![] + } else { + let parts = membrane_parts(doc, n.id, &membrane_graphics, &f, &mut graphic_copies); + *dropped |= parts.is_none(); + parts.unwrap_or_default() + }; + let drawn = parts.iter().any(|p| !p.is_empty()); let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { - surface(n, f, &paint, opacity, blend, colored, split && shared.get(shape).copied().unwrap_or(false)) + let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false)); + with_surface_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts) }; (depths, art, scopes, ends) }) @@ -2157,14 +2278,15 @@ fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option { /// Where the graphics of the 3D effect of `n` (on the object itself with `item` `None`, else on its /// fill or stroke `item`) are drawn: the bounds its solids are built with and the maps of their -/// planar faces ([`graphics::GraphicFrame`]). `None` when `n` has no visible Extrude & Bevel or -/// Rotate there, or its art can't be built. +/// planar faces, or Inflate's puffed faces ([`graphics::GraphicFrame`]). `None` when `n` has no +/// visible Extrude & Bevel, Inflate or Rotate there, or its art can't be built. pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option) -> Option { frame_of(doc, n, item, &solid) } /// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude & -/// Bevel, Rotate or Revolve. Revolve's frame is its unrolled side seen from the front, centered on +/// Bevel, Rotate, Revolve or Inflate. Inflate's frame places handles on the pieces of its puffed +/// front and back the viewer sees. Revolve's frame is its unrolled side seen from the front, centered on /// the origin, with no face maps: it sizes a new graphic and places no handles. pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option, index: usize) -> Option { frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && is_three_d(&e.id)).map(|e| (index, e))) @@ -2231,7 +2353,16 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' let plane = vectorcraft_three_d::plane_face_map(b, view); return Some(graphics::GraphicFrame::new(b, plane, None)); } - let (_, bounds) = solid_parts(&shapes, b); + let (parts, bounds) = solid_parts(&shapes, b); + if fx.id == INFLATE { + // Inflate's graphics lie on its puffed front and back: the pieces the viewer sees place + // their handles. Solids that can't be built place none. + let built: Vec = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true) + .filter_map(|r| r.ok().flatten()) + .flat_map(|(f, _)| f) + .collect(); + return Some(graphics::GraphicFrame::inflated(bounds, graphics::MembraneFrame::of(&built))); + } let options = extrude_options(&p); let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face); Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back))) diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 7c0087e15b..1d7e4e8d45 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -13,7 +13,14 @@ //! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the //! middle of that surface, x around the axis and y along the profile, and each face of the side //! draws the part of the graphics that falls on it ([`surface_parts`]). +//! +//! On Inflate the graphics lie on the puffed front, and on the puffed back when Both Sides is on: +//! each is placed in the art's plane as on Extrude & Bevel's caps and carried straight out onto +//! the surface above it, so it follows the puff. Each piece of the surface draws the part of the +//! graphics that falls on it, as on Revolve's side, and the twist and taper carry the back's +//! graphics with the back. +use std::borrow::Cow; use std::sync::Arc; use serde_json::{Map, Value, json}; @@ -47,7 +54,7 @@ const MAX_NESTING: usize = 8; const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH; /// The error for graphics on a 3D effect that takes none. -pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude and Revolve object types"; +pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude, Revolve and Inflate object types"; /// The buckets around the unrolled side surface that the pieces of Revolve's graphics are sorted /// into, so each face looks only at the pieces near it. @@ -148,10 +155,10 @@ impl MappedGraphic { } } -/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane) and Revolve -/// (its swept side). +/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane), Revolve (its +/// swept side) and Inflate (its puffed front and back). pub fn takes_graphics(id: &str) -> bool { - id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE + id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE || id == super::INFLATE } /// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold @@ -163,9 +170,9 @@ pub fn mapped_graphics(p: &Value) -> Vec { } } -/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and -/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named -/// the front. +/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate, +/// Revolve and Inflate take graphics; a plane has only a front, and Revolve's graphics go on its +/// side, named the front. pub fn validate(id: &str, p: &Value) -> Result<(), String> { let list = match p.get(GRAPHICS) { None => return Ok(()), @@ -533,14 +540,15 @@ struct Unrolled { place: Affine, } -/// The areas of `graphics` (those of the front: Revolve's side) placed on the unrolled side -/// surface, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is +/// The areas of `graphics` on `face` (the front, for Revolve's side; Inflate's front or back) +/// placed on the unrolled side surface, or in the art's plane about the center of the object's +/// bounds, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is /// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than /// [`MAX_ELEMENTS`] points together. -fn unrolled(doc: &Document, graphics: &[MappedGraphic]) -> Option> { +fn unrolled(doc: &Document, graphics: &[MappedGraphic], face: PlanarFace) -> Option> { let mut pieces = vec![]; let mut points = 0usize; - for g in graphics.iter().filter(|g| g.face == PlanarFace::Front) { + for g in graphics.iter().filter(|g| g.face == face) { let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; let Ok(art) = pieces_of(doc, symbol) else { continue }; let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; @@ -617,20 +625,85 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option> (*points <= MAX_ELEMENTS).then_some(polygons) } -/// Do the graphics in Revolve parameters `p` fit the limits with the symbols of `doc`? Their art, -/// cut into straight pieces on the side surface, may take up to [`MAX_ELEMENTS`] points together. -pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), String> { +/// Do the graphics on `face` in parameters `p` (the front of Revolve; Inflate's front or back) fit +/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the surface, may +/// take up to [`MAX_ELEMENTS`] points together. +pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFace) -> Result<(), String> { let list = mapped_graphics(p); - if list.is_empty() || unrolled(doc, &list).is_some() { + if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() { return Ok(()); } Err("The graphics are too complex: simplify the symbols' art".into()) } -/// The parts of `graphics` that fall on each of `faces`, a revolved surface's faces in drawing -/// order, for an object with id `id`: for each face, the nodes to draw right after it. Only faces -/// of the swept side that show their outside to the viewer carry a part, so a graphic narrows -/// toward the silhouette, is hidden past it and is covered by the nearer faces drawn after it. +/// A face of a surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's swept +/// side, or a piece of Inflate's front or back. +pub(crate) trait SurfaceFace { + /// Where the face lies on the surface, when it carries graphics and shows the surface's outside + /// to the viewer. + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell>; + /// The outline the face's parts are cut to, when it is not the polygon of its cell's corners: + /// its curved outline, when its edges along an end are curved, or the outline of a piece cut + /// from a larger face. + fn curved(&self) -> Option>; + fn rgb_light(&self) -> Option; + fn light(&self) -> [f64; 3]; + fn outline_path(&self) -> PathData; +} + +impl SurfaceFace for vectorcraft_three_d::Face { + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { + self.surface.as_ref().filter(|c| c.outward && !self.cap) + } + fn curved(&self) -> Option> { + self.outline.as_ref().map(Cow::Borrowed) + } + fn rgb_light(&self) -> Option { + self.rgb_gradient + } + fn light(&self) -> [f64; 3] { + self.illumination + } + fn outline_path(&self) -> PathData { + self.path() + } +} + +/// A piece of Inflate's front or back ([`Facet::membrane`]) that carries graphics on `face` only. +pub(crate) struct OnFace<'a> { + pub(crate) facet: &'a Facet, + pub(crate) face: PlanarFace, +} + +impl SurfaceFace for OnFace<'_> { + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { + self.facet.surface.as_ref().filter(|c| c.outward && self.facet.membrane == Some(self.face)) + } + fn curved(&self) -> Option> { + if let Some(outline) = &self.facet.outline { + return Some(Cow::Borrowed(outline)); + } + // A piece of a stroke's face cut where it passes through another face keeps its face's + // cell, and its parts are cut to its own outline. + let cut = self.facet.surface.as_ref().is_some_and(|c| self.facet.contours.len() != 1 || self.facet.contours.first() != Some(&c.page)); + cut.then(|| Cow::Owned(self.facet.path())) + } + fn rgb_light(&self) -> Option { + self.facet.rgb_gradient + } + fn light(&self) -> [f64; 3] { + self.facet.illumination + } + fn outline_path(&self) -> PathData { + self.facet.path() + } +} + +/// The parts of the graphics on `face` of `graphics` (the front of Revolve; Inflate's front or +/// back) that fall on each of `faces`, a surface's faces in drawing order, for an object with id +/// `id`: for each face, the nodes to draw right after it. Only faces of the surface that show their +/// outside to the viewer carry a part, so a graphic narrows toward the silhouette, is hidden past +/// it and is covered by the nearer faces drawn after it. /// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the /// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol /// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past @@ -638,17 +711,17 @@ pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value) -> Result<(), /// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take /// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for /// them: commands refuse such graphics, and a loaded file draws the surface without them. -pub(crate) fn surface_parts( +pub(crate) fn surface_parts( doc: Option<&Document>, id: NodeId, - graphics: &[MappedGraphic], - faces: &[vectorcraft_three_d::Face], - shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + (graphics, face): (&[MappedGraphic], PlanarFace), + faces: &[F], + shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint, copies: &mut usize, ) -> Option>>> { let mut out: Vec>> = vec![vec![]; faces.len()]; let Some(doc) = doc else { return Some(out) }; - let pieces = unrolled(doc, graphics)?; + let pieces = unrolled(doc, graphics, face)?; let Some(all) = pieces.iter().map(|p| p.bounds).reduce(|a, b| a.union(b)) else { return Some(out) }; // Each piece listed in the buckets of the surface's x its bounds reach across. let width = (all.width() / SURFACE_BUCKETS as f64).max(1e-9); @@ -664,11 +737,12 @@ pub(crate) fn surface_parts( let mut cut_points = 0usize; let mut triangle_id = 0usize; for (face, parts) in faces.iter().zip(out.iter_mut()) { - let Some(cell) = face.surface.as_ref().filter(|c| c.outward && !face.cap) else { continue }; + let Some(cell) = face.outer_cell() else { continue }; if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) { continue; } let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + let curved = face.curved(); for corners in triangles { triangle_id += 1; let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::>>(); @@ -679,7 +753,7 @@ pub(crate) fn surface_parts( // where the graphic runs past the end of the profile. A four-cornered face is cut into // two triangles along its diagonal from corner 0 to corner 2: each takes the part of // the outline on its own side of it. - let window = if face.outline.is_some() { grown(window, 3.0) } else { window }; + let window = if curved.is_some() { grown(window, 3.0) } else { window }; // The pieces are looked up over the whole of the window they are cut to. let Some(reach) = window.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { continue }; if reach.x1 < all.x0 || reach.x0 > all.x1 || reach.y1 < all.y0 || reach.y0 > all.y1 { @@ -706,7 +780,7 @@ pub(crate) fn surface_parts( } near.sort_unstable(); let own = corners.iter().find(|k| **k != 0 && **k != 2).and_then(|k| cell.page.get(*k)).filter(|_| triangles.len() == 2); - let rim = face.outline.as_ref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { + let rim = curved.as_deref().map(|outline| match (own, cell.page.first(), cell.page.get(2)) { (Some(&toward), Some(&a), Some(&b)) => { let side = side_of(a, b, toward); vectorcraft_pathops::boolean(outline, FillRule::NonZero, &side, FillRule::NonZero, vectorcraft_pathops::BoolOp::Intersect) @@ -769,21 +843,21 @@ pub(crate) fn surface_parts( /// The node of the part `path` (on the page, filled under `rule`) of `piece`, which `map` takes /// from the unrolled surface onto `face`. -fn surface_piece( +fn surface_piece( id: NodeId, piece: &Unrolled, (path, rule): (BezPath, FillRule), map: Affine, - face: &vectorcraft_three_d::Face, - shade: &dyn Fn(&vectorcraft_three_d::Face, vectorcraft_doc::color::Color) -> Paint, + face: &F, + shade: &dyn Fn(&F, vectorcraft_doc::color::Color) -> Paint, ) -> Node { let gradient_map = map * piece.place; // Under several lights a face's light varies across it in each channel: a solid color draws // as the face's own lit art in that color, clipped to the part. An opaque part also draws that // art clipped to a band of the seam stroke's width around its edges, as the other parts take // a stroke over their seams. - if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_gradient) { - let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.path(), &Paint::solid(c), light)); + if let (Some(c), Some(light)) = (piece.paint.color().filter(|_| matches!(piece.paint, Paint::Solid { .. })), face.rgb_light()) { + let lit = Arc::new(crate::lighting::rgb_gradient_art(id, &face.outline_path(), &Paint::solid(c), light)); let clipped = |area: &BezPath, rule: FillRule| { let mut clip = Node::path(id, PathData::from_bezpath(area), Appearance::default()); if let NodeKind::Path { rule: r, .. } = &mut clip.kind { @@ -816,7 +890,7 @@ fn surface_piece( match solid { Some(c) => f.paint = shade(face, c), None => { - vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.illumination)); + vectorcraft_doc::recolor::map_paint(&mut f.paint, &|c| crate::lighting::shade(c, face.light())); } } } @@ -931,17 +1005,82 @@ pub(super) fn art_bounds(doc: &Document, name: &str) -> Option { } /// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics' -/// offsets are from their center) and the maps of its front and back faces, when it has them. -#[derive(Clone, Copy, Debug, PartialEq)] +/// offsets are from their center), the maps of its front and back faces, when it has them, and +/// for Inflate the pieces of its puffed faces the viewer sees. +#[derive(Clone, Debug, PartialEq)] pub struct GraphicFrame { pub bounds: Rect, front: Option, back: Option, + membrane: Option, +} + +/// The pieces of Inflate's front and puffed back that show their outside to the viewer, as the +/// graphics are drawn on them ([`surface_parts`]): each piece's face, its corners in the art's plane +/// (offsets from the center of the object's bounds) and on the page, and its depth (larger is +/// nearer). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MembraneFrame { + pieces: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +struct MembranePiece { + face: PlanarFace, + uv: [Point; 3], + page: [Point; 3], + depth: f64, +} + +impl MembraneFrame { + /// The pieces of `facets` that carry where they lie in the art's plane and show the outside of + /// Inflate's front or back. + pub(super) fn of<'a>(facets: impl IntoIterator) -> Self { + let pieces = facets + .into_iter() + .filter_map(|f| { + let face = f.membrane?; + let cell = f.surface.as_ref().filter(|c| c.outward)?; + let uv = <[Point; 3]>::try_from(cell.uv.as_slice()).ok()?; + let page = <[Point; 3]>::try_from(cell.page.as_slice()).ok()?; + Some(MembranePiece { face, uv, page, depth: f.depth }) + }) + .collect(); + Self { pieces } + } + + /// Point `p` of `face` in the art's plane mapped onto the page, or with `from_page` a page point + /// mapped into the art's plane, through the nearest piece of that face that holds it. `None` + /// when no piece the viewer sees holds it. + fn map(&self, face: PlanarFace, p: Point, from_page: bool) -> Option { + let inside = |t: &[Point; 3], q: Point| { + let side = |a: Point, b: Point| (b - a).cross(q - a); + let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])]; + s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9) + }; + let mut best: Option<(Point, f64)> = None; + for piece in self.pieces.iter().filter(|piece| piece.face == face) { + let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) }; + if !inside(from, p) || best.is_some_and(|(_, depth)| depth >= piece.depth) { + continue; + } + if let Some(q) = triangle_map(from, to).map(|m| m * p).filter(|q| q.is_finite()) { + best = Some((q, piece.depth)); + } + } + best.map(|(q, _)| q) + } } impl GraphicFrame { pub(super) fn new(bounds: Rect, front: Option, back: Option) -> Self { - Self { bounds, front, back } + Self { bounds, front, back, membrane: None } + } + + /// The frame of an Inflate object built about `bounds`, whose graphics are drawn on the pieces + /// of `membrane`. + pub(super) fn inflated(bounds: Rect, membrane: MembraneFrame) -> Self { + Self { bounds, front: None, back: None, membrane: Some(membrane) } } pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> { @@ -962,19 +1101,37 @@ impl GraphicFrame { } /// Where graphic `g`'s center lands on the page, and whether its face is turned toward the - /// viewer. `None` when the object has no such face or the point has no page point. + /// viewer. `None` when the object has no such face or the point has no page point. On Inflate + /// the center lands on the puffed face above it, and is `None` where the viewer does not see + /// that face. pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> { + if let Some(membrane) = &self.membrane { + let uv = match g.face { + PlanarFace::Front => Point::new(g.x, g.y), + PlanarFace::Back => Point::new(-g.x, g.y), + }; + return Some((membrane.map(g.face, uv, false)?, true)); + } let map = self.map(g.face)?; Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible)) } - /// The offset of a graphic on `face` whose center lands on page point `page`. + /// The offset of a graphic on `face` whose center lands on page point `page`. On Inflate, only + /// a point on the part of the puffed face the viewer sees has one. pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> { - let art = self.map(face)?.to_art(page)?; - let c = self.bounds.center(); - let (x, y) = match face { - PlanarFace::Front => (art.x - c.x, art.y - c.y), - PlanarFace::Back => (c.x - art.x, art.y - c.y), + let (x, y) = if let Some(membrane) = &self.membrane { + let uv = membrane.map(face, page, true)?; + match face { + PlanarFace::Front => (uv.x, uv.y), + PlanarFace::Back => (-uv.x, uv.y), + } + } else { + let art = self.map(face)?.to_art(page)?; + let c = self.bounds.center(); + match face { + PlanarFace::Front => (art.x - c.x, art.y - c.y), + PlanarFace::Back => (c.x - art.x, art.y - c.y), + } }; (x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y)) } diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 945eb639aa..27f41eb9a1 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -774,6 +774,8 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { side: true, away: false, end: None, + surface: None, + membrane: None, plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), }; let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index f0da6b992b..0729ddf2ba 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -504,7 +504,8 @@ fn graphics_are_checked() { assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}"); } assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err()); - assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err()); + // Inflate takes graphics on its front and its puffed back. + assert!(check(INFLATE, json!([{"symbol": "Mark"}, {"symbol": "Mark", "face": "back"}])).is_ok()); // Revolve takes graphics on its side, named the front; Revolve (Classic) takes none. assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok()); assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err()); @@ -924,3 +925,85 @@ fn only_an_opaque_part_on_revolve_takes_a_seam_stroke() { // A pattern's tile may hold transparent art, which the overlap would show. assert!(!takes_seam(&piece(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, 1.0, BlendMode::Normal))); } + +/// The paths in `art` filled in a shade of red: the parts of the "Mark" graphic. +fn red_parts(art: &Node) -> Vec { + let mut out = vec![]; + art.walk(&mut |n| { + let Some(path) = n.path_data() else { return }; + let red = n.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1 && c.to_rgb()[2] < 0.1), + AppearanceItem::Stroke(_) => false, + }); + if red { + out.push(path.clone()); + } + }); + out +} + +fn reach(parts: &[PathData]) -> Rect { + parts.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap() +} + +#[test] +fn an_inflate_graphic_lies_on_its_puffed_front_where_the_art_is() { + let d = document(); + let n = object(INFLATE, json!({"graphics": [{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + // Straight on, the puff rises toward the viewer and the graphic is carried straight out onto it: + // a 20 × 20 square centered 20 right of and 10 above (50, 50). + let parts = red_parts(&art); + assert!(!parts.is_empty()); + assert!(close(reach(&parts), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", reach(&parts)); + // Turned, the graphic moves and foreshortens with the puff under it. + let n = object(INFLATE, json!({"rotationY": 40.0, "graphics": [{"symbol": "Mark", "scale": 200.0}]})); + let turned = reach(&red_parts(&solid_art_in(Some(&d), &n).unwrap())); + assert!(turned.width() < 20.0 - 0.5 && (turned.height() - 20.0).abs() < 2.0, "{turned:?}"); + // Without the document nothing is drawn. + assert!(red_parts(&solid_art_in(None, &n).unwrap()).is_empty()); +} + +#[test] +fn an_inflate_back_takes_its_graphic_with_both_sides_and_twist_carries_it() { + let d = document(); + let back = |extra: Value| { + let mut p = json!({"rotationY": 180.0, "graphics": [{"symbol": "Mark", "face": "back", "x": 20.0, "scale": 200.0}]}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + red_parts(&solid_art_in(Some(&d), &object(INFLATE, p)).unwrap()) + }; + // Without Both sides the back is flat and open, with no puffed face to carry the graphic. + assert!(back(json!({})).is_empty()); + // Seen from behind, the back reads left to right: 20 to the right as seen from behind is 20 to + // the left of the art's center, which turned half a turn lies 20 right on the page. + let plain = back(json!({"bothSides": true})); + assert!(!plain.is_empty()); + let r = reach(&plain); + assert!((r.center().x - 70.0).abs() < 0.5 && (r.center().y - 50.0).abs() < 0.5 && (r.width() - 20.0).abs() < 0.5, "{r:?}"); + // Twist turns the back, and the graphic turns with it. + let twisted = reach(&back(json!({"bothSides": true, "twist": 45.0}))); + assert!(twisted.width() > r.width() + 3.0, "{twisted:?} {r:?}"); +} + +#[test] +fn an_inflate_frame_puts_the_handle_on_the_puff_and_reads_it_back() { + let d = document(); + let n = object(INFLATE, json!({"bothSides": true})); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "x": 20.0, "y": -10.0})).unwrap(); + let (page, shown) = frame.handle(&g).unwrap(); + assert!(shown && (page.x - 70.0).abs() < 1e-6 && (page.y - 40.0).abs() < 1e-6, "{page:?}"); + let (x, y) = frame.offset_at(PlanarFace::Front, page).unwrap(); + assert!((x - 20.0).abs() < 1e-6 && (y + 10.0).abs() < 1e-6, "{x} {y}"); + // From the front the back is out of sight: it has no handle and no offset. + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back"})).unwrap(); + assert!(frame.handle(&g).is_none()); + assert!(frame.offset_at(PlanarFace::Back, Point::new(50.0, 50.0)).is_none()); + // Turned half a turn, the back's handle reads back its offset, as seen from behind. + let n = object(INFLATE, json!({"bothSides": true, "rotationY": 180.0})); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": 15.0, "y": 5.0})).unwrap(); + let (page, _) = frame.handle(&g).unwrap(); + let (x, y) = frame.offset_at(PlanarFace::Back, page).unwrap(); + assert!((x - 15.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}"); +} diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index e80c1b2d36..1c9d3e2afa 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -1,5 +1,6 @@ //! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single -//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side). The +//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side, Inflate's +//! puffed front and back). The //! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams` //! also edits. @@ -28,7 +29,7 @@ pub(super) fn specs() -> Vec { "Map Graphic", [], None, - "{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}", + "{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face; on Inflate the back takes graphics only with Both sides and Cap on), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Inflate in the art's plane, the graphic carried straight out onto the puffed face; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and on Inflate following the puff, Twist and Taper carrying the back's, each drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type), Revolve or Inflate; one undo step → {ids, graphic}", has_doc, map_graphic ), @@ -124,6 +125,13 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) { return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0))); } + // Inflate's back takes graphics where it puffs out: with Both sides and Cap on. + if base.face == effects::PlanarFace::Back && effect.id == effects::INFLATE { + let o = effects::inflate_options(&merged); + if !(o.both_sides && o.cap) { + return Err(bad(C, format!("object {}: Inflate's back takes graphics with Both sides and Cap on", id.0))); + } + } let mut graphic = base.clone(); if p.get("scale").is_none() && let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol)) diff --git a/crates/engine/src/cmd/effectcmd/graphics_tests.rs b/crates/engine/src/cmd/effectcmd/graphics_tests.rs index a9d3a754ce..dcd4c1e99c 100644 --- a/crates/engine/src/cmd/effectcmd/graphics_tests.rs +++ b/crates/engine/src/cmd/effectcmd/graphics_tests.rs @@ -95,10 +95,10 @@ fn map_graphic_puts_a_graphic_on_the_side_of_a_revolve() { #[test] fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() { - let (mut s, id) = setup("threeD.inflate"); + let (mut s, id) = setup("threeD.classicExtrude"); let history = undo_len(&s); let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string(); - assert!(e.contains("Plane, Extrude and Revolve"), "{e}"); + assert!(e.contains("Plane, Extrude, Revolve and Inflate"), "{e}"); let (mut s, id) = setup("threeD.rotate"); for (p, says) in [ (json!({"symbol": "Gone"}), "no symbol named"), @@ -147,11 +147,36 @@ fn set_params_edits_graphics_and_checks_them() { let null = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": null}}); assert!(s.execute("effect.setParams", &null).is_err()); assert_eq!(graphics(&s, id), moved); - // Extrude to Plane keeps the graphics; to Inflate drops them. + // Extrude to Plane keeps the graphics, and so does Inflate. s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "plane"})).unwrap(); assert_eq!(graphics(&s, id), moved); s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "inflate"})).unwrap(); - assert_eq!(graphics(&s, id), Value::Null); + assert_eq!(graphics(&s, id), moved); +} + +#[test] +fn map_graphic_puts_a_graphic_on_an_inflate_and_its_back_only_with_both_sides() { + let (mut s, id) = setup("threeD.inflate"); + let plain = { + let d = &s.doc().unwrap().doc; + vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()) + }; + let history = undo_len(&s); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap(); + assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 0.0, "y": 0.0, "scale": 100.0, "rotation": 0.0}])); + assert_eq!(undo_len(&s), history + 1); + let d = &s.doc().unwrap().doc; + assert_ne!(vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()), plain, "the graphic is drawn"); + // The back is flat until Both sides puffs it. + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("Both sides and Cap"), "{e}"); + assert_eq!(undo_len(&s), history); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"bothSides": true, "cap": false}})).unwrap(); + assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).is_err()); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"cap": true}})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap(); + assert_eq!(graphics(&s, id)[1]["face"], "back"); } #[test] diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 18ef7d6d1b..a66e72af1c 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -241,11 +241,15 @@ pub struct Inflate { pub taper: f64, /// A closed back (a solid) or none, so the inflated front is a shell open behind. pub cap: bool, + /// Graphics are mapped onto the front or the puffed back: the pieces of those faces are drawn + /// as triangles, each carrying where its corners lie in the art's plane ([`Facet::surface`]). + /// Off by default, which leaves the facets without one. + pub map_surface: bool, } impl Default for Inflate { fn default() -> Self { - Self { depth: 0.0, volume: 50.0, both_sides: false, twist: 0.0, taper: 1.0, cap: true } + Self { depth: 0.0, volume: 50.0, both_sides: false, twist: 0.0, taper: 1.0, cap: true, map_surface: false } } } @@ -296,6 +300,14 @@ pub struct Facet { /// The planar end of the solid the facet is: Extrude & Bevel's front or back cap, or a plane /// (its front). `None` for every other facet. pub end: Option, + /// For a piece of Inflate's front or puffed back built for graphics ([`Inflate::map_surface`]): + /// where its corners lie in the art's plane, as offsets from the center of the bounds the solid + /// was built with ([`crate::SurfaceCell`]). The back's corners are where they were in the art + /// before the twist and taper turned and scaled it. + pub surface: Option, + /// The face of Inflate's solid that a facet with a [`Facet::surface`] is a piece of: its front + /// or its puffed back. + pub membrane: Option, /// The face's plane in view space and the projection it was drawn with, for its depth at a /// point of the drawing ([`Facet::depth_at`]). `None` for a face whose corners lie more than /// 0.001 pt off one plane (a piece of a twisted wall) or reach the eye. @@ -384,6 +396,8 @@ impl Facet { // A revolved cap is not one of the planar faces graphics map onto. end: None, away: false, + surface: None, + membrane: None, plane: face.plane, #[cfg(test)] view: vec![], diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index d734161343..9cff25bab5 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -211,6 +211,8 @@ impl<'a> Builder<'a> { side: false, away: behind, end: None, + surface: None, + membrane: None, plane, #[cfg(test)] view, diff --git a/crates/three-d/src/solid/inflate.rs b/crates/three-d/src/solid/inflate.rs index 5edf57a894..5b3c883211 100644 --- a/crates/three-d/src/solid/inflate.rs +++ b/crates/three-d/src/solid/inflate.rs @@ -1,7 +1,7 @@ use super::build::{Builder, Built, Camera, Keep, Order, Turn, check_bounds, cuts, fit, newell, outward}; use super::membrane::{Edges, MAX_MATERIAL_SEGMENTS, Membrane, cell_triangles, clip, crossings, filled, material}; use super::rings::{MAX_SOLID_POINTS, TOO_COMPLEX_SURFACE, curve_pieces, signed_area, solid_rings}; -use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, Point, Rect, V3, Vec2, View}; +use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, PlanarFace, Point, Rect, V3, Vec2, View}; /// The slices the sides are cut into: more to follow a twist or taper. fn slices(o: &Inflate) -> usize { @@ -198,6 +198,22 @@ thread_local! { pub(super) static GRID_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; } +/// Marks the facet the builder `b` added after it held `before` facets, if it added one, as a piece +/// of `face` (Inflate's front or puffed back) whose corners lie at the art points `points`, as +/// offsets from `center` ([`Facet::surface`]). `outward` is the triangle's normal pointing out of +/// the solid: the piece shows the outside of the surface when it was neither turned around to show +/// its inside (on a shell open behind) nor kept turned away. +fn mark_surface(b: &mut Builder<'_>, before: usize, points: [Point; 3], center: Point, outward: V3, face: PlanarFace) { + if b.facets.len() <= before { + return; + } + let Some(f) = b.facets.last_mut() else { return }; + let Some(page) = f.contours.first().filter(|c| c.len() == 3).cloned() else { return }; + let shows = !f.away && f.normal[0] * outward.0 + f.normal[1] * outward.1 + f.normal[2] * outward.2 > 0.0; + f.surface = Some(crate::SurfaceCell { page, uv: points.iter().map(|q| Point::new(q.x - center.x, q.y - center.y)).collect(), outward: shows }); + f.membrane = Some(face); +} + /// The facets of one inflated shape, for a camera that allows for a puff `reach` high (or the /// shape's own, if higher): `reach` is the highest puff of the shapes drawn together. Its faces /// before projection instead, or both, as `keep` asks. @@ -241,6 +257,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee }; let smooth = view.shade && view.has_colored_lights(); let camera = Camera::new(view, bounds, o.depth + 2.0 * height.max(reach)); + // A graphic's offsets are from the center of the bounds the solid is built with. + let center = bounds.center(); // Without its back cap the object is a shell open behind, its inside showing. let mut b = Builder::new(&camera, o.cap, false, keep); let half = o.depth / 2.0; @@ -410,22 +428,47 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee out }) .collect(); - if height > 0.0 - && smooth + // Smooth shading draws the pieces as triangles, and so do graphics mapped onto + // the front or back: each triangle then carries where its corners lie in the + // art's plane. + let smoothed = height > 0.0 && smooth; + if (smoothed || o.map_surface) && let Some(triangles) = cell_triangles(&pieces) { + let order = if flat { Order::Last } else { Order::Depth }; for points in triangles { let front = points.map(|q| camera.place(q, half + lift(q))); - b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false)?; + let before = b.facets.len(); + let outward = newell(&[front.to_vec()]); + if smoothed { + b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false)?; + } else { + b.face(vec![front.to_vec()], outward, order)?; + } + if o.map_surface { + mark_surface(&mut b, before, points, center, outward, PlanarFace::Front); + } if o.both_sides && o.cap { let back = points.map(|q| camera.place(back_turn.apply(q), -half - lift(q) * back_turn.scale)); - let normals = points.map(|q| { - let n = normal(q); - // A uniform taper scales all three coordinates equally; - // twist turns the back normal about the shape's z-axis. - camera.rotate(V3(back_turn.cos * n.0 - back_turn.sin * n.1, back_turn.sin * n.0 + back_turn.cos * n.1, -n.2)) - }); - b.smooth_triangle(back, normals, true)?; + let before = b.facets.len(); + let n = newell(&[back.to_vec()]); + // The back winds the same way round as the front, so its outward + // normal is reversed. + let outward = V3(-n.0, -n.1, -n.2); + if smoothed { + let normals = points.map(|q| { + let n = normal(q); + // A uniform taper scales all three coordinates equally; + // twist turns the back normal about the shape's z-axis. + camera.rotate(V3(back_turn.cos * n.0 - back_turn.sin * n.1, back_turn.sin * n.0 + back_turn.cos * n.1, -n.2)) + }); + b.smooth_triangle(back, normals, true)?; + } else { + b.face(vec![back.to_vec()], outward, order)?; + } + if o.map_surface { + mark_surface(&mut b, before, points, center, outward, PlanarFace::Back); + } } } continue; diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index a75821e696..8dd1662e4d 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -423,6 +423,47 @@ fn inflate_leaves_holes_open() { assert!(close(area(&f), 100.0 * 100.0 - 40.0 * 40.0, 1e-3), "{}", area(&f)); } +#[test] +fn inflate_marks_where_each_piece_lies_in_the_art_for_graphics() { + let (p, r) = shape(&square(0.0, 0.0, 100.0)); + let on = |o: Inflate, view: View| inflate(&p, FillRule::EvenOdd, r, Inflate { map_surface: true, ..o }, view).unwrap(); + // Without the request no piece carries a surface point. + assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).unwrap().iter().all(|f| f.surface.is_none() && f.membrane.is_none())); + // Straight on, every piece is a front triangle whose corners lie where the art does, as + // offsets from the center of the bounds, and together they cover the shape. + let f = on(Inflate::default(), front()); + let marked: Vec<&Facet> = f.iter().filter(|f| f.surface.is_some()).collect(); + assert!(marked.len() > 20, "{}", marked.len()); + assert!(close(marked.iter().map(|f| signed_area(&f.contours[0]).abs()).sum::(), 100.0 * 100.0, 1e-3)); + for f in &marked { + let s = f.surface.as_ref().unwrap(); + assert_eq!(f.membrane, Some(PlanarFace::Front)); + assert!(s.outward); + for (page, uv) in s.page.iter().zip(&s.uv) { + assert!(close(page.x, uv.x + 50.0, 1e-6) && close(page.y, uv.y + 50.0, 1e-6), "{page:?} {uv:?}"); + } + } + // Both sides puffs a back: seen from behind its pieces show their outside, and under Twist + // they keep the untwisted art points while the pieces turn on the page. + let behind = View { rotation_y: 180.0, ..front() }; + let back = |o: Inflate| { + on(o, behind) + .into_iter() + .filter(|f| f.membrane == Some(PlanarFace::Back) && f.surface.as_ref().is_some_and(|s| s.outward)) + .collect::>() + }; + let plain = back(Inflate { both_sides: true, ..Inflate::default() }); + assert!(!plain.is_empty()); + let twisted = back(Inflate { both_sides: true, twist: 30.0, ..Inflate::default() }); + assert!(!twisted.is_empty()); + let uv_extent = + |f: &[Facet]| f.iter().flat_map(|f| f.surface.as_ref().unwrap().uv.clone()).fold(Rect::new(0.0, 0.0, 0.0, 0.0), |r, q| r.union_pt(q)); + assert!(close(uv_extent(&twisted).width(), 100.0, 1e-6) && close(uv_extent(&twisted).height(), 100.0, 1e-6)); + assert!(extent(&twisted).width() > extent(&plain).width() + 10.0, "{:?} {:?}", extent(&twisted), extent(&plain)); + // Without Both sides there is no back to mark. + assert!(on(Inflate::default(), behind).iter().all(|f| f.membrane != Some(PlanarFace::Back))); +} + #[test] fn malformed_and_degenerate_input_is_bounded() { let (p, b) = shape(&square(0.0, 0.0, 100.0)); @@ -446,7 +487,7 @@ fn malformed_and_degenerate_input_is_bounded() { &p, FillRule::EvenOdd, b, - Inflate { depth: -5.0, volume: f64::NAN, both_sides: true, twist: f64::INFINITY, taper: f64::NAN, cap: true }, + Inflate { depth: -5.0, volume: f64::NAN, both_sides: true, twist: f64::INFINITY, taper: f64::NAN, cap: true, map_surface: false }, front() ) .is_ok() diff --git a/crates/ui-egui/src/dialogs/three_d_materials.rs b/crates/ui-egui/src/dialogs/three_d_materials.rs index 3091a00cac..e0af93a825 100644 --- a/crates/ui-egui/src/dialogs/three_d_materials.rs +++ b/crates/ui-egui/src/dialogs/three_d_materials.rs @@ -1,6 +1,6 @@ //! The 3D and Materials panel's Materials tab: the document's Graphics (its symbols) as thumbnails, -//! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces, or -//! Revolve's side) with their face, position, size and turn. Picking a thumbnail maps that graphic +//! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces, +//! Revolve's side, or Inflate's puffed faces) with their face, position, size and turn. Picking a thumbnail maps that graphic //! onto the selected objects (`threeD.mapGraphic`); art dropped on the thumbnails becomes a graphic //! (`threeD.addGraphic`). Editing a mapped graphic changes the effect's `graphics` parameter, which //! the panel sends as it sends every other setting. @@ -96,7 +96,7 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) } ui.add_space(10.0); if !takes { - dim_label(ui, tl!("Graphics map onto the Plane, Extrude and Revolve object types.")); + dim_label(ui, tl!("Graphics map onto the Plane, Extrude, Revolve and Inflate object types.")); return; } let raw = d.fields.get(GRAPHICS).cloned().unwrap_or(Value::Null); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 3ed3ca8331..a19eb6864f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6229,7 +6229,7 @@ digits Malayalam Malaiàlam @msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` ha de ser front o back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` ha de ser un nombre de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` ha de ser una matriu -@msg Graphics map onto the Plane, Extrude and Revolve object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió i Revolució +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió, Revolució i Infla @msg Revolve maps graphics onto its side: map them onto the front Revoluciona aplica els gràfics al seu lateral: aplica’ls a la cara davantera @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Els gràfics són massa complexos per a aquesta superfície: simplifica la il·lustració dels símbols o redueix Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admet com a màxim {MAX_GRAPHICS} gràfics diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 161e235c56..3e0962a519 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6045,7 +6045,7 @@ mark-style Japanese Japonské @msg `{GRAPHICS}` face must be front or back face v `{GRAPHICS}` musí být front nebo back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} v `{GRAPHICS}` musí být číslo od {lo} do {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musí být pole -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafika se mapuje na typy objektu Rovina, Vysunutí a Rotační těleso +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafika se mapuje na typy objektu Rovina, Vysunutí, Rotační těleso a Nafouknutí @msg Revolve maps graphics onto its side: map them onto the front Rotační těleso mapuje grafiku na svůj bok: umístěte ji na přední stranu @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafika je pro tento povrch příliš složitá: zjednodušte kresbu symbolů nebo snižte Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` přijímá nejvýše {MAX_GRAPHICS} grafik diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index fd0b7c042e..69a7f64c4e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -318,7 +318,7 @@ @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`: face skal være front eller back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`: {key} skal være et tal fra {lo} til {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` skal være et array -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafik kortlægges på objekttyperne Plan, Ekstrudér og Omdrej +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafik kortlægges på objekttyperne Plan, Ekstrudér, Omdrej og Pust op @msg Revolve maps graphics onto its side: map them onto the front Omdrej kortlægger grafik på siden: kortlæg den på forsiden @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikken er for kompleks til denne overflade: forenkl symbolernes grafik, eller reducér Segmenter @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tager højst {MAX_GRAPHICS} grafikelementer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2a5f32a5d9..72ce446449 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5619,7 +5619,7 @@ lighting Light Licht @msg `{GRAPHICS}` face must be front or back face in `{GRAPHICS}` muss front oder back sein @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} in `{GRAPHICS}` muss eine Zahl von {lo} bis {hi} sein @msg `{GRAPHICS}` must be an array `{GRAPHICS}` muss ein Array sein -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafiken werden auf die Objekttypen Ebene, Extrudieren und Kreiseln abgebildet +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiken werden auf die Objekttypen Ebene, Extrudieren, Kreiseln und Aufblasen abgebildet @msg Revolve maps graphics onto its side: map them onto the front Kreiseln bildet Grafiken auf seiner Mantelfläche ab: Bilden Sie sie auf der Vorderseite ab @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Die Grafiken sind für diese Oberfläche zu komplex: Vereinfachen Sie das Bildmaterial der Symbole oder verringern Sie Segmente @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` nimmt höchstens {MAX_GRAPHICS} Grafiken auf diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index b1b7b4d039..d1e476d8cf 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5406,7 +5406,7 @@ digits Malayalam Μαλαγιάλαμ @msg `{GRAPHICS}` face must be front or back το face του `{GRAPHICS}` πρέπει να είναι front ή back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} το {key} του `{GRAPHICS}` πρέπει να είναι αριθμός από {lo} έως {hi} @msg `{GRAPHICS}` must be an array το `{GRAPHICS}` πρέπει να είναι πίνακας -@msg Graphics map onto the Plane, Extrude and Revolve object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση και Περιστροφή γύρω από άξονα +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση, Περιστροφή γύρω από άξονα και Φούσκωμα @msg Revolve maps graphics onto its side: map them onto the front Η Περιστροφή γύρω από άξονα αντιστοιχίζει τα γραφικά στην πλευρική της επιφάνεια: αντιστοιχίστε τα στην μπροστινή όψη @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Τα γραφικά είναι πολύ σύνθετα για αυτή την επιφάνεια: απλοποιήστε το σχέδιο των συμβόλων ή μειώστε τα Τμήματα @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics το `{GRAPHICS}` δέχεται το πολύ {MAX_GRAPHICS} γραφικά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5b3c675f7b..b85486760c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5988,8 +5988,8 @@ mark-style Japanese Japonesas @msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` debe ser front o back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` debe ser un número de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` debe ser una matriz -@msg Graphics map onto the Plane, Extrude and Revolve object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión y Revolución - Graphics map onto the Plane, Extrude and Revolve object types. Los gráficos se asignan a los tipos de objeto Plano, Extrusión y Revolución. +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión, Revolución e Inflar + Graphics map onto the Plane, Extrude, Revolve and Inflate object types. Los gráficos se asignan a los tipos de objeto Plano, Extrusión, Revolución e Inflar. @msg Revolve maps graphics onto its side: map them onto the front Revolución asigna los gráficos a su lateral: asígnelos a la cara frontal @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Los gráficos son demasiado complejos para esta superficie: simplifique la ilustración de los símbolos o reduzca Segmentos @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admite como máximo {MAX_GRAPHICS} gráficos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e77a617c52..a512131070 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5928,7 +5928,7 @@ mark-style Japanese Japanilainen @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`-kohteen face-arvon on oltava front tai back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`-kohteen {key}-arvon on oltava luku, joka on vähintään {lo} ja enintään {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` on oltava taulukko -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafiikat sijoitetaan objektityypeille Taso, Pursota ja Pyöräytä +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiikat sijoitetaan objektityypeille Taso, Pursota, Pyöräytä ja Täytä ilmalla @msg Revolve maps graphics onto its side: map them onto the front Pyöräytä sijoittaa grafiikat kylkeensä: sijoita ne etupuolelle @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiikat ovat liian monimutkaisia tälle pinnalle: yksinkertaista symbolien kuvitusta tai pienennä Segmentit-arvoa @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` hyväksyy enintään {MAX_GRAPHICS} grafiikkaa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2762d2a954..a91bacd012 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5613,7 +5613,7 @@ lighting Light Lumière @msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` doit valoir front ou back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` doit être un nombre de {lo} à {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` doit être un tableau -@msg Graphics map onto the Plane, Extrude and Revolve object types Les graphiques s'appliquent aux types d'objet Plan, Extrusion et Révolution +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Les graphiques s'appliquent aux types d'objet Plan, Extrusion, Révolution et Gonfler @msg Revolve maps graphics onto its side: map them onto the front Révolution applique les graphiques sur sa face latérale : appliquez-les sur la face avant @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Les graphiques sont trop complexes pour cette surface : simplifiez l'illustration des symboles ou réduisez Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accepte au plus {MAX_GRAPHICS} graphiques diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 1c96900b2b..aebe0dc3af 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4619,7 +4619,7 @@ antiAlias Sharp શાર્પ Align On: આના પર સંરેખિત કરો: Delete Tab ટૅબ કાઢી નાખો Face સપાટી - Graphics map onto the Plane, Extrude and Revolve object types. ગ્રાફિક્સને Plane, Extrude અને Revolve પ્રકારના ઑબ્જેક્ટ્સ પર મેપ કરી શકાય છે. + Graphics map onto the Plane, Extrude, Revolve and Inflate object types. ગ્રાફિક્સને Plane, Extrude, Revolve અને Inflate પ્રકારના ઑબ્જેક્ટ્સ પર મેપ કરી શકાય છે. Justify with last line aligned center છેલ્લી લાઇન મધ્યમાં રાખીને જસ્ટિફાઇ કરો Justify with last line aligned right છેલ્લી લાઇન જમણે રાખીને જસ્ટિફાઇ કરો Leader: લીડર: diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 548f961f51..fd22ef72f2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8059,7 +8059,7 @@ antiAlias Sharp शार्प @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` का face, front या back होना चाहिए @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` का {key}, {lo} से {hi} तक की संख्या होना चाहिए @msg `{GRAPHICS}` must be an array `{GRAPHICS}` एक ऐरे होना चाहिए -@msg Graphics map onto the Plane, Extrude and Revolve object types ग्राफ़िक्स समतल, एक्सट्रूड और रिवॉल्व ऑब्जेक्ट प्रकारों पर लगते हैं +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types ग्राफ़िक्स समतल, एक्सट्रूड, रिवॉल्व और फुलाएँ ऑब्जेक्ट प्रकारों पर लगते हैं @msg Revolve maps graphics onto its side: map them onto the front रिवॉल्व ग्राफ़िक्स को अपनी बगल वाली सतह पर लगाता है: उन्हें सामने वाले फ़ेस पर लगाएँ @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments ग्राफ़िक्स इस सतह के लिए बहुत जटिल हैं: सिंबल्स के आर्ट को सरल बनाएँ या सेगमेंट कम करें @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` अधिकतम {MAX_GRAPHICS} ग्राफ़िक्स लेता है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 200b45d1b1..2cb919f15b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6028,7 +6028,7 @@ imageTrace Outline Körvonal @msg `{GRAPHICS}` face must be front or back a `{GRAPHICS}` face értéke front vagy back lehet @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} a `{GRAPHICS}` {key} értéke {lo} és {hi} közötti szám lehet @msg `{GRAPHICS}` must be an array a `{GRAPHICS}` értéke tömb kell legyen -@msg Graphics map onto the Plane, Extrude and Revolve object types A grafikák a Sík, a Kihúzás és a Forgatás tengely körül objektumtípusra kerülnek +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types A grafikák a Sík, a Kihúzás, a Forgatás tengely körül és a Felfújás objektumtípusra kerülnek @msg Revolve maps graphics onto its side: map them onto the front A Forgatás tengely körül a grafikákat a palástjára helyezi: az elülső oldalra helyezze őket @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments A grafikák túl összetettek ehhez a felülethez: egyszerűsítse a szimbólumok rajzát, vagy csökkentse a Szakaszok értékét @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics a `{GRAPHICS}` legfeljebb {MAX_GRAPHICS} grafikát fogad diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 90ec79404c..a6753f670d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5661,7 +5661,7 @@ lighting Light Luce @msg `{GRAPHICS}` face must be front or back face di `{GRAPHICS}` deve essere front o back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} di `{GRAPHICS}` deve essere un numero da {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve essere un array -@msg Graphics map onto the Plane, Extrude and Revolve object types Le grafiche si applicano ai tipi di oggetto Piano, Estrusione e Rivoluzione +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Le grafiche si applicano ai tipi di oggetto Piano, Estrusione, Rivoluzione e Gonfia @msg Revolve maps graphics onto its side: map them onto the front Rivoluzione applica le grafiche sul suo lato: applicatele sulla faccia anteriore @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Le grafiche sono troppo complesse per questa superficie: semplificate il disegno dei simboli o riducete Segmenti @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accetta al massimo {MAX_GRAPHICS} grafiche diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d98acfa22d..c6b574b9db 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5703,8 +5703,8 @@ lighting Light ライト @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` の face には front または back を指定してください @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` の {key} は {lo} から {hi} までの数値にしてください @msg `{GRAPHICS}` must be an array `{GRAPHICS}` は配列にしてください -@msg Graphics map onto the Plane, Extrude and Revolve object types グラフィックはオブジェクトの種類が平面、押し出し、回転体のときにマッピングされます - Graphics map onto the Plane, Extrude and Revolve object types. グラフィックはオブジェクトの種類が平面、押し出し、回転体のときにマッピングされます。 +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types グラフィックはオブジェクトの種類が平面、押し出し、回転体、膨張のときにマッピングされます + Graphics map onto the Plane, Extrude, Revolve and Inflate object types. グラフィックはオブジェクトの種類が平面、押し出し、回転体、膨張のときにマッピングされます。 @msg Revolve maps graphics onto its side: map them onto the front 回転体はグラフィックを側面にマッピングします。前面にマッピングしてください @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments グラフィックがこのサーフェスには複雑すぎます。シンボルのアートを単純化するか、分割数を減らしてください @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` に指定できるグラフィックは {MAX_GRAPHICS} 個までです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 794e5454a9..b2d8e56f4d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5326,7 +5326,7 @@ font-technology Variable ცვლადი @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`-ის face უნდა იყოს front ან back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`-ის {key} უნდა იყოს რიცხვი {lo}-დან {hi}-მდე @msg `{GRAPHICS}` must be an array `{GRAPHICS}` უნდა იყოს მასივი -@msg Graphics map onto the Plane, Extrude and Revolve object types გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“ და „ბრუნვა“ +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“, „ბრუნვა“ და „გაბერვა“ @msg Revolve maps graphics onto its side: map them onto the front ბრუნვა გრაფიკას თავის გვერდით ზედაპირზე ათავსებს: განათავსეთ ისინი წინა მხარეზე @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments გრაფიკა ზედმეტად რთულია ამ ზედაპირისთვის: გაამარტივეთ სიმბოლოების ნახატი ან შეამცირეთ სეგმენტები @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` იღებს მაქსიმუმ {MAX_GRAPHICS} გრაფიკას diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bb8676df71..5f907c5480 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5622,7 +5622,7 @@ lighting Light 광원 @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`의 face는 front 또는 back이어야 합니다 @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`의 {key}은(는) {lo}에서 {hi} 사이의 숫자여야 합니다 @msg `{GRAPHICS}` must be an array `{GRAPHICS}`은(는) 배열이어야 합니다 -@msg Graphics map onto the Plane, Extrude and Revolve object types 그래픽은 평면, 돌출, 회전체 개체 유형에 매핑됩니다 +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 그래픽은 평면, 돌출, 회전체, 부풀리기 개체 유형에 매핑됩니다 @msg Revolve maps graphics onto its side: map them onto the front 회전체는 그래픽을 옆면에 매핑합니다. 앞면에 매핑하십시오 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 그래픽이 이 표면에 비해 너무 복잡합니다. 심볼의 아트를 단순화하거나 세그먼트를 줄이십시오 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}`에는 그래픽을 최대 {MAX_GRAPHICS}개까지 넣을 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a597a03fd0..37b0232c9a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7805,7 +7805,7 @@ mark-style Japanese Japans @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} in `{GRAPHICS}` moet een getal van {lo} tot {hi} zijn @msg `{GRAPHICS}` must be an array `{GRAPHICS}` moet een array zijn @msg Graphics map onto planar faces: use the Extrude or Plane object type Illustraties worden op platte vlakken geplaatst: gebruik het objecttype Extruderen of Vlak -@msg Graphics map onto the Plane, Extrude and Revolve object types Illustraties worden op de objecttypen Vlak, Extruderen en Draaien geplaatst +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Illustraties worden op de objecttypen Vlak, Extruderen, Draaien en Opblazen geplaatst @msg Revolve maps graphics onto its side: map them onto the front Draaien plaatst illustraties op de zijkant: plaats ze op de voorkant @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments De illustraties zijn te complex voor dit oppervlak: vereenvoudig de illustraties van de symbolen of verlaag Segmenten @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` neemt maximaal {MAX_GRAPHICS} illustraties op diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 99ee2080b8..b04f60ab7e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5876,7 +5876,7 @@ mark-style Japanese Japońskie @msg `{GRAPHICS}` face must be front or back face w `{GRAPHICS}` musi mieć wartość front lub back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} w `{GRAPHICS}` musi być liczbą od {lo} do {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musi być tablicą -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafiki są nakładane na obiekty typu Płaszczyzna, Wyciągnięcie i Obrót +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiki są nakładane na obiekty typu Płaszczyzna, Wyciągnięcie, Obrót i Nadmuchanie @msg Revolve maps graphics onto its side: map them onto the front Obrót nakłada grafiki na swoją powierzchnię boczną: umieść je na przedniej stronie @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiki są zbyt złożone dla tej powierzchni: uprość rysunki symboli lub zmniejsz Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` przyjmuje najwyżej {MAX_GRAPHICS} grafik diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 677c8e460f..d86a571004 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5994,7 +5994,7 @@ mark-style Japanese Japonesas @msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` deve ser front ou back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` deve ser um número de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve ser uma matriz -@msg Graphics map onto the Plane, Extrude and Revolve object types Os gráficos são mapeados nos tipos de objeto Plano, Extrusão e Revolver +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Os gráficos são mapeados nos tipos de objeto Plano, Extrusão, Revolver e Inflar @msg Revolve maps graphics onto its side: map them onto the front Revolver mapeia os gráficos na sua lateral: mapeie-os na face frontal @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Os gráficos são complexos demais para esta superfície: simplifique a arte dos símbolos ou reduza Segmentos @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` aceita no máximo {MAX_GRAPHICS} gráficos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 106343cddd..6533a1dfd4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5648,7 +5648,7 @@ lighting Light Свет @msg `{GRAPHICS}` face must be front or back face в `{GRAPHICS}` должен быть front или back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} в `{GRAPHICS}` должен быть числом от {lo} до {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` должен быть массивом -@msg Graphics map onto the Plane, Extrude and Revolve object types Графика наносится на объекты типов «Плоскость», «Выдавливание» и «Вращение» +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графика наносится на объекты типов «Плоскость», «Выдавливание», «Вращение» и «Надувание» @msg Revolve maps graphics onto its side: map them onto the front «Вращение» наносит графику на свою боковую поверхность: размещайте её на передней стороне @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графика слишком сложна для этой поверхности: упростите иллюстрации символов или уменьшите «Сегменты» @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` принимает не более {MAX_GRAPHICS} графических элементов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index cc854aa362..2f61b31373 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5512,7 +5512,7 @@ lighting Light Ljus @msg `{GRAPHICS}` face must be front or back face i `{GRAPHICS}` måste vara front eller back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} i `{GRAPHICS}` måste vara ett tal från {lo} till {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` måste vara en matris -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafik placeras på objekttyperna Plan, Extrudera och Rotera runt axel +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafik placeras på objekttyperna Plan, Extrudera, Rotera runt axel och Blås upp @msg Revolve maps graphics onto its side: map them onto the front Rotera runt axel placerar grafik på sin mantelyta: placera den på framsidan @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiken är för komplex för den här ytan: förenkla symbolernas teckning eller minska Segment @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tar högst {MAX_GRAPHICS} grafiker diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f2888a30f0..583ac05f33 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5375,7 +5375,7 @@ lighting Light Işık @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` face değeri front veya back olmalıdır @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` {key} değeri {lo} ile {hi} arasında bir sayı olmalıdır @msg `{GRAPHICS}` must be an array `{GRAPHICS}` bir dizi olmalıdır -@msg Graphics map onto the Plane, Extrude and Revolve object types Grafikler Düzlem, Ekstrüzyon ve Döndür nesne türlerine eşlenir +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafikler Düzlem, Ekstrüzyon, Döndür ve Şişir nesne türlerine eşlenir @msg Revolve maps graphics onto its side: map them onto the front Döndür grafikleri yan yüzeyine eşler: onları ön yüze eşle @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikler bu yüzey için çok karmaşık: sembollerin resmini basitleştir veya Segmentler değerini azalt @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` en fazla {MAX_GRAPHICS} grafik alır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 411b2c3baf..405fd9814f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5641,7 +5641,7 @@ lighting Light Світло @msg `{GRAPHICS}` face must be front or back face у `{GRAPHICS}` має бути front або back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} у `{GRAPHICS}` має бути числом від {lo} до {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` має бути масивом -@msg Graphics map onto the Plane, Extrude and Revolve object types Графіка наноситься на об’єкти типів «Площина», «Видавлювання» та «Обертання» +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графіка наноситься на об’єкти типів «Площина», «Видавлювання», «Обертання» та «Надування» @msg Revolve maps graphics onto its side: map them onto the front «Обертання» наносить графіку на свою бічну поверхню: розміщуйте її на передній стороні @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графіка надто складна для цієї поверхні: спростіть ілюстрації символів або зменште «Сегменти» @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` приймає не більше {MAX_GRAPHICS} графічних елементів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 1460910197..6dfc1e65f9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5429,7 +5429,7 @@ theme Appearance Giao diện @msg `{GRAPHICS}` face must be front or back face của `{GRAPHICS}` phải là front hoặc back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} của `{GRAPHICS}` phải là số từ {lo} đến {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` phải là một mảng -@msg Graphics map onto the Plane, Extrude and Revolve object types Đồ họa được đặt lên các loại đối tượng Mặt phẳng, Kéo dài và Xoay tròn +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Đồ họa được đặt lên các loại đối tượng Mặt phẳng, Kéo dài, Xoay tròn và Phình @msg Revolve maps graphics onto its side: map them onto the front Xoay tròn đặt đồ họa lên mặt bên của nó: hãy đặt chúng lên mặt trước @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Đồ họa quá phức tạp cho bề mặt này: hãy đơn giản hóa hình vẽ của các ký hiệu hoặc giảm Đoạn @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` nhận tối đa {MAX_GRAPHICS} đồ họa diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3fe2f9e009..2033b20112 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5915,8 +5915,8 @@ lighting Light 光源 @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` 的 face 必须是 front 或 back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` 的 {key} 必须是 {lo} 到 {hi} 之间的数字 @msg `{GRAPHICS}` must be an array `{GRAPHICS}` 必须是数组 -@msg Graphics map onto the Plane, Extrude and Revolve object types 图形映射到平面、突出和回转对象类型上 - Graphics map onto the Plane, Extrude and Revolve object types. 图形映射到平面、突出和回转对象类型上。 +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 图形映射到平面、突出、回转和膨胀对象类型上 + Graphics map onto the Plane, Extrude, Revolve and Inflate object types. 图形映射到平面、突出、回转和膨胀对象类型上。 @msg Revolve maps graphics onto its side: map them onto the front 回转将图形映射到其侧面:请将图形映射到正面 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 图形对此表面过于复杂:请简化符号的图稿或减少分段数 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` 最多接受 {MAX_GRAPHICS} 个图形 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ab7f9d9dd2..29ada7e4a4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5750,8 +5750,8 @@ lighting Light 光源 @msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` 的 face 必須是 front 或 back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` 的 {key} 必須是介於 {lo} 到 {hi} 之間的數字 @msg `{GRAPHICS}` must be an array `{GRAPHICS}` 必須是陣列 -@msg Graphics map onto the Plane, Extrude and Revolve object types 圖形會對應到「平面」、「突出」與「迴轉」物件類型 - Graphics map onto the Plane, Extrude and Revolve object types. 圖形會對應到「平面」、「突出」與「迴轉」物件類型。 +@msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 圖形會對應到「平面」、「突出」、「迴轉」與「膨脹」物件類型 + Graphics map onto the Plane, Extrude, Revolve and Inflate object types. 圖形會對應到「平面」、「突出」、「迴轉」與「膨脹」物件類型。 @msg Revolve maps graphics onto its side: map them onto the front 迴轉會將圖形對應到其側面:請將圖形對應到正面 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 圖形對此表面過於複雜:請簡化符號的圖稿或減少分段數 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` 最多接受 {MAX_GRAPHICS} 個圖形 diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 72ce8004b5..a76c6ce05c 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -438,12 +438,16 @@ fn the_materials_tab_lists_the_graphics_and_maps_one_in_one_undo_step() { let nodes = controls(&mut app, &ctx); named(&nodes, "Remove Graphic"); named(&nodes, "Scale"); - // Inflate takes no graphics. + // Inflate keeps the graphic and lists it with its face and settings. set_type(&mut app, "inflate").unwrap(); + assert_eq!(graphics(&app).as_array().map(Vec::len), Some(1)); + let nodes = controls(&mut app, &ctx); + named(&nodes, "Remove Graphic"); + named(&nodes, "Scale"); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui)); out.textures_delta.clear(); let text = crate::tests_labels::shapes_text(&out); - assert!(text.contains("Graphics map onto the Plane, Extrude and Revolve object types"), "{text}"); + assert!(text.contains("Face") && !text.contains("Graphics map onto"), "{text}"); } #[test] diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 342a5171b6..219e5b9621 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -180,7 +180,7 @@ VectorCraft choices; an original approximation, never compared with another appl |---|---| | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | -| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, soft shadows or ray tracing | +| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, wrapped around Revolve's side, and carried onto Inflate's puffed front and back ([three-d.md](three-d.md#graphics)); no base materials, graphics on Extrude & Bevel's walls and bevels, soft shadows or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Map Art: none | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object collects an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | diff --git a/docs/mcp.md b/docs/mcp.md index 8ca4121032..12b57030b1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4114,15 +4114,17 @@ offset in points of the graphic's center from the center of the object's bounds percentage of the symbol's size (1..10000; omitted, 100 or less so the graphic fits inside the object) and `rotation` is in degrees counterclockwise (-360..360). Without `index` each object's first 3D effect takes it, and `item` is refused. Every object's 3D effect must be Extrude & Bevel with Cap on (front only at a depth of 0), Rotate (the Plane type, -front only) or Revolve (front only: its swept side), and `symbol` must name a document symbol; otherwise the command is refused and nothing changes. It returns `{ids, graphic}`. +front only), Revolve (front only: its swept side) or Inflate (back only with Both sides and Cap on), and `symbol` must name a document symbol; otherwise the command is refused and nothing changes. It returns `{ids, graphic}`. On Revolve, `x` and `y` are measured on the side unrolled flat from its middle, and a graphic that does not fit starts scaled to fit the half of the side seen from the front ([three-d.md](three-d.md#graphics)). +On Inflate, `x` and `y` are measured in the art's plane, and the graphic is carried straight out onto the puffed +face, Twist and Taper turning and shrinking the back's with it. -The graphics are the `graphics` parameter of `threeD.extrude`, `threeD.rotate` and `threeD.revolve`, which `effect.setParams` also +The graphics are the `graphics` parameter of `threeD.extrude`, `threeD.rotate`, `threeD.revolve` and `threeD.inflate`, which `effect.setParams` also edits: an array of up to 64 `{symbol, face, x, y, scale, rotation}` objects, drawn on the face turned, foreshortened and shaded with it and clipped to it ([Map artworks on 3D object](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). Revolve takes graphics on its swept side and shades them with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)); -how a graphic wraps around the side is VectorCraft's own rule. +how a graphic wraps around the side, and how one follows Inflate's puff, are VectorCraft's own rules. A graphic naming a symbol the document does not have is refused, unless the effect already holds a graphic of it. The drawing rules are VectorCraft's own; see [three-d.md](three-d.md#graphics). diff --git a/docs/three-d.md b/docs/three-d.md index f12ca4675c..acfa006845 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -364,8 +364,8 @@ The public [Map artworks on 3D object](https://helpx.adobe.com/illustrator/deskt page describes graphics: art kept with the document and placed on single surfaces of a 3D object, and the [3D and Materials panel options](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html) page lists Graphics and Add Materials and Graphics on the Materials tab. VectorCraft maps graphics onto -Extrude & Bevel's front and back caps, the plane of the Plane type (Rotate), and the swept side of Revolve, which the -public page's example of a label on a bottle describes. +Extrude & Bevel's front and back caps, the plane of the Plane type (Rotate), the swept side of Revolve, which the +public page's example of a label on a bottle describes, and Inflate's puffed front and back. - The panel's **Materials** tab shows the document's graphics as thumbnails. A graphic is a document symbol, as the public page allows existing symbols to be used. **Add as Single Graphic** keeps the selected art as a new @@ -374,7 +374,7 @@ public page's example of a label on a bottle describes. - Clicking a thumbnail maps that graphic onto the front of the 3D effect of each selected object (`threeD.mapGraphic`), in one undo step. A graphic larger than the object starts scaled down to fit inside it. - Below the thumbnails the tab lists the graphics mapped onto the first selected object. The selected one shows - its Face (Front or Back; Plane and Revolve show no Face, as a plane has only a front and Revolve's graphics go + its Face (Front or Back, on Inflate its puffed front or back; Plane and Revolve show no Face, as a plane has only a front and Revolve's graphics go on its side), X and Y (the offset of its center from the center of the object's bounds, in the face's plane), Scale (a percentage of the symbol's size) and Rotation (counterclockwise), and **Remove Graphic** takes it off. Each change is one undo step. @@ -397,6 +397,17 @@ These rules are VectorCraft's own: their own. A graphic on a face turned away from the viewer is not drawn. - On the back cap, X runs to the right as the back is seen from behind, so the graphic reads the right way round there. +- On Inflate a graphic is placed in the art's plane, X and Y measured from the center of the object's bounds as on + a cap, and carried straight out onto the puffed face above each point, so it follows the puff. The back takes + graphics only with Both sides and Cap on (`threeD.mapGraphic` refuses one otherwise, and one already there is + not drawn); it reads the right way round from behind, and Twist and Taper turn and shrink its graphics with it. + The membrane is cut into triangles, and each one draws the part of the graphic that falls on it, shaded as + that triangle is shaded and drawn only where the surface's outside faces the viewer; nearer triangles drawn + after it cover it. A cell of the membrane that cannot be cut into triangles takes no graphic. Every solid of + the object (a fill's, and a stroke's outline) carries the graphics. The handle sits on the point of the puffed + face above the graphic's center, and only where the viewer sees that face. The cutting into straight pieces, + the seam strokes and the limits below are those of Revolve; when the triangles take more faces than a 3D + effect draws, the object draws without its graphics and commands refuse them. - On Revolve a graphic lies on the swept side, which has one face (Front), unrolled flat. X runs around the axis: the angle from the middle of the side times the profile's distance from the axis at that point, so a graphic keeps its size at every distance and wraps farther around the axis where the profile comes nearer to it. Y runs @@ -431,9 +442,9 @@ These rules are VectorCraft's own: past either limit. A loaded file draws the object without a graphic past the first limit, and without all of its graphics past the second. - A hollow Extrude & Bevel has no caps, so its graphics are not drawn until Cap is turned on again, and - `threeD.mapGraphic` refuses to map a new one onto it. Changing the type to Inflate drops the graphics, and - changing between Extrude, Plane and Revolve keeps them, except that Plane and Revolve drop the graphics on the - back cap; on Revolve the front's graphics go on its side. + `threeD.mapGraphic` refuses to map a new one onto it. Changing between Extrude, Plane, Revolve and Inflate keeps + the graphics, except that Plane and Revolve drop the graphics on the back cap; on Revolve the front's graphics go + on its side, and on Inflate they go on the puffed faces. - `effect.apply` and `effect.setParams` refuse a graphic that names a symbol the document does not have, unless the effect already holds a graphic of that symbol. A graphic whose symbol is deleted is no longer drawn. Renaming a symbol renames it in the graphics that use it, in the layers, in the art of symbols, patterns, graph designs, brushes and opacity masks, and in graphic @@ -447,7 +458,7 @@ These rules are VectorCraft's own: uses: `rotationX`, `rotationY`, `rotationZ`, `perspectiveAngle` (degrees), `shade`, `lightColor` (`#rrggbb`, default `#ffffff`), `lightIntensity` (%), `lightRotation`, `lightHeight` (degrees), `lightSoftness` (%), `ambient` (%, to 200), `lightBehind`. Lengths are points and scale with the object (Scale Strokes & Effects). Commands validate the shape and the parameters before the document changes. All four also take `lights`: null (the default, use the earlier single-light fields), or an array of one to ten objects. Each object takes `color` (opaque `#rrggbb`, white), `intensity` (0..100%, 80), `rotation` (-180..180 degrees, 125.26), `height` (0..90 degrees, 30), `softness` (0..100%, 0), and `behind` (boolean, false). Omitted settings use those defaults. An explicit list replaces the earlier single light; `ambient` and `shade` remain shared. Set `lights` to null to return to the single-light fields. Invalid lists, counts, keys and values are rejected before editing; malformed loaded lists fall back to the earlier light safely. All four take `shadow` (boolean, false), `shadowPosition` (`behind` or `below`), `shadowDistance` (0..100%, 0) and `shadowBounds` (10..400%, 100) ([Shadows](#shadows)); values out of range are rejected before editing. -`threeD.extrude`, `threeD.rotate` and `threeD.revolve` take `graphics` ([Graphics](#graphics)): an array of up to 64 objects, each +`threeD.extrude`, `threeD.rotate`, `threeD.revolve` and `threeD.inflate` take `graphics` ([Graphics](#graphics)): an array of up to 64 objects, each with `symbol` (the name of a document symbol), `face` (`front` or `back`, default `front`; `threeD.rotate` and `threeD.revolve` take `front` only), `x` and `y` (points, default 0), `scale` (1..10000%, default 100) and `rotation` (-360..360 degrees, default 0). Other keys, values out of range and graphics on the other 3D effects are rejected before editing. @@ -459,10 +470,10 @@ and [Create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effe pages, and the archived Extrude & Bevel option list (depth 0–2,000, cap on/off, bevel height, bevel extent in or out, perspective). No Adobe software, assets, presets or bevel shapes were used. -- **Materials** (base and Adobe Substance), graphics on Inflate and on Extrude & Bevel's walls and bevels, soft +- **Materials** (base and Adobe Substance), graphics on Extrude & Bevel's walls and bevels, soft shadows, shadows of lights after the first, and **ray-traced rendering** are not built: shading uses directional lights, in the paint of the fill or stroke the solid is built for ([Fills and strokes](#fills-and-strokes)), and - the shadow is hard-edged ([Shadows](#shadows)). Graphics map onto planar faces and Revolve's side only + the shadow is hard-edged ([Shadows](#shadows)). Graphics map onto planar faces, Revolve's side and Inflate's puffed faces only ([Graphics](#graphics)). - The bevel shapes and their names are our own; custom bevel paths are not supported. - Visibility is a painter's algorithm: faces of a closed solid turned away are left out, and the rest are drawn From 0dc5ecfbb0f439c725d3b24e2c062ecf197a9ab2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:29:28 -0800 Subject: [PATCH 08/69] i18n: Map Graphic's Inflate back refusal is translated threeD.mapGraphic refuses Inflate's back while Both sides or Cap is off, and that message had no @msg row in any catalog, so it showed in English in every language. Each complete-message catalog now has a row for it, next to the Revolve refusal, and a test checks that the refusal shows translated, with the object's number, in every complete-message language. --- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 25 files changed, 46 insertions(+) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f552f968f8..bc61095051 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6357,6 +6357,7 @@ digits Malayalam Malaiàlam @msg `{GRAPHICS}` must be an array `{GRAPHICS}` ha de ser una matriu @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió, Revolució i Infla @msg Revolve maps graphics onto its side: map them onto the front Revoluciona aplica els gràfics al seu lateral: aplica’ls a la cara davantera +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on l’objecte {_1}: la cara posterior d’Infla només admet gràfics amb Tots dos costats i Tapa activats @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Els gràfics són massa complexos per a aquesta superfície: simplifica la il·lustració dels símbols o redueix Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admet com a màxim {MAX_GRAPHICS} gràfics @msg A plane has one face: map its graphics onto the front Un pla té una sola cara: aplica’n els gràfics a la cara davantera diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 5bd83f10cc..bc93c728ad 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6154,6 +6154,7 @@ mark-style Japanese Japonské @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musí být pole @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafika se mapuje na typy objektu Rovina, Vysunutí, Rotační těleso a Nafouknutí @msg Revolve maps graphics onto its side: map them onto the front Rotační těleso mapuje grafiku na svůj bok: umístěte ji na přední stranu +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objekt {_1}: zadní strana Nafouknutí přijímá grafiku jen se zapnutými volbami Obě strany a Uzávěr @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafika je pro tento povrch příliš složitá: zjednodušte kresbu symbolů nebo snižte Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` přijímá nejvýše {MAX_GRAPHICS} grafik @msg A plane has one face: map its graphics onto the front Rovina má jednu stranu: umístěte její grafiku na přední stranu diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d5464fa7f8..d1c920ea61 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -333,6 +333,7 @@ @msg `{GRAPHICS}` must be an array `{GRAPHICS}` skal være et array @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafik kortlægges på objekttyperne Plan, Ekstrudér, Omdrej og Pust op @msg Revolve maps graphics onto its side: map them onto the front Omdrej kortlægger grafik på siden: kortlæg den på forsiden +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objektet {_1}: bagsiden af Pust op tager kun imod grafik, når Begge sider og Kappe er slået til @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikken er for kompleks til denne overflade: forenkl symbolernes grafik, eller reducér Segmenter @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tager højst {MAX_GRAPHICS} grafikelementer @msg A plane has one face: map its graphics onto the front Et plan har én flade: kortlæg dets grafik på forsiden diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 7ab61d0481..518d4c1c01 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5725,6 +5725,7 @@ lighting Light Licht @msg `{GRAPHICS}` must be an array `{GRAPHICS}` muss ein Array sein @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiken werden auf die Objekttypen Ebene, Extrudieren, Kreiseln und Aufblasen abgebildet @msg Revolve maps graphics onto its side: map them onto the front Kreiseln bildet Grafiken auf seiner Mantelfläche ab: Bilden Sie sie auf der Vorderseite ab +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on Objekt {_1}: Die Rückseite von „Aufblasen“ nimmt Grafiken nur mit aktivierten Optionen „Beidseitig“ und „Deckflächen“ auf @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Die Grafiken sind für diese Oberfläche zu komplex: Vereinfachen Sie das Bildmaterial der Symbole oder verringern Sie Segmente @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` nimmt höchstens {MAX_GRAPHICS} Grafiken auf @msg A plane has one face: map its graphics onto the front Eine Ebene hat nur eine Seite: Bilden Sie ihre Grafiken auf der Vorderseite ab diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 13d301b21b..69f29e8d8b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5528,6 +5528,7 @@ digits Malayalam Μαλαγιάλαμ @msg `{GRAPHICS}` must be an array το `{GRAPHICS}` πρέπει να είναι πίνακας @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση, Περιστροφή γύρω από άξονα και Φούσκωμα @msg Revolve maps graphics onto its side: map them onto the front Η Περιστροφή γύρω από άξονα αντιστοιχίζει τα γραφικά στην πλευρική της επιφάνεια: αντιστοιχίστε τα στην μπροστινή όψη +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on το αντικείμενο {_1}: η πίσω όψη του Φουσκώματος δέχεται γραφικά μόνο με ενεργά τα Και οι δύο πλευρές και Κλείσιμο άκρου @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Τα γραφικά είναι πολύ σύνθετα για αυτή την επιφάνεια: απλοποιήστε το σχέδιο των συμβόλων ή μειώστε τα Τμήματα @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics το `{GRAPHICS}` δέχεται το πολύ {MAX_GRAPHICS} γραφικά @msg A plane has one face: map its graphics onto the front Ένα επίπεδο έχει μία όψη: αντιστοιχίστε τα γραφικά του στην μπροστινή όψη diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9b31169a5f..ca1ed2ad54 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6108,6 +6108,7 @@ mark-style Japanese Japonesas @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión, Revolución e Inflar Graphics map onto the Plane, Extrude, Revolve and Inflate object types. Los gráficos se asignan a los tipos de objeto Plano, Extrusión, Revolución e Inflar. @msg Revolve maps graphics onto its side: map them onto the front Revolución asigna los gráficos a su lateral: asígnelos a la cara frontal +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on el objeto {_1}: la cara posterior de Inflar admite gráficos solo con Ambos lados y Tapa activados @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Los gráficos son demasiado complejos para esta superficie: simplifique la ilustración de los símbolos o reduzca Segmentos @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admite como máximo {MAX_GRAPHICS} gráficos @msg A plane has one face: map its graphics onto the front Un plano tiene una sola cara: asigne sus gráficos a la cara frontal diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 4634f0e67a..a43c7f1990 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6049,6 +6049,7 @@ mark-style Japanese Japanilainen @msg `{GRAPHICS}` must be an array `{GRAPHICS}` on oltava taulukko @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiikat sijoitetaan objektityypeille Taso, Pursota, Pyöräytä ja Täytä ilmalla @msg Revolve maps graphics onto its side: map them onto the front Pyöräytä sijoittaa grafiikat kylkeensä: sijoita ne etupuolelle +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objekti {_1}: Täytä ilmalla -tehosteen takapuoli ottaa grafiikoita vain, kun Molemmat puolet ja Pääty ovat käytössä @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiikat ovat liian monimutkaisia tälle pinnalle: yksinkertaista symbolien kuvitusta tai pienennä Segmentit-arvoa @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` hyväksyy enintään {MAX_GRAPHICS} grafiikkaa @msg A plane has one face: map its graphics onto the front Tasolla on yksi puoli: sijoita sen grafiikat etupuolelle diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 72ab16b430..b6a666f4d1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5722,6 +5722,7 @@ lighting Light Lumière @msg `{GRAPHICS}` must be an array `{GRAPHICS}` doit être un tableau @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Les graphiques s'appliquent aux types d'objet Plan, Extrusion, Révolution et Gonfler @msg Revolve maps graphics onto its side: map them onto the front Révolution applique les graphiques sur sa face latérale : appliquez-les sur la face avant +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objet {_1} : l’arrière de Gonfler n’accepte des graphiques qu’avec Deux côtés et Fermeture activés @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Les graphiques sont trop complexes pour cette surface : simplifiez l'illustration des symboles ou réduisez Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accepte au plus {MAX_GRAPHICS} graphiques @msg A plane has one face: map its graphics onto the front Un plan n'a qu'une face : appliquez ses graphiques sur la face avant diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 198d9b740c..99c831f667 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8190,6 +8190,7 @@ antiAlias Sharp शार्प @msg `{GRAPHICS}` must be an array `{GRAPHICS}` एक ऐरे होना चाहिए @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types ग्राफ़िक्स समतल, एक्सट्रूड, रिवॉल्व और फुलाएँ ऑब्जेक्ट प्रकारों पर लगते हैं @msg Revolve maps graphics onto its side: map them onto the front रिवॉल्व ग्राफ़िक्स को अपनी बगल वाली सतह पर लगाता है: उन्हें सामने वाले फ़ेस पर लगाएँ +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on ऑब्जेक्ट {_1}: फुलाएँ का पिछला फ़ेस ग्राफ़िक्स तभी लेता है जब दोनों तरफ़ और कैप चालू हों @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments ग्राफ़िक्स इस सतह के लिए बहुत जटिल हैं: सिंबल्स के आर्ट को सरल बनाएँ या सेगमेंट कम करें @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` अधिकतम {MAX_GRAPHICS} ग्राफ़िक्स लेता है @msg A plane has one face: map its graphics onto the front समतल का एक ही फ़ेस होता है: उसके ग्राफ़िक्स को सामने वाले फ़ेस पर लगाएँ diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a0182d1f0f..ce9870eb87 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6138,6 +6138,7 @@ imageTrace Outline Körvonal @msg `{GRAPHICS}` must be an array a `{GRAPHICS}` értéke tömb kell legyen @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types A grafikák a Sík, a Kihúzás, a Forgatás tengely körül és a Felfújás objektumtípusra kerülnek @msg Revolve maps graphics onto its side: map them onto the front A Forgatás tengely körül a grafikákat a palástjára helyezi: az elülső oldalra helyezze őket +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on {_1} objektum: a Felfújás hátoldala csak a Mindkét oldal és a Zárólap bekapcsolásával fogad grafikát @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments A grafikák túl összetettek ehhez a felülethez: egyszerűsítse a szimbólumok rajzát, vagy csökkentse a Szakaszok értékét @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics a `{GRAPHICS}` legfeljebb {MAX_GRAPHICS} grafikát fogad @msg A plane has one face: map its graphics onto the front A síknak egy oldala van: a grafikáit az elülső oldalra helyezze diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8616ae9c25..2cf2c5020a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5769,6 +5769,7 @@ lighting Light Luce @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve essere un array @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Le grafiche si applicano ai tipi di oggetto Piano, Estrusione, Rivoluzione e Gonfia @msg Revolve maps graphics onto its side: map them onto the front Rivoluzione applica le grafiche sul suo lato: applicatele sulla faccia anteriore +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on oggetto {_1}: il retro di Gonfia accetta grafiche solo con Entrambi i lati e Chiusura attivi @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Le grafiche sono troppo complesse per questa superficie: semplificate il disegno dei simboli o riducete Segmenti @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accetta al massimo {MAX_GRAPHICS} grafiche @msg A plane has one face: map its graphics onto the front Un piano ha una sola faccia: applicate le sue grafiche sulla faccia anteriore diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index cdfe627f57..5c2d2e8948 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5813,6 +5813,7 @@ lighting Light ライト @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types グラフィックはオブジェクトの種類が平面、押し出し、回転体、膨張のときにマッピングされます Graphics map onto the Plane, Extrude, Revolve and Inflate object types. グラフィックはオブジェクトの種類が平面、押し出し、回転体、膨張のときにマッピングされます。 @msg Revolve maps graphics onto its side: map them onto the front 回転体はグラフィックを側面にマッピングします。前面にマッピングしてください +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on オブジェクト {_1}: 「膨張」の背面にグラフィックをマッピングするには「両面」と「キャップ」をオンにしてください @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments グラフィックがこのサーフェスには複雑すぎます。シンボルのアートを単純化するか、分割数を減らしてください @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` に指定できるグラフィックは {MAX_GRAPHICS} 個までです @msg A plane has one face: map its graphics onto the front 平面には面が 1 つしかありません。グラフィックは前面にマッピングしてください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a02a2ffd30..ad71f6d901 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7514,6 +7514,7 @@ font-technology Variable ცვლადი @msg `{GRAPHICS}` must be an array `{GRAPHICS}` უნდა იყოს მასივი @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“, „ბრუნვა“ და „გაბერვა“ @msg Revolve maps graphics onto its side: map them onto the front ბრუნვა გრაფიკას თავის გვერდით ზედაპირზე ათავსებს: განათავსეთ ისინი წინა მხარეზე +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on ობიექტი {_1}: გაბერვის უკანა მხარე გრაფიკას იღებს მხოლოდ ჩართული „ორივე მხარე“ და „თავსახური“ პარამეტრებით @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments გრაფიკა ზედმეტად რთულია ამ ზედაპირისთვის: გაამარტივეთ სიმბოლოების ნახატი ან შეამცირეთ სეგმენტები @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` იღებს მაქსიმუმ {MAX_GRAPHICS} გრაფიკას @msg A plane has one face: map its graphics onto the front სიბრტყეს ერთი მხარე აქვს: მისი გრაფიკა წინა მხარეზე განათავსეთ diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 213ef60172..e1148a76e0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5731,6 +5731,7 @@ lighting Light 광원 @msg `{GRAPHICS}` must be an array `{GRAPHICS}`은(는) 배열이어야 합니다 @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 그래픽은 평면, 돌출, 회전체, 부풀리기 개체 유형에 매핑됩니다 @msg Revolve maps graphics onto its side: map them onto the front 회전체는 그래픽을 옆면에 매핑합니다. 앞면에 매핑하십시오 +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on 개체 {_1}: 부풀리기의 뒷면에 그래픽을 매핑하려면 양면과 캡을 켜세요 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 그래픽이 이 표면에 비해 너무 복잡합니다. 심볼의 아트를 단순화하거나 세그먼트를 줄이십시오 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}`에는 그래픽을 최대 {MAX_GRAPHICS}개까지 넣을 수 있습니다 @msg A plane has one face: map its graphics onto the front 평면에는 면이 하나뿐입니다. 그래픽을 앞면에 매핑하십시오 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5f7cc834ce..f81a5d07ac 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7908,6 +7908,7 @@ mark-style Japanese Japans @msg Graphics map onto planar faces: use the Extrude or Plane object type Illustraties worden op platte vlakken geplaatst: gebruik het objecttype Extruderen of Vlak @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Illustraties worden op de objecttypen Vlak, Extruderen, Draaien en Opblazen geplaatst @msg Revolve maps graphics onto its side: map them onto the front Draaien plaatst illustraties op de zijkant: plaats ze op de voorkant +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on object {_1}: de achterkant van Opblazen neemt alleen afbeeldingen aan met Beide zijden en Dop ingeschakeld @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments De illustraties zijn te complex voor dit oppervlak: vereenvoudig de illustraties van de symbolen of verlaag Segmenten @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` neemt maximaal {MAX_GRAPHICS} illustraties op @msg A plane has one face: map its graphics onto the front Een vlak heeft één zijde: plaats de illustraties ervan op de voorkant diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 7130db0392..3aae706a4b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5984,6 +5984,7 @@ mark-style Japanese Japońskie @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musi być tablicą @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiki są nakładane na obiekty typu Płaszczyzna, Wyciągnięcie, Obrót i Nadmuchanie @msg Revolve maps graphics onto its side: map them onto the front Obrót nakłada grafiki na swoją powierzchnię boczną: umieść je na przedniej stronie +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on obiekt {_1}: tył Nadmuchania przyjmuje grafiki tylko przy włączonych opcjach Obie strony i Zakończenie @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiki są zbyt złożone dla tej powierzchni: uprość rysunki symboli lub zmniejsz Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` przyjmuje najwyżej {MAX_GRAPHICS} grafik @msg A plane has one face: map its graphics onto the front Płaszczyzna ma jedną stronę: umieść jej grafiki na przedniej stronie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 9ff4493250..938e74605b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6105,6 +6105,7 @@ mark-style Japanese Japonesas @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve ser uma matriz @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Os gráficos são mapeados nos tipos de objeto Plano, Extrusão, Revolver e Inflar @msg Revolve maps graphics onto its side: map them onto the front Revolver mapeia os gráficos na sua lateral: mapeie-os na face frontal +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objeto {_1}: o verso de Inflar recebe gráficos apenas com Ambos os Lados e Tampa ativados @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Os gráficos são complexos demais para esta superfície: simplifique a arte dos símbolos ou reduza Segmentos @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` aceita no máximo {MAX_GRAPHICS} gráficos @msg A plane has one face: map its graphics onto the front Um plano tem uma única face: mapeie seus gráficos na face frontal diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 21a7cf7af1..b6fd9ade6f 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5767,6 +5767,7 @@ lighting Light Свет @msg `{GRAPHICS}` must be an array `{GRAPHICS}` должен быть массивом @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графика наносится на объекты типов «Плоскость», «Выдавливание», «Вращение» и «Надувание» @msg Revolve maps graphics onto its side: map them onto the front «Вращение» наносит графику на свою боковую поверхность: размещайте её на передней стороне +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on объект {_1}: задняя сторона «Надувания» принимает графику только при включённых параметрах «С обеих сторон» и «Торцы» @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графика слишком сложна для этой поверхности: упростите иллюстрации символов или уменьшите «Сегменты» @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` принимает не более {MAX_GRAPHICS} графических элементов @msg A plane has one face: map its graphics onto the front У плоскости одна сторона: размещайте её графику на передней стороне diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 53c8b2a9dc..5d19bb0562 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5630,6 +5630,7 @@ lighting Light Ljus @msg `{GRAPHICS}` must be an array `{GRAPHICS}` måste vara en matris @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafik placeras på objekttyperna Plan, Extrudera, Rotera runt axel och Blås upp @msg Revolve maps graphics onto its side: map them onto the front Rotera runt axel placerar grafik på sin mantelyta: placera den på framsidan +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objekt {_1}: baksidan av Blås upp tar emot grafik bara när Båda sidor och Lock är på @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiken är för komplex för den här ytan: förenkla symbolernas teckning eller minska Segment @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tar högst {MAX_GRAPHICS} grafiker @msg A plane has one face: map its graphics onto the front Ett plan har en sida: placera dess grafik på framsidan diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b632e5cac3..b11b4676ef 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2772,6 +2772,28 @@ fn three_d_refusals_translate_with_their_values() { assert_eq!(message(de(), &errors[1].0), "ungültige Parameter für `effect.apply`: Licht: intensity muss eine Zahl von 0 bis 100 sein"); } +/// Map Graphic's refusal of Inflate's back while Both sides or Cap is off shows in every +/// complete-message language, with the object's number as given. +#[test] +fn inflate_back_refusal_translates_in_every_complete_catalog() { + use serde_json::json; + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let mark = s.execute("path.create", &json!({"d": "M300 300L310 300L310 320L300 320Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [mark]})).unwrap(); + let id = s.execute("path.create", &json!({"d": "M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "threeD.inflate", "item": null, "params": {}})).unwrap(); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id]})).unwrap_err().to_string(); + let english = "Inflate's back takes graphics with Both sides and Cap on"; + assert!(e.ends_with(&format!("object {id}: {english}")), "{e}"); + assert_eq!(message(Lang::EN, &e), e); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &e); + assert!(!shown.contains(english) && shown.contains(&id.to_string()) && shown.contains("`threeD.mapGraphic`"), "{code}: {e} -> {shown}"); + } +} + /// A value a message quotes is a name and is shown as written, even when a catalog row translates /// the same text: a symbol called Rotate stays Rotate while the effect's name is translated. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 6a0254cb9f..7867dd5f2f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5474,6 +5474,7 @@ lighting Light Işık @msg `{GRAPHICS}` must be an array `{GRAPHICS}` bir dizi olmalıdır @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafikler Düzlem, Ekstrüzyon, Döndür ve Şişir nesne türlerine eşlenir @msg Revolve maps graphics onto its side: map them onto the front Döndür grafikleri yan yüzeyine eşler: onları ön yüze eşle +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on nesne {_1}: Şişir efektinin arka yüzü yalnızca Her iki taraf ve Kapak açıkken grafik alır @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikler bu yüzey için çok karmaşık: sembollerin resmini basitleştir veya Segmentler değerini azalt @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` en fazla {MAX_GRAPHICS} grafik alır @msg A plane has one face: map its graphics onto the front Bir düzlemin tek yüzü vardır: grafiklerini ön yüze eşle diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 44c176f2c0..b1a36df896 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5749,6 +5749,7 @@ lighting Light Світло @msg `{GRAPHICS}` must be an array `{GRAPHICS}` має бути масивом @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графіка наноситься на об’єкти типів «Площина», «Видавлювання», «Обертання» та «Надування» @msg Revolve maps graphics onto its side: map them onto the front «Обертання» наносить графіку на свою бічну поверхню: розміщуйте її на передній стороні +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on об’єкт {_1}: задній бік «Надування» приймає графіку лише з увімкненими параметрами «З обох боків» і «Торці» @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графіка надто складна для цієї поверхні: спростіть ілюстрації символів або зменште «Сегменти» @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` приймає не більше {MAX_GRAPHICS} графічних елементів @msg A plane has one face: map its graphics onto the front Площина має одну сторону: розміщуйте її графіку на передній стороні diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8b2a49afc3..07b6c6b51b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5550,6 +5550,7 @@ theme Appearance Giao diện @msg `{GRAPHICS}` must be an array `{GRAPHICS}` phải là một mảng @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Đồ họa được đặt lên các loại đối tượng Mặt phẳng, Kéo dài, Xoay tròn và Phình @msg Revolve maps graphics onto its side: map them onto the front Xoay tròn đặt đồ họa lên mặt bên của nó: hãy đặt chúng lên mặt trước +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on đối tượng {_1}: mặt sau của Phình chỉ nhận đồ họa khi bật Cả hai mặt và Nắp @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Đồ họa quá phức tạp cho bề mặt này: hãy đơn giản hóa hình vẽ của các ký hiệu hoặc giảm Đoạn @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` nhận tối đa {MAX_GRAPHICS} đồ họa @msg A plane has one face: map its graphics onto the front Mặt phẳng chỉ có một mặt: hãy đặt đồ họa của nó lên mặt trước diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 542eaf60d8..ebc782b2de 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6024,6 +6024,7 @@ lighting Light 光源 @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 图形映射到平面、突出、回转和膨胀对象类型上 Graphics map onto the Plane, Extrude, Revolve and Inflate object types. 图形映射到平面、突出、回转和膨胀对象类型上。 @msg Revolve maps graphics onto its side: map them onto the front 回转将图形映射到其侧面:请将图形映射到正面 +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on 对象 {_1}:只有打开“双面”和“封口”后,膨胀的背面才能贴图 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 图形对此表面过于复杂:请简化符号的图稿或减少分段数 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` 最多接受 {MAX_GRAPHICS} 个图形 @msg A plane has one face: map its graphics onto the front 平面只有一个面:请将其图形映射到正面 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ccaa45c48a..4fb593e175 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5860,6 +5860,7 @@ lighting Light 光源 @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 圖形會對應到「平面」、「突出」、「迴轉」與「膨脹」物件類型 Graphics map onto the Plane, Extrude, Revolve and Inflate object types. 圖形會對應到「平面」、「突出」、「迴轉」與「膨脹」物件類型。 @msg Revolve maps graphics onto its side: map them onto the front 迴轉會將圖形對應到其側面:請將圖形對應到正面 +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on 物件 {_1}:只有開啟「雙面」和「封口」後,膨脹的背面才能對應圖形 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 圖形對此表面過於複雜:請簡化符號的圖稿或減少分段數 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` 最多接受 {MAX_GRAPHICS} 個圖形 @msg A plane has one face: map its graphics onto the front 平面只有一個面:請將其圖形對應到正面 From 3f23c67afefb0a19024187725061b8b507f6224c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:03:58 -0800 Subject: [PATCH 09/69] 3D: graphics on Inflate cover cells around a hole A cell of Inflate's front or back that held a whole hole, or a piece with more than 128 corners, was drawn as one polygon without the art points graphics need, so a graphic crossing it left a gap there. With graphics mapped, such a cell is now cut into triangles with its holes bridged, keeping the corners along its border that neighboring cells share, and each triangle carries its art points. All such cells of one surface share one work budget, and the cut stops as soon as it passes that budget. A cell whose pieces have more than 4,096 corners, or a surface past the budget, is refused as too complex. --- crates/three-d/src/mesh.rs | 42 +++++++++++++--- crates/three-d/src/mesh/tests.rs | 30 ++++++++++++ crates/three-d/src/solid.rs | 4 +- crates/three-d/src/solid/inflate.rs | 48 ++++++++++++++++-- crates/three-d/src/solid/tests.rs | 75 +++++++++++++++++++++++++++++ 5 files changed, 187 insertions(+), 12 deletions(-) diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index cd9623191c..fc01b76785 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -8,7 +8,7 @@ //! turned plane) are cut into triangles: each hole is joined to its outline by a bridge, then the //! outline is cut by ear clipping. -use vectorcraft_geom::{FillRule, PathData, Rect}; +use vectorcraft_geom::{FillRule, PathData, Point, Rect}; use crate::solid::{Face3, Keep, extrude_faces, inflate_faces, plane_faces}; use crate::{Extrude, Facet, Inflate, Revolve, V3, View}; @@ -211,6 +211,12 @@ fn spend(work: &mut usize, steps: usize) -> Result<(), String> { /// The triangles covering one face: `contours` (outlines one way round, holes the other) on the /// plane across `normal` (its Newell normal). fn triangulate(contours: &[Vec], normal: V3, work: &mut usize) -> Result, String> { + triangulate_keeping(contours, normal, work, false) +} + +/// [`triangulate`], keeping the corners that lie straight between their neighbors as triangle +/// corners when `keep_straight` is set. +fn triangulate_keeping(contours: &[Vec], normal: V3, work: &mut usize, keep_straight: bool) -> Result, String> { // Cut the face on the coordinate plane it is least slanted to, turned so outlines run // counterclockwise. let (ax, ay, az) = (normal.0.abs(), normal.1.abs(), normal.2.abs()); @@ -281,11 +287,30 @@ fn triangulate(contours: &[Vec], normal: V3, work: &mut usize) -> Result], work: &mut usize, budget: usize) -> Option> { + let contours: Vec> = rings.iter().map(|r| r.iter().map(|q| V3(q.x, q.y, 0.0)).collect()).collect(); + // Counted up from MAX_WORK less the budget, the cut's own checks stop it at the budget. + let start = MAX_WORK - budget.min(MAX_WORK); + let mut spent = start.saturating_add(*work); + let triangles = triangulate_keeping(&contours, V3(0.0, 0.0, 1.0), &mut spent, true); + *work = spent.saturating_sub(start); + let triangles = triangles.ok()?; + let triangles = triangles.into_iter().map(|t| t.map(|v| Point::new(v.0, v.1))); + Some(triangles.filter(|[a, b, c]| (*b - *a).cross(*c - *a) > 0.0).collect()) +} + /// Do segments `a`–`b` and `c`–`d` cross (touching at a shared end does not count)? fn crosses(a: (f64, f64), b: (f64, f64), c: (f64, f64), d: (f64, f64)) -> bool { let same = |p: (f64, f64), q: (f64, f64)| (p.0 - q.0).hypot(p.1 - q.1) < 1e-9; @@ -350,9 +375,10 @@ fn bridge(ring: Vec, hole: &[Corner], others: &[Vec], work: &mut } /// Cut `ring` (counterclockwise, possibly joined to its holes by bridges) into triangles by ear -/// clipping. A corner in line with its neighbors goes without a triangle. If no ear is left (a -/// ring that crosses itself), the rest is cut as a fan. -fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize) -> Result<(), String> { +/// clipping. A corner in line with its neighbors goes without a triangle, unless `keep_straight` +/// is set and it lies straight between them: it then stays a corner of the triangles beside it. If +/// no ear is left (a ring that crosses itself), the rest is cut as a fan. +fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight: bool) -> Result<(), String> { let n = ring.len(); if n < 3 { return Ok(()); @@ -368,8 +394,10 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize) -> Result<(), let turn = cross(pa, pb, pc); let scale = (pb.x - pa.x).hypot(pb.y - pa.y) * (pc.x - pb.x).hypot(pc.y - pb.y); let mut ear = false; - let drop = turn.abs() <= 1e-12 * scale.max(1e-300); - if !drop && turn > 0.0 { + let flat = turn.abs() <= 1e-12 * scale.max(1e-300); + let straight = keep_straight && flat && (pb.x - pa.x) * (pc.x - pb.x) + (pb.y - pa.y) * (pc.y - pb.y) > 0.0; + let drop = flat && !straight; + if !flat && turn > 0.0 { spend(work, left)?; ear = true; let mut k = next[c]; diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 76f9b04ecc..3866565d34 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -173,6 +173,36 @@ fn a_bridge_through_another_corner_touches_it() { assert!(!super::touches((5.0, 1.0), (0.0, 0.0), (10.0, 0.0))); } +#[test] +fn flat_triangles_keep_corners_that_lie_along_an_edge() { + // A square with a hole, its edges carrying corners midway, as a cell shares with its finer + // neighbors: every corner is a corner of some triangle, and the triangles cover the face. + let p = |x: f64, y: f64| Point::new(x, y); + let outline = vec![p(5.0, 0.0), p(10.0, 0.0), p(10.0, 5.0), p(10.0, 10.0), p(5.0, 10.0), p(0.0, 10.0), p(0.0, 5.0), p(0.0, 0.0)]; + let hole = vec![p(1.0, 4.0), p(1.0, 6.0), p(2.0, 6.0), p(2.0, 4.0)]; + let mut work = 0; + let triangles = flat_triangles(&[outline.clone(), hole], &mut work, usize::MAX).unwrap(); + let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0; + assert!(triangles.iter().all(|t| area(t) > 0.0)); + assert!((triangles.iter().map(area).sum::() - 98.0).abs() < 1e-9); + for q in &outline { + assert!(triangles.iter().any(|t| t.contains(q)), "{q:?} is no triangle's corner"); + } + assert!(work > 0); +} + +#[test] +fn flat_triangles_stop_at_their_budget() { + let p = |x: f64, y: f64| Point::new(x, y); + let outline = vec![p(0.0, 0.0), p(10.0, 0.0), p(10.0, 10.0), p(0.0, 10.0)]; + let hole = vec![p(1.0, 4.0), p(1.0, 6.0), p(2.0, 6.0), p(2.0, 4.0)]; + let mut all = 0; + assert!(flat_triangles(&[outline.clone(), hole.clone()], &mut all, usize::MAX).is_some()); + let mut work = 0; + assert!(flat_triangles(&[outline, hole], &mut work, all - 1).is_none()); + assert!(work >= all, "{work} of {all}"); +} + #[test] fn a_beveled_extrusion_stays_closed() { let mut b = BezPath::new(); diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index a66e72af1c..428acca547 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -29,10 +29,10 @@ use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; pub use build::{extrude, plane}; pub use face_map::{FaceMap, extrude_face_map, plane_face_map}; -#[cfg(test)] -use inflate::GRID_WORK; pub(crate) use inflate::inflate_faces; #[cfg(test)] +use inflate::{FLAT_BUDGET, FLAT_WORK, GRID_WORK, MAX_FLAT_CORNERS, MAX_FLAT_WORK}; +#[cfg(test)] pub(crate) use inflate::{INFLATED, PUFFED, SOLVE_FIRST}; pub use inflate::{inflate, inflate_each, inflate_together}; #[cfg(test)] diff --git a/crates/three-d/src/solid/inflate.rs b/crates/three-d/src/solid/inflate.rs index 5b3c883211..812cf88a42 100644 --- a/crates/three-d/src/solid/inflate.rs +++ b/crates/three-d/src/solid/inflate.rs @@ -196,6 +196,28 @@ thread_local! { pub(crate) static INFLATED: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The grid work of the last solid this thread inflated in full, for the tests. pub(super) static GRID_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The work of cutting cells with holes for graphics in the last solid this thread inflated + /// in full, for the tests. + pub(super) static FLAT_WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The work the next solids of this thread may take cutting cells with holes for graphics, + /// for the tests. + pub(super) static FLAT_BUDGET: std::cell::Cell = const { std::cell::Cell::new(MAX_FLAT_WORK) }; +} + +/// Most work one inflated surface may take cutting the cells graphics are mapped onto that +/// [`cell_triangles`] can't take (a hole inside the cell, or a ring of more corners), all its +/// cells together ([`crate::mesh::flat_triangles`]). +pub(super) const MAX_FLAT_WORK: usize = 1 << 26; + +/// Most corners the pieces of one such cell may have. +pub(super) const MAX_FLAT_CORNERS: usize = 4096; + +/// The work cutting cells with holes for graphics may take. +fn flat_budget() -> usize { + #[cfg(test)] + return FLAT_BUDGET.with(std::cell::Cell::get); + #[cfg(not(test))] + MAX_FLAT_WORK } /// Marks the facet the builder `b` added after it held `before` facets, if it added one, as a piece @@ -278,6 +300,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee // builds the topology of every outline ring near its cell, so a self-crossing outline cost its // crossings again in every cell it spans. Past it, cells take their clipped pieces. let material_left = std::cell::Cell::new(MAX_MATERIAL_SEGMENTS); + // The work of cutting cells with holes for graphics, all the cells together ([`MAX_FLAT_WORK`]). + let mut flat_work = 0usize; // Every ring's bounds, and the crossings of the last few rows the cells' centres lie on (a // row of cells has at most seven, at its three levels). let ring_bounds: Vec> = @@ -432,9 +456,25 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee // the front or back: each triangle then carries where its corners lie in the // art's plane. let smoothed = height > 0.0 && smooth; - if (smoothed || o.map_surface) - && let Some(triangles) = cell_triangles(&pieces) - { + let triangles = match (smoothed || o.map_surface).then(|| cell_triangles(&pieces)) { + // A cell graphics are mapped onto that the quick cut can't take (a hole + // inside it, or a ring of more corners) is cut with its holes, against one + // budget for the whole surface. Drawn whole instead, its piece would show + // no graphics. + Some(None) if o.map_surface => { + if pieces.iter().map(Vec::len).fold(0usize, usize::saturating_add) > MAX_FLAT_CORNERS { + return Err(TOO_COMPLEX_SURFACE.into()); + } + let budget = flat_budget(); + let holed = crate::mesh::flat_triangles(&pieces, &mut flat_work, budget); + if flat_work > budget { + return Err(TOO_COMPLEX_SURFACE.into()); + } + Some(holed.ok_or_else(|| TOO_COMPLEX_SURFACE.to_string())?) + } + quick => quick.flatten(), + }; + if let Some(triangles) = triangles { let order = if flat { Order::Last } else { Order::Depth }; for points in triangles { let front = points.map(|q| camera.place(q, half + lift(q))); @@ -550,6 +590,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee } #[cfg(test)] GRID_WORK.with(|w| w.set(edges.work())); + #[cfg(test)] + FLAT_WORK.with(|w| w.set(flat_work)); if edges.spent() { return Err(TOO_COMPLEX_SURFACE.into()); } diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index 0f527d968d..4e1a7f3247 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -464,6 +464,81 @@ fn inflate_marks_where_each_piece_lies_in_the_art_for_graphics() { assert!(on(Inflate::default(), behind).iter().all(|f| f.membrane != Some(PlanarFace::Back))); } +/// A square 0.3 pt across with its corner at the lattice point `(qx, qy)` of the grid of a +/// 100 pt shape, offset 0.1 pt: it lies inside one quarter cell of that grid. +fn speck(qx: f64, qy: f64) -> BezPath { + let unit = 100.0 / 48.0 / 4.0; + square(qx * unit + 0.1, qy * unit + 0.1, 0.3) +} + +/// The area of the pieces marked for graphics on `face`. +fn mapped_area(f: &[Facet], face: PlanarFace) -> f64 { + f.iter().filter(|f| f.membrane == Some(face)).map(|f| signed_area(&f.contours[0]).abs()).sum() +} + +/// A hole inside one cell of the surface's grid leaves that cell's piece with a hole in it: +/// graphics still map onto the rest of the cell, front and back, and the hole stays open. +#[test] +fn inflate_maps_graphics_around_a_hole_inside_one_cell() { + let mut b = square(0.0, 0.0, 100.0); + b.extend(speck(96.0, 96.0)); + let (p, r) = shape(&b); + let o = Inflate { map_surface: true, both_sides: true, ..Inflate::default() }; + let f = inflate(&p, FillRule::EvenOdd, r, o, front()).unwrap(); + let mapped = mapped_area(&f, PlanarFace::Front); + assert!(close(mapped, 100.0 * 100.0 - 0.3 * 0.3, 1e-3), "{mapped}"); + let f = inflate(&p, FillRule::EvenOdd, r, o, View { rotation_y: 180.0, ..front() }).unwrap(); + let mapped = mapped_area(&f, PlanarFace::Back); + assert!(close(mapped, 100.0 * 100.0 - 0.3 * 0.3, 1e-3), "{mapped}"); +} + +/// The cells graphics are mapped onto that need their holes cut out share one budget for the +/// whole surface: past it the surface is refused, however little each cell takes. +#[test] +fn inflate_cuts_holed_cells_for_graphics_within_one_budget() { + let mut b = square(0.0, 0.0, 100.0); + for i in 0..8 { + for j in 0..8 { + b.extend(speck(20.0 + 20.0 * i as f64, 20.0 + 20.0 * j as f64)); + } + } + let (p, r) = shape(&b); + let o = Inflate { map_surface: true, ..Inflate::default() }; + let f = inflate(&p, FillRule::EvenOdd, r, o, front()).unwrap(); + assert!(close(mapped_area(&f, PlanarFace::Front), 100.0 * 100.0 - 64.0 * 0.3 * 0.3, 1e-3)); + let all = FLAT_WORK.with(std::cell::Cell::get); + assert!(all > 0); + // Half the work all 64 cells took is far more than any one of them takes. + FLAT_BUDGET.with(|w| w.set(all / 2)); + let half = inflate(&p, FillRule::EvenOdd, r, o, front()); + FLAT_BUDGET.with(|w| w.set(MAX_FLAT_WORK)); + assert_eq!(half.err().as_deref(), Some(TOO_COMPLEX_SOLID)); + // The art draws without graphics as before. + assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).is_ok()); +} + +/// A cell graphics are mapped onto whose pieces have more corners than one cut may take refuses +/// the surface rather than drawing that cell without its graphics. +#[test] +fn inflate_refuses_graphics_on_a_cell_with_too_many_corners() { + let mut b = square(0.0, 0.0, 100.0); + let unit = 100.0 / 48.0 / 4.0; + let c = Point::new(96.5 * unit, 96.5 * unit); + let n = MAX_FLAT_CORNERS + 10; + let mut ring = BezPath::new(); + for k in 0..n { + let a = -std::f64::consts::TAU * k as f64 / n as f64; + let q = (c.x + 0.2 * a.cos(), c.y + 0.2 * a.sin()); + if k == 0 { ring.move_to(q) } else { ring.line_to(q) } + } + ring.close_path(); + b.extend(ring); + let (p, r) = shape(&b); + let mapped = inflate(&p, FillRule::EvenOdd, r, Inflate { map_surface: true, ..Inflate::default() }, front()); + assert_eq!(mapped.err().as_deref(), Some(TOO_COMPLEX_SOLID)); + assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).is_ok()); +} + #[test] fn malformed_and_degenerate_input_is_bounded() { let (p, b) = shape(&square(0.0, 0.0, 100.0)); From f725dd8caaf61b25fbc246b1986066b376cab769 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:16:05 -0800 Subject: [PATCH 10/69] 3D: a wireframe is not refused for graphics it does not draw Extrude & Bevel, Inflate and Rotate in wireframe mode draw the faces' edges with no graphics, but the graphics' art was still checked against its limits, and Inflate still built its puffed surface with the graphics on it, so a wireframe could be refused as too complex. Neither check runs in wireframe mode now, as Revolve already skips them. --- crates/effects/src/solids.rs | 8 ++++--- crates/effects/src/solids/tests_graphics.rs | 25 +++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 548b89ec39..767322769f 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -309,7 +309,8 @@ pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) /// Inflate or Rotate, as drawn, or a new one after its other effects when it has none. fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: (Option, Option)) -> Result<(), String> { validate_solid_params(id, p)?; - if let Some(doc) = doc { + // In wireframe mode the edges are drawn with no graphics, and their art is not checked. + if let Some(doc) = doc.filter(|_| !wireframe::wireframe_params(id, p)) { graphics::validate_symbols(doc, p)?; } let label = label_of(id); @@ -362,10 +363,11 @@ fn check_cast(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { /// past their limits on the front and puffed back of the solids of `shapes`: their art, or the /// parts they draw on its pieces ([`graphics::surface_parts`]), or when the solids can't be built /// with their pieces carrying the graphics. They are built as the art builds them -/// ([`surfaces_with`]). Without `doc` nothing is drawn, and nothing is checked. +/// ([`surfaces_with`]). Without `doc` nothing is drawn, and nothing is checked. In wireframe mode no +/// graphics are drawn, and none are checked. fn check_membrane_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { let Some(doc) = doc else { return Ok(()) }; - if id != INFLATE || mapped_graphics(p).is_empty() { + if id != INFLATE || wireframe::wireframe_params(id, p) || mapped_graphics(p).is_empty() { return Ok(()); } for face in PlanarFace::ALL { diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index 0729ddf2ba..45fbb1c489 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -463,6 +463,31 @@ fn the_symbol_check_counts_what_the_view_draws() { assert!(validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &flat).is_ok()); } +#[test] +fn a_wireframe_is_not_refused_for_graphics_it_does_not_draw() { + let check = |d: &Document, id: &str, mut p: Value, wire: bool| { + if wire { + p["render"] = json!({"mode": "wireframe"}); + } + validate_three_d_in(Some(d), &object(id, p.clone()), id, &p) + }; + // The straight 30,000-sided polygon at 1000% fits the symbol limit, but cut into pieces on + // Inflate's puffed front it is too complex. + let straight = dense_document(false); + let big = json!({"perspectiveAngle": 0.0, "graphics": [{"symbol": "Dense", "scale": 1000.0}]}); + assert!(validate_symbols(&straight, &big).is_ok()); + let e = check(&straight, INFLATE, big.clone(), false).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); + // Two copies of the curved one under a perspective are past the symbol limit on Extrude & Bevel. + let curved = dense_document(true); + let two = json!({"perspectiveAngle": 60.0, "graphics": [{"symbol": "Dense"}, {"symbol": "Dense", "face": "back"}]}); + let e = check(&curved, EXTRUDE, two.clone(), false).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); + // A wireframe draws the faces' edges and no graphics, so neither is checked. + assert_eq!(check(&straight, INFLATE, big, true), Ok(())); + assert_eq!(check(&curved, EXTRUDE, two, true), Ok(())); +} + #[test] fn a_plane_and_a_hollow_solid() { let d = document(); diff --git a/docs/mcp.md b/docs/mcp.md index a53da0fc79..a425ad2e9f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4244,7 +4244,8 @@ joins the edges, so with such an effect its paths can differ from the drawn ones draw the edges, and `effect.expandAppearance` keeps them as paths. Past 1,000,000 edges the source path is drawn, as it is for a solid past its limits. A `render` that is not an object, a key other than `mode`, another mode, and `render` on Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic) are refused before the document -changes. See [three-d.md](three-d.md#3d-and-materials-panel). +changes. In wireframe mode the graphics' art is not checked against the graphics limits, so art too complex for the +shaded surface does not refuse the wireframe. See [three-d.md](three-d.md#3d-and-materials-panel). ```json {"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"item":null,"params":{"render":{"mode":"wireframe"}}}}} From a0862097c7956ed8da56756183d4a429156beb76 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:01:58 -0800 Subject: [PATCH 11/69] Color Wheel: color.used reads the tiles of patterns used inside pattern tiles A pattern whose tile is painted with another pattern now adds that pattern's tile colors too. Each pattern is read once, so patterns that use each other are read once each. --- crates/engine/src/cmd/recolor.rs | 15 ++++++++++----- crates/engine/src/tests/recolor.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 26680d39fc..b2c8a021a7 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -965,8 +965,8 @@ struct Used { } /// The unique colours of the objects `ids` and the objects inside them, most used first (ties by -/// key): fills, strokes, gradient stops, text, mesh points and the tiles of the patterns used as -/// fills or strokes. With `only`, an object not in it is left out with everything it holds. +/// key): fills, strokes, gradient stops, text, mesh points, the tiles of the patterns used as +/// fills or strokes, and the tiles of the patterns those tiles use. With `only`, an object not in it is left out with everything it holds. fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> Vec { fn read<'a>(n: &'a Node, only: Option<&BTreeSet>, out: &mut Vec<&'a Node>) { if only.is_some_and(|o| !o.contains(&n.id)) { @@ -999,7 +999,8 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> } } }; - // The patterns used as fills or strokes: their tiles count once each. + // The patterns used as fills or strokes, and the patterns their tiles use: each tile counts + // once, and a pattern whose tile uses itself, directly or through other patterns, counts once. let mut patterns: Vec<&str> = vec![]; let mut nodes = vec![]; for n in ids.iter().filter_map(|id| d.node(*id)) { @@ -1008,8 +1009,12 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> for m in nodes { paints(m, &mut count_tint, &mut patterns); } - for def in patterns.iter().filter_map(|p| d.pattern(p)) { - def.art.iter().for_each(|n| n.walk(&mut |m| paints(m, &mut count_tint, &mut vec![]))); + let mut next = 0; + while let Some(&name) = patterns.get(next) { + next += 1; + for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() { + a.walk(&mut |m| paints(m, &mut count_tint, &mut patterns)); + } } used.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(&b.0))); used.into_iter().map(|(_, u)| u).collect() diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index a6e8c56b1b..0e9bf78f3d 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -204,6 +204,32 @@ fn used_colors_name_the_swatch_and_tint_a_color_is_linked_to() { assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}"); } +#[test] +fn used_colors_read_the_tiles_of_patterns_used_inside_pattern_tiles() { + let mut s = session(); + let red = rect(&mut s, json!("#ff0000")); + run(&mut s, "select.set", json!({"ids": [red.0]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + let middle = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [middle.0], "swatch": "Inner"})); + run(&mut s, "select.set", json!({"ids": [middle.0]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + let square = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [square.0], "swatch": "Outer"})); + // The inner tile's square is stroked with the outer pattern, so the two patterns use each other. + let outer = s.doc().unwrap().doc.node(square).unwrap().appearance.fill_paint().clone(); + let st = s.doc_mut().unwrap(); + let doc = std::sync::Arc::make_mut(&mut st.doc); + let tile = doc.pattern_mut("Inner").unwrap().art.first_mut().unwrap(); + std::sync::Arc::make_mut(tile).appearance.set_stroke(outer); + run(&mut s, "select.set", json!({"ids": [square.0]})); + let r = run(&mut s, "color.used", json!({})); + let colors = r["colors"].as_array().unwrap(); + assert_eq!(colors.iter().map(|c| (c["hex"].as_str(), c["count"].as_u64())).collect::>(), [(Some("#ff0000"), Some(1))], "{r}"); +} + #[test] fn used_colors_give_no_swatch_for_a_stop_that_mixes_its_ink_with_process_inks() { use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint}; From de1d83fd04e86a1fcfb19635391fb1c2c9f45771 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:01:59 -0800 Subject: [PATCH 12/69] Color Wheel: a widened document colors row waits for the interaction and the half second A row widened past the colors last read kept reading them on every widening step, during an interaction and in art with more than 5,000 color uses. It now keeps the colors it has until the interaction ends, and in such art until half a second after the last read. --- crates/ui-egui/src/panels/color_wheel.rs | 10 ++--- .../tests_color_wheel_document_colors.rs | 41 +++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index eae319008b..340ac2971a 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -214,7 +214,8 @@ impl Used { /// document revision and selection and kept as they are while an interaction is in progress (a /// preview raises the revision on every frame of a drag). In art with more than [`LARGE_USES`] /// color uses, an edit reads them again only after [`LARGE_EVERY`] seconds. A row that holds more -/// than the colors last asked for reads them again. +/// than the colors last asked for reads them again once no interaction is in progress, and in such +/// art only after the same wait. fn used_colors(app: &mut VectorcraftApp, ui: &Ui, per_row: usize) -> Arc { let limit = per_row.max(MAX_CHIPS); let key: UsedKey = app.session.active().map(|d| { @@ -223,10 +224,9 @@ fn used_colors(app: &mut VectorcraftApp, ui: &Ui, per_row: usize) -> Arc>>(ui.ctx(), USED) - && (cache.limit >= per_row || cache.colors.len() < cache.limit) - { - if cache.key == key || app.session.in_interaction() { + if let Some(cache) = pstate::>>(ui.ctx(), USED) { + let fits = cache.limit >= per_row || cache.colors.len() < cache.limit; + if app.session.in_interaction() || (cache.key == key && fits) { return cache; } let scope = |k: &UsedKey| k.map(|(doc, _, n, h)| (doc, n, h)); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs index e8db930a4a..b14e90c50a 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs @@ -305,6 +305,47 @@ fn in_large_art_an_edit_reads_the_colors_again_after_half_a_second() { assert!(!has(&h, &label("#00ff00", 3))); } +/// A row widened past the 128 colors last read keeps them while an interaction is in progress, and +/// in art with more than 5,000 color uses until half a second after the last read. +#[test] +fn a_widened_row_waits_for_the_interaction_and_the_half_second() { + let (mut app, reds, _) = app(); + let hex = |i: usize| format!("#{:02x}{:02x}80", i % 256, i / 256 + 1); + for i in 0..160 { + rect(&mut app, 170.0, json!({"color": hex(i)})); + } + for _ in 0..5 { + app.run("select.all", json!({})).unwrap(); + app.run("edit.duplicate", json!({})).unwrap(); + } + app.run("select.none", json!({})).unwrap(); + let uses = app.session.execute("color.used", &json!({})).unwrap()["uses"].as_u64().unwrap(); + assert!(uses > 5_000, "{uses} uses"); + let (narrow, wide) = (vec2(260.0, 360.0), vec2(3400.0, 360.0)); + let mut h = Harness::builder().with_size(narrow).with_step_dt(0.1).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(6); + let shown = |h: &Harness<'static, VectorcraftApp>| (0..160).filter(|i| has(h, &label(&hex(*i), 32))).count(); + // During an interaction the wide row keeps the 128 colors read for the narrow one. + h.state_mut().session.begin_interaction("test").unwrap(); + h.set_size(wide); + h.run_steps(6); + assert!(shown(&h) <= 128, "{} colors show during the interaction", shown(&h)); + h.state_mut().session.cancel_interaction().unwrap(); + h.run_steps(6); + assert!(shown(&h) > 128, "{} colors show after the interaction", shown(&h)); + // An edit read in the narrow row, then a wide row within half a second, waits for the half second. + h.set_size(narrow); + h.run_steps(1); + h.state_mut().run("paint.setFill", json!({"ids": [reds[0]], "color": "#00ff00"})).unwrap(); + h.run_steps(1); + assert!(has(&h, &label("#ff0000", 95)), "the edit is read at once"); + h.set_size(wide); + h.run_steps(1); + assert!(shown(&h) <= 128, "{} colors show within half a second", shown(&h)); + h.run_steps(5); + assert!(shown(&h) > 128, "{} colors show after half a second", shown(&h)); +} + /// Without the setting the row is not drawn, and the panel menu's Show Document Colors turns it on. #[test] fn the_panel_menu_turns_the_row_on_and_off() { From 30f852b62bb23e35bf7b7e6a37da60327943dcbf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 18:13:55 -0800 Subject: [PATCH 13/69] 3D: an Inflate frame places no handles when a fill's solid fails When a later fill of an Inflate object could not be built, or the solids together passed the face limit, the graphic frame kept the facets of the solids built before it and showed graphic handles, while the art drew its source path. The frame now places no handle in that case. A stroke left out past its limits still places none of its own. --- crates/effects/src/solids.rs | 10 ++++++---- crates/effects/src/solids/tests.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 07b10dfada..8ffcb1cef4 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -2412,11 +2412,13 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' let (parts, bounds) = solid_parts(&shapes, b); if fx.id == INFLATE { // Inflate's graphics lie on its puffed front and back: the pieces the viewer sees place - // their handles. Solids that can't be built place none. + // their handles. A stroke left out places none of its own. When a fill's solid can't be + // built, or the solids together pass the limit, the art draws its source and no piece + // places a handle. let built: Vec = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true) - .filter_map(|r| r.ok().flatten()) - .flat_map(|(f, _)| f) - .collect(); + .collect::, String>>() + .map(|solids| solids.into_iter().flatten().flat_map(|(f, _)| f).collect()) + .unwrap_or_default(); return Some(graphics::GraphicFrame::inflated(bounds, graphics::MembraneFrame::of(&built))); } let options = extrude_options(&p); diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 986e575689..d2ad2cb0cc 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1206,6 +1206,33 @@ fn a_groups_solids_together_past_the_limit_draw_the_source() { assert_eq!(three_d_wireframe_in(None, &past), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string())); } +/// An Inflate group whose second member's fill is past the limits draws its source art, and its +/// frame places no graphic handle on the first member's puff. +#[test] +fn an_inflate_frame_places_no_handle_when_a_fill_is_past_the_limits() { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((40_000.0, 0.0)); + b.line_to((40_000.0, 40_000.0)); + b.line_to((0.0, 40_000.0)); + b.close_path(); + let square = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + let view = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0}); + let group = |members: Vec| { + let mut g = Node::group(NodeId(9999), members.into_iter().map(Arc::new).collect()); + g.appearance.effects.push(fx(INFLATE, view.clone())); + g + }; + let center = MappedGraphic::from_value(&json!({"symbol": "Mark"})).unwrap(); + // The square alone builds, and the graphic's handle sits on its puff. + let alone = group(vec![square.clone()]); + assert!(graphic_frame(None, &alone, None).unwrap().handle(¢er).is_some()); + // 70,000 corners: more points than a fill's solid takes. + let past = group(vec![square, polygon_node(2, 70_000)]); + assert!(solid_art(&past).is_none(), "the source art draws"); + assert!(graphic_frame(None, &past, None).unwrap().handle(¢er).is_none()); +} + /// A fill and strokes whose solids each fit, but not all of them together, draw the source art, /// and the strokes after the one past the limit are not left out to make room. #[test] From 63d02a2568bb2ab74b0f8d15ae3580c6f0a73186 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 18:42:33 -0800 Subject: [PATCH 14/69] 3D: a drag over overlapping Inflate pieces maps through the nearer one Where two pieces of Inflate's puffed front or back overlap on the page, a handle drag picked the piece whose center was nearer, so a tilted piece hidden at the pointer could take the drag and move the graphic to the wrong offset. Each piece now keeps its plane, and the pointer maps through the piece that is nearest at that point. --- crates/effects/src/solids/graphics.rs | 29 ++++++++++++++------- crates/effects/src/solids/tests_graphics.rs | 24 +++++++++++++++++ 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 1d7e4e8d45..03ae75a927 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -28,7 +28,7 @@ use vectorcraft_doc::color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol}; use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape}; use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2}; -use vectorcraft_three_d::{FaceMap, Facet, PlanarFace}; +use vectorcraft_three_d::{DepthPlane, FaceMap, Facet, PlanarFace}; /// The effect parameter that holds the graphics. pub const GRAPHICS: &str = "graphics"; @@ -1017,8 +1017,8 @@ pub struct GraphicFrame { /// The pieces of Inflate's front and puffed back that show their outside to the viewer, as the /// graphics are drawn on them ([`surface_parts`]): each piece's face, its corners in the art's plane -/// (offsets from the center of the object's bounds) and on the page, and its depth (larger is -/// nearer). +/// (offsets from the center of the object's bounds) and on the page, its depth (larger is nearer) +/// and its plane, for its depth at a point of the page. #[derive(Clone, Debug, Default, PartialEq)] pub struct MembraneFrame { pieces: Vec, @@ -1030,6 +1030,15 @@ struct MembranePiece { uv: [Point; 3], page: [Point; 3], depth: f64, + plane: Option, +} + +impl MembranePiece { + /// The piece's depth at page point `p`: its plane's depth there, or its own depth when it has + /// no plane or the plane gives none. + fn depth_at(&self, p: Point) -> f64 { + self.plane.and_then(|plane| plane.depth_at(p)).unwrap_or(self.depth) + } } impl MembraneFrame { @@ -1043,15 +1052,15 @@ impl MembraneFrame { let cell = f.surface.as_ref().filter(|c| c.outward)?; let uv = <[Point; 3]>::try_from(cell.uv.as_slice()).ok()?; let page = <[Point; 3]>::try_from(cell.page.as_slice()).ok()?; - Some(MembranePiece { face, uv, page, depth: f.depth }) + Some(MembranePiece { face, uv, page, depth: f.depth, plane: f.plane }) }) .collect(); Self { pieces } } /// Point `p` of `face` in the art's plane mapped onto the page, or with `from_page` a page point - /// mapped into the art's plane, through the nearest piece of that face that holds it. `None` - /// when no piece the viewer sees holds it. + /// mapped into the art's plane, through the piece of that face that holds it and is nearest at + /// that point of the page. `None` when no piece the viewer sees holds it. fn map(&self, face: PlanarFace, p: Point, from_page: bool) -> Option { let inside = |t: &[Point; 3], q: Point| { let side = |a: Point, b: Point| (b - a).cross(q - a); @@ -1061,11 +1070,13 @@ impl MembraneFrame { let mut best: Option<(Point, f64)> = None; for piece in self.pieces.iter().filter(|piece| piece.face == face) { let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) }; - if !inside(from, p) || best.is_some_and(|(_, depth)| depth >= piece.depth) { + if !inside(from, p) { continue; } - if let Some(q) = triangle_map(from, to).map(|m| m * p).filter(|q| q.is_finite()) { - best = Some((q, piece.depth)); + let Some(q) = triangle_map(from, to).map(|m| m * p).filter(|q| q.is_finite()) else { continue }; + let depth = piece.depth_at(if from_page { p } else { q }); + if best.is_none_or(|(_, nearest)| depth > nearest) { + best = Some((q, depth)); } } best.map(|(q, _)| q) diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index 45fbb1c489..2fe175a4aa 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -1032,3 +1032,27 @@ fn an_inflate_frame_puts_the_handle_on_the_puff_and_reads_it_back() { let (x, y) = frame.offset_at(PlanarFace::Back, page).unwrap(); assert!((x - 15.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}"); } + +/// Where two pieces of an Inflate face overlap on the page, a point maps through the piece nearer +/// at that point, though the other is nearer at its center. +#[test] +fn overlapping_inflate_pieces_map_a_point_through_the_one_nearer_there() { + let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)]; + let piece = |shift: f64, depth: f64, normal: [f64; 3], offset: f64| MembranePiece { + face: PlanarFace::Front, + uv: page.map(|p| p + Vec2::new(shift, 0.0)), + page, + depth, + plane: Some(DepthPlane { normal, offset, center: Point::ORIGIN, eye: None }), + }; + // The tilted piece is nearer at its center (depth 10) but at depth 0 where x is 10; the flat + // one lies at depth 5 everywhere. + let tilted = piece(0.0, 10.0, [1.0, 0.0, 1.0], 10.0); + let flat = piece(100.0, 5.0, [0.0, 0.0, 1.0], 5.0); + let frame = GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces: vec![tilted, flat] }); + let (x, y) = frame.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).unwrap(); + assert!((x - 110.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}"); + // Near the tilted piece's left corner it is the nearer one. + let (x, _) = frame.offset_at(PlanarFace::Front, Point::new(2.0, 0.5)).unwrap(); + assert!((x - 2.0).abs() < 1e-6, "{x}"); +} From f190b81896d5854451b81c4bddb441dcd29eaa97 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 18:42:33 -0800 Subject: [PATCH 15/69] 3D: the Materials tab builds the graphics frame once per edit While the Materials tab was open, the artboard built the selected object's graphics frame on every frame it drew, which for Inflate means building its whole solid. The frame is now kept until the document changes, and an object without mapped graphics builds none. --- crates/ui-egui/src/panels/tests_three_d.rs | 31 ++++++++++++++++++++++ crates/ui-egui/src/panels/three_d.rs | 31 +++++++++++++++++++--- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index f06994c1dc..f3b860afed 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -624,6 +624,8 @@ fn a_graphics_handle_drags_it_over_its_face_in_one_undo_step() { let n = std::sync::Arc::make_mut(&mut st.doc).node_mut(id).unwrap(); n.appearance.effects[0].visible = false; n.appearance.effects.push(vectorcraft_effects::new_effect("threeD.extrude", &json!({})).unwrap()); + // An edit moves the revision, as a command's does. + st.revision += 1; } let mut shown = true; ctx.run_ui(egui::RawInput::default(), |ui| { @@ -639,6 +641,35 @@ fn a_graphics_handle_drags_it_over_its_face_in_one_undo_step() { assert!(!frame(&mut app, vec![button(target, true)])); } +/// The frame the graphics' handles are placed on is built once for each revision of the document, +/// and not at all for an object without graphics. +#[test] +fn the_graphics_frame_is_built_once_for_each_revision() { + type Cached = (super::FrameKey, Option>); + let (mut app, ctx) = materials_app(); + let cached = |ctx: &egui::Context| ctx.data(|m| m.get_temp::(super::frame_cache_id())).and_then(|(_, frame)| frame); + let handles = |app: &VectorcraftApp| { + let mut shown = false; + ctx.run_ui(egui::RawInput::default(), |ui| { + crate::panels::set_pstate(ui.ctx(), super::DRAWN, Some(super::root_pass(ui.ctx()))); + shown = super::graphic_handles(app, ui.ctx()).is_some(); + }) + .textures_delta + .clear(); + shown + }; + assert!(!handles(&app)); + assert!(cached(&ctx).is_none(), "no graphics, no frame"); + app.run("threeD.mapGraphic", json!({"symbol": "Graphic"})).unwrap(); + assert!(handles(&app)); + let first = cached(&ctx).unwrap(); + assert!(handles(&app)); + assert!(std::sync::Arc::ptr_eq(&first, &cached(&ctx).unwrap()), "the same revision reuses the frame"); + app.run("threeD.mapGraphic", json!({"symbol": "Graphic"})).unwrap(); + assert!(handles(&app)); + assert!(!std::sync::Arc::ptr_eq(&first, &cached(&ctx).unwrap()), "an edit builds it again"); +} + /// One frame of the artboard's graphic handles over an 800 × 600 canvas with `events`: whether the /// handles took the pointer. fn handles_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> bool { diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index be7731daf5..db47e73ac4 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -8,6 +8,8 @@ //! adds the selected objects that have a 3D effect to Asset Export as 3D assets (`assets.add3D`) //! and shows that panel with their assets selected. +use std::sync::Arc; + use egui::Ui; use serde_json::{Map, Value, json}; use vectorcraft_doc::{Effect, Node, NodeId, NodeKind}; @@ -392,7 +394,7 @@ fn materials_open(ctx: &egui::Context) -> bool { /// What [`graphic_handles`] gives: the object's frame, its graphics, and each seen graphic's index /// and page point. -type Handles = (vectorcraft_effects::GraphicFrame, Vec, Vec<(usize, vectorcraft_geom::Point)>); +type Handles = (Arc, Vec, Vec<(usize, vectorcraft_geom::Point)>); /// The handles of the graphics mapped onto the first selected object, while the Materials tab is /// open: each graphic's index, its face and where its center lands on the page, for the graphics @@ -410,8 +412,6 @@ fn graphic_handles(app: &VectorcraftApp, ctx: &egui::Context) -> Option if t.item.is_some_and(|k| n.appearance.items.get(k).is_none_or(|it| !it.visible())) { return None; } - // The frame of the effect whose graphics are listed: none while that effect is hidden. - let frame = vectorcraft_effects::graphic_frame_at(Some(&st.doc), n, t.item, t.index)?; // A geometry effect after the 3D effect of any selected object moves or bends its drawn // graphics away from their places in the frame: no handles, so a drag does not put a graphic // away from the pointer. @@ -420,15 +420,40 @@ fn graphic_handles(app: &VectorcraftApp, ctx: &egui::Context) -> Option return None; } let list = vectorcraft_effects::mapped_graphics(&vectorcraft_effects::merged_params(&t.effect, &t.params)); + // Without graphics there are no handles, and no frame is built. + if list.is_empty() { + return None; + } // Selected objects with different graphics show no handles: a drag sends the whole list. let graphics_of = |t: Target| vectorcraft_effects::mapped_graphics(&vectorcraft_effects::merged_params(&t.effect, &t.params)); if st.selection.objects.iter().skip(1).filter_map(|id| find(st.doc.node(*id)?)).any(|o| graphics_of(o) != list) { return None; } + // The frame of the effect whose graphics are listed: none while that effect is hidden. It is + // built once for each revision of the document, not on every frame the panel draws. + let key: FrameKey = (st.uid, st.revision, n.id.0, t.item, t.index); + let cached = ctx.data(|m| m.get_temp::<(FrameKey, Option>)>(frame_cache_id())); + let frame = match cached { + Some((k, frame)) if k == key => frame, + _ => { + let frame = vectorcraft_effects::graphic_frame_at(Some(&st.doc), n, t.item, t.index).map(Arc::new); + ctx.data_mut(|m| m.insert_temp(frame_cache_id(), (key, frame.clone()))); + frame + } + }?; let handles = list.iter().enumerate().filter_map(|(i, g)| frame.handle(g).filter(|(_, seen)| *seen).map(|(p, _)| (i, p))).collect(); Some((frame, list, handles)) } +/// What the cached frame of [`graphic_handles`] was built for: the document's uid and revision, the +/// object's id, and the fill or stroke and index of its 3D effect. +type FrameKey = (u64, u64, u64, Option, usize); + +/// Temp-memory key of the frame [`graphic_handles`] last built. +fn frame_cache_id() -> egui::Id { + egui::Id::unique("three-d-graphic-frame") +} + /// Temp-memory key of a drag of a graphic's handle on the artboard. fn handle_drag_id() -> egui::Id { egui::Id::unique("three-d-graphic-handle-drag") From 48a708dc0ffa56018396a054898806d5e62f776b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 18:53:09 -0800 Subject: [PATCH 16/69] 3D: Inflate faces that carry graphics keep their colored-light underlay Under colored lights with smooth shading, a face of Inflate's front or back that carries part of a mapped graphic is drawn as a group of the face and those parts. The underlay that closes the seams between faces did not take such a group, so the whole run was drawn without it and hairline gaps could show between triangles. Such a face now takes its facet's underlay and stays in the order with its parts. --- crates/effects/src/lighting.rs | 13 +++++++++++-- crates/effects/src/solids/tests.rs | 24 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/crates/effects/src/lighting.rs b/crates/effects/src/lighting.rs index e62e34b55e..7f7f1099e3 100644 --- a/crates/effects/src/lighting.rs +++ b/crates/effects/src/lighting.rs @@ -173,11 +173,20 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr /// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave /// uncovered with the neighbors' own colors, so the background does not show through. `None` unless /// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed -/// in a clip of its footprint, neither with an opacity mask. +/// in a clip of its footprint, neither with an opacity mask. A face drawn with the parts of Inflate's +/// graphics on it, a group of the facet and those parts, takes its facet's underlay and stays in the +/// order with its parts, which are cut to the facet's outline, so the clip keeps them. pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc]) -> Option { use std::sync::Arc; use vectorcraft_doc::{Node, NodeKind}; - let (clip, mut underlay) = underlay(id, faces)?; + let facets: Vec> = faces + .iter() + .map(|face| match &face.kind { + NodeKind::Group { children, clip: false } if face.extras().mask.is_none() => children.first().cloned(), + _ => Some(face.clone()), + }) + .collect::>()?; + let (clip, mut underlay) = underlay(id, &facets)?; underlay.extend(faces.iter().cloned()); Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true })) } diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index d2ad2cb0cc..c4a33a76a2 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -587,6 +587,30 @@ fn drawn_face_bounds(f: &Node) -> Rect { } } +/// Under a colored light, an Inflate in a solid color with a graphic on its front lies over an +/// underlay of its faces, the faces that carry parts of the graphic included. +#[test] +fn a_colored_inflate_with_a_graphic_lies_over_an_underlay_of_its_faces() { + let mut d = Document::new(1000.0, 1000.0); + let mark = Node::path( + NodeId(0), + vectorcraft_geom::shapes::rectangle(Rect::new(500.0, 500.0, 510.0, 510.0)), + Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0), + ); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(mark) }); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let mut n = Node::path(NodeId(7), square, Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + let p = json!({"rotationX": -20, "rotationY": -30, "rotationZ": 0, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark", "scale": 300.0}]}); + n.appearance.effects.push(fx(INFLATE, p)); + let art = solid_art_in(Some(&d), &n).unwrap(); + let order = art.children().unwrap()[0].children().unwrap(); + let faces: Vec> = order.iter().flat_map(unsealed).collect(); + assert!(faces.len() > order.len(), "the faces lie over an underlay"); + let carrying = faces.iter().filter(|f| matches!(f.kind, NodeKind::Group { clip: false, .. })).count(); + assert!(carrying > 0, "faces carry parts of the graphic"); + assert!(order.iter().all(|run| !Arc::ptr_eq(&unsealed(run)[0], run)), "every face is in a sealed run"); +} + /// Under a light that is not white, a solid-color fill and a solid-color stroke, plain, dashed or /// with a width profile, draw their faces in one order, the faces of both solids in the order of /// their depths where they overlap, in Inflate and in Extrude & Bevel, with and without perspective From 5d262e2f6eb71907c9bc9548488669fc437896a9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:34:23 -0800 Subject: [PATCH 17/69] i18n: French catalog row the merge of main split The merge of main joined the source and translation of the "graphics are too complex for this surface" message without a tab, so bundled_catalogs_are_consistent rejected fr.tsv. The row now matches main's. The merge also kept the old "Plane, Extrude and Revolve" message row, whose source string the branch replaced; it has been removed. --- crates/ui-egui/src/i18n/fr.tsv | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3069219a0f..b70ee1c079 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5815,10 +5815,9 @@ lighting Light Lumière @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` doit être un nombre de {lo} à {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` doit être un tableau @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Les graphiques s’appliquent aux types d’objet Plan, Extrusion, Révolution et Gonfler -@msg Graphics map onto the Plane, Extrude and Revolve object types Les graphiques s’appliquent aux types d’objet Plan, Extrusion et Révolution @msg Revolve maps graphics onto its side: map them onto the front Révolution applique les graphiques sur sa face latérale : appliquez-les sur la face avant @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objet {_1} : l’arrière de Gonfler n’accepte des graphiques qu’avec Deux côtés et Fermeture activés -@msg The graphics are too complex for this surface: simplify the symbols' art or reduce SegmentsLes graphiques sont trop complexes pour cette surface : simplifiez l’illustration des symboles ou réduisez Segments +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Les graphiques sont trop complexes pour cette surface : simplifiez l’illustration des symboles ou réduisez Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accepte au plus {MAX_GRAPHICS} graphiques @msg A plane has one face: map its graphics onto the front Un plan n’a qu’une face : appliquez ses graphiques sur la face avant @msg The graphics are too complex: simplify the symbols' art Les graphiques sont trop complexes : simplifiez l’illustration des symboles From f4d7260c620306380f7c310bb4a4029d0f5eef5e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:41:52 -0800 Subject: [PATCH 18/69] i18n: no-break space before the colon in the French Inflate back refusal french_catalog_uses_nonbreaking_prose_punctuation requires a no-break space before a colon in French prose. The row for the Inflate back refusal had an ordinary space. --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b70ee1c079..3e7a7ad55a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5816,7 +5816,7 @@ lighting Light Lumière @msg `{GRAPHICS}` must be an array `{GRAPHICS}` doit être un tableau @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Les graphiques s’appliquent aux types d’objet Plan, Extrusion, Révolution et Gonfler @msg Revolve maps graphics onto its side: map them onto the front Révolution applique les graphiques sur sa face latérale : appliquez-les sur la face avant -@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objet {_1} : l’arrière de Gonfler n’accepte des graphiques qu’avec Deux côtés et Fermeture activés +@msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objet {_1} : l’arrière de Gonfler n’accepte des graphiques qu’avec Deux côtés et Fermeture activés @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Les graphiques sont trop complexes pour cette surface : simplifiez l’illustration des symboles ou réduisez Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accepte au plus {MAX_GRAPHICS} graphiques @msg A plane has one face: map its graphics onto the front Un plan n’a qu’une face : appliquez ses graphiques sur la face avant From f2376b05f7a095c25479c11ed6553e224f0ae2a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 00:13:32 -0800 Subject: [PATCH 19/69] 3D: Inflate graphics keep membrane corners on an ear's new edge With corners kept along a cell's edges, ear clipping could still take an ear whose new edge ran through kept corners, leaving them off every triangle and the triangles beside them flat. Such an ear is now passed over. docs/three-d.md now says that a membrane cell that cannot be cut into triangles makes the object draw without its graphics, and commands refuse them. --- crates/three-d/src/mesh.rs | 5 +++++ crates/three-d/src/mesh/tests.rs | 14 ++++++++++++++ docs/three-d.md | 3 ++- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index d0ce362f1e..fbc5546d18 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -408,6 +408,11 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight ear = false; break; } + // A kept corner on the ear's new edge would be left off every triangle. + if keep_straight && touches((p.x, p.y), (pc.x, pc.y), (pa.x, pa.y)) { + ear = false; + break; + } k = next[k]; } } diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index a4db1d77fb..9980e900d1 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -191,6 +191,20 @@ fn flat_triangles_keep_corners_that_lie_along_an_edge() { assert!(work > 0); } +#[test] +fn flat_triangles_keep_corners_on_the_edge_an_ear_would_cut() { + // The first ear's new edge runs along the bottom, through its two middle corners. + let p = |x: f64, y: f64| Point::new(x, y); + let outline = vec![p(0.0, 3.0), p(0.0, 0.0), p(1.0, 0.0), p(2.0, 0.0), p(3.0, 0.0)]; + let mut work = 0; + let triangles = flat_triangles(std::slice::from_ref(&outline), &mut work, usize::MAX).unwrap(); + let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0; + assert!((triangles.iter().map(area).sum::() - 4.5).abs() < 1e-9); + for q in &outline { + assert!(triangles.iter().any(|t| t.contains(q)), "{q:?} is no triangle's corner"); + } +} + #[test] fn flat_triangles_stop_at_their_budget() { let p = |x: f64, y: f64| Point::new(x, y); diff --git a/docs/three-d.md b/docs/three-d.md index 45531ad4df..d01b6ab6de 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -508,7 +508,8 @@ These rules are VectorCraft's own: not drawn); it reads the right way round from behind, and Twist and Taper turn and shrink its graphics with it. The membrane is cut into triangles, and each one draws the part of the graphic that falls on it, shaded as that triangle is shaded and drawn only where the surface's outside faces the viewer; nearer triangles drawn - after it cover it. A cell of the membrane that cannot be cut into triangles takes no graphic. Every solid of + after it cover it. When a cell of the membrane cannot be cut into triangles, the object draws without its + graphics and commands refuse them, as when the triangles take more faces than a 3D effect draws. Every solid of the object (a fill's, and a stroke's outline) carries the graphics. The handle sits on the point of the puffed face above the graphic's center, and only where the viewer sees that face. The cutting into straight pieces, the seam strokes and the limits below are those of Revolve; when the triangles take more faces than a 3D From 8f47eaa23f53f3fcbe8d697ae6945d6cd8286af3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 00:20:01 -0800 Subject: [PATCH 20/69] 3D: no Inflate graphic handle where a nearer facet covers it A graphic's handle on Inflate's front or back was placed through the nearest piece of its own face only, so a nearer piece of the other face, a side or a back cap could hide a handle that still showed and could be dragged. The handle and the offset read from the page are now left out where a facet drawn over that point of the page covers it: one clearly nearer there, or one drawn last (a cap turned toward the viewer), unless the piece is itself drawn last after it. --- crates/effects/src/solids/graphics.rs | 87 +++++++++++++++++---- crates/effects/src/solids/tests_graphics.rs | 53 ++++++++++++- 2 files changed, 123 insertions(+), 17 deletions(-) diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 03ae75a927..2ef74b1b10 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -1018,10 +1018,41 @@ pub struct GraphicFrame { /// The pieces of Inflate's front and puffed back that show their outside to the viewer, as the /// graphics are drawn on them ([`surface_parts`]): each piece's face, its corners in the art's plane /// (offsets from the center of the object's bounds) and on the page, its depth (larger is nearer) -/// and its plane, for its depth at a point of the page. +/// and its plane, for its depth at a point of the page. The other facets the viewer sees (the +/// sides, and pieces that show the surface's inside) are kept as `covers`, for where they hide +/// a piece. #[derive(Clone, Debug, Default, PartialEq)] pub struct MembraneFrame { pieces: Vec, + covers: Vec, +} + +/// A facet that can hide a piece of Inflate's front or back: its contours on the page (nonzero +/// winding), its depth, its plane and its place among the solid's facets. +#[derive(Clone, Debug, PartialEq)] +struct Cover { + contours: Vec>, + depth: f64, + plane: Option, + index: usize, +} + +impl Cover { + /// Does the facet hold page point `p`? + fn holds(&self, p: Point) -> bool { + let mut winding = 0i32; + for c in &self.contours { + for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) { + let side = (*b - *a).cross(p - *a); + if a.y <= p.y && b.y > p.y && side > 0.0 { + winding += 1; + } else if a.y > p.y && b.y <= p.y && side < 0.0 { + winding -= 1; + } + } + } + winding != 0 + } } #[derive(Clone, Debug, PartialEq)] @@ -1031,6 +1062,9 @@ struct MembranePiece { page: [Point; 3], depth: f64, plane: Option, + /// The piece's place among the solid's facets: of two facets drawn last, the later one is drawn + /// over the other. + index: usize, } impl MembranePiece { @@ -1043,31 +1077,35 @@ impl MembranePiece { impl MembraneFrame { /// The pieces of `facets` that carry where they lie in the art's plane and show the outside of - /// Inflate's front or back. + /// Inflate's front or back, and the other facets not turned away from the viewer as covers. pub(super) fn of<'a>(facets: impl IntoIterator) -> Self { - let pieces = facets - .into_iter() - .filter_map(|f| { - let face = f.membrane?; - let cell = f.surface.as_ref().filter(|c| c.outward)?; + let (mut pieces, mut covers) = (Vec::new(), Vec::new()); + for (index, f) in facets.into_iter().enumerate() { + let piece = f.membrane.zip(f.surface.as_ref().filter(|c| c.outward)).and_then(|(face, cell)| { let uv = <[Point; 3]>::try_from(cell.uv.as_slice()).ok()?; let page = <[Point; 3]>::try_from(cell.page.as_slice()).ok()?; - Some(MembranePiece { face, uv, page, depth: f.depth, plane: f.plane }) - }) - .collect(); - Self { pieces } + Some(MembranePiece { face, uv, page, depth: f.depth, plane: f.plane, index }) + }); + match piece { + Some(piece) => pieces.push(piece), + None if !f.away => covers.push(Cover { contours: f.contours.clone(), depth: f.depth, plane: f.plane, index }), + None => {} + } + } + Self { pieces, covers } } /// Point `p` of `face` in the art's plane mapped onto the page, or with `from_page` a page point /// mapped into the art's plane, through the piece of that face that holds it and is nearest at - /// that point of the page. `None` when no piece the viewer sees holds it. + /// that point of the page. `None` when no piece the viewer sees holds it, or when a nearer piece + /// of the other face or a nearer cover hides that point of the page. fn map(&self, face: PlanarFace, p: Point, from_page: bool) -> Option { let inside = |t: &[Point; 3], q: Point| { let side = |a: Point, b: Point| (b - a).cross(q - a); let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])]; s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9) }; - let mut best: Option<(Point, f64)> = None; + let mut best: Option<(Point, f64, &MembranePiece)> = None; for piece in self.pieces.iter().filter(|piece| piece.face == face) { let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) }; if !inside(from, p) { @@ -1075,11 +1113,28 @@ impl MembraneFrame { } let Some(q) = triangle_map(from, to).map(|m| m * p).filter(|q| q.is_finite()) else { continue }; let depth = piece.depth_at(if from_page { p } else { q }); - if best.is_none_or(|(_, nearest)| depth > nearest) { - best = Some((q, depth)); + if best.is_none_or(|(_, nearest, _)| depth > nearest) { + best = Some((q, depth, piece)); } } - best.map(|(q, _)| q) + let (q, depth, shown) = best?; + let at = if from_page { p } else { q }; + // A facet drawn last (depth `f64::MAX`) is drawn over every other one, and over another + // drawn last before it. Otherwise, where the front, the back and the sides meet, they give + // the same depth there, and only a facet clearly nearer covers. + let hides = |raw: f64, there: f64, index: usize| match (raw == f64::MAX, shown.depth == f64::MAX) { + (true, true) => index > shown.index, + (true, false) => true, + (false, true) => false, + (false, false) => there > depth + 1e-6 * depth.abs().max(1.0), + }; + let covered = self + .pieces + .iter() + .filter(|piece| piece.face != face) + .any(|piece| inside(&piece.page, at) && hides(piece.depth, piece.depth_at(at), piece.index)) + || self.covers.iter().any(|c| c.holds(at) && hides(c.depth, c.plane.and_then(|plane| plane.depth_at(at)).unwrap_or(c.depth), c.index)); + (!covered).then_some(q) } } diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index 2fe175a4aa..1873156469 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -1044,15 +1044,66 @@ fn overlapping_inflate_pieces_map_a_point_through_the_one_nearer_there() { page, depth, plane: Some(DepthPlane { normal, offset, center: Point::ORIGIN, eye: None }), + index: 0, }; // The tilted piece is nearer at its center (depth 10) but at depth 0 where x is 10; the flat // one lies at depth 5 everywhere. let tilted = piece(0.0, 10.0, [1.0, 0.0, 1.0], 10.0); let flat = piece(100.0, 5.0, [0.0, 0.0, 1.0], 5.0); - let frame = GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces: vec![tilted, flat] }); + let frame = GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces: vec![tilted, flat], covers: vec![] }); let (x, y) = frame.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).unwrap(); assert!((x - 110.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}"); // Near the tilted piece's left corner it is the nearer one. let (x, _) = frame.offset_at(PlanarFace::Front, Point::new(2.0, 0.5)).unwrap(); assert!((x - 2.0).abs() < 1e-6, "{x}"); } + +/// A graphic on Inflate's back has no handle where a nearer piece of the front covers its center +/// on the page, and the back has no offset there; where the back is nearer, it has both. +#[test] +fn an_inflate_back_graphic_covered_by_a_nearer_front_piece_has_no_handle() { + let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)]; + let piece = |face: PlanarFace, depth: f64| MembranePiece { face, uv: page, page, depth, plane: None, index: 0 }; + let frame = |front: f64, back: f64| { + let pieces = vec![piece(PlanarFace::Front, front), piece(PlanarFace::Back, back)]; + GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces, covers: vec![] }) + }; + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": -10.0, "y": 5.0})).unwrap(); + let covered = frame(10.0, 5.0); + assert!(covered.handle(&g).is_none()); + assert!(covered.offset_at(PlanarFace::Back, Point::new(10.0, 5.0)).is_none()); + assert!(covered.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).is_some()); + let seen = frame(5.0, 10.0); + let (at, _) = seen.handle(&g).unwrap(); + assert!((at.x - 10.0).abs() < 1e-6 && (at.y - 5.0).abs() < 1e-6, "{at:?}"); + assert!(seen.offset_at(PlanarFace::Back, Point::new(10.0, 5.0)).is_some()); +} + +/// A nearer side facet that covers a graphic's center on Inflate's front hides its handle; one +/// behind the front, or beside the center, leaves it. A facet drawn last (a back cap) hides it +/// whatever its plane's depth, unless the front piece is drawn last too, after it. +#[test] +fn an_inflate_graphic_covered_by_a_nearer_side_has_no_handle() { + let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)]; + let front = |depth: f64, index: usize| MembranePiece { face: PlanarFace::Front, uv: page, page, depth, plane: None, index }; + let side = |x0: f64, depth: f64, index: usize| Cover { + contours: vec![vec![Point::new(x0, 0.0), Point::new(x0 + 4.0, 0.0), Point::new(x0 + 4.0, 20.0), Point::new(x0, 20.0)]], + depth, + // A plane behind the front, as a back cap's is. + plane: Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: 1.0, center: Point::ORIGIN, eye: None }), + index, + }; + let frame = |piece: MembranePiece, cover: Cover| { + GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces: vec![piece], covers: vec![cover] }) + }; + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "front", "x": 10.0, "y": 5.0})).unwrap(); + let mut nearer = side(8.0, 10.0, 1); + nearer.plane = None; + assert!(frame(front(5.0, 0), nearer.clone()).handle(&g).is_none()); + assert!(frame(front(5.0, 0), nearer).offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).is_none()); + assert!(frame(front(5.0, 0), side(8.0, 10.0, 1)).handle(&g).is_some()); + assert!(frame(front(5.0, 0), side(14.0, 10.0, 1)).handle(&g).is_some()); + assert!(frame(front(5.0, 0), side(8.0, f64::MAX, 1)).handle(&g).is_none()); + assert!(frame(front(f64::MAX, 0), side(8.0, f64::MAX, 1)).handle(&g).is_none()); + assert!(frame(front(f64::MAX, 2), side(8.0, f64::MAX, 1)).handle(&g).is_some()); +} From 227b6b9984faec2686b46ed6825a10fb09cf41fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 01:05:46 -0800 Subject: [PATCH 21/69] 3D: no Inflate graphic handle where a nearer piece of its own face covers it Where two pieces of an Inflate face overlap on the page, a graphic's center mapped through the farther piece had a handle at a point the nearer piece covers, and that point read back as a different offset. Every other piece now counts as a cover, of either face. A piece drawn last is chosen over the others by draw order, as the cover check orders them, so two overlapping pieces drawn last map through the later one. --- crates/effects/src/solids/graphics.rs | 16 ++++++++++++---- crates/effects/src/solids/tests_graphics.rs | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 2ef74b1b10..ad0c802728 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -1097,8 +1097,8 @@ impl MembraneFrame { /// Point `p` of `face` in the art's plane mapped onto the page, or with `from_page` a page point /// mapped into the art's plane, through the piece of that face that holds it and is nearest at - /// that point of the page. `None` when no piece the viewer sees holds it, or when a nearer piece - /// of the other face or a nearer cover hides that point of the page. + /// that point of the page. `None` when no piece the viewer sees holds it, or when another nearer + /// piece, of either face, or a nearer cover hides that point of the page. fn map(&self, face: PlanarFace, p: Point, from_page: bool) -> Option { let inside = |t: &[Point; 3], q: Point| { let side = |a: Point, b: Point| (b - a).cross(q - a); @@ -1113,7 +1113,15 @@ impl MembraneFrame { } let Some(q) = triangle_map(from, to).map(|m| m * p).filter(|q| q.is_finite()) else { continue }; let depth = piece.depth_at(if from_page { p } else { q }); - if best.is_none_or(|(_, nearest, _)| depth > nearest) { + // A piece drawn last is drawn over every other one, and the later of two drawn last is + // drawn over the other, whatever their planes' depths. + let over = |(_, nearest, other): (Point, f64, &MembranePiece)| match (piece.depth == f64::MAX, other.depth == f64::MAX) { + (true, true) => piece.index > other.index, + (true, false) => true, + (false, true) => false, + (false, false) => depth > nearest, + }; + if best.is_none_or(over) { best = Some((q, depth, piece)); } } @@ -1131,7 +1139,7 @@ impl MembraneFrame { let covered = self .pieces .iter() - .filter(|piece| piece.face != face) + .filter(|piece| !std::ptr::eq(*piece, shown)) .any(|piece| inside(&piece.page, at) && hides(piece.depth, piece.depth_at(at), piece.index)) || self.covers.iter().any(|c| c.holds(at) && hides(c.depth, c.plane.and_then(|plane| plane.depth_at(at)).unwrap_or(c.depth), c.index)); (!covered).then_some(q) diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index 1873156469..ca3ba46d59 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -1056,6 +1056,24 @@ fn overlapping_inflate_pieces_map_a_point_through_the_one_nearer_there() { // Near the tilted piece's left corner it is the nearer one. let (x, _) = frame.offset_at(PlanarFace::Front, Point::new(2.0, 0.5)).unwrap(); assert!((x - 2.0).abs() < 1e-6, "{x}"); + // A graphic's center has a handle only where its own piece is the nearer one, and the handle + // maps back to the same offset. + let mark = |x: f64, y: f64| MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "front", "x": x, "y": y})).unwrap(); + assert!(frame.handle(&mark(10.0, 5.0)).is_none()); + for (x, y) in [(2.0, 0.5), (110.0, 5.0)] { + let (at, _) = frame.handle(&mark(x, y)).unwrap(); + let (bx, by) = frame.offset_at(PlanarFace::Front, at).unwrap(); + assert!((bx - x).abs() < 1e-6 && (by - y).abs() < 1e-6, "{x} {y}: {bx} {by}"); + } + // Of two overlapping pieces drawn last, the later one is drawn over the other, though the + // earlier one's plane is nearer. + let last = |shift: f64, offset: f64, index: usize| MembranePiece { index, ..piece(shift, f64::MAX, [0.0, 0.0, 1.0], offset) }; + let pieces = vec![last(0.0, 10.0, 0), last(100.0, 0.0, 1)]; + let frame = GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces, covers: vec![] }); + let (x, _) = frame.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).unwrap(); + assert!((x - 110.0).abs() < 1e-6, "{x}"); + assert!(frame.handle(&mark(10.0, 5.0)).is_none()); + assert!(frame.handle(&mark(110.0, 5.0)).is_some()); } /// A graphic on Inflate's back has no handle where a nearer piece of the front covers its center From 241fec357956b9f9d19b9b51ffda7a563adeb1ce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 09:21:53 -0800 Subject: [PATCH 22/69] Command Palette: commands that cannot run now are dimmed A result that cannot run now stays in its place in the list and is drawn in the disabled text color: an engine command whose engine check fails (Ungroup with nothing selected, Paste with an empty clipboard and nothing to paste from the system clipboard), a UI command the menus dim, a filter plug-in or an effect whose menu item is dimmed, and a panel in Presentation Mode. Tools are never dimmed. The engine's reason, or that the command is not available right now, shows on hover, as the row's screen-reader description, and in the footer while the row is highlighted: beside the count, or on a line of its own under the recent picks of an empty search. The row's screen-reader node is marked disabled. Both messages are existing status messages, so no catalog changes. Only the drawn rows are checked, each once per state: the key is what the native menu bar's rows depend on (native_menu::state_hash, now pub(crate)), plus unsaved changes, the screen mode, an open dialog and background saves, exports, file reads, plug-in runs and traces, and a frame with a click. Typing in the search field keeps the answers. One engine check took 102 ms on a 20,000-object selection in a release build. The check does not change the ranking, and a pick of a dimmed result does what it did before. --- crates/ui-egui/src/native_menu.rs | 2 +- crates/ui-egui/src/palette.rs | 272 +++++++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 3 files changed, 268 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 510131be0e..40ebc46ba5 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -610,7 +610,7 @@ pub fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { /// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's /// preview, or a typing session), the revision, which each of its previews changes, is left out: /// the hash changes as the interaction begins and as it ends. -fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { +pub(crate) fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { let mut h = DefaultHasher::new(); input.hash(&mut h); app.run_count.hash(&mut h); diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index dbd19f3f57..6f6acb5643 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -437,6 +437,73 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { } } +/// Why the result `id` can't run now, as an English status message, or `None` while it can: the +/// engine's reason when it gives one, else the status line a dimmed menu item's pick gives +/// ([`crate::shortcut_editor::dimmed`]). A panel can't be shown in Presentation Mode, a tool can +/// always be chosen, and every other result asks [`menus::enabled`] about the command its pick +/// runs. +fn unavailable(app: &VectorcraftApp, id: &str) -> Option { + if id.starts_with("tool:") { + return None; + } + if id.starts_with("panel:") && app.ui.screen_mode >= 3 { + return Some("panels can't be shown in Presentation Mode".to_string()); + } + // The command the pick runs. + let id = if id.starts_with("panel:") || id.starts_with("plugin:") || id.starts_with("effect:") { + crate::keymap::command_of(id).id + } else { + id.to_string() + }; + if menus::enabled(app, &id) { + return None; + } + let why = vectorcraft_engine::find_command(&id).and_then(|c| (c.enabled)(&app.session).err()); + Some(why.unwrap_or_else(|| format!("command `{id}` is not available right now"))) +} + +/// The drawn results' [`unavailable`] answers, in the interface language, for the state `key` +/// ([`availability_key`]) they were read in. An engine check can take tens of milliseconds on a +/// large selection, so each result is asked once per state instead of on every frame. +#[derive(Clone, Default)] +struct Availability { + key: u64, + known: std::collections::HashMap>, +} + +impl Availability { + /// Why the result `id` can't run now, translated, or `None` while it can. + fn why(&mut self, app: &VectorcraftApp, id: &str) -> Option { + if let Some(why) = self.known.get(id) { + return why.clone(); + } + let why = unavailable(app, id).map(|why| crate::i18n::msg(&why)); + self.known.insert(id.to_string(), why.clone()); + why + } +} + +/// What the results' availability depends on: what the native menu bar's rows depend on +/// ([`crate::native_menu::state_hash`]: commands run, the document's revision, selection, history +/// and clipboard, the language and more), whether the document has unsaved changes, the screen +/// mode, an open dialog, and the background saves and exports, file reads, plug-in runs and traces +/// that run or show their progress. A frame with a pointer button release also changes it, for +/// what it leaves out (a panel shown, a tool chosen); typing in the search field does not. +fn availability_key(app: &VectorcraftApp, ctx: &egui::Context) -> u64 { + use std::hash::{Hash, Hasher}; + let click = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. }))); + let mut h = std::collections::hash_map::DefaultHasher::new(); + crate::native_menu::state_hash(app, click.then_some(app.host_iteration)).hash(&mut h); + let running = app.background.jobs.iter().filter(|j| j.progress.is_some() && !j.cancelled()).count(); + (app.ui.screen_mode, app.ui.dialog.is_some(), app.background.jobs.len(), running).hash(&mut h); + (app.opening.pending.len(), crate::opening::any_shown(app)).hash(&mut h); + // A background save marks the document saved without a new revision. + app.session.active().map(|d| (d.path.is_some(), d.converted, d.is_dirty())).hash(&mut h); + let plugins = (crate::plugin_runs::any_running(app), crate::plugin_runs::any_shown(app)); + (plugins, crate::trace_runs::any_running(app), crate::trace_runs::any_shown(app)).hash(&mut h); + h.finish() +} + /// The entries the query `q` matches, best first ([`search::rank`]), with the commands picked most /// often (`uses`) first among the entries that match as well, and then the picks that Recent /// Commands lists for the ids `recent_ids` ([`recent`]). The ranking of the last query is kept, so @@ -788,6 +855,13 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); } let screen = ctx.content_rect(); + // The drawn results' availability, kept while the state it was read in lasts. + let availability_id = egui::Id::unique("palette-availability"); + let key = availability_key(app, ctx); + let mut availability = ctx + .data_mut(|d| d.remove_temp::(availability_id)) + .filter(|a| a.key == key) + .unwrap_or(Availability { key, known: Default::default() }); // The highlighted result the rows and the field's description are drawn with. let mut drawn = sel; // The backdrop covers the canvas, the toolbars, the docked panels and the app bar under the @@ -884,19 +958,32 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if on { ui.painter().rect_filled(rect, 4.0, ui.visuals().selection.bg_fill); } + // A result that can't run now stays in its place, drawn dimmed, and says + // why on hover and to screen readers. + let why = availability.why(app, &e.id); + let (name_color, shortcut_color) = if why.is_some() { (t.text_disabled, t.text_disabled) } else { (t.text, t.text_dim) }; let font = egui::TextStyle::Body.resolve(ui.style()); let shortcut = menus::shown_shortcut(&e.shortcut); let p = ui.painter(); let shortcut_at = rect.right_center() - egui::vec2(8.0, 0.0); - let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), t.text_dim); + let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), shortcut_color); let name_end = if shortcut.is_empty() { rect.right() - 8.0 } else { used.left() - 12.0 }; let name_at = rect.left() + 8.0; - let name = name_galley(p, &e.shown, font, t.text, name_end - name_at); - p.galley(egui::pos2(name_at, rect.center().y - name.size().y / 2.0), name, t.text); + let name = name_galley(p, &e.shown, font, name_color, name_end - name_at); + p.galley(egui::pos2(name_at, rect.center().y - name.size().y / 2.0), name, name_color); // `WidgetInfo::selected` reaches screen readers as a toggled state, so the // row sets the selected state on its node itself. - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, row_label(e))); - ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(on)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, why.is_none(), row_label(e))); + ui.ctx().accesskit_node_builder(resp.id, |node| { + node.set_selected(on); + if let Some(why) = &why { + node.set_description(why.clone()); + } + }); + let resp = match why { + Some(why) => resp.on_hover_text(why), + None => resp, + }; if resp.clicked() { run = Some(e.id.clone()); } @@ -911,10 +998,23 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); } + // While the highlighted result can't run now, the footer also says why, so a keyboard + // user reads it too: on the count's line, or alone under the recent picks, so the + // footer stays the height counted above. + let why = matches.get(sel).and_then(|e| availability.why(app, &e.id)); // Under the recent picks no count is shown; with none, one dimmed line says so. if !empty { ui.add_space(6.0); - ui.label(egui::RichText::new(footer(n, total)).color(t.text_dim)); + let count = ui.label(egui::RichText::new(footer(n, total)).color(t.text_dim)); + if let Some(why) = why { + let right = ui.max_rect().right(); + let at = egui::Rect::from_x_y_ranges((count.rect.right() + 12.0).min(right)..=right, count.rect.y_range()); + let why = egui::RichText::new(why).color(t.text_dim); + ui.put(at, egui::Label::new(why).truncate().halign(egui::Align::Max)); + } + } else if let Some(why) = why { + ui.add_space(6.0); + ui.add(egui::Label::new(egui::RichText::new(why).color(t.text_dim)).truncate()); } else if n == 0 { ui.label(egui::RichText::new(tl!("No recent commands")).color(t.text_dim)); } @@ -951,6 +1051,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ctx.data_mut(|d| { d.insert_temp::(sel_id, (sel, q, offset, view, sel_key)); d.insert_temp(rsel_id, rsel); + d.insert_temp(availability_id, availability); }); if let Some(id) = run { app.ui.palette_open = false; @@ -2621,6 +2722,165 @@ mod tests { assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status); } + /// The open palette on `query` over the session `session`. + fn open_on(query: &str, session: vectorcraft_engine::Session) -> Open { + let mut open = Open::new(query, WINDOW); + open.app = VectorcraftApp::new(session, crate::Services::default()); + open.app.ui.palette_open = true; + open.app.ui.palette_query = query.into(); + open.frame(vec![]); + open + } + + /// The screen-reader node of the result row named `name`. + fn row_named<'a>(nodes: &'a [egui::accesskit::Node], name: &str) -> &'a egui::accesskit::Node { + nodes + .iter() + .filter(|n| n.role() == egui::accesskit::Role::ListItem) + .find(|n| n.label().is_some_and(|l| l == name || l.starts_with(&format!("{name}, ")))) + .unwrap_or_else(|| panic!("a row named {name}: {:?}", rows(nodes))) + } + + /// Highlights the result `id` with the arrow keys: the frame's screen-reader tree. + fn highlight(open: &mut Open, id: &str) -> Vec { + let k = open.listed().iter().position(|e| e == id).unwrap_or_else(|| panic!("{id} is listed")); + assert!(k < VISIBLE_ROWS, "{:?}", open.listed()); + let nodes = open.press(egui::Key::ArrowDown, k); + assert_eq!(open.highlighted(), k); + nodes + } + + /// With nothing selected, Ungroup stays listed in its place, dimmed, with the engine's reason in + /// its screen-reader description and in the footer while it is highlighted. Selecting art while + /// the palette stays open shows it as available on the next frame, in the same order. (A query + /// other tests' plug-in names do not match, so the list stays the same between frames.) + #[test] + fn a_result_that_cannot_run_now_is_dimmed_and_says_why() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let why = crate::i18n::msg(&(vectorcraft_engine::find_command("object.ungroup").unwrap().enabled)(&session).unwrap_err()); + let mut open = open_on("ungroup", session); + let name = entries(&open.ctx, Lang::EN).iter().find(|e| e.id == "object.ungroup").map(row_label).unwrap(); + let order = open.listed(); + let nodes = highlight(&mut open, "object.ungroup"); + let ungroup = row_named(&nodes, &name); + assert!(ungroup.is_disabled(), "{ungroup:?}"); + assert_eq!(ungroup.description(), Some(why.as_str())); + let footer_says = |nodes: &[egui::accesskit::Node]| labels(nodes).contains(&why); + assert!(footer_says(&nodes), "{:?}", labels(&nodes)); + let dimmed_rows: Vec = rows(&nodes).into_iter().map(|r| r.0).collect(); + + open.app.run("select.all", json!({})).unwrap(); + let nodes = open.frame(vec![]); + let ungroup = row_named(&nodes, &name); + assert!(!ungroup.is_disabled() && ungroup.description().is_none(), "{ungroup:?}"); + assert!(!footer_says(&nodes), "{:?}", labels(&nodes)); + // Whether a result can run never moves it. + assert_eq!(open.listed(), order); + assert_eq!(rows(&nodes).into_iter().map(|r| r.0).collect::>(), dimmed_rows); + } + + /// Under an empty search, a highlighted recent pick that can't run now is dimmed and the line + /// under the picks says why. + #[test] + fn a_recent_pick_that_cannot_run_now_says_why() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let why = crate::i18n::msg(&(vectorcraft_engine::find_command("object.ungroup").unwrap().enabled)(&session).unwrap_err()); + let mut open = open_on("", session); + open.app.ui.recent_commands = vec!["object.ungroup".to_string(), "object.group".to_string()]; + let nodes = open.frame(vec![]); + assert_eq!(open.highlighted(), 0); + let rows: Vec<_> = nodes.iter().filter(|n| n.role() == egui::accesskit::Role::ListItem).collect(); + assert_eq!(rows.len(), 2, "{rows:?}"); + assert!(rows.iter().all(|n| n.is_disabled()), "{rows:?}"); + assert!(labels(&nodes).contains(&why), "{:?}", labels(&nodes)); + let popup = open.popup(); + assert!(popup.bottom() <= WINDOW.y, "{popup:?}"); + } + + /// The drawn results are asked whether they can run once per state: keys pressed in the palette + /// keep the answers, and a command run or a click asks again. + #[test] + fn availability_is_read_once_per_state() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let mut open = open_on("ungroup", session); + let id = egui::Id::unique("palette-availability"); + let read = |open: &Open| open.ctx.data(|d| d.get_temp::(id)).expect("the availability is kept"); + let first = read(&open); + assert!(first.known.get("object.ungroup").is_some_and(Option::is_some), "{:?}", first.known); + // The key also takes in state shared by every test (the language, the loaded fonts, the + // installed plug-ins), which other tests change at the same time, so the presses are tried + // again until one try keeps the key. + let kept = (0..20).any(|_| { + open.frame(vec![]); + let before = read(&open).key; + open.press(egui::Key::ArrowDown, 1); + open.press(egui::Key::X, 1); + read(&open).key == before + }); + assert!(kept, "key presses keep the answers"); + let first = read(&open); + open.app.run("select.all", json!({})).unwrap(); + open.frame(vec![]); + let after = read(&open); + assert_ne!(after.key, first.key); + assert_eq!(after.known.get("object.ungroup"), Some(&None), "asked again: {:?}", after.known); + let release = egui::Event::PointerButton { + pos: egui::pos2(1.0, 1.0), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }; + open.frame(vec![release]); + assert_ne!(read(&open).key, after.key, "a click asks again"); + } + + /// Paste is dimmed while the clipboard is empty and nothing can be pasted from the system + /// clipboard, and not while the system clipboard can be pasted. + #[test] + fn paste_is_dimmed_only_while_nothing_can_be_pasted() { + let mut open = open_on("paste", vectorcraft_testkit::fixtures::Fixture::Multi.session()); + open.app.system_paste = false; + let nodes = open.frame(vec![]); + let paste = row_named(&nodes, "Edit › Paste"); + assert!(paste.is_disabled(), "{paste:?}"); + assert_eq!(paste.description(), Some(crate::i18n::msg("clipboard is empty").as_str())); + open.app.system_paste = true; + let nodes = open.frame(vec![]); + assert!(!row_named(&nodes, "Edit › Paste").is_disabled()); + } + + /// A tool can always be chosen; a panel can't be shown in Presentation Mode, and says so. + #[test] + fn tools_are_never_dimmed_and_panels_are_in_presentation_mode() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let tools: Vec = build(Lang::EN).into_iter().map(|e| e.id).filter(|id| id.starts_with("tool:")).collect(); + assert!(!tools.is_empty()); + assert!(tools.iter().all(|id| unavailable(&app, id).is_none()), "{tools:?}"); + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + assert_eq!(unavailable(&app, "panel:layers"), None); + app.ui.screen_mode = 3; + assert_eq!(unavailable(&app, "panel:layers").as_deref(), Some("panels can't be shown in Presentation Mode")); + } + + /// A UI command without an engine reason says it is not available, and a filter plug-in or an + /// effect asks about the command its pick runs. + #[test] + fn a_result_without_an_engine_reason_says_it_is_not_available() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + assert!(vectorcraft_engine::find_command("ui.newBrush").is_none()); + assert_eq!(unavailable(&app, "ui.newBrush").as_deref(), Some("command `ui.newBrush` is not available right now")); + assert_eq!(unavailable(&app, "plugin:any.filter").as_deref(), Some("command `plugin.dialog` is not available right now")); + let effect = crate::shortcut_editor::effect_items().first().map(|e| format!("effect:{}", e.effect)).expect("an Effect menu item"); + assert!(unavailable(&app, &effect).is_some(), "{effect}"); + let app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + assert_eq!(unavailable(&app, "ui.newBrush"), None); + assert_eq!(unavailable(&app, "plugin:any.filter"), None); + assert_eq!(unavailable(&app, &effect), None, "{effect}"); + } + /// Screen readers stay on the field: its description names the highlighted result and its /// place, and follows the highlight; the rows are list items, the highlighted one selected, and /// the footer's count is a label. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5fc911bc7a..4a1d5c828e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1312,6 +1312,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do, the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades and the matches through a typo, a description or a word with the same meaning, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows, which also holds a pick whose command could not run. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`). A Command Palette query word also finds a command by what the command's description says: "transparent background" lists Remove Background… among the first 3 results, and "png" lists it after every result with "png" in its name or menu path. The description is the command's params text (an engine or plug-in command's, a UI command's, or an effect's) without each `{…}` group that is not inside a `{`, `[` or `(` group, without each such `[…]` or `(…)` group just after a `→`, and without the `→` before a removed group, cut to its first 300 characters at the end of a word. The words of a schema ("corners" for Remove Background…) and of a result written as a group do not find the command; a result written as words after a `→` stays in the description. Words of 2 characters or fewer, words with no letter, and "the", "and", "ids", "true", "false" and "null" are left out. A query word that is a word of a description, shares an English base word with one, starts one or has the same meaning as one finds the result, and such a result ranks below every result that the query matches in its name, menu path or id, as text inside a word or through a typo. Descriptions are English only, and a typo does not match them. Tools, panels and filter plug-ins have no description (`palette::search` tests `a_description_leaves_out_the_schema_and_the_result`, `a_word_of_the_description_finds_the_result`, `a_description_match_ranks_below_a_typo`, `words_of_a_description_find_the_command`). + A Command Palette result that cannot run now stays in its place in the list and is drawn dimmed: an engine command whose engine check fails (Ungroup with nothing selected, Paste with an empty clipboard and nothing to paste from the system clipboard), a UI command the menus dim, a filter plug-in or an effect whose menu item is dimmed, and a panel in Presentation Mode. Tools are never dimmed. The engine's reason, or that the command is not available right now, shows on hover, in the row's screen-reader description and in the footer while the row is highlighted, beside the count or, under the recent picks of an empty search, on a line of its own. Only the drawn rows are checked, each once for as long as the state it was checked in lasts: a command run, an edit, a change of selection, document, history, clipboard, language, screen mode or open dialog, a save that marks the document saved, a background save, export, file read, plug-in run or trace that starts, ends or shows its progress window, or a click checks them again on the next frame, while typing in the search field does not. The check never changes the ranking. A pick of a dimmed result does what it did before (`palette` tests `a_result_that_cannot_run_now_is_dimmed_and_says_why`, `paste_is_dimmed_only_while_nothing_can_be_pasted`, `tools_are_never_dimmed_and_panels_are_in_presentation_mode`, `a_result_without_an_engine_reason_says_it_is_not_available`, `a_recent_pick_that_cannot_run_now_says_why`, `availability_is_read_once_per_state`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. From 2dcefa14e6d8dc0975b9fc4e07172faf5e485999 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 11:52:27 -0800 Subject: [PATCH 23/69] Command Palette: the search field's description says why the highlighted result can't run Arrow keys keep screen readers on the search field, so its description now adds the highlighted result's reason on a second line when the result can't run now. --- crates/ui-egui/src/palette.rs | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 6f6acb5643..b702cf66e3 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -930,12 +930,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // keep the highlighted result in view. let resized = (view - last_view).abs() > 0.5; // Screen readers stay on the field: its description names the highlighted result and - // its place among every match, as the footer counts them. + // its place among every match, as the footer counts them, and on a second line why it + // can't run now when it can't. if let Some(e) = matches.get(sel) { let rank = if sel + 1 == matches.len() { kept.unwrap_or(sel) } else { sel }; let pos = (rank + 1).to_string(); let of = total.to_string(); - let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &row_label(e))]); + let mut said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &row_label(e))]); + if let Some(why) = availability.why(app, &e.id) { + said = format!("{said}\n{why}"); + } ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); } if n > 0 { @@ -1648,7 +1652,7 @@ mod tests { assert_eq!(after.get(1).map(String::as_str), Some(tool), "only the pick moves"); let entries = entries(&open.ctx, Lang::EN); let label = entries.iter().find(|e| e.id == effect).map(row_label).unwrap(); - assert_eq!(field_description(&nodes), format!("1 of {}: {label}", after.len())); + assert_eq!(field_place(&nodes), format!("1 of {}: {label}", after.len())); open.press(egui::Key::Enter, 1); assert_eq!(open.app.ui.recent_commands, [effect], "Enter ran the effect again"); } @@ -2466,6 +2470,12 @@ mod tests { field.description().unwrap_or_default().to_string() } + /// The first line of the search field's description: the highlighted result's place and name, + /// without the reason a result that can't run now adds under it. + fn field_place(nodes: &[egui::accesskit::Node]) -> String { + field_description(nodes).lines().next().unwrap_or_default().to_string() + } + const WINDOW: egui::Vec2 = egui::vec2(1280.0, 900.0); /// Each result is a 20-point row, rows touch, and 12 show at once; the popup is shorter than @@ -2660,7 +2670,7 @@ mod tests { let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); let label = entries.iter().find(|e| e.id == listed[3]).map(row_label).unwrap(); assert_eq!(lit, std::slice::from_ref(&label)); - assert_eq!(field_description(&nodes), format!("4 of {}: {label}", matching(&entries, "select", &[]).len())); + assert_eq!(field_place(&nodes), format!("4 of {}: {label}", matching(&entries, "select", &[]).len())); } /// A name too long for its row is cut short with "…" and stays inside the width it is given. @@ -2768,6 +2778,9 @@ mod tests { assert_eq!(ungroup.description(), Some(why.as_str())); let footer_says = |nodes: &[egui::accesskit::Node]| labels(nodes).contains(&why); assert!(footer_says(&nodes), "{:?}", labels(&nodes)); + // The arrow keys leave screen readers on the search field, so its description says why too. + let place = format!("{} of {}: {name}", open.highlighted() + 1, order.len()); + assert_eq!(field_description(&nodes), format!("{place}\n{why}")); let dimmed_rows: Vec = rows(&nodes).into_iter().map(|r| r.0).collect(); open.app.run("select.all", json!({})).unwrap(); @@ -2775,6 +2788,7 @@ mod tests { let ungroup = row_named(&nodes, &name); assert!(!ungroup.is_disabled() && ungroup.description().is_none(), "{ungroup:?}"); assert!(!footer_says(&nodes), "{:?}", labels(&nodes)); + assert_eq!(field_description(&nodes), place); // Whether a result can run never moves it. assert_eq!(open.listed(), order); assert_eq!(rows(&nodes).into_iter().map(|r| r.0).collect::>(), dimmed_rows); @@ -2894,19 +2908,19 @@ mod tests { // More results match than the list holds: the place counts every match, as the footer does. let total = matching(&entries, "show panel", &[]).len(); assert!(total > MAX_RESULTS && listed.len() == MAX_RESULTS, "{total}"); - assert_eq!(field_description(&nodes), format!("1 of {total}: {}", label(0))); + assert_eq!(field_place(&nodes), format!("1 of {total}: {}", label(0))); let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); assert_eq!(lit, [label(0)]); assert!(labels(&nodes).contains(&format!("50 of {total} results. Keep typing to narrow them.")), "{:?}", labels(&nodes)); let nodes = open.press(egui::Key::ArrowDown, 1); - assert_eq!(field_description(&nodes), format!("2 of {total}: {}", label(1))); + assert_eq!(field_place(&nodes), format!("2 of {total}: {}", label(1))); // Fewer results match than the list holds. let mut open = Open::new("eyedropper", WINDOW); let n = open.listed().len(); assert!((1..MAX_RESULTS).contains(&n), "{n}"); let first = entries.iter().find(|e| e.id == open.listed()[0]).map(row_label).unwrap(); let nodes = open.frame(vec![]); - assert_eq!(field_description(&nodes), format!("1 of {n}: {first}")); + assert_eq!(field_place(&nodes), format!("1 of {n}: {first}")); assert!(labels(&nodes).contains(&footer(n, n)), "{:?}", labels(&nodes)); } @@ -3293,6 +3307,6 @@ mod tests { assert_eq!((sel, &now), (MAX_RESULTS - 1, &id), "the highlight stays on its result, in the last row"); let label = row_label(ranked[MAX_RESULTS]); assert!(rows(&nodes).iter().any(|r| r.1 && r.0 == label), "its row is drawn and highlighted"); - assert_eq!(field_description(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len())); + assert_eq!(field_place(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len())); } } From 3c9db048e014d9b1a176a9f606a0756227d6335b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 12:36:08 -0800 Subject: [PATCH 24/69] Command Palette: dimmed results name themselves, not their command id MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A result's reason is the status line a pick of its dimmed menu item gives, with the result's name in place of the command id: "command `Object › Ungroup` is not available right now: nothing selected". `shortcut_editor::dimmed` builds it for both, so the hover reason and the pick's status line read alike. The reason is kept in English and translated when it is shown. - The engine's check of a dimmed engine command runs once: the new `menus::why_off` gives `menus::enabled`'s answer with the engine's reason. `menu_target_now` and the palette's effect picks use it too. - The Recent Commands list beside the search field draws a pick that can't run now dimmed, disabled for screen readers with the reason as its description, and with the reason on hover. - The palette drops its answers when it closes, so opening it again with the keyboard asks again. - A frame with a click asks again on that frame only: the click is no longer part of the key, so the next frame keeps the answers. --- crates/ui-egui/src/menus.rs | 1 + crates/ui-egui/src/menus/state.rs | 26 ++- crates/ui-egui/src/palette.rs | 303 +++++++++++++++++++++----- crates/ui-egui/src/shortcut_editor.rs | 36 ++- docs/target-app-parity.md | 2 +- 5 files changed, 294 insertions(+), 74 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 4e2d80bb45..2a0db30223 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -78,6 +78,7 @@ pub use run::{check_params, run_ui_command}; pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; #[cfg(test)] use slots::RECENT_FONT_IDS; +pub(crate) use state::why_off; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; pub(crate) use submenus::PATH_EFFECTS; pub use tree::{menu_tree, menu_tree_named}; diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index d4dda4698b..f22c79576b 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -200,22 +200,38 @@ pub(super) fn has_subject(app: &VectorcraftApp) -> bool { /// Can command `id` run now? An engine command asks the engine, a UI command the app's state; /// none that would act on text an input method is still composing. pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { + why_off(app, id).is_none() +} + +/// Why command `id` can't run now ([`enabled`]): `None` while it can, else `Some` with the +/// engine's reason when the engine's check of an engine command fails. The engine's check runs at +/// most once. +pub(crate) fn why_off(app: &VectorcraftApp, id: &str) -> Option> { if waits_for_ime(app, id) { - return false; + return Some(None); } if SUBJECT_COMMANDS.contains(&id) { - return has_subject(app); + return (!has_subject(app)).then_some(None); } // The Artboard tool's canvas menu measured this when it opened. if id == "artboard.deleteEmpty" && let Some(facts) = crate::panels::artboards::open_menu_facts(app) { - return facts.any_empty; + return (!facts.any_empty).then_some(None); } if let Some(c) = vectorcraft_engine::find_command(id) { - // The system clipboard's contents can be pasted with an empty internal clipboard. - return (c.enabled)(&app.session).is_ok() || app.system_paste && id.starts_with("edit.paste"); + return match (c.enabled)(&app.session) { + Ok(()) => None, + // The system clipboard's contents can be pasted with an empty internal clipboard. + Err(_) if app.system_paste && id.starts_with("edit.paste") => None, + Err(why) => Some(Some(why)), + }; } + (!ui_enabled(app, id)).then_some(None) +} + +/// Can UI command `id` run now? +fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { match id { // Save is off for a clean document that already has its own file. "file.save" => app.session.active().is_some_and(|d| d.path.is_none() || d.converted || d.is_dirty()), diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index b702cf66e3..49338b0d2c 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -421,10 +421,10 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { let command = crate::keymap::command_of(id); // While the Effect menu dims the item (nothing selected), no dialog opens and the status // line says why. - if id.starts_with("effect:") && !menus::enabled(app, &command.id) { - if let Err(why) = crate::shortcut_editor::dimmed(app, &command.id) { - app.status(why); - } + if id.starts_with("effect:") + && let Some(why) = crate::shortcut_editor::dimmed(app, &command.id, &command.id) + { + app.status(why); } else { menus::invoke(app, &command.id, command.params); } @@ -437,12 +437,12 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { } } -/// Why the result `id` can't run now, as an English status message, or `None` while it can: the -/// engine's reason when it gives one, else the status line a dimmed menu item's pick gives -/// ([`crate::shortcut_editor::dimmed`]). A panel can't be shown in Presentation Mode, a tool can -/// always be chosen, and every other result asks [`menus::enabled`] about the command its pick -/// runs. -fn unavailable(app: &VectorcraftApp, id: &str) -> Option { +/// Why the result `id`, shown as `name`, can't run now, as an English status message, or `None` +/// while it can: the status line a pick of its dimmed menu item gives +/// ([`crate::shortcut_editor::dimmed`]), with the engine's reason when it gives one and `name` in +/// place of the command's id. A panel can't be shown in Presentation Mode, a tool can always be +/// chosen, and every other result asks about the command its pick runs. +fn unavailable(app: &VectorcraftApp, id: &str, name: &str) -> Option { if id.starts_with("tool:") { return None; } @@ -455,31 +455,38 @@ fn unavailable(app: &VectorcraftApp, id: &str) -> Option { } else { id.to_string() }; - if menus::enabled(app, &id) { - return None; - } - let why = vectorcraft_engine::find_command(&id).and_then(|c| (c.enabled)(&app.session).err()); - Some(why.unwrap_or_else(|| format!("command `{id}` is not available right now"))) + crate::shortcut_editor::dimmed(app, &id, name) } -/// The drawn results' [`unavailable`] answers, in the interface language, for the state `key` -/// ([`availability_key`]) they were read in. An engine check can take tens of milliseconds on a -/// large selection, so each result is asked once per state instead of on every frame. +/// The drawn results' [`unavailable`] answers for the state `key` ([`availability_key`]) they were +/// read in. An engine check can take tens of milliseconds on a large selection, so each result is +/// asked once per state instead of on every frame. #[derive(Clone, Default)] struct Availability { key: u64, + /// Each asked result's answer: why it can't run now, in English, or `None` while it can. known: std::collections::HashMap>, + /// How many results were asked since the key was set. + #[cfg(test)] + asked: usize, } impl Availability { - /// Why the result `id` can't run now, translated, or `None` while it can. - fn why(&mut self, app: &VectorcraftApp, id: &str) -> Option { - if let Some(why) = self.known.get(id) { - return why.clone(); - } - let why = unavailable(app, id).map(|why| crate::i18n::msg(&why)); - self.known.insert(id.to_string(), why.clone()); - why + /// Why the result `e` can't run now, in the interface language, or `None` while it can. + fn why(&mut self, app: &VectorcraftApp, e: &Entry) -> Option { + let why = match self.known.get(&e.id) { + Some(why) => why.clone(), + None => { + #[cfg(test)] + { + self.asked += 1; + } + let why = unavailable(app, &e.id, &e.shown); + self.known.insert(e.id.clone(), why.clone()); + why + } + }; + why.map(|why| crate::i18n::msg(&why)) } } @@ -487,13 +494,12 @@ impl Availability { /// ([`crate::native_menu::state_hash`]: commands run, the document's revision, selection, history /// and clipboard, the language and more), whether the document has unsaved changes, the screen /// mode, an open dialog, and the background saves and exports, file reads, plug-in runs and traces -/// that run or show their progress. A frame with a pointer button release also changes it, for -/// what it leaves out (a panel shown, a tool chosen); typing in the search field does not. -fn availability_key(app: &VectorcraftApp, ctx: &egui::Context) -> u64 { +/// that run or show their progress. A click asks again for what it leaves out (a panel shown, a +/// tool chosen) without changing it ([`show`]); typing in the search field does not. +fn availability_key(app: &VectorcraftApp) -> u64 { use std::hash::{Hash, Hasher}; - let click = ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. }))); let mut h = std::collections::hash_map::DefaultHasher::new(); - crate::native_menu::state_hash(app, click.then_some(app.host_iteration)).hash(&mut h); + crate::native_menu::state_hash(app, None).hash(&mut h); let running = app.background.jobs.iter().filter(|j| j.progress.is_some() && !j.cancelled()).count(); (app.ui.screen_mode, app.ui.dialog.is_some(), app.background.jobs.len(), running).hash(&mut h); (app.opening.pending.len(), crate::opening::any_shown(app)).hash(&mut h); @@ -752,11 +758,14 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let focus_id = egui::Id::unique("palette-focus-before"); let field_id = egui::Id::unique("palette-field"); let sel_id = egui::Id::unique("palette-selected"); + let availability_id = egui::Id::unique("palette-availability"); if !app.ui.palette_open { // The palette opens again with its first row highlighted and its list scrolled to the top - // (a list height of 0 scrolls it to the highlighted row). + // (a list height of 0 scrolls it to the highlighted row), and asks its results again + // whether they can run. let field = ctx.data_mut(|d| { d.remove::(sel_id); + d.remove::(availability_id); let field = d.get_temp::(field_id); d.remove::(field_id); field @@ -855,13 +864,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); } let screen = ctx.content_rect(); - // The drawn results' availability, kept while the state it was read in lasts. - let availability_id = egui::Id::unique("palette-availability"); - let key = availability_key(app, ctx); + // The drawn results' availability, kept while the state it was read in lasts. A frame with a + // pointer button release asks again, once, for what the state leaves out. + let key = availability_key(app); let mut availability = ctx .data_mut(|d| d.remove_temp::(availability_id)) .filter(|a| a.key == key) - .unwrap_or(Availability { key, known: Default::default() }); + .unwrap_or_else(|| Availability { key, ..Default::default() }); + if ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. }))) { + availability.known.clear(); + } // The highlighted result the rows and the field's description are drawn with. let mut drawn = sel; // The backdrop covers the canvas, the toolbars, the docked panels and the app bar under the @@ -900,7 +912,25 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.add_enabled(false, egui::Button::new(tl!("No recent commands"))); } for (i, e) in recent.iter().enumerate() { - let row = ui.add(egui::Button::new(e.shown.as_str()).shortcut_text(menus::shown_shortcut(&e.shortcut))); + // A pick that can't run now is drawn dimmed, as in the results, and says + // why on hover and to screen readers; it can still be chosen. + let why = availability.why(app, e); + let (name, shortcut) = (egui::RichText::new(e.shown.as_str()), egui::RichText::new(menus::shown_shortcut(&e.shortcut))); + let (name, shortcut) = match why { + Some(_) => (name.color(t.text_disabled), shortcut.color(t.text_disabled)), + None => (name, shortcut), + }; + let row = ui.add(egui::Button::new(name).shortcut_text(shortcut)); + ui.ctx().accesskit_node_builder(row.id, |node| { + if let Some(why) = &why { + node.set_disabled(); + node.set_description(why.clone()); + } + }); + let row = match why { + Some(why) => row.on_hover_text(why), + None => row, + }; if i == rsel { row.request_focus(); } @@ -937,7 +967,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let pos = (rank + 1).to_string(); let of = total.to_string(); let mut said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &row_label(e))]); - if let Some(why) = availability.why(app, &e.id) { + if let Some(why) = availability.why(app, e) { said = format!("{said}\n{why}"); } ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); @@ -964,7 +994,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } // A result that can't run now stays in its place, drawn dimmed, and says // why on hover and to screen readers. - let why = availability.why(app, &e.id); + let why = availability.why(app, e); let (name_color, shortcut_color) = if why.is_some() { (t.text_disabled, t.text_disabled) } else { (t.text, t.text_dim) }; let font = egui::TextStyle::Body.resolve(ui.style()); let shortcut = menus::shown_shortcut(&e.shortcut); @@ -1005,7 +1035,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // While the highlighted result can't run now, the footer also says why, so a keyboard // user reads it too: on the count's line, or alone under the recent picks, so the // footer stays the height counted above. - let why = matches.get(sel).and_then(|e| availability.why(app, &e.id)); + let why = matches.get(sel).and_then(|e| availability.why(app, e)); // Under the recent picks no count is shown; with none, one dimmed line says so. if !empty { ui.add_space(6.0); @@ -2388,6 +2418,8 @@ mod tests { time: f64, /// Whether the last frame asked for another one at once. repaint: bool, + /// What the last frame drew. + shapes: Vec, } impl Open { @@ -2401,7 +2433,7 @@ mod tests { ctx.enable_accesskit(); crate::theme::install_fonts(&ctx); crate::theme::apply(&ctx, Default::default()); - let mut open = Open { app, ctx, size, time: 0.0, repaint: false }; + let mut open = Open { app, ctx, size, time: 0.0, repaint: false, shapes: Vec::new() }; open.frame(vec![]); open } @@ -2415,6 +2447,7 @@ mod tests { let mut out = self.ctx.run_ui(input, |ui| show(app, ui.ctx())); out.textures_delta.clear(); self.repaint = out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()); + self.shapes = std::mem::take(&mut out.shapes); out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() } @@ -2424,6 +2457,18 @@ mod tests { self.frame(vec![key; times]) } + /// The color the last frame drew the text `text` in. + fn color_of(&self, text: &str) -> Option { + fn find(shape: &egui::Shape, text: &str) -> Option { + match shape { + egui::Shape::Text(t) if t.galley.text() == text => Some(t.fallback_color), + egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| find(s, text)), + _ => None, + } + } + self.shapes.iter().find_map(|s| find(&s.shape, text)) + } + /// The highlighted result's index. fn highlighted(&self) -> usize { self.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap().0 @@ -2768,14 +2813,18 @@ mod tests { fn a_result_that_cannot_run_now_is_dimmed_and_says_why() { let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); session.execute("select.none", &json!({})).unwrap(); - let why = crate::i18n::msg(&(vectorcraft_engine::find_command("object.ungroup").unwrap().enabled)(&session).unwrap_err()); + let why = ungroup_reason(&session); let mut open = open_on("ungroup", session); - let name = entries(&open.ctx, Lang::EN).iter().find(|e| e.id == "object.ungroup").map(row_label).unwrap(); + let entries = entries(&open.ctx, Lang::EN); + let entry = entries.iter().find(|e| e.id == "object.ungroup").unwrap(); + let name = row_label(entry); let order = open.listed(); let nodes = highlight(&mut open, "object.ungroup"); let ungroup = row_named(&nodes, &name); assert!(ungroup.is_disabled(), "{ungroup:?}"); assert_eq!(ungroup.description(), Some(why.as_str())); + let t = Tokens::get(&open.ctx); + assert_eq!(open.color_of(&entry.shown), Some(t.text_disabled), "the name is drawn dimmed"); let footer_says = |nodes: &[egui::accesskit::Node]| labels(nodes).contains(&why); assert!(footer_says(&nodes), "{:?}", labels(&nodes)); // The arrow keys leave screen readers on the search field, so its description says why too. @@ -2787,6 +2836,7 @@ mod tests { let nodes = open.frame(vec![]); let ungroup = row_named(&nodes, &name); assert!(!ungroup.is_disabled() && ungroup.description().is_none(), "{ungroup:?}"); + assert_eq!(open.color_of(&entry.shown), Some(t.text)); assert!(!footer_says(&nodes), "{:?}", labels(&nodes)); assert_eq!(field_description(&nodes), place); // Whether a result can run never moves it. @@ -2794,13 +2844,40 @@ mod tests { assert_eq!(rows(&nodes).into_iter().map(|r| r.0).collect::>(), dimmed_rows); } + /// Why Object › Ungroup can't run in `session`, as the palette shows it: the engine's reason, + /// with the result's name and no command id. + fn ungroup_reason(session: &vectorcraft_engine::Session) -> String { + let reason = (vectorcraft_engine::find_command("object.ungroup").unwrap().enabled)(session).unwrap_err(); + let why = crate::i18n::msg(&format!("command `Object › Ungroup` is not available right now: {reason}")); + assert!(!why.contains("object.ungroup"), "{why}"); + why + } + + /// The pointer resting on a result that can't run now shows why in a tooltip, as well as in + /// the footer of the result it highlights. + #[test] + fn hovering_a_result_that_cannot_run_now_says_why() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let why = ungroup_reason(&session); + let mut open = open_on("ungroup", session); + let name = entries(&open.ctx, Lang::EN).iter().find(|e| e.id == "object.ungroup").map(row_label).unwrap(); + let nodes = open.frame(vec![]); + let b = row_named(&nodes, &name).bounds().unwrap(); + let at = egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + open.frame(vec![egui::Event::PointerMoved(at)]); + let says = |nodes: &[egui::accesskit::Node]| labels(nodes).iter().filter(|l| **l == why).count(); + let shown = (0..30).map(|_| says(&open.frame(vec![]))).max().unwrap_or(0); + assert_eq!(shown, 2, "the footer and the tooltip"); + } + /// Under an empty search, a highlighted recent pick that can't run now is dimmed and the line /// under the picks says why. #[test] fn a_recent_pick_that_cannot_run_now_says_why() { let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); session.execute("select.none", &json!({})).unwrap(); - let why = crate::i18n::msg(&(vectorcraft_engine::find_command("object.ungroup").unwrap().enabled)(&session).unwrap_err()); + let why = ungroup_reason(&session); let mut open = open_on("", session); open.app.ui.recent_commands = vec!["object.ungroup".to_string(), "object.group".to_string()]; let nodes = open.frame(vec![]); @@ -2813,8 +2890,90 @@ mod tests { assert!(popup.bottom() <= WINDOW.y, "{popup:?}"); } + /// The Recent Commands list beside the search field draws a pick that can't run now dimmed, + /// disabled for screen readers with the reason as its description, and says why on hover. + #[test] + fn a_recent_command_that_cannot_run_now_is_dimmed_in_the_list() { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + app.run("select.none", json!({})).unwrap(); + let why = ungroup_reason(&app.session); + app.ui.recent_commands = vec!["object.ungroup".into(), "select.all".into()]; + let mut h = palette_harness(app); + h.ctx.all_styles_mut(|s| s.interaction.tooltip_delay = 0.0); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + let shown = |id: &str| entries(&h.ctx, Lang::EN).iter().find(|e| e.id == id).map(|e| e.shown.clone()).unwrap(); + let (ungroup, all) = (shown("object.ungroup"), shown("select.all")); + // A row's label also holds its shortcut. + let row = |name: &str| { + let name = name.to_string(); + move |n: &egui_kittest::kittest::AccessKitNode<'_>| n.role() == Role::Button && n.label().is_some_and(|l| l.contains(&name)) + }; + let ungroup_row = h.get_by(row(&ungroup)); + assert!(ungroup_row.accesskit_node().is_disabled()); + assert_eq!(ungroup_row.accesskit_node().description().as_deref(), Some(why.as_str())); + let all_row = h.get_by(row(&all)); + assert!(!all_row.accesskit_node().is_disabled() && all_row.accesskit_node().description().is_none()); + h.get_by(row(&ungroup)).hover(); + h.run_steps(3); + assert!(h.query_by_label(&why).is_some(), "the tooltip says why"); + } + + /// The palette drops its answers when it closes, so opening it again, with the keyboard too, + /// asks its results again. + #[test] + fn the_palette_asks_again_when_it_opens_again() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let mut open = open_on("ungroup", session); + let id = egui::Id::unique("palette-availability"); + let kept = |open: &Open| open.ctx.data(|d| d.get_temp::(id)); + assert!(kept(&open).is_some_and(|a| a.known.contains_key("object.ungroup"))); + open.app.ui.palette_open = false; + open.frame(vec![]); + assert!(kept(&open).is_none(), "the answers go when the palette closes"); + open.app.ui.palette_open = true; + open.frame(vec![]); + assert!(kept(&open).is_some_and(|a| a.asked > 0 && a.known.contains_key("object.ungroup")), "asked again"); + } + + /// What the results' availability depends on changes the key it is kept under: an open dialog, + /// the screen mode, a background job, and a save that marks the document saved without a new + /// revision. + #[test] + fn availability_is_asked_again_when_what_it_depends_on_changes() { + let write_shared: crate::background::SharedWriteFn = std::sync::Arc::new(|_: &str, _: &[u8]| Ok(())); + let services = crate::Services { write_shared: Some(write_shared), ..Default::default() }; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), services); + let mut key = availability_key(&app); + let mut changed = |app: &VectorcraftApp, what: &str| { + let now = availability_key(app); + assert_ne!(now, key, "{what}"); + key = now; + }; + app.ui.dialog = Some(crate::state::Dialog::new("about", json!({}))); + changed(&app, "a dialog opens"); + app.ui.dialog = None; + changed(&app, "the dialog closes"); + app.ui.screen_mode = 3; + changed(&app, "Presentation Mode"); + let started = crate::background::run(&mut app, true, "Saving".into(), None, |_| Ok(json!({})), |_, r| r).unwrap(); + assert_eq!(started.get("background"), Some(&json!(true)), "{started}"); + changed(&app, "a background job starts"); + app.run("select.all", json!({})).unwrap(); + app.run("object.group", json!({})).unwrap(); + changed(&app, "an edit"); + let revision = app.session.active().map(|d| d.revision); + app.session.active_mut().unwrap().mark_saved(); + assert_eq!(app.session.active().map(|d| d.revision), revision); + changed(&app, "the document is saved"); + } + /// The drawn results are asked whether they can run once per state: keys pressed in the palette - /// keep the answers, and a command run or a click asks again. + /// keep the answers, a command run asks again, and a frame with a click asks again once, + /// without changing the state the answers are kept for. #[test] fn availability_is_read_once_per_state() { let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); @@ -2847,8 +3006,18 @@ mod tests { pressed: false, modifiers: egui::Modifiers::NONE, }; - open.frame(vec![release]); - assert_ne!(read(&open).key, after.key, "a click asks again"); + // The same retries as for the key presses. + let once = (0..20).any(|_| { + open.frame(vec![]); + let before = read(&open); + open.frame(vec![release.clone()]); + let clicked = read(&open); + open.frame(vec![]); + let next = read(&open); + let asked_again = clicked.key == before.key && clicked.asked > before.asked; + asked_again && (next.key, next.asked) == (clicked.key, clicked.asked) + }); + assert!(once, "a click asks again on its own frame only"); } /// Paste is dimmed while the clipboard is empty and nothing can be pasted from the system @@ -2860,7 +3029,7 @@ mod tests { let nodes = open.frame(vec![]); let paste = row_named(&nodes, "Edit › Paste"); assert!(paste.is_disabled(), "{paste:?}"); - assert_eq!(paste.description(), Some(crate::i18n::msg("clipboard is empty").as_str())); + assert_eq!(paste.description(), Some("command `Edit › Paste` is not available right now: clipboard is empty")); open.app.system_paste = true; let nodes = open.frame(vec![]); assert!(!row_named(&nodes, "Edit › Paste").is_disabled()); @@ -2872,27 +3041,45 @@ mod tests { let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); let tools: Vec = build(Lang::EN).into_iter().map(|e| e.id).filter(|id| id.starts_with("tool:")).collect(); assert!(!tools.is_empty()); - assert!(tools.iter().all(|id| unavailable(&app, id).is_none()), "{tools:?}"); + assert!(tools.iter().all(|id| unavailable(&app, id, id).is_none()), "{tools:?}"); let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); - assert_eq!(unavailable(&app, "panel:layers"), None); + assert_eq!(unavailable(&app, "panel:layers", "Window › Layers"), None); app.ui.screen_mode = 3; - assert_eq!(unavailable(&app, "panel:layers").as_deref(), Some("panels can't be shown in Presentation Mode")); + assert_eq!(unavailable(&app, "panel:layers", "Window › Layers").as_deref(), Some("panels can't be shown in Presentation Mode")); } /// A UI command without an engine reason says it is not available, and a filter plug-in or an - /// effect asks about the command its pick runs. + /// effect asks about the command its pick runs. The message names the result as the palette + /// shows it, never by the command's id. #[test] fn a_result_without_an_engine_reason_says_it_is_not_available() { let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); assert!(vectorcraft_engine::find_command("ui.newBrush").is_none()); - assert_eq!(unavailable(&app, "ui.newBrush").as_deref(), Some("command `ui.newBrush` is not available right now")); - assert_eq!(unavailable(&app, "plugin:any.filter").as_deref(), Some("command `plugin.dialog` is not available right now")); + let brush = unavailable(&app, "ui.newBrush", "New Brush…"); + assert_eq!(brush.as_deref(), Some("command `New Brush…` is not available right now")); + let filter = unavailable(&app, "plugin:any.filter", "Object › Plug-ins › Any Filter…"); + assert_eq!(filter.as_deref(), Some("command `Object › Plug-ins › Any Filter…` is not available right now")); let effect = crate::shortcut_editor::effect_items().first().map(|e| format!("effect:{}", e.effect)).expect("an Effect menu item"); - assert!(unavailable(&app, &effect).is_some(), "{effect}"); + let why = unavailable(&app, &effect, "Effect › Any").unwrap_or_else(|| panic!("{effect}")); + assert!(why.starts_with("command `Effect › Any` is not available right now"), "{why}"); let app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); - assert_eq!(unavailable(&app, "ui.newBrush"), None); - assert_eq!(unavailable(&app, "plugin:any.filter"), None); - assert_eq!(unavailable(&app, &effect), None, "{effect}"); + assert_eq!(unavailable(&app, "ui.newBrush", "New Brush…"), None); + assert_eq!(unavailable(&app, "plugin:any.filter", "Any Filter…"), None); + assert_eq!(unavailable(&app, &effect, "Effect › Any"), None, "{effect}"); + } + + /// Every result's reason names it as the palette shows it: no command id appears in it. + #[test] + fn no_reason_shows_a_command_id() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let entries = build(Lang::EN); + let reasons: Vec<(String, String)> = + entries.iter().filter_map(|e| unavailable(&app, &e.id, &e.shown).map(|why| (e.id.clone(), why))).collect(); + assert!(reasons.len() > 100, "with no document most results can't run: {}", reasons.len()); + for (id, why) in &reasons { + let command = crate::keymap::command_of(id).id; + assert!(!why.contains(&format!("`{command}`")), "{id}: {why}"); + } } /// Screen readers stay on the field: its description names the highlighted result and its diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index cbf90d9ecd..0697b4bde7 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -918,17 +918,27 @@ pub(crate) fn menu_target(id: &str) -> Option<(String, Value)> { /// status line ([`dimmed`]), as for Remove Background… with no image selected. pub(crate) fn menu_target_now(app: &VectorcraftApp, id: &str) -> Option> { let target = menu_target(id)?; - Some(if menus::enabled(app, id) { Ok(target) } else { dimmed(app, id) }) + Some(match dimmed(app, id, id) { + None => Ok(target), + Some(why) => Err(why), + }) } -/// What [`menu_target_now`] gives for command `id` while its menu bar item is dimmed: the status -/// line, with the engine's reason when it gives one. The app's own rules ([`menus::enabled`]) dim -/// UI commands, and some commands the engine would run, without giving a reason. -pub(crate) fn dimmed(app: &VectorcraftApp, id: &str) -> Result<(String, Value), String> { - let Some(why) = vectorcraft_engine::find_command(id).and_then(|c| (c.enabled)(&app.session).err()) else { - return Err(format!("command `{id}` is not available right now")); +/// What [`menu_target_now`] gives for command `id` while its menu bar item is dimmed, or `None` +/// while the item is not dimmed: the status line, which calls the command `name` (its id on the +/// status line), with the engine's reason when it gives one. The app's own rules +/// ([`menus::enabled`]) dim UI commands, and some commands the engine would run, without giving a +/// reason. The engine's check runs at most once. +pub(crate) fn dimmed(app: &VectorcraftApp, id: &str, name: &str) -> Option { + let why = match menus::why_off(app, id)? { + Some(why) => Some(why), + // Dimmed before the engine was asked (no Appearance subject, an input method composing). + None => vectorcraft_engine::find_command(id).and_then(|c| (c.enabled)(&app.session).err()), }; - Err(vectorcraft_engine::EngineError::Disabled(id.to_string(), why).to_string()) + Some(match why { + Some(why) => vectorcraft_engine::EngineError::Disabled(name.to_string(), why).to_string(), + None => format!("command `{name}` is not available right now"), + }) } /// Is `key` a command with no default shortcut that a key press can't run: no item of the menu @@ -2968,13 +2978,19 @@ mod tests { use vectorcraft_testkit::fixtures::Fixture; let none = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); assert!(!menus::enabled(&none, "edit.findReplace")); - assert_eq!(dimmed(&none, "edit.findReplace"), Err("command `edit.findReplace` is not available right now: no document open".into())); + let why = "command `edit.findReplace` is not available right now: no document open"; + assert_eq!(dimmed(&none, "edit.findReplace", "edit.findReplace").as_deref(), Some(why)); + // A name to show takes the id's place. + let shown = "command `Edit › Find and Replace…` is not available right now: no document open"; + assert_eq!(dimmed(&none, "edit.findReplace", "Edit › Find and Replace…").as_deref(), Some(shown)); let empty = VectorcraftApp::new(Fixture::Empty.session(), crate::Services::default()); for id in ["appearance.addFill", "ui.cropImage"] { assert!(!menus::enabled(&empty, id), "{id}"); assert!(vectorcraft_engine::find_command(id).is_none_or(|c| (c.enabled)(&empty.session).is_ok()), "{id}: the engine gives no reason"); - assert_eq!(dimmed(&empty, id), Err(format!("command `{id}` is not available right now"))); + assert_eq!(dimmed(&empty, id, id), Some(format!("command `{id}` is not available right now"))); } + assert!(menus::enabled(&empty, "edit.findReplace")); + assert_eq!(dimmed(&empty, "edit.findReplace", "edit.findReplace"), None, "not dimmed"); } /// Every command the editor lists, run as a key press runs it on a document with one or with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4a1d5c828e..505137a39b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1312,7 +1312,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do, the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades and the matches through a typo, a description or a word with the same meaning, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows, which also holds a pick whose command could not run. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`). A Command Palette query word also finds a command by what the command's description says: "transparent background" lists Remove Background… among the first 3 results, and "png" lists it after every result with "png" in its name or menu path. The description is the command's params text (an engine or plug-in command's, a UI command's, or an effect's) without each `{…}` group that is not inside a `{`, `[` or `(` group, without each such `[…]` or `(…)` group just after a `→`, and without the `→` before a removed group, cut to its first 300 characters at the end of a word. The words of a schema ("corners" for Remove Background…) and of a result written as a group do not find the command; a result written as words after a `→` stays in the description. Words of 2 characters or fewer, words with no letter, and "the", "and", "ids", "true", "false" and "null" are left out. A query word that is a word of a description, shares an English base word with one, starts one or has the same meaning as one finds the result, and such a result ranks below every result that the query matches in its name, menu path or id, as text inside a word or through a typo. Descriptions are English only, and a typo does not match them. Tools, panels and filter plug-ins have no description (`palette::search` tests `a_description_leaves_out_the_schema_and_the_result`, `a_word_of_the_description_finds_the_result`, `a_description_match_ranks_below_a_typo`, `words_of_a_description_find_the_command`). - A Command Palette result that cannot run now stays in its place in the list and is drawn dimmed: an engine command whose engine check fails (Ungroup with nothing selected, Paste with an empty clipboard and nothing to paste from the system clipboard), a UI command the menus dim, a filter plug-in or an effect whose menu item is dimmed, and a panel in Presentation Mode. Tools are never dimmed. The engine's reason, or that the command is not available right now, shows on hover, in the row's screen-reader description and in the footer while the row is highlighted, beside the count or, under the recent picks of an empty search, on a line of its own. Only the drawn rows are checked, each once for as long as the state it was checked in lasts: a command run, an edit, a change of selection, document, history, clipboard, language, screen mode or open dialog, a save that marks the document saved, a background save, export, file read, plug-in run or trace that starts, ends or shows its progress window, or a click checks them again on the next frame, while typing in the search field does not. The check never changes the ranking. A pick of a dimmed result does what it did before (`palette` tests `a_result_that_cannot_run_now_is_dimmed_and_says_why`, `paste_is_dimmed_only_while_nothing_can_be_pasted`, `tools_are_never_dimmed_and_panels_are_in_presentation_mode`, `a_result_without_an_engine_reason_says_it_is_not_available`, `a_recent_pick_that_cannot_run_now_says_why`, `availability_is_read_once_per_state`). + A Command Palette result that cannot run now stays in its place in the list and is drawn dimmed: an engine command whose engine check fails (Ungroup with nothing selected, Paste with an empty clipboard and nothing to paste from the system clipboard), a UI command the menus dim, a filter plug-in or an effect whose menu item is dimmed, and a panel in Presentation Mode. Tools are never dimmed. The reason shows on hover, in the row's screen-reader description, on a second line of the search field's screen-reader description and in the footer while the row is highlighted, beside the count or, under the recent picks of an empty search, on a line of its own. The reason is the status line a pick of the dimmed menu item gives, with the result's name in place of the command's id: "command `Object › Ungroup` is not available right now: nothing selected", or without the engine's reason when it gives none. The Recent Commands list beside the search field draws such a pick dimmed too, with the same reason on hover and for screen readers. Only the drawn rows are checked, each once for as long as the state it was checked in lasts: a command run, an edit, a change of selection, document, history, clipboard, language, screen mode or open dialog, a save that marks the document saved, or a background save, export, file read, plug-in run or trace that starts, ends or shows its progress window checks them again on the next frame, and a frame with a click checks them again on that frame only. Typing in the search field does not check them again, and the palette checks them again each time it opens. The check never changes the ranking. A pick of a dimmed result does what it did before (`palette` tests `a_result_that_cannot_run_now_is_dimmed_and_says_why`, `hovering_a_result_that_cannot_run_now_says_why`, `paste_is_dimmed_only_while_nothing_can_be_pasted`, `tools_are_never_dimmed_and_panels_are_in_presentation_mode`, `a_result_without_an_engine_reason_says_it_is_not_available`, `no_reason_shows_a_command_id`, `a_recent_pick_that_cannot_run_now_says_why`, `a_recent_command_that_cannot_run_now_is_dimmed_in_the_list`, `availability_is_asked_again_when_what_it_depends_on_changes`, `availability_is_read_once_per_state`, `the_palette_asks_again_when_it_opens_again`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. From 4a5931641addd00d3632bb2b5c37208b41989a39 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 05:02:42 -0800 Subject: [PATCH 25/69] 3D: test that Inflate graphics pass over an ear whose new edge runs through a dent Adds a test for a ring whose first ear's new edge runs through a dent's corner: the ear is passed over, so no triangle edge runs through a corner of the ring. --- crates/three-d/src/mesh/tests.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index 9980e900d1..d17101f66e 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -205,6 +205,24 @@ fn flat_triangles_keep_corners_on_the_edge_an_ear_would_cut() { } } +#[test] +fn flat_triangles_pass_over_an_ear_whose_new_edge_runs_through_a_dent() { + // The first ear's new edge, from (0, 4) to (4, 0), runs through the dent's corner at (2, 2). + let p = |x: f64, y: f64| Point::new(x, y); + let outline = vec![p(0.0, 0.0), p(4.0, 0.0), p(4.0, 4.0), p(2.0, 2.0), p(0.0, 4.0)]; + let mut work = 0; + let triangles = flat_triangles(std::slice::from_ref(&outline), &mut work, usize::MAX).unwrap(); + let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0; + assert!((triangles.iter().map(area).sum::() - 12.0).abs() < 1e-9); + for t in &triangles { + for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] { + for q in &outline { + assert!(!super::touches((q.x, q.y), (a.x, a.y), (b.x, b.y)), "{q:?} lies inside the edge {a:?} to {b:?}"); + } + } + } +} + #[test] fn flat_triangles_stop_at_their_budget() { let p = |x: f64, y: f64| Point::new(x, y); From f2feee89233c7601d7de53cde0f4a6156df7d834 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 08:57:30 -0800 Subject: [PATCH 26/69] Clipboard: pass the document to used() in show_merged_colors --- crates/engine/src/cmd/clipboard/resources.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 562b6f910a..69e1126388 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1150,7 +1150,7 @@ impl Clipboard { if same_doc { return; } - let used = self.used(); + let used = self.used(d); let colors: BTreeMap = self .conflicts(d, &used) .into_iter() From 895f17fdaca0a156dcee0b5239b65de2cff55e49 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:35:25 -0800 Subject: [PATCH 27/69] Brushes: Add original Ornamental library --- crates/engine/src/cmd/brushlib.rs | 47 +++++++++++++++++++ crates/engine/src/tests/brushlib.rs | 39 +++++++++++++-- crates/ui-egui/src/i18n/bg.tsv | 5 ++ crates/ui-egui/src/i18n/bs.tsv | 5 ++ crates/ui-egui/src/i18n/ca.tsv | 5 ++ crates/ui-egui/src/i18n/cs.tsv | 5 ++ crates/ui-egui/src/i18n/da.tsv | 5 ++ crates/ui-egui/src/i18n/de.tsv | 5 ++ crates/ui-egui/src/i18n/el.tsv | 5 ++ crates/ui-egui/src/i18n/es.tsv | 5 ++ crates/ui-egui/src/i18n/fi.tsv | 5 ++ crates/ui-egui/src/i18n/fr.tsv | 5 ++ crates/ui-egui/src/i18n/gu.tsv | 5 ++ crates/ui-egui/src/i18n/hi.tsv | 5 ++ crates/ui-egui/src/i18n/hu.tsv | 5 ++ crates/ui-egui/src/i18n/id.tsv | 5 ++ crates/ui-egui/src/i18n/it.tsv | 5 ++ crates/ui-egui/src/i18n/ja.tsv | 5 ++ crates/ui-egui/src/i18n/ka.tsv | 5 ++ crates/ui-egui/src/i18n/ko.tsv | 5 ++ crates/ui-egui/src/i18n/nl.tsv | 5 ++ crates/ui-egui/src/i18n/pl.tsv | 5 ++ crates/ui-egui/src/i18n/pt-br.tsv | 5 ++ crates/ui-egui/src/i18n/ru.tsv | 5 ++ crates/ui-egui/src/i18n/sv.tsv | 5 ++ crates/ui-egui/src/i18n/tests.rs | 3 +- crates/ui-egui/src/i18n/tr.tsv | 5 ++ crates/ui-egui/src/i18n/uk.tsv | 5 ++ crates/ui-egui/src/i18n/vi.tsv | 5 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 5 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 5 ++ .../src/panels/tests_brush_libraries.rs | 12 +++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 34 files changed, 240 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 34becd7c02..dea614eb6b 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -174,6 +174,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs }, BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, + BuiltinBrushLibrary { id: "ornamental", name: "Ornamental", make: ornamental }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails }, BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams }, @@ -475,6 +476,52 @@ fn pattern_borders() -> BrushLibrary { built("Pattern Borders", Document::new(100.0, 100.0), brushes) } +/// Ornamental: one-pass flourishes and arrow accents that stretch with the path rather than +/// repeating a pattern tile. Every shape is original filled vector art. +fn ornamental() -> BrushLibrary { + let scrollwork = group(vec![ + black(band(100.0, 1.2, 64, |x| 2.6 * (x / 100.0 * std::f64::consts::TAU).sin())), + ring(Point::new(7.0, 0.0), 4.0, 2.0), + ring(Point::new(93.0, 0.0), 4.0, 2.0), + black(polygon(&[(28.0, 1.0), (34.0, -5.0), (40.0, -3.0), (33.0, 2.0)])), + black(polygon(&[(60.0, 3.0), (66.0, 5.0), (72.0, -1.0), (67.0, -2.0)])), + ]); + let arrow = group(vec![ + black(shapes::rectangle(Rect::new(4.0, -0.7, 84.0, 0.7))), + black(polygon(&[(80.0, -6.5), (100.0, 0.0), (80.0, 6.5), (85.0, 0.0)])), + ring(Point::new(7.0, 0.0), 4.0, 1.7), + black(polygon(&[(25.0, -0.4), (31.0, -4.4), (37.0, -2.0), (31.0, 0.8)])), + black(polygon(&[(43.0, 0.4), (49.0, 4.4), (55.0, 2.0), (49.0, -0.8)])), + ]); + let mut petals = vec![black(band(100.0, 1.0, 48, |x| 1.8 * (x / 100.0 * std::f64::consts::PI).sin()))]; + for x in [19.0, 43.0, 67.0, 87.0] { + let y = 1.8 * (x / 100.0 * std::f64::consts::PI).sin(); + petals.push(black(shapes::ellipse(Rect::new(x - 4.5, y - 7.5, x + 4.5, y - 0.3)))); + petals.push(black(shapes::ellipse(Rect::new(x - 3.5, y + 0.3, x + 3.5, y + 5.5)))); + } + let petal_sweep = group(petals); + let twin_curl = group(vec![ + black(band(100.0, 0.9, 64, |x| -3.8 + 1.6 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())), + black(band(100.0, 0.9, 64, |x| 3.8 - 1.6 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())), + ring(Point::new(8.0, -3.8), 3.0, 1.5), + ring(Point::new(92.0, 3.8), 3.0, 1.5), + ]); + let ornament = |name: &str, art: Node| Brush { + name: name.into(), + kind: BrushKind::Art(ArtBrush { art, width: 300.0, colorization: Colorization::Tints, ..Default::default() }), + }; + built( + "Ornamental", + Document::new(100.0, 100.0), + vec![ + ornament("Scrollwork", scrollwork), + ornament("Filigree Arrow", arrow), + ornament("Petal Sweep", petal_sweep), + ornament("Twin Curl", twin_curl), + ], + ) +} + fn scatter(name: &str, art: Node, s: Scatter) -> Brush { Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) } } diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 4f0b739951..a29aaf2f6b 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -112,6 +112,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "calligraphic-nibs", "bristle-brushes", "pattern-borders", + "ornamental", "scatter-shapes", "game-trails", "energy-beams", @@ -131,19 +132,19 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"] ); - assert_eq!(libs[6]["count"].as_u64(), Some(4)); + assert_eq!(libs[7]["count"].as_u64(), Some(4)); let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"})); assert_eq!( beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"] ); - assert_eq!(libs[7]["count"].as_u64(), Some(4)); + assert_eq!(libs[8]["count"].as_u64(), Some(4)); let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"})); assert_eq!( dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::>(), [("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")] ); - assert_eq!((libs[8]["name"].as_str(), libs[8]["count"].as_u64()), (Some("Dry Media"), Some(4))); + assert_eq!((libs[9]["name"].as_str(), libs[9]["count"].as_u64()), (Some("Dry Media"), Some(4))); run(&mut s, "file.new", json!({"width": 200, "height": 200})); let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap(); let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]})); @@ -156,6 +157,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("calligraphic-nibs", "calligraphic"), ("bristle-brushes", "bristle"), ("pattern-borders", "pattern"), + ("ornamental", "art"), ("scatter-shapes", "scatter"), ("game-trails", "art"), ("energy-beams", "art"), @@ -299,6 +301,37 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() { assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } +#[test] +fn ornamental_brushes_draw_flourishes_and_survive_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Ornamental").unwrap(); + let names = ["Scrollwork", "Filigree Arrow", "Petal Sweep", "Twin Curl"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap(); + let mut curve = line_to(20.0); + curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0)); + for b in &lib.brushes { + let BrushKind::Art(art) = &b.kind else { panic!("{} is not an art brush", b.name) }; + assert_eq!(art.colorization, vectorcraft_brush::Colorization::Tints); + assert_eq!(art.width, 300.0); + for line in [line_to(2.0), line_to(180.0), curve.clone()] { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke()); + let points = anchors(&pieces.iter().collect::>()); + assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name); + } + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "ornamental", "name": b.name, "apply": true, "ids": [path]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([path])); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str())); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + /// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two /// translucent washes, with names of their own and a few paths of art each. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..445a667bdd 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7237,3 +7237,8 @@ breakText Glyphs Глифи @msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Ornamental Орнаментални + Scrollwork Завитък + Filigree Arrow Филигранна стрела + Petal Sweep Венчелистен замах + Twin Curl Двоен завитък diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..28fac7e7ef 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7291,3 +7291,8 @@ shape Open Otvoren @msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" + Ornamental Ornamentalno + Scrollwork Ukrasni zavoj + Filigree Arrow Filigranska strelica + Petal Sweep Potez latica + Twin Curl Dvostruki zavoj diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..b1238d92d0 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -8126,3 +8126,8 @@ breakText Glyphs Glifs @msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, frontisses: {hinges}, errors: {errors}, avisos: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Ornamental Ornamental + Scrollwork Voluta + Filigree Arrow Fletxa de filigrana + Petal Sweep Traç de pètals + Twin Curl Voluta doble diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..21bf4767ab 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9917,3 +9917,8 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Ornamental Ornamentální + Scrollwork Rozvilina + Filigree Arrow Filigránový šíp + Petal Sweep Tah okvětních lístků + Twin Curl Dvojitá rozvilina diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..d10d6f40eb 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -10025,3 +10025,8 @@ breakText Glyphs Glyffer @msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, hængsler: {hinges}, fejl: {errors}, advarsler: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" + Ornamental Ornamentik + Scrollwork Slyngværk + Filigree Arrow Filigranpil + Petal Sweep Kronbladssvirp + Twin Curl Dobbelt slyng diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..aa68d5f1b9 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9516,3 +9516,8 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Ornamental Ornamental + Scrollwork Schnörkel + Filigree Arrow Filigranpfeil + Petal Sweep Blütenblattschwung + Twin Curl Doppelschnörkel diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..aa7449fac5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -8100,3 +8100,8 @@ breakText Glyphs Γλύφοι @msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, μεντεσέδες: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" + Ornamental Διακοσμητικά μοτίβα + Scrollwork Σπείρα + Filigree Arrow Φιλιγκράν βέλος + Petal Sweep Καμπύλη πετάλων + Twin Curl Διπλή σπείρα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..4169bd32f7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -8087,3 +8087,8 @@ breakText Glyphs Glifos @msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, bisagras: {hinges}, errores: {errors}, advertencias: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Ornamental Ornamental + Scrollwork Voluta + Filigree Arrow Flecha de filigrana + Petal Sweep Trazo de pétalos + Twin Curl Voluta doble diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..800965e310 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8183,3 +8183,8 @@ breakText Glyphs Merkit @msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, saranat: {hinges}, virheet: {errors}, varoitukset: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" + Ornamental Koristekuviot + Scrollwork Kiemura + Filigree Arrow Filigraanin nuoli + Petal Sweep Terälehtipyyhkäisy + Twin Curl Kaksoiskiemura diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..6fbb483a76 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9902,3 +9902,8 @@ breakText Glyphs Glyphes @msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} charnière(s), {errors} erreur(s), {warnings} avertissement(s) @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution + Ornamental Ornemental + Scrollwork Volute + Filigree Arrow Flèche filigrane + Petal Sweep Courbe de pétales + Twin Curl Double volute diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..7ea119a3ea 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4987,3 +4987,8 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" + Ornamental અલંકારિક + Scrollwork વળાંકવાળી સજાવટ + Filigree Arrow નાજુક કોતરણીવાળું તીર + Petal Sweep પાંખડીઓનો વળાંક + Twin Curl બેવડો વળાંક diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..371084c7f6 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9524,3 +9524,8 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Ornamental अलंकरण + Scrollwork अलंकारी घुमाव + Filigree Arrow जालीदार तीर + Petal Sweep पंखुड़ियों का घुमाव + Twin Curl दोहरा घुमाव diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..13af1123ab 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9905,3 +9905,8 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Ornamental Díszítőmotívumok + Scrollwork Kacskaringó + Filigree Arrow Filigrán nyíl + Petal Sweep Sziromív + Twin Curl Kettős kacskaringó diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..eb146493e5 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7252,3 +7252,8 @@ breakText Glyphs Glif @msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" + Ornamental Ornamental + Scrollwork Sulur Hias + Filigree Arrow Panah Filigran + Petal Sweep Sapuan Kelopak + Twin Curl Sulur Ganda diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..85c89f0a5f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9550,3 +9550,8 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Ornamental Ornamentale + Scrollwork Voluta + Filigree Arrow Freccia filigranata + Petal Sweep Tratto a petali + Twin Curl Doppia voluta diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..91690383a5 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9617,3 +9617,8 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Ornamental 装飾模様 + Scrollwork スクロール装飾 + Filigree Arrow フィリグリーの矢 + Petal Sweep 花びらの流線 + Twin Curl 二重カール diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..a1aeb1b000 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10285,3 +10285,8 @@ font-script Japanese იაპონური @msg A fold line is on a non-printing layer. მოკეცვის ხაზი არაბეჭდვად შრეზეა. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ანჯამები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" + Ornamental ორნამენტული + Scrollwork ხვეული + Filigree Arrow ფილიგრანული ისარი + Petal Sweep ფურცლების რკალი + Twin Curl ორმაგი ხვეული diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..4a73e2b033 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9514,3 +9514,8 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Ornamental 장식 문양 + Scrollwork 소용돌이 장식 + Filigree Arrow 세공 화살표 + Petal Sweep 꽃잎 곡선 + Twin Curl 이중 소용돌이 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..cdcfea3bd8 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9953,3 +9953,8 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Ornamental Ornamentaal + Scrollwork Krulwerk + Filigree Arrow Filigraanpijl + Petal Sweep Bloemblaadjeszwaai + Twin Curl Dubbele krul diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..e398daaa06 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9770,3 +9770,8 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Ornamental Ornamentalne + Scrollwork Zawijas + Filigree Arrow Filigranowa strzałka + Petal Sweep Smuga płatków + Twin Curl Podwójny zawijas diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..77590f21b1 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9988,3 +9988,8 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Ornamental Ornamental + Scrollwork Voluta + Filigree Arrow Seta filigranada + Petal Sweep Traço de pétalas + Twin Curl Voluta dupla diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..e4a3002633 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -10011,3 +10011,8 @@ shape Open Открытый @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, шарниры: {hinges}, ошибки: {errors}, предупреждения: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Ornamental Орнаментальные + Scrollwork Завиток + Filigree Arrow Филигранная стрела + Petal Sweep Лепестковый росчерк + Twin Curl Двойной завиток diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..36b7ee35e5 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9601,3 +9601,8 @@ digits Hindi Hindi @msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, gångjärn: {hinges}, fel: {errors}, varningar: {warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen + Ornamental Ornament + Scrollwork Snirkel + Filigree Arrow Filigranpil + Petal Sweep Kronbladssvep + Twin Curl Dubbel snirkel diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 97fccd9167..bf6fa61a89 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -501,8 +501,9 @@ fn built_in_library_brush_names_are_in_complete_catalogs() { .flat_map(|(_, lib)| lib.brushes.iter().map(|b| b.name.clone()).collect::>()) .collect(); names.sort(); + let duplicates: Vec<&str> = names.windows(2).filter(|pair| pair[0] == pair[1]).map(|pair| pair[0].as_str()).collect(); + assert_eq!(duplicates, ["Zigzag"], "only the established Pattern Borders / Game Trails name is shared"); names.dedup(); - assert_eq!(names.len(), 46, "{names:?}"); let mut bad = vec![]; for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { let missing: Vec<&String> = names.iter().filter(|n| lang.catalog().plain(n).is_none()).collect(); diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..4f42278cb1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9875,3 +9875,8 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Ornamental Süslemeli + Scrollwork Kıvrım süsü + Filigree Arrow Telkari ok + Petal Sweep Yaprakçık kıvrımı + Twin Curl Çift kıvrım diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..0dfa6803ae 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9526,3 +9526,8 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Ornamental Орнаментальні + Scrollwork Завиток + Filigree Arrow Філігранна стріла + Petal Sweep Пелюстковий розчерк + Twin Curl Подвійний завиток diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..8286f1454e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7759,3 +7759,8 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" + Ornamental Hoa văn + Scrollwork Nét cuộn + Filigree Arrow Mũi tên hoa văn + Petal Sweep Nét cánh hoa + Twin Curl Nét cuộn đôi diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..902c7d1645 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9758,3 +9758,8 @@ breakText Glyphs 字形 @msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},铰链:{hinges},错误:{errors},警告:{warnings} @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 + Ornamental 装饰纹样 + Scrollwork 卷饰 + Filigree Arrow 花丝箭头 + Petal Sweep 花瓣曲线 + Twin Curl 双重卷饰 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..2a1885adb4 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9568,3 +9568,8 @@ breakText Glyphs 字符 @msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},鉸鏈:{hinges},錯誤:{errors},警告:{warnings} @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 + Ornamental 裝飾紋樣 + Scrollwork 卷飾 + Filigree Arrow 花絲箭頭 + Petal Sweep 花瓣曲線 + Twin Curl 雙重卷飾 diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index 87fe34953f..8007781eaf 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -197,6 +197,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("calligraphic-nibs"), json!("bristle-brushes"), json!("pattern-borders"), + json!("ornamental"), json!("scatter-shapes"), json!("game-trails"), json!("energy-beams"), @@ -232,6 +233,17 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { click(&mut app, &ctx, "Circuit Trace", Modifiers::NONE, 2.0); assert!(has(&app, "Circuit Trace") && !has(&app, "Bus Lines")); assert_eq!(undo_len(&app), undo + 1); + let r = app.run("window.brushLibrary", json!({"library": "Ornamental"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("ornamental"), Some(4))); + let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap(); + let undo = undo_len(&app); + click(&mut app, &ctx, "Scrollwork", Modifiers::NONE, 3.0); + assert!(has(&app, "Scrollwork") && !has(&app, "Twin Curl")); + assert_eq!(undo_len(&app), undo + 1); + assert_eq!( + app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), + Some("Scrollwork") + ); // Without brushes there is nothing to save. let all: Vec = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect(); app.run("brush.delete", json!({ "names": all })).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..53dda537ac 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5035,8 +5035,8 @@ error. ## Brush libraries -Brush libraries are read-only sets of brushes: ten generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle -Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and +Brush libraries are read-only sets of brushes: eleven generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle +Brushes with one bristle brush for each tip shape, Pattern Borders, Ornamental with Scrollwork, Filigree Arrow, Petal Sweep and Twin Curl, Scatter Shapes, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and Charcoal Dust art brushes, id `dry-media`, and Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..6ff05bd909 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1102,6 +1102,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. + - **Ornamental library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Ornamental offers Scrollwork, Filigree Arrow, Petal Sweep and Twin Curl. These four original art brushes stretch curled lines, arrow-like accents and petal details along a path instead of repeating tiles; they take the stroke color as tints. The public source describes the Ornamental category, while the preset designs and names are VectorCraft's own. Evidence: `ornamental_brushes_draw_flourishes_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers finite output on short, long and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`). - A canvas context menu: right-click selects the object under the pointer and lists what applies to the selection (Undo/Redo, clipboard, group, isolation, join, Remove Anchor Points when anchors are selected, masks, compound paths, guides, Transform, Arrange, Select, Export Selection, and on type Bullets and Numbering and Spelling › Auto Spell Check, checked while it is on), or the view commands on empty canvas. From c2c4e650176f934588d4c0a752833cafdead8727 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 12:07:57 -0800 Subject: [PATCH 28/69] ci: retry timed-out Ornamental gate From 1901799b7683c7277f8e801df8ccf106b37c0dc5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 15:56:21 -0800 Subject: [PATCH 29/69] Shapes: Circle Tool Options set what the Circle tool shows and where its anchors go Double-clicking the Circle tool, or `tool.options {tool: "circle"}`, opens Circle Tool Options. Show Center, Show Radii and Show Diameter switch the center cross, the radius lines and the diameter label the tool shows while a circle is drawn, and Color sets the color of the cross and the lines (red, blue, magenta, green, black or gray). With Anchors at Standard Positions off, the circle's anchors are at the points it was drawn through, plus evenly spaced anchors between them so that no curve turns more than a quarter of the circle. With Third Point by Dragging off, a second click places the second point and a third click draws the circle through the three; a double-click on the second point draws the circle on the two. Every option is on by default, and the options are kept with the preferences. `shape.circleThroughPoints` takes `anchors: "standard"|"points"`. `tool.setOption` rejects a value the Circle tool's options do not take. --- ROADMAP.md | 1 + crates/engine/src/cmd/create.rs | 24 +- crates/engine/src/tests/circle_through.rs | 29 +++ crates/engine/src/tooling.rs | 3 + crates/geom/src/shapes.rs | 80 +++++++ crates/tools/src/circle.rs | 219 +++++++++++++++++-- crates/tools/src/circle/tests.rs | 175 +++++++++++++++ crates/tools/src/settings.rs | 2 + crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/circle_options.rs | 169 ++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/toolbar.rs | 5 +- docs/mcp.md | 28 +++ 41 files changed, 838 insertions(+), 22 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/circle_options.rs diff --git a/ROADMAP.md b/ROADMAP.md index e9d2cc56b5..7f2a055bc4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -139,6 +139,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index e9fcad8883..61b22d12b9 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -62,7 +62,7 @@ pub fn specs() -> Vec { "Circle Through Points", [], None, - "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", has_doc, circle_through_points ), @@ -414,20 +414,32 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { } /// A live ellipse whose edge passes through two or three points: `points`, or the two or three -/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One -/// undo step, named as an Ellipse tool drag is. +/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. With +/// `anchors: "points"` the circle is a plain path with an anchor at each point +/// ([`shapes::circle_with_anchors_at`]); otherwise it is a live ellipse. One undo step, named as an +/// Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.circleThroughPoints"; let points = match p.get("points").filter(|v| !v.is_null()) { Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, }; + let key = "anchors"; + let at_points = match p.get(key).filter(|v| !v.is_null()).map(Value::as_str) { + None | Some(Some("standard")) => false, + Some(Some("points")) => true, + Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))), + }; let (center, radius) = shapes::circle_through_points(&points) .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; - let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; // Not pixel-aligned: the circle stays through the points. - let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; + let mut out = if at_points { + add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))? + } else { + let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; + add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))? + }; out["cx"] = json!(center.x); out["cy"] = json!(center.y); out["radius"] = json!(radius); diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index e91c48e76a..a6f69d1bea 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -204,6 +204,35 @@ fn the_circle_is_not_moved_onto_the_pixel_grid() { assert!(!node(&s, id).extras().pixel_aligned); } +/// `anchors: "points"` puts an anchor exactly at each point, with one more on each half of a +/// diameter's circle; the circle is a plain path, not pixel-aligned, and one undo step. Any other +/// `anchors` value is an error and draws nothing. +#[test] +fn anchors_at_the_points_puts_an_anchor_at_each_point() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let undo = undo_len(&s); + let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)]; + let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); + let id = id_of(&s.execute(C, &json!({ "points": pairs, "anchors": "points" })).unwrap()); + let n = node(&s, id); + let anchors: Vec = n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert!(points.iter().all(|p| anchors.contains(p)), "{anchors:?}"); + assert!(matches!(n.kind, NodeKind::Path { live: None, .. }), "{:?}", n.kind); + assert!(!n.extras().pixel_aligned); + assert_eq!(undo_len(&s), undo + 1); + let id = id_of(&s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": "points" })).unwrap()); + let anchors: Vec = node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(anchors.len(), 4, "{anchors:?}"); + assert_eq!((anchors[0], anchors[2]), (Point::new(0.0, 0.0), Point::new(100.0, 0.0))); + let (count, undo) = (object_count(&s), undo_len(&s)); + for bad in [json!("corners"), json!(true), json!(4)] { + let e = s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": bad })).unwrap_err().to_string(); + assert!(e.contains("`anchors` must be one of standard, points"), "{e}"); + } + assert_eq!((object_count(&s), undo_len(&s)), (count, undo)); +} + fn view() -> ViewInfo { ViewInfo { smart_guides: false, ..ViewInfo::default() } } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 8b8cf4628b..d17caea3dd 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1369,6 +1369,9 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; + if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::circle::ID { + vectorcraft_tools::circle::check_options(&values)?; + } if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID { use vectorcraft_tools::cropimage as crop; // The most the selected image can be cropped to, when one is selected. diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 838015115b..d194fcac4e 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -367,6 +367,53 @@ pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> { circle.filter(|(c, r)| c.is_finite() && r.is_finite() && *r > 0.0) } +/// The circle at `center` with `radius` as a closed path whose anchors are `points` (points on the +/// circle, as [`circle_through_points`] gives it) plus as many more as split each arc between two +/// of them into equal parts of at most a quarter turn. The path starts at the first point and runs +/// as [`ellipse`] does (left, top, right on the page); each curve's handles are 4/3·tan(θ/4) of +/// the radius along the tangents at its ends (θ, its turn). A point given twice is one anchor; +/// with no points it starts at the left, as [`ellipse`] does. +pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> PathData { + let quarter = PI / 2.0; + let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); + let start = points.first().map_or(PI, |p| angle(*p)); + // (turn from the first point, the point itself). + let mut placed: Vec<(f64, Point)> = points.iter().map(|p| ((angle(*p) - start).rem_euclid(TAU), *p)).collect(); + placed.sort_by(|a, b| a.0.total_cmp(&b.0)); + placed.dedup_by(|a, b| a.1 == b.1); + if placed.is_empty() { + placed.push((0.0, Point::new(center.x - radius, center.y))); + } + let on_circle = |t: f64| Point::new(center.x + radius * (start + t).cos(), center.y + radius * (start + t).sin()); + // Every anchor: (turn, position), the given points where they are and the others on the circle. + let mut turns: Vec<(f64, Point)> = Vec::new(); + for (i, &(t, p)) in placed.iter().enumerate() { + turns.push((t, p)); + let next = placed.get(i + 1).map_or(TAU, |n| n.0); + let gap = next - t; + // At most 4 parts for the whole turn: a gap is never more than a full turn. + let parts = (gap / quarter - 1e-9).ceil().clamp(1.0, 4.0); + for k in 1..parts as u32 { + let tk = t + gap * f64::from(k) / parts; + turns.push((tk, on_circle(tk))); + } + } + let n = turns.len(); + let anchors = (0..n) + .filter_map(|i| { + let &(t, p) = turns.get(i)?; + let prev = if i == 0 { turns.last()?.0 - TAU } else { turns.get(i - 1)?.0 }; + let next = turns.get(i + 1).map_or(TAU, |n| n.0); + // The unit tangent along the run (y down: increasing angle). + let a = start + t; + let tangent = Vec2::new(-a.sin(), a.cos()); + let handle = |turn: f64| radius * 4.0 / 3.0 * (turn / 4.0).tan(); + Some(Anchor { p, h_in: p - tangent * handle(t - prev), h_out: p + tangent * handle(next - t), kind: AnchorKind::Smooth }) + }) + .collect(); + PathData::single(SubPath::new(anchors, true)) +} + /// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre. pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData { let n = sides.max(3); @@ -781,6 +828,39 @@ mod tests { } } + /// The anchors are the given points exactly, plus enough more that no curve turns more than a + /// quarter; every anchor and every curve's middle lies on the circle, and the path starts at + /// the first point. + #[test] + fn a_circle_with_its_anchors_at_given_points() { + use kurbo::ParamCurve; + let (a, b, c) = (Point::new(8.0, 0.0), Point::new(0.0, 6.0), Point::ORIGIN); + let center = Point::new(4.0, 3.0); + for (points, count) in [(&[a, b][..], 4), (&[a, b, c][..], 5), (&[b, a, c, b][..], 5), (&[][..], 4)] { + let path = circle_with_anchors_at(center, 5.0, points); + let sub = &path.subpaths[0]; + assert!(sub.closed, "{points:?}"); + assert_eq!(sub.anchors.len(), count, "{points:?}: {sub:?}"); + for p in points { + assert!(sub.anchors.iter().any(|q| q.p == *p), "{p:?} is an anchor: {sub:?}"); + } + if let Some(first) = points.first() { + assert_eq!(sub.anchors[0].p, *first); + } + for q in &sub.anchors { + assert!((q.p.distance(center) - 5.0).abs() < 1e-9, "{q:?}"); + } + for seg in path.to_bezpath().segments() { + let turn = { + let (p0, p1) = (seg.start() - center, seg.end() - center); + p0.cross(p1).atan2(p0.dot(p1)) + }; + assert!(turn > 0.0 && turn <= PI / 2.0 + 1e-9, "{turn} for {seg:?}"); + assert!((seg.eval(0.5).distance(center) - 5.0).abs() < 5.0 * 1e-3, "{seg:?}"); + } + } + } + /// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta /// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular /// bisector; a point 10⁻¹² off it does not. diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 76e5a2df36..e8d5a4f4e2 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -15,8 +15,17 @@ //! circle passes through the points (two are the same, three lie on one line) or the circle would //! reach past the canvas, the tool shows none and the release draws nothing; for three different //! points on one line, or a circle past the canvas, the pointer shows "Circle too large". +//! +//! The tool's options (Circle Tool Options, `tool.setOption`; kept with the preferences): +//! `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the +//! diameter label; `color` is the color of the cross and the lines (one of [`COLORS`]); +//! `standardAnchors` off puts the circle's anchors at the points it was drawn through instead of +//! at 0°, 90°, 180° and 270° (`anchors: "points"`); `dragThird` off places the second point with +//! a click and draws the circle through three points with a third click, and a click on the second +//! point again (as a double-click there does) draws the circle on the two points. Every option is +//! on by default, and `color` is blue. -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; use vectorcraft_doc::MAX_COORD; use vectorcraft_geom::{Point, Rect, Vec2, shapes}; @@ -34,6 +43,71 @@ const REACH_PX: f64 = 3.0; /// The longest outline (screen points) the preview draws dashed, about 7,000 dashes. const DASHED_PX: f64 = 50_000.0; +/// The colors the center cross and the radius lines can be drawn in, by option value. Blue is the +/// feedback color the other drawing tools use. +pub const COLORS: &[(&str, [u8; 3])] = &[ + ("red", [0xe5, 0x2d, 0x27]), + ("blue", crate::draw2::FEEDBACK), + ("magenta", [0xd6, 0x2c, 0xd6]), + ("green", [0x1f, 0xb4, 0x4b]), + ("black", [0x00, 0x00, 0x00]), + ("gray", [0x80, 0x80, 0x80]), +]; + +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird"]; + +/// The tool's options (see the module comment). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Options { + center: bool, + radii: bool, + diameter: bool, + /// An entry of [`COLORS`]. + color: usize, + standard_anchors: bool, + drag_third: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true } + } +} + +impl Options { + fn switch(&mut self, key: &str) -> Option<&mut bool> { + Some(match key { + "center" => &mut self.center, + "radii" => &mut self.radii, + "diameter" => &mut self.diameter, + "standardAnchors" => &mut self.standard_anchors, + "dragThird" => &mut self.drag_third, + _ => return None, + }) + } +} + +/// Is every value in `values` one the tool takes? `tool.setOption` checks them all before setting +/// any; [`Tool::set_option`] skips a value it cannot read. +pub fn check_options(values: &Map) -> Result<(), String> { + for (key, v) in values { + if SWITCHES.contains(&key.as_str()) { + if !v.is_boolean() { + return Err(format!("`{key}` must be true or false")); + } + } else if key == "color" { + if !v.as_str().is_some_and(|s| COLORS.iter().any(|(name, _)| *name == s)) { + let names: Vec<&str> = COLORS.iter().map(|(name, _)| *name).collect(); + return Err(format!("`{key}` must be one of {}", names.join(", "))); + } + } else { + return Err(format!("unknown Circle tool option `{key}`")); + } + } + Ok(()) +} + /// The press in progress. #[derive(Clone, Copy, Debug, PartialEq)] enum Press { @@ -46,23 +120,36 @@ enum Press { /// places the third point and the circle passes through `snapped`. A press within /// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let /// go there it places nothing, and dragged out it draws the circle on the diameter it drags out. + /// With `dragThird` off, a drag moves the second point and the release places it. Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool }, + /// With `dragThird` off, the press after the second point was placed, at `at` (snapped). Let go + /// on the second point (`on_second`), it draws the circle on the two points; let go on the + /// first point it places nothing; otherwise it draws the circle through the three points. + Third { at: Point, from: Point, on_first: bool, on_second: bool, dragged: bool }, } #[derive(Default)] pub struct CircleTool { snap: DrawSnap, + options: Options, /// The first point, placed by a click (or by the press of a drag in progress). first: Option, + /// With `dragThird` off, the second point, placed by a click where it is shown (snapped, with + /// Alt's rounding of the diameter when Alt was held), and where the click let go: a press near + /// either is a press on the second point, so the second click of a double-click finds it even + /// where Alt's rounding moved it away from the pointer. + second: Option<(Point, Point)>, press: Option, /// Where the pointer is, snapped: the point the next press or release places. pointer: Option, } -/// The command the tool runs for `points`. -fn command(points: &[Point]) -> (String, Value) { +/// The command the tool runs for `points`; with `standard_anchors` off, the circle's anchors are +/// at the points. +fn command(points: &[Point], standard_anchors: bool) -> (String, Value) { let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); - ("shape.circleThroughPoints".into(), json!({ "points": pairs })) + let params = if standard_anchors { json!({ "points": pairs }) } else { json!({ "points": pairs, "anchors": "points" }) }; + ("shape.circleThroughPoints".into(), params) } /// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` @@ -91,35 +178,49 @@ fn too_large(points: &[Point]) -> bool { impl CircleTool { fn clear(&mut self) { self.first = None; + self.second = None; self.press = None; self.pointer = None; self.snap.clear(); } - /// How the second point keeps to the first: Shift's 45° steps and the construction guides. + /// How the second point keeps to the first: Shift's 45° steps and the construction guides. A + /// third point keeps to neither. fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { - self.first.map(|a| Leave::segment(cx, a, mods.shift)) + self.first.filter(|_| self.second.is_none()).map(|a| Leave::segment(cx, a, mods.shift)) } /// The points the circle passes through as the tool shows it now. fn points(&self) -> Vec { let mut out: Vec = self.first.into_iter().collect(); + if let Some((b, _)) = self.second { + out.push(b); + out.extend(self.pointer); + return out; + } match self.press { Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), // A press on the first point adds no point: a drag from it drags out a diameter. Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), Some(Press::Second { at, dragged: false, .. }) => out.push(at), + // With `dragThird` off, a drag moves the second point. + Some(Press::Second { at, .. }) if !self.options.drag_third => out.push(at), Some(Press::Second { snapped, dragged: true, .. }) => { out.push(snapped); out.extend(self.pointer); } + Some(Press::Third { .. }) => {} } out } /// The second point as the tool shows it: none for a press on the first point. fn second(&self) -> Option { + if let Some((b, _)) = self.second { + return Some(b); + } match self.press { + Some(Press::Second { on_first: false, at, .. }) if !self.options.drag_third => Some(at), Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at), Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped), _ => None, @@ -133,9 +234,25 @@ impl CircleTool { if circle_of(points).is_none() { return vec![]; } - let (c, v) = command(points); + let (c, v) = command(points, self.options.standard_anchors); vec![Action::Exec(c, v)] } + + /// With `dragThird` off, the release of a press after the second point was placed: on the + /// second point it draws the circle on the two points, on the first it places nothing, and + /// elsewhere it draws the circle through the three, or keeps the points where none passes + /// through them. + fn third_up(&mut self, at: Point, on_first: bool, on_second: bool, dragged: bool) -> Vec { + let (Some(a), Some((b, _))) = (self.first, self.second) else { return vec![] }; + if on_second && !dragged { + return self.draw(&[a, b]); + } + if (on_first && !dragged) || circle_of(&[a, b, at]).is_none() { + self.snap.clear(); + return vec![]; + } + self.draw(&[a, b, at]) + } } impl Tool for CircleTool { @@ -151,10 +268,20 @@ impl Tool for CircleTool { PointerKind::Move => { let leave = self.leave(cx, ev.mods); let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); - self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + // Alt's rounding of the diameter is for the second point only. + let rounds = self.first.filter(|_| self.second.is_none()); + self.pointer = Some(rounds.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); vec![] } PointerKind::Down => { + if let (Some(a), Some((b, clicked))) = (self.first, self.second) { + let at = self.snap.press(cx, ev.pos, &[], None); + let on = |q: Point| at == q || ev.pos.distance(q) <= cx.tol(REACH_PX); + let on_second = on(b) || ev.pos.distance(clicked) <= cx.tol(REACH_PX); + self.press = Some(Press::Third { at, from: ev.pos, on_first: on(a), on_second, dragged: false }); + self.pointer = Some(at); + return vec![]; + } match self.first { None => { let at = self.snap.press(cx, ev.pos, &[], None); @@ -174,7 +301,23 @@ impl Tool for CircleTool { vec![] } PointerKind::Drag => { + let drag_third = self.options.drag_third; + let first = self.first; match &mut self.press { + // With `dragThird` off, the second point follows the pointer as it does before + // the press. + Some(Press::Second { at, snapped, from, on_first: false, dragged }) if !drag_third => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift)); + *snapped = self.snap.drag(cx, ev.pos, leave.as_ref()); + *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods)); + self.pointer = Some(*at); + } + Some(Press::Third { at, from, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + *at = self.snap.drag(cx, ev.pos, None); + self.pointer = Some(*at); + } Some(Press::First { at, from, dragged }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = Leave::segment(cx, *at, ev.mods.shift); @@ -197,6 +340,16 @@ impl Tool for CircleTool { vec![] } PointerKind::Up => match (self.press.take(), self.first, self.pointer) { + (Some(Press::Third { at, on_first, on_second, dragged, .. }), ..) => self.third_up(at, on_first, on_second, dragged), + // With `dragThird` off, the release places the second point; let go on the first + // point, as a press there is, it places nothing. + (Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.options.drag_third => { + if !(at == a || snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX)) { + self.second = Some((at, ev.pos)); + } + self.snap.clear(); + vec![] + } (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]), // A click places the first point; the guides of the press go. (Some(Press::First { .. }), ..) => { @@ -269,13 +422,19 @@ impl Tool for CircleTool { // than DASHED_PX on screen is drawn solid instead. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); o.push(Overlay::Path { path, color, width: 1.0, dashed }); - for p in &points { - o.push(Overlay::Line { a: c, b: *p, color, dashed: false }); + let opts = self.options; + let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb); + if opts.radii { + for p in &points { + o.push(Overlay::Line { a: c, b: *p, color: lines, dashed: false }); + } } - let arm = cx.tol(CROSS_PX); - o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false }); - o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false }); - if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) { + if opts.center { + let arm = cx.tol(CROSS_PX); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: lines, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: lines, dashed: false }); + } + if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) { o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); } } else if let Some(p) = self.pointer.filter(|_| too_large(&points)) { @@ -290,6 +449,38 @@ impl Tool for CircleTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { Cursor::Crosshair } + + fn options(&self) -> Value { + let o = self.options; + let color = COLORS.get(o.color).map_or("blue", |(name, _)| *name); + json!({ + "center": o.center, + "radii": o.radii, + "diameter": o.diameter, + "color": color, + "standardAnchors": o.standard_anchors, + "dragThird": o.drag_third, + }) + } + + /// Sets one option; a value the option does not take leaves it as it was. Switching + /// `dragThird` drops the points placed so far. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "color" { + if let Some(i) = value.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)) { + self.options.color = i; + } + return; + } + let Some(on) = value.as_bool() else { return }; + let was = self.options.drag_third; + if let Some(switch) = self.options.switch(key) { + *switch = on; + } + if self.options.drag_third != was { + self.clear(); + } + } } #[cfg(test)] diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index a6caafbc1d..6b83f73838 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -94,6 +94,181 @@ fn a_click_and_a_drag_draw_the_circle_through_three_points() { assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); } +/// The lines the tool shows from the center `c`: (radius lines, arms of the center cross), each +/// with its color. +fn annotations(o: &[Overlay], c: Point) -> (Vec<[u8; 3]>, Vec<[u8; 3]>) { + let (mut radii, mut cross) = (vec![], vec![]); + for o in o { + if let Overlay::Line { a, b, color, .. } = o { + if *a == c { + radii.push(*color); + } else if a.midpoint(*b).distance(c) < 1e-9 { + cross.push(*color); + } + } + } + (radii, cross) +} + +/// `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the +/// diameter label, each on its own, and `color` is the color of the cross and the lines; the +/// outline stays in the feedback color. Each option lasts in [`Tool::options`]. +#[test] +fn the_options_show_or_hide_the_center_radii_and_diameter_in_their_color() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default())); + let c = Point::new(340.0, 330.0); + let blue = crate::draw2::FEEDBACK; + assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![blue; 2])); + let diameter = |t: &CircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { .. })); + assert!(diameter(&t)); + t.set_option("center", &json!(false)); + assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![])); + t.set_option("radii", &json!(false)); + assert_eq!(annotations(&t.overlays(&cx), c), (vec![], vec![])); + assert!(diameter(&t)); + t.set_option("diameter", &json!(false)); + assert!(!diameter(&t)); + t.set_option("center", &json!(true)); + t.set_option("radii", &json!(true)); + t.set_option("color", &json!("red")); + let red = [0xe5, 0x2d, 0x27]; + let o = t.overlays(&cx); + assert_eq!(annotations(&o, c), (vec![red; 2], vec![red; 2])); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { color, .. } if *color == blue)), "{o:?}"); + assert_eq!(t.options(), json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true})); + // A value an option does not take leaves it as it was. + for (key, value) in [("color", json!("orange")), ("center", json!("no")), ("radii", json!(0))] { + t.set_option(key, &value); + } + assert_eq!(t.options()["color"], json!("red")); + assert_eq!((&t.options()["center"], &t.options()["radii"]), (&json!(true), &json!(true))); +} + +/// With `standardAnchors` off, the circle's anchors go at the points it was drawn through. +#[test] +fn anchors_at_the_points_asks_for_them() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()); + let points = json!([[300.0, 300.0], [380.0, 360.0]]); + assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]); +} + +/// With `dragThird` off, a second click places the second point and a third click draws the circle +/// through the three; a click on the second point again (as a double-click there does) draws the +/// circle on the two; a second point let go on the first places nothing; a drag from the first +/// point still draws the circle on its diameter. +#[test] +fn with_third_point_by_dragging_off_three_clicks_draw_the_circle() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(click(&mut t, &cx, (380.0, 300.0)), vec![]); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 360.0), Mods::default())); + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle through the three is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}"); + // A click on the first point places nothing and keeps both points. + assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]); + assert!(t.busy()); + assert_eq!(click(&mut t, &cx, (300.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); + assert!(!t.busy()); + // The events of a double-click on the second point: its first click places it, the second + // draws the circle on the two points, and the double-click event that follows adds nothing. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), circle(&[(100.0, 100.0), (200.0, 100.0)])); + assert_eq!(t.pointer(&cx, &ev(PointerKind::DoubleClick, (200.0, 100.0), Mods::default())), vec![]); + assert!(!t.busy()); + // A drag that moves the second point places it where it is let go. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(drag(&mut t, &cx, (150.0, 100.0), &[(180.0, 100.0), (200.0, 100.0)], Mods::default()), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // Three points on one line keep the two placed: the next click elsewhere draws. + click(&mut t, &cx, (100.0, 100.0)); + click(&mut t, &cx, (200.0, 100.0)); + assert_eq!(click(&mut t, &cx, (300.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // A second press elsewhere, dragged back and let go on the first point, places nothing: the + // next click places the second point. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(drag(&mut t, &cx, (200.0, 100.0), &[(150.0, 100.0), (100.0, 100.0)], Mods::default()), vec![]); + assert!(t.busy()); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // A drag from the first point. + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); + // Switching the option drops the points placed so far. + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("dragThird", &json!(true)); + assert!(!t.busy()); +} + +/// With `dragThird` off, an Alt-click places the second point where Alt's rounding of the diameter +/// puts it (88 pt rounds to 90 pt at 100%), and the tool shows it there: the marker, the preview, +/// the circle on the two points and the circle through three all use it. +#[test] +fn an_alt_click_places_the_second_point_where_it_is_shown() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 390.0), Mods::default())); + let o = t.overlays(&cx); + let second = Point::new(390.0, 300.0); + assert!(o.iter().any(|o| matches!(o, Overlay::Anchor { p, .. } if p.distance(second) < 1e-9)), "{o:?}"); + // (300, 300), (390, 300) and (300, 390): center (345, 345), radius 45·√2. + let r = 45.0 * 2f64.sqrt(); + assert!(near(preview(&o).unwrap(), Rect::new(345.0 - r, 345.0 - r, 345.0 + r, 345.0 + r)), "{o:?}"); + assert_eq!(click(&mut t, &cx, (300.0, 390.0)), circle(&[(300.0, 300.0), (390.0, 300.0), (300.0, 390.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt)); + assert_eq!(click(&mut t, &cx, (390.0, 300.0)), circle(&[(300.0, 300.0), (390.0, 300.0)])); + // In inches the ticks are farther apart, and the rounding can move the point more than the + // 3 screen points a click reaches: the second click of a double-click, where the first let go, + // still draws the circle on the two points, at the rounded point. + let inches = ToolContext { unit: vectorcraft_doc::Unit::Inches, ..cx }; + let d = 94.4; + let rounded = vectorcraft_doc::Unit::Inches.snap_to_ruler_tick(d, 1.0); + assert!((rounded - d).abs() > 3.0, "{rounded}"); + click(&mut t, &inches, (300.0, 300.0)); + t.pointer(&inches, &ev(PointerKind::Down, (300.0 + d, 300.0), alt)); + t.pointer(&inches, &ev(PointerKind::Up, (300.0 + d, 300.0), alt)); + assert_eq!(click(&mut t, &inches, (300.0 + d, 300.0)), circle(&[(300.0, 300.0), (300.0 + rounded, 300.0)])); +} + +/// `tool.setOption`'s check takes the values the options take and nothing else. +#[test] +fn check_options_takes_only_the_values_the_options_take() { + let ok = json!({"center": false, "radii": true, "diameter": false, "color": "gray", "standardAnchors": false, "dragThird": false}); + assert_eq!(check_options(ok.as_object().unwrap()), Ok(())); + for (bad, error) in [ + (json!({"center": 1}), "`center` must be true or false"), + (json!({"dragThird": null}), "`dragThird` must be true or false"), + (json!({"color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"), + (json!({"colour": "red"}), "unknown Circle tool option `colour`"), + ] { + assert_eq!(check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}"); + } +} + /// Three points on one line show no circle, and the release draws nothing and starts afresh. A /// circle past the canvas is not shown either. #[test] diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 97e980e3c0..a2b579706c 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -53,6 +53,8 @@ const ROWS: &[Row] = &[ (&["star"], None, &["points"]), // The Ellipse dialog's Anchors. (&["ellipse"], None, &["anchors"]), + // Circle Tool Options (`circle::CircleTool`). + (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9e54eb12f6..843de6c68d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -23,6 +23,7 @@ pub mod brush_replace_art; pub mod bullets_numbering; pub mod char_style_options; pub mod check_spelling; +pub mod circle_options; pub mod color_balance; pub mod color_guide_options; mod color_picker; @@ -449,6 +450,7 @@ registry! { FreehandOptions: [freehand::KIND] => freehand::SPEC, ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC, + CircleOptions: [circle_options::KIND] => circle_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC, diff --git a/crates/ui-egui/src/dialogs/circle_options.rs b/crates/ui-egui/src/dialogs/circle_options.rs new file mode 100644 index 0000000000..6a828a7e17 --- /dev/null +++ b/crates/ui-egui/src/dialogs/circle_options.rs @@ -0,0 +1,169 @@ +//! Circle Tool Options (double-click the Circle tool, or `tool.options`): Show Center, Show Radii +//! and Show Diameter switch the center cross, the radius lines and the diameter label the tool +//! shows while a circle is drawn; Color is the color of the cross and the lines; Anchors at +//! Standard Positions off puts the circle's anchors at the points it was drawn through; Third +//! Point by Dragging off places the second point with a click and the third with another. OK sets +//! them with `tool.setOption {tool: "circle", values}`; they last across tool switches and are +//! saved with the preferences. + +use serde_json::{Map, Value, json}; +use vectorcraft_tools::circle::{COLORS, ID as TOOL}; + +use super::{DialogSpec, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Circle Tool Options. +pub const KIND: &str = "circleOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 300.0, ..DialogSpec::FORM }; + +/// The options the dialog edits, in the order it shows its check boxes, with their labels. +const SWITCHES: [(&str, &str); 5] = [ + ("center", "Show Center"), + ("radii", "Show Radii"), + ("diameter", "Show Diameter"), + ("standardAnchors", "Anchors at Standard Positions"), + ("dragThird", "Third Point by Dragging"), +]; + +/// The labels of [`COLORS`], in its order. +const COLOR_LABELS: [&str; 6] = ["Red", "Blue", "Magenta", "Green", "Black", "Gray"]; + +/// Width of the label column. +const LABEL_W: f32 = 60.0; + +fn heading(_: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +/// Open the tool's options with their current values. +pub fn open(app: &mut VectorcraftApp) -> Value { + let o = app.session.tool_options_of(TOOL); + let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]); + let fields: Map = keys.filter_map(|key| Some((key.to_string(), o.get(key)?.clone()))).collect(); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { + let on = d.bool(key); + if widgets::check(ui, tl!(label), on, true) { + d.fields.insert(key.into(), json!(!on)); + } +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + for (key, label) in &SWITCHES[..3] { + check(ui, d, key, label); + } + let color = d.str("color"); + let at = COLORS.iter().position(|(name, _)| *name == color).unwrap_or(1); + widgets::label_row(ui, tl!("Color:"), LABEL_W, |ui| { + let shown = COLOR_LABELS.get(at).copied().unwrap_or("Blue"); + if let Some((name, _)) = + widgets::dropdown_named(ui, "circle-options-color", Some(tl!("Color:")), shown, &COLOR_LABELS, 110.0).and_then(|i| COLORS.get(i)) + { + d.fields.insert("color".into(), json!(name)); + } + }); + ui.add_space(8.0); + for (key, label) in &SWITCHES[3..] { + check(ui, d, key, label); + } + false +} + +/// OK: set the tool's options. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]); + let values: Map = keys.filter_map(|key| Some((key.to_string(), d.fields.get(key)?.clone()))).collect(); + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app + } + + /// The labels the open dialog paints. + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + /// Every label the dialog shows has a row for each of [`COLORS`]. + #[test] + fn every_color_has_a_label() { + assert_eq!(COLOR_LABELS.len(), COLORS.len()); + for (label, (name, _)) in COLOR_LABELS.iter().zip(COLORS) { + assert_eq!(label.to_lowercase(), *name); + } + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_ok_sets_them() { + let mut app = app(); + let o = app.session.tool_options_of(TOOL); + for key in ["center", "radii", "diameter", "standardAnchors", "dragThird"] { + assert_eq!(o[key], json!(true), "{key}"); + } + assert_eq!(o["color"], json!("blue")); + let r = app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert_eq!(r["dialog"], json!(KIND)); + let text = painted(&mut app); + for label in [ + "Circle Tool Options", + "Show Center", + "Show Radii", + "Show Diameter", + "Color:", + "Blue", + "Anchors at Standard Positions", + "Third Point by Dragging", + "OK", + "Cancel", + ] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + for key in ["radii", "standardAnchors", "dragThird"] { + assert!(d.bool(key), "{key}"); + d.fields.insert(key.into(), json!(false)); + } + d.fields.insert("color".into(), json!("magenta")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let o = app.session.tool_options_of(TOOL); + let got: Vec<&Value> = ["center", "radii", "diameter", "standardAnchors", "dragThird", "color"].iter().map(|k| &o[*k]).collect(); + assert_eq!(got, [&json!(true), &json!(false), &json!(true), &json!(false), &json!(false), &json!("magenta")]); + // They last while another tool is chosen, and the dialog opens on them again. + app.select_tool(TOOL); + app.select_tool("selection"); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.bool("standardAnchors") && d.bool("center")); + assert_eq!(d.str("color"), "magenta"); + } + + /// `tool.setOption` takes only the values the options take, and an invalid one changes none. + #[test] + fn invalid_values_are_errors_and_change_nothing() { + let mut app = app(); + for (values, error) in [ + (json!({"center": false, "radii": "no"}), "`radii` must be true or false"), + (json!({"center": false, "color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"), + (json!({"center": false, "size": 3}), "unknown Circle tool option `size`"), + ] { + let e = app.run("tool.setOption", json!({"tool": TOOL, "values": values})).unwrap_err(); + assert!(e.contains(error), "{e}"); + assert_eq!(app.session.tool_options_of(TOOL)["center"], json!(true)); + } + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d347439b69..b5e75362ea 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -467,6 +467,10 @@ font-technology Variable Променливи Circle Кръг Circle Tool Инструмент Кръг Circle too large Кръгът е твърде голям + Show Radii Показване на радиуси + Show Diameter Показване на диаметър + Anchors at Standard Positions Опорни точки в стандартни позиции + Third Point by Dragging Трета точка чрез плъзгане Classic Defaults Класически по подразбиране Clean Up… Почистване… Clear Изчистване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 6fea288f77..da7713e4d4 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4527,6 +4527,10 @@ font-technology Variable Varijabilni Circle Krug Circle Tool Alat za krug Circle too large Krug je prevelik + Show Radii Prikaži poluprečnike + Show Diameter Prikaži prečnik + Anchors at Standard Positions Sidrene tačke na standardnim položajima + Third Point by Dragging Treća tačka povlačenjem Clip to Art Isijeci prema crtežu Colorize Oboji Gamma Gama diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e99406bffe..67de169b13 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -702,6 +702,10 @@ antiAlias Sharp Nítid Circle Cercle Circle Tool Eina de cercle Circle too large El cercle és massa gran + Show Radii Mostra els radis + Show Diameter Mostra el diàmetre + Anchors at Standard Positions Punts d’ancoratge en posicions estàndard + Third Point by Dragging Tercer punt arrossegant Circle (open) Cercle (obert) Classic Clàssic Classic Defaults Valors predeterminats clàssics diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b217199fe0..89f568143c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4631,6 +4631,10 @@ font-technology Variable Variabilní Circle Kruh Circle Tool Nástroj Kruh Circle too large Kruh je příliš velký + Show Radii Zobrazit poloměry + Show Diameter Zobrazit průměr + Anchors at Standard Positions Kotevní body ve standardních polohách + Third Point by Dragging Třetí bod tažením Clip to Art Oříznout podle kresby Colorize Obarvit Gamma Gama diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index de726e7860..a83d6d6a5e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7030,6 +7030,10 @@ font-technology Variable Variable Circle Cirkel Circle Tool Cirkelværktøj Circle too large Cirklen er for stor + Show Radii Vis radier + Show Diameter Vis diameter + Anchors at Standard Positions Ankerpunkter i standardpositioner + Third Point by Dragging Tredje punkt ved træk Clip to Art Beskær til grafik Colorize Farvelæg Gamma Gamma diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index f85240675f..e9a9c1d875 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -458,6 +458,11 @@ font-technology Variable Variabel Circle Kreis Circle Tool Kreis-Werkzeug Circle too large Kreis zu groß + Show Radii Radien anzeigen + Show Diameter Durchmesser anzeigen + Anchors at Standard Positions Ankerpunkte an Standardpositionen + Third Point by Dragging Dritter Punkt durch Ziehen + Gray Grau Classic Defaults Klassische Standardwerte Clean Up… Aufräumen… Clear Löschen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a26550a5ac..86c6928b6a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -451,6 +451,10 @@ font-technology Variable Μεταβλητές Circle Κύκλος Circle Tool Εργαλείο κύκλου Circle too large Ο κύκλος είναι πολύ μεγάλος + Show Radii Εμφάνιση ακτίνων + Show Diameter Εμφάνιση διαμέτρου + Anchors at Standard Positions Σημεία αγκύρωσης σε τυπικές θέσεις + Third Point by Dragging Τρίτο σημείο με σύρσιμο Classic Defaults Κλασικές προεπιλογές Clean Up… Εκκαθάριση… Clear Εκκαθάριση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 74e4627a9c..394b8c4793 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -481,6 +481,10 @@ font-technology Variable Variables Circle Círculo Circle Tool Herramienta Círculo Circle too large Círculo demasiado grande + Show Radii Mostrar radios + Show Diameter Mostrar diámetro + Anchors at Standard Positions Puntos de ancla en posiciones estándar + Third Point by Dragging Tercer punto arrastrando Classic Defaults Valores predeterminados clásicos Clean Up… Limpiar… Clear Borrar diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 170db8da57..fa9c958eaa 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4550,6 +4550,10 @@ font-technology Variable Muuttuvat Circle Ympyrä Circle Tool Ympyrätyökalu Circle too large Ympyrä on liian suuri + Show Radii Näytä säteet + Show Diameter Näytä halkaisija + Anchors at Standard Positions Ankkuripisteet vakiokohdissa + Third Point by Dragging Kolmas piste vetämällä Clip to Art Rajaa kuvitukseen Colorize Väritä Gamma Gamma diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 9ca4919a2e..22a5b6a1d7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -482,6 +482,10 @@ font-technology Variable Variables Circle Cercle Circle Tool Outil Cercle Circle too large Cercle trop grand + Show Radii Afficher les rayons + Show Diameter Afficher le diamètre + Anchors at Standard Positions Points d’ancrage aux positions standard + Third Point by Dragging Troisième point par glissement Classic Defaults Valeurs par défaut classiques Clean Up… Nettoyer… Clear Effacer diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 532fcb06cb..e1c3a43ab6 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -564,6 +564,11 @@ Circle વર્તુળ Circle Tool વર્તુળ ટૂલ Circle too large વર્તુળ ખૂબ મોટું છે + Show Radii ત્રિજ્યાઓ બતાવો + Show Diameter વ્યાસ બતાવો + Anchors at Standard Positions પ્રમાણભૂત સ્થાનો પર એન્કર બિંદુઓ + Third Point by Dragging ખેંચીને ત્રીજું બિંદુ + Gray રાખોડી Circle: વર્તુળ: Classic ક્લાસિક Clean Up સાફ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 3bfe38fb3e..622cc7cc4f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -822,6 +822,10 @@ antiAlias Sharp शार्प Circle वृत्त Circle Tool वृत्त टूल Circle too large वृत्त बहुत बड़ा है + Show Radii त्रिज्याएँ दिखाएँ + Show Diameter व्यास दिखाएँ + Anchors at Standard Positions मानक स्थानों पर एंकर पॉइंट्स + Third Point by Dragging खींचकर तीसरा बिंदु Circle (open) सर्किल (ओपन) Circle: वृत्त: Classic क्लासिक diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index cfc6c224a3..4bcdc856cd 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -643,6 +643,10 @@ font-technology Variable Változó Circle Kör Circle Tool Kör eszköz Circle too large A kör túl nagy + Show Radii Sugarak megjelenítése + Show Diameter Átmérő megjelenítése + Anchors at Standard Positions Horgonypontok szabványos helyeken + Third Point by Dragging Harmadik pont húzással Circle (open) Kör (nyitott) Classic Defaults Klasszikus alapértékek Clean Up… Tisztítás… diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0526f18380..162d4c2158 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4282,6 +4282,10 @@ font-technology Variable Variabel Circle Lingkaran Circle Tool Alat lingkaran Circle too large Lingkaran terlalu besar + Show Radii Tampilkan jari-jari + Show Diameter Tampilkan diameter + Anchors at Standard Positions Titik jangkar di posisi standar + Third Point by Dragging Titik ketiga dengan menyeret Clip to Art Pangkas ke karya seni Colorize Warnai Gamma Gamma diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 066a4ef6fd..2024a50923 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -483,6 +483,11 @@ font-technology Variable Variabili Circle Cerchio Circle Tool Strumento Cerchio Circle too large Cerchio troppo grande + Show Radii Mostra raggi + Show Diameter Mostra diametro + Anchors at Standard Positions Punti di ancoraggio in posizioni standard + Third Point by Dragging Terzo punto trascinando + Gray Grigio Classic Defaults Valori predefiniti classici Clean Up… Pulisci… Clear Cancella diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 597abda551..a574d4b49f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1299,6 +1299,11 @@ antiAlias Sharp シャープ Circle 円 Circle Tool 円ツール Circle too large 円が大きすぎます + Show Radii 半径を表示 + Show Diameter 直径を表示 + Anchors at Standard Positions アンカーポイントを標準位置に配置 + Third Point by Dragging 3 点目をドラッグで指定 + Gray グレー Clear All Tabs すべてのタブを消去 Above Text テキストの上 Position Panel Above Text テキストの上にパネルを配置 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0eb74ca1c0..88db3c988a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6348,6 +6348,10 @@ font-technology Variable ცვლადი Circle წრე Circle Tool წრის ხელსაწყო Circle too large წრე ზედმეტად დიდია + Show Radii რადიუსების ჩვენება + Show Diameter დიამეტრის ჩვენება + Anchors at Standard Positions საყრდენი წერტილები სტანდარტულ პოზიციებზე + Third Point by Dragging მესამე წერტილი გადათრევით Clip to Art ნახატზე მოჭრა Colorize გაფერადება Gamma გამა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 83219f8de8..eb99376108 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1289,6 +1289,11 @@ antiAlias Sharp 날카롭게 Circle 원 Circle Tool 점 기준 원 도구 Circle too large 원이 너무 큽니다 + Show Radii 반지름 표시 + Show Diameter 지름 표시 + Anchors at Standard Positions 표준 위치에 앵커 포인트 + Third Point by Dragging 드래그로 세 번째 점 지정 + Gray 회색 Clear All Tabs 모든 탭 지우기 Above Text 문자 위 Position Panel Above Text 패널을 문자 위에 배치 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f40a61047c..feb3c77362 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4904,6 +4904,10 @@ font-technology Variable Variabel Circle Cirkel Circle Tool Cirkelgereedschap Circle too large Cirkel te groot + Show Radii Stralen tonen + Show Diameter Diameter tonen + Anchors at Standard Positions Ankerpunten op standaardposities + Third Point by Dragging Derde punt door slepen Clip to Art Clippen op artwork Colorize Inkleuren Gamma Gamma diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 52e33d639a..a75736d725 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4472,6 +4472,11 @@ font-technology Variable Zmienne Circle Okrąg Circle Tool Narzędzie Okrąg Circle too large Okrąg jest za duży + Show Radii Pokaż promienie + Show Diameter Pokaż średnicę + Anchors at Standard Positions Punkty kontrolne w standardowych położeniach + Third Point by Dragging Trzeci punkt przez przeciągnięcie + Gray Szary Clip to Art Przytnij do kompozycji Colorize Koloruj Gamma Gamma diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5ae5b28f19..690ab56e7f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -448,6 +448,10 @@ antiAlias Sharp Nítido Circle Círculo Circle Tool Ferramenta Círculo Circle too large Círculo grande demais + Show Radii Mostrar Raios + Show Diameter Mostrar Diâmetro + Anchors at Standard Positions Pontos de Ancoragem em Posições Padrão + Third Point by Dragging Terceiro Ponto Arrastando Clean Up… Limpar… Clear Limpar Clear All Tabs Limpar Todas as Paradas de Tabulação diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 3dc089a76d..7559717a49 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -479,6 +479,10 @@ font-technology Variable Вариативные Circle Круг Circle Tool Инструмент «Круг» Circle too large Круг слишком большой + Show Radii Показать радиусы + Show Diameter Показать диаметр + Anchors at Standard Positions Опорные точки в стандартных позициях + Third Point by Dragging Третья точка перетаскиванием Classic Defaults Классические значения по умолчанию Clean Up… Очистить… Clear Очистить diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5e852da822..674f2c21e7 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -469,6 +469,10 @@ font-technology Variable Variabla Circle Cirkel Circle Tool Cirkelverktyg Circle too large Cirkeln är för stor + Show Radii Visa radier + Show Diameter Visa diameter + Anchors at Standard Positions Ankarpunkter på standardpositioner + Third Point by Dragging Tredje punkt genom att dra Classic Defaults Klassiska standardvärden Clean Up… Rensa upp… Clear Rensa diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index de1d7280f1..80ce287e83 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -463,6 +463,10 @@ font-technology Variable Değişken Circle daire Circle Tool Daire Aracı Circle too large Daire çok büyük + Show Radii Yarıçapları Göster + Show Diameter Çapı Göster + Anchors at Standard Positions Standart Konumlarda Bağlantı Noktaları + Third Point by Dragging Sürükleyerek Üçüncü Nokta Classic Defaults Klasik Varsayılanlar Clean Up… Temizleme… Clear Temizle diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index e82439dca3..e646a0f45c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -477,6 +477,11 @@ font-technology Variable Варіативні Circle Коло Circle Tool Інструмент «Коло» Circle too large Коло завелике + Show Radii Показати радіуси + Show Diameter Показати діаметр + Anchors at Standard Positions Опорні точки в стандартних позиціях + Third Point by Dragging Третя точка перетягуванням + Gray Сірий Classic Defaults Класичні значення за промовчанням Clean Up… Очистити… Clear Очистити diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 0f088fec2b..9cc7f93932 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -559,6 +559,11 @@ font-technology Variable Biến thiên Circle Hình tròn Circle Tool Công cụ Hình tròn Circle too large Hình tròn quá lớn + Show Radii Hiện bán kính + Show Diameter Hiện đường kính + Anchors at Standard Positions Điểm neo ở vị trí chuẩn + Third Point by Dragging Điểm thứ ba bằng cách kéo + Gray Xám Classic Cổ điển Classic Defaults Mặc định cổ điển Clean Up… Dọn dẹp… diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ed027b9f23..2ab7d69a78 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -430,6 +430,10 @@ antiAlias Sharp 锐利 Circle 圆形 Circle Tool 圆形工具 Circle too large 圆形过大 + Show Radii 显示半径 + Show Diameter 显示直径 + Anchors at Standard Positions 锚点位于标准位置 + Third Point by Dragging 拖动放置第三点 Classic Defaults 经典默认 Clean Up… 清理… Clear 清除 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d5d613a7d8..b8c42e647f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -445,6 +445,11 @@ font-technology Variable 可變 Circle 圓形 Circle Tool 圓形工具 Circle too large 圓形過大 + Show Radii 顯示半徑 + Show Diameter 顯示直徑 + Anchors at Standard Positions 錨點位於標準位置 + Third Point by Dragging 拖曳放置第三點 + Gray 灰 Classic Defaults 經典預設值 Clean Up… 清除… Clear 清除 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 677b804720..04be4bbc55 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -980,7 +980,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 3c78f12df0..da85c2fbc0 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -423,7 +423,7 @@ pub(crate) fn flyout_press(ui: &Ui, resp: &egui::Response, rect: egui::Rect) -> /// Reflect and Shear tools' are their Object › Transform dialogs, the selection tools' are the /// Move dialog, and the Pencil, Paintbrush, Smooth, Blob Brush, Eraser, Shape Builder and Objects /// on Path tools' are their Tool Options, as are the Line Segment, Arc, Rectangular Grid and Polar Grid tools' -/// ([`crate::dialogs::shapes::open_options`]). The Type on a Path and Vertical Type on a Path +/// ([`crate::dialogs::shapes::open_options`]) and the Circle tool's ([`crate::dialogs::circle_options::open`]). The Type on a Path and Vertical Type on a Path /// tools' are Type on a Path Options for the selected type on a path. pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result { match tool { @@ -460,6 +460,9 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result crate::dialogs::shapes::open_options(app, tool), + // The Circle tool: what it shows while a circle is drawn, where its anchors go and how + // the third point is placed. + vectorcraft_tools::circle::ID => Ok(crate::dialogs::circle_options::open(app)), // The Flare tool: its options, which draw the next flare (OK draws none). "flare" => Ok(crate::dialogs::flare_options::open(app, None)), // A double click on the Print Tiling tool puts the pages back where the placement puts them. diff --git a/docs/mcp.md b/docs/mcp.md index bdfa886286..e74ddf58e5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6189,6 +6189,12 @@ one line (twice the triangle's area at most 10⁻¹⁰ of its longest side squar canvas (4,000,000 pt from the origin), when `points` is not two or three pairs of numbers, and when `points` is left out and the selection does not hold two or three anchor points of paths. +`anchors` sets where the circle's anchors go. With `"standard"`, the default, the circle has four anchors at 0°, 90°, +180° and 270°. With `"points"`, the circle is a plain path with an anchor exactly at each point, and more anchors +between them, evenly spaced, so that no curve turns more than a quarter of the circle: two points give four anchors, +and three points give four to six. Any other `anchors` value is an error (`` `anchors` must be one of standard, points ``), and nothing +is drawn. + The Circle tool, after the Ellipse tool in its toolbar group, draws with this command. A drag from one point to another, or a click on each, draws the circle with the two points as the ends of a diameter. A click on a first point, then a press on a second point dragged to a third, draws the circle through the three. Shift keeps the second point at @@ -6203,6 +6209,28 @@ Escape, a dropped press, and an edit, Undo or Redo made outside the tool drop th screen points of the first point, or one that snaps to it, is a press on it: let go there (a double-click), it places no second point, and dragged out, it draws the circle on the diameter it drags out. +Circle Tool Options (`tool.options {tool: "circle"}`, or a double-click on the tool, dialog `circleOptions`) sets the +tool's options, which `tool.setOption {tool: "circle", values}` also sets and the preferences keep. All are on by +default, and `color` is `"blue"`: + +- `center`, `radii` and `diameter` (Show Center, Show Radii, Show Diameter) show or hide the cross at the center, the + lines from the center to the points and the diameter label. The diameter label also needs Measurement Labels on. +- `color` (Color) is the color of the cross and the lines: `"red"`, `"blue"`, `"magenta"`, `"green"`, `"black"` or + `"gray"`. The outline stays blue. +- `standardAnchors` (Anchors at Standard Positions) off draws the circle with `anchors: "points"`, so its anchors are + at the points it was drawn through. +- `dragThird` (Third Point by Dragging) off changes how the points are placed. A click on a second point places it, and + a click on a third point draws the circle through the three. A click on the second point again, as the second click + of a double-click there is, draws the circle on the two points. An Alt-click places the second point where Alt's + rounding of the diameter puts it, and both circles pass through it there. A click on the first point, or a second + point dragged back and let go on it, places nothing, and a click on the line through the first two points draws + nothing and keeps them. A drag from the first point still draws the circle on the diameter it drags out, and a drag + from a second point places it where it is let go. Switching `dragThird` drops the points placed so far. + +`tool.setOption` returns an error and changes none of the options when a value is not one the option takes +(`` `radii` must be true or false ``, `` `color` must be one of red, blue, magenta, green, black, gray ``) or the key is +not one of these (`` unknown Circle tool option `size` ``). + With the Ellipse tool, the first two Shift-clicks place points, and the third draws the circle through the three with this command. After two points the tool previews the circle through them and the pointer as a dashed outline. Once a point is placed, a Shift-click on the selection's handles, center point or shape widgets places a point too. Escape, a From 8af2a300e6d341226a7b85f1e14ea3e4b6cd76ed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:41:58 -0800 Subject: [PATCH 30/69] Shapes: a Circle tool drag of the second or third point ends where it is let go With Third Point by Dragging off, a release away from the last drag of the second or third point now places that point at the release position. --- crates/tools/src/circle/tests.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index afab9bb291..c0a82a51ef 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -215,6 +215,25 @@ fn with_third_point_by_dragging_off_three_clicks_draw_the_circle() { assert!(!t.busy()); } +/// With `dragThird` off, a drag of the second or third point ends where it is let go, also when the +/// release is away from the last drag. +#[test] +fn with_third_point_by_dragging_off_a_drag_ends_where_it_is_let_go() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (350.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (400.0, 300.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(down, (350.0, 350.0), Mods::default())); + t.pointer(&cx, &ev(drag, (320.0, 380.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (400.0, 300.0), (300.0, 400.0)])); +} + /// With `dragThird` off, an Alt-click places the second point where Alt's rounding of the diameter /// puts it (88 pt rounds to 90 pt at 100%), and the tool shows it there: the marker, the preview, /// the circle on the two points and the circle through three all use it. From e144392bec1f7db9f7ff221494a3c018602e7745 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:09:52 -0800 Subject: [PATCH 31/69] Shapes: shape.circleThroughPoints refuses a null anchors --- crates/engine/src/cmd/create.rs | 2 +- crates/engine/src/tests/circle_through.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 61b22d12b9..dc28eef546 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -425,7 +425,7 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result { None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, }; let key = "anchors"; - let at_points = match p.get(key).filter(|v| !v.is_null()).map(Value::as_str) { + let at_points = match p.get(key).map(Value::as_str) { None | Some(Some("standard")) => false, Some(Some("points")) => true, Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))), diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index a6f69d1bea..c9b66f9f06 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -226,7 +226,7 @@ fn anchors_at_the_points_puts_an_anchor_at_each_point() { assert_eq!(anchors.len(), 4, "{anchors:?}"); assert_eq!((anchors[0], anchors[2]), (Point::new(0.0, 0.0), Point::new(100.0, 0.0))); let (count, undo) = (object_count(&s), undo_len(&s)); - for bad in [json!("corners"), json!(true), json!(4)] { + for bad in [json!("corners"), json!(true), json!(4), Value::Null] { let e = s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": bad })).unwrap_err().to_string(); assert!(e.contains("`anchors` must be one of standard, points"), "{e}"); } From cb1689c3a82012f1eee7866f33547c8f504ead42 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:14:15 -0800 Subject: [PATCH 32/69] Tests: the menu dialog command list counts Tracing Presets beside main's new entry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Main's list already grew to 40 entries; with Tracing Presets… it holds 41, and the comment names the Edit menu's preset dialogs. --- crates/ui-egui/src/shortcuts/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index d117d88638..4c114accb7 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -456,8 +456,8 @@ fn a_shortcut_runs_what_its_menu_item_runs() { /// add-on, Set Corners…, Divide into Dashes, Tangent Circle…, Find Nearest Swatch, the swatch legend, the type /// tools, the select add-on and Select by Link Status…), three "…" items whose menu entry gives /// params, Smart Punctuation…, Edit Custom Dictionary…, Composite Fonts…, Recolor Artwork…, the Edit menu's preset -/// dialogs and Apply SVG Filter…. -const MENU_DIALOG_COMMANDS: [&str; 40] = [ +/// dialogs (Transparency Flattener, Print, PDF, Tracing and Perspective Grid Presets…) and Apply SVG Filter…. +const MENU_DIALOG_COMMANDS: [&str; 41] = [ "object.path.smooth", "object.path.simplify", "object.path.offsetPath", From 22d799fd41a8e367b17c104e541dd60b11307278 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:19:38 -0800 Subject: [PATCH 33/69] Shapes: the Circle tool shows no circle its anchored path cannot draw With Standard Anchors off, a circle near the canvas edge whose path with anchors at the points curves past the edge is no longer previewed or drawn, as shape.circleThroughPoints refuses it. --- crates/tools/src/circle.rs | 23 +++++++++++++++++------ crates/tools/src/circle/tests.rs | 26 ++++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index f2686cd5a4..fb19af46e0 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -159,6 +159,17 @@ pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> { shapes::circle_through_points(points).filter(on_canvas) } +/// [`circle_of`], as the tool draws it: with `standard_anchors` off, also none where the path with +/// an anchor at each point ([`shapes::circle_with_anchors_at`]) reaches past the canvas, since its +/// curves can reach slightly outside the circle. +fn drawn_circle(points: &[Point], standard_anchors: bool) -> Option<(Point, f64)> { + let fits = |(c, r): &(Point, f64)| { + let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, points).to_bezpath()); + [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD) + }; + circle_of(points).filter(|c| standard_anchors || fits(c)) +} + /// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on /// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and /// when that rounding leaves no distance. @@ -170,9 +181,9 @@ fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point /// Are the points two or more different points through which no circle is drawn: three on one /// line, or a circle that would reach past the canvas? -fn too_large(points: &[Point]) -> bool { +fn too_large(points: &[Point], standard_anchors: bool) -> bool { let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p)); - points.len() >= 2 && distinct && circle_of(points).is_none() + points.len() >= 2 && distinct && drawn_circle(points, standard_anchors).is_none() } impl CircleTool { @@ -231,7 +242,7 @@ impl CircleTool { /// (the tool showed none), it only starts afresh. fn draw(&mut self, points: &[Point]) -> Vec { self.clear(); - if circle_of(points).is_none() { + if drawn_circle(points, self.options.standard_anchors).is_none() { return vec![]; } let (c, v) = command(points, self.options.standard_anchors); @@ -247,7 +258,7 @@ impl CircleTool { if on_second && !dragged { return self.draw(&[a, b]); } - if (on_first && !dragged) || circle_of(&[a, b, at]).is_none() { + if (on_first && !dragged) || drawn_circle(&[a, b, at], self.options.standard_anchors).is_none() { self.snap.clear(); return vec![]; } @@ -431,7 +442,7 @@ impl Tool for CircleTool { let mut o = self.snap.guides().to_vec(); let points = self.points(); let color = crate::draw2::FEEDBACK; - if let Some((c, r)) = circle_of(&points) { + if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) { let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); // The canvas draws a dashed outline dash by dash along its whole length: a circle longer // than DASHED_PX on screen is drawn solid instead. @@ -452,7 +463,7 @@ impl Tool for CircleTool { if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) { o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); } - } else if let Some(p) = self.pointer.filter(|_| too_large(&points)) { + } else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.options.standard_anchors)) { o.push(Overlay::Label { p, text: "Circle too large".into(), color }); } for p in self.first.into_iter().chain(self.second()) { diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index c0a82a51ef..40be85c4e7 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -162,6 +162,28 @@ fn anchors_at_the_points_asks_for_them() { assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]); } +/// With `standardAnchors` off, a circle within 1 pt of the canvas edge whose path with anchors at +/// the points curves past that edge is not shown and not drawn; with standard anchors it is. +#[test] +fn anchors_at_the_points_keep_the_path_on_the_canvas() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let r = MAX_COORD - 1.0; + let at = |deg: f64| (r * deg.to_radians().cos(), r * deg.to_radians().sin()); + let points = [at(0.0), at(70.0), at(180.0)]; + let geom: Vec = points.iter().map(|(x, y)| Point::new(*x, *y)).collect(); + assert!(drawn_circle(&geom, true).is_some()); + assert_eq!(drawn_circle(&geom, false), None); + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + click(&mut t, &cx, points[0]); + t.pointer(&cx, &ev(PointerKind::Down, points[1], Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, points[2], Mods::default())); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, points[2], Mods::default())), vec![]); +} + /// With `dragThird` off, a second click places the second point and a third click draws the circle /// through the three; a click on the second point again (as a double-click there does) draws the /// circle on the two; a second point let go on the first places nothing; a drag from the first @@ -419,8 +441,8 @@ fn points_on_one_line_say_the_circle_is_too_large() { assert_eq!(label(&t), None, "a circle is shown"); t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default())); assert_eq!(label(&t), None, "the third point is on the second"); - assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)])); - assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)])); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true)); + assert!(!too_large(&[Point::new(0.0, 0.0)], true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], true)); } /// Escape drops the first point; so do a dropped press and an edit made outside the tool. A From e4d2922b210a3e3d4f9448fd0261fa0e35da4d96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 20:28:17 -0800 Subject: [PATCH 34/69] Command Palette: a palette closed and opened at once starts on its first row A pick or a press outside the palette now drops the highlight and the availability answers on the frame that closes it, so a command that opens the palette again before a closed frame is drawn starts on the first row and checks the rows again. The ranking line now says a recent pick ranks after the pick count's grade. --- crates/ui-egui/src/palette.rs | 33 +++++++++++++++++++++++++++++++-- docs/target-app-parity.md | 2 +- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index df5ec12d9e..1be4f36489 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1086,10 +1086,18 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ctx.request_repaint(); } let sel_key = matches.get(sel).map(|e| e.id.clone()).unwrap_or_default(); + // A palette that closes on this frame forgets its highlight and its answers here, as a closed + // frame does, so a command that opens it again before that frame starts it afresh. + let closing = run.is_some() || outside; ctx.data_mut(|d| { - d.insert_temp::(sel_id, (sel, q, offset, view, sel_key)); + if closing { + d.remove::(sel_id); + d.remove::(availability_id); + } else { + d.insert_temp::(sel_id, (sel, q, offset, view, sel_key)); + d.insert_temp(availability_id, availability); + } d.insert_temp(rsel_id, rsel); - d.insert_temp(availability_id, availability); }); if let Some(id) = run { app.ui.palette_open = false; @@ -1939,6 +1947,27 @@ mod tests { assert!(top.2 >= f64::from(open.popup().top()), "the first row is in view: {shown:?}"); } + /// A palette closed by a press outside it and opened again before a closed frame is drawn + /// starts with its first row highlighted and asks its results again whether they can run. + #[test] + fn the_palette_opened_again_at_once_after_closing_starts_afresh() { + let mut open = Open::new("", WINDOW); + open.app.ui.recent_commands = vec!["paint.swap".into(), "object.group".into(), "view.zoomIn".into()]; + open.frame(vec![]); + open.press(egui::Key::ArrowDown, 2); + assert_eq!(open.highlighted(), 2); + let at = egui::pos2(2.0, 2.0); + assert!(!open.popup().contains(at), "{at:?} is outside {:?}", open.popup()); + let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + open.frame(vec![egui::Event::PointerMoved(at), press]); + assert!(!open.app.ui.palette_open, "the press outside closes the palette"); + let availability = egui::Id::unique("palette-availability"); + assert!(open.ctx.data(|d| d.get_temp::(availability)).is_none(), "the answers go when the palette closes"); + open.app.ui.palette_open = true; + open.frame(vec![]); + assert_eq!(open.highlighted(), 0, "the first row is highlighted"); + } + /// #1757: Up and Down move the highlighted result, wrapping at the ends; a new query starts /// from the first again. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1ae54a2154..a75f48513a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1405,7 +1405,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches without one, and among them the query is read with the misspelled word replaced by the word it meets, so they come in the order the word spelled right gives; then a result whose label holds the word comes before one whose menu path holds it. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and results without typos keep their order (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `misspelled_words_find_the_command`). A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`). - The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do, the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades and the matches through a typo, a description or a word with the same meaning, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows, which also holds a pick whose command could not run. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). + The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do and were picked as often (see the pick counts below), the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades, the matches through a typo, a description or a word with the same meaning, and the pick count's grade, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows, which also holds a pick whose command could not run. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`). A Command Palette query word also finds a command by what the command's description says: "transparent background" lists Remove Background… among the first 3 results, and "png" lists it after every result with "png" in its name or menu path. The description is the command's params text (an engine or plug-in command's, a UI command's, or an effect's) without each `{…}` group that is not inside a `{`, `[` or `(` group, without each such `[…]` or `(…)` group just after a `→`, and without the `→` before a removed group, cut to its first 300 characters at the end of a word. The words of a schema ("corners" for Remove Background…) and of a result written as a group do not find the command; a result written as words after a `→` stays in the description. Words of 2 characters or fewer, words with no letter, and "the", "and", "ids", "true", "false" and "null" are left out. A query word that is a word of a description, shares an English base word with one, starts one or has the same meaning as one finds the result, and such a result ranks below every result that the query matches in its name, menu path or id, as text inside a word or through a typo. Descriptions are English only, and a typo does not match them. Tools, panels and filter plug-ins have no description (`palette::search` tests `a_description_leaves_out_the_schema_and_the_result`, `a_word_of_the_description_finds_the_result`, `a_description_match_ranks_below_a_typo`, `words_of_a_description_find_the_command`). A Command Palette result that cannot run now stays in its place in the list and is drawn dimmed: an engine command whose engine check fails (Ungroup with nothing selected, Paste with an empty clipboard and nothing to paste from the system clipboard), a UI command the menus dim, a filter plug-in or an effect whose menu item is dimmed, and a panel in Presentation Mode. Tools are never dimmed. The reason shows on hover, in the row's screen-reader description, on a second line of the search field's screen-reader description and in the footer while the row is highlighted, beside the count or, under the recent picks of an empty search, on a line of its own. The reason is the status line a pick of the dimmed menu item gives, with the result's name in place of the command's id: "command `Object › Ungroup` is not available right now: nothing selected", or without the engine's reason when it gives none. The Recent Commands list beside the search field draws such a pick dimmed too, with the same reason on hover and for screen readers. Only the drawn rows are checked, each once for as long as the state it was checked in lasts: a command run, an edit, a change of selection, document, history, clipboard, language, screen mode or open dialog, a save that marks the document saved, or a background save, export, file read, plug-in run or trace that starts, ends or shows its progress window checks them again on the next frame, and a frame with a click checks them again on that frame only. Typing in the search field does not check them again, and the palette checks them again each time it opens. The check never changes the ranking. A pick of a dimmed result does what it did before (`palette` tests `a_result_that_cannot_run_now_is_dimmed_and_says_why`, `hovering_a_result_that_cannot_run_now_says_why`, `paste_is_dimmed_only_while_nothing_can_be_pasted`, `tools_are_never_dimmed_and_panels_are_in_presentation_mode`, `a_result_without_an_engine_reason_says_it_is_not_available`, `no_reason_shows_a_command_id`, `a_recent_pick_that_cannot_run_now_says_why`, `a_recent_command_that_cannot_run_now_is_dimmed_in_the_list`, `availability_is_asked_again_when_what_it_depends_on_changes`, `availability_is_read_once_per_state`, `the_palette_asks_again_when_it_opens_again`). From 5c858d24e25db9ce1d6050086c7d6bdf4f1bf0c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 21:20:52 -0800 Subject: [PATCH 35/69] i18n: the French replace-presets question has a narrow no-break space before ? --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8c20ef51a6..45c6e23b2e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1765,7 +1765,7 @@ font-technology Variable Variables Tracing Presets… Paramètres prédéfinis de vectorisation… Import Image Trace Presets Importer des paramètres prédéfinis de vectorisation de l’image Export Image Trace Presets Exporter les paramètres prédéfinis de vectorisation de l’image - Replace the saved presets that have these names? Remplacer les paramètres prédéfinis enregistrés qui portent ces noms ? + Replace the saved presets that have these names? Remplacer les paramètres prédéfinis enregistrés qui portent ces noms ? Image Trace Presets Paramètres prédéfinis de vectorisation de l’image Image: Image : Images: Images : From f4a8f7b0d1e649e5dc78270e4cb8f49b63a70db4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 22:29:51 -0800 Subject: [PATCH 36/69] Image Trace: tracing preset settings scroll past the preset list's height The manager and the preset editor showed every settings row, so a Color preset with Document Library and Ignore Color made both dialogs taller than a short screen. The settings now scroll once they are taller than the manager's preset list. --- crates/ui-egui/src/dialogs/tracing_presets.rs | 18 +++++-- .../src/dialogs/tracing_presets/tests.rs | 54 +++++++++++++++++++ 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tracing_presets.rs b/crates/ui-egui/src/dialogs/tracing_presets.rs index 57abc052b3..52c075c09b 100644 --- a/crates/ui-egui/src/dialogs/tracing_presets.rs +++ b/crates/ui-egui/src/dialogs/tracing_presets.rs @@ -36,6 +36,10 @@ pub const REPLACE_KIND: &str = "tracingPresetsReplace"; /// The editor's field naming the saved preset it edits. const EDITING: &str = "editing"; +/// The tallest the tracing settings draw, in the manager and the editor, before they scroll (the +/// height of the manager's preset list), so the dialog's buttons stay on short screens. +const SETTINGS_HEIGHT: f32 = 300.0; + pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Tracing Presets").into(), body, @@ -148,9 +152,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.set_width(320.0); ui.label(egui::RichText::new(list_label(&preset)).color(t.text_strong).strong()); ui.add_space(8.0); - // The selected preset's settings, as the editor shows them, to read only. + // The selected preset's settings, as the editor shows them, to read only. They scroll + // past the height of the preset list. let mut params = preset.1.clone(); - ui.add_enabled_ui(false, |ui| settings_editor(app, ui, "tracing-presets", &mut params)); + egui::ScrollArea::vertical().id_salt("tracing-preset-details").max_height(SETTINGS_HEIGHT).show(ui, |ui| { + ui.add_enabled_ui(false, |ui| settings_editor(app, ui, "tracing-presets", &mut params)); + }); if builtin { ui.add_space(6.0); ui.label(egui::RichText::new(tl!("Built-in presets don't change: New makes a copy you can edit.")).color(t.text_dim).size(11.5)); @@ -332,7 +339,12 @@ fn preset_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b }); ui.add_space(8.0); let mut params = d.fields.get("params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); - if settings_editor(app, ui, "tracing-preset", &mut params) { + let changed = egui::ScrollArea::vertical() + .id_salt("tracing-preset-settings") + .max_height(SETTINGS_HEIGHT) + .show(ui, |ui| settings_editor(app, ui, "tracing-preset", &mut params)) + .inner; + if changed { d.fields.insert("params".into(), params); } false diff --git a/crates/ui-egui/src/dialogs/tracing_presets/tests.rs b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs index 5f0cc5e385..7176efbbc8 100644 --- a/crates/ui-egui/src/dialogs/tracing_presets/tests.rs +++ b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs @@ -385,3 +385,57 @@ fn a_long_list_of_names_keeps_replace_on_screen() { assert!(rect.is_some_and(|r| screen.contains_rect(r)), "{button} is drawn on screen: {rect:?}"); } } + +/// The tracing settings scroll past the height of the preset list, in the manager and in the +/// editor: a preset with every row shown (Color, Document Library, Ignore Color) makes neither +/// dialog taller than a Black and White one does. +#[test] +fn tall_settings_scroll_instead_of_growing_the_dialog() { + fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + /// The height from the dialog's heading to the bottom of its button `button`. + fn height(app: &mut VectorcraftApp, heading: &str, button: &str) -> f32 { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 2000.0)); + let mut texts = vec![]; + for k in 0..6 { + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + texts.clear(); + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + } + let at = |t: &str| texts.iter().find(|(s, _)| s == t).map(|(_, r)| *r).unwrap_or_else(|| panic!("{t}: {texts:?}")); + at(button).max.y - at(heading).min.y + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let short = listed(&mut app, "Default"); + let mut tall = short.clone(); + tall["mode"] = json!("color"); + tall["palette"] = json!("documentLibrary"); + tall["colorGroup"] = json!("Brand Colors"); + tall["ignoreWhite"] = json!(true); + for (name, params) in [("Short", &short), ("Tall", &tall)] { + app.run("imageTrace.presets.save", json!({ "name": name, "preset": "Default", "params": params })).unwrap(); + } + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + let mut heights = vec![]; + for name in ["Short", "Tall"] { + set(&mut app, "selected", json!(name)); + let manager = height(&mut app, "Tracing Presets", "Close"); + press(&mut app, Action::Edit, name).unwrap(); + assert_eq!(kind(&app), Some(PRESET_KIND)); + let editor = height(&mut app, "Save Preset", "OK"); + app.ui.dialog = super::super::parent(app.ui.dialog.as_ref().unwrap()); + heights.push((manager, editor)); + } + let [(manager, editor), (tall_manager, tall_editor)] = heights[..] else { panic!("{heights:?}") }; + assert!(tall_manager <= manager + 0.5, "the manager grows from {manager} to {tall_manager}"); + assert!(tall_editor <= editor + 0.5, "the editor grows from {editor} to {tall_editor}"); +} From ef6d607ac4dffd4189a2aa74da589328d7aad36c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 01:07:34 -0800 Subject: [PATCH 37/69] Docs: count Ornamental among the eleven built-in brush libraries The progress rows, the G5 gap entry, the M10 milestone row and the brush library list now name Ornamental and count eleven built-in brush libraries. The ROADMAP progress log gets an Ornamental line. --- ROADMAP.md | 1 + docs/gaps.md | 2 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 8 ++++---- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index b3877be5c8..2da3c938cd 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -126,6 +126,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. - 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged. +- 2026-11-18: Built-in Ornamental brush library: Scrollwork, Filigree Arrow, Petal Sweep and Twin Curl, original art brushes generated in code that stretch curled lines, arrow-like accents and petal details along a path and take the stroke color as tints. Eleven built-in brush libraries (part of Gap 5); headline numbers unchanged. - 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. - 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged. diff --git a/docs/gaps.md b/docs/gaps.md index 5dee50afa1..c7bee05a35 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -698,7 +698,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Fine Grain, Canvas Weave, Burlap Sack, Cracked Glaze, Mosaic Floor, Quilted Squares, Leaded Glass and Damp Paper, painted with the texture effects; User Defined; Other Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). -- **Missing:** more built-in brush libraries beyond the ten shipped (and further graphic-style libraries beyond the eleven shipped, and further symbol libraries beyond Basic +- **Missing:** more built-in brush libraries beyond the eleven shipped (and further graphic-style libraries beyond the eleven shipped, and further symbol libraries beyond Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write. - **Estimate:** 3–13 h (estimated). diff --git a/docs/roadmap.md b/docs/roadmap.md index 3c09bde829..2a7a0f8fcf 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -169,7 +169,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, eleven generated libraries including Ornamental, Tech Circuit, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f699d9db68..d4189d2728 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -257,7 +257,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (ten generated libraries including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (eleven generated libraries including Ornamental, Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | @@ -526,7 +526,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (ten generated in code including Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (eleven generated in code including Ornamental, Tech Circuit, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | @@ -578,7 +578,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries ten (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries eleven (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Ornamental, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -1146,7 +1146,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **The Symbols and Properties panels find selected symbol instances once per revision:** whether the selection or its groups hold a symbol instance (Break Link to Symbol), one with appearance changes of its own (Reset Symbol Instance and the Properties panel's Reset), or one Reset Transformation would change is worked out in one walk of the selected objects for each document revision, and later frames reuse it. The buttons and menu items are enabled as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per frame; the first read after a change now takes about 3 ms and later frames about 5 ns (Linux, opt-level 3, median of 7 runs). In a small document the difference is too small to notice. Tests: `panels::symbols::tests::instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection`, `properties_and_symbols_panels_walk_the_selection_once_per_revision`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. + - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Ornamental, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). - **Bristle strokes follow recorded pen input** ([brush documentation](https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=201)): a Bristle brush in VectorCraft widens its strand spread and thickness with pressure along the stroke; pen tilt changes the spread, and bearing and barrel rotation turn it in the path's local frame. Missing pen channels use neutral values, and mouse strokes keep their existing appearance. This is VectorCraft's own rendering model; hardware-specific output has not been verified. `bristle_pen_pressure_changes_its_footprint`, `bristle_pen_pressure_is_sampled_along_the_stroke`, `trimmed_bristle_strands_read_pressure_where_they_begin` and `bristle_pen_orientation_changes_its_footprint` cover the geometry in `crates/brush/src/tests.rs`; `bristle_path_keeps_and_draws_its_pen_pose` covers saving and export in `crates/engine/src/tests/brushsym.rs`; area scores unchanged. - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. From da0e39289a61d63cd5ec6a5673b8c5fc881a06c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 06:25:29 -0800 Subject: [PATCH 38/69] Command Palette: a pick of a dimmed result runs nothing With no document open, the Asset Export commands are listed dimmed, but a pick of one still opened the Asset Export panel. A pick of any result that is drawn dimmed now leaves everything as it is, and the status line says why the command can't run, as the row does. --- crates/ui-egui/src/palette.rs | 37 ++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index cd740dbcb9..8130493277 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -418,9 +418,9 @@ fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec { /// Runs the palette result `id`: selects a tool, or invokes a command with the params its entry /// stands for. A command whose menu bar item gives params runs what a click on that item runs /// ([`crate::shortcut_editor::menu_target_now`]), so Clean Up… and Find and Replace… open their -/// dialogs. While that item is dimmed, no dialog opens and the status line says why the command -/// can't run. A panel's result shows the panel, and an effect's result runs what its Effect menu -/// item runs ([`crate::keymap::command_of`]). +/// dialogs. While a result is dimmed ([`unavailable`]), its pick runs nothing, opens no dialog or +/// panel, and the status line says why the command can't run. A panel's result shows the panel, +/// and an effect's result runs what its Effect menu item runs ([`crate::keymap::command_of`]). pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { if let Some(tool) = id.strip_prefix("tool:") { app.select_tool(tool); @@ -435,11 +435,9 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { } } else if id.starts_with("plugin:") || id.starts_with("effect:") { let command = crate::keymap::command_of(id); - // While the Effect menu dims the item (nothing selected), no dialog opens and the status - // line says why. - if id.starts_with("effect:") - && let Some(why) = crate::shortcut_editor::dimmed(app, &command.id, &command.id) - { + // While the item is dimmed (an effect with nothing selected), no dialog opens and the + // status line says why. + if let Some(why) = crate::shortcut_editor::dimmed(app, &command.id, &command.id) { app.status(why); } else { menus::invoke(app, &command.id, command.params); @@ -448,7 +446,12 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) { match crate::shortcut_editor::menu_target_now(app, id) { Some(Ok((id, p))) => menus::invoke(app, &id, p), Some(Err(why)) => app.status(why), - None => menus::invoke(app, id, json!({})), + // A dimmed result does not run: the Asset Export commands with no document open show + // no panel. + None => match crate::shortcut_editor::dimmed(app, id, id) { + Some(why) => app.status(why), + None => menus::invoke(app, id, json!({})), + }, } } } @@ -1420,6 +1423,22 @@ mod tests { } } + /// With no document open, the Asset Export commands are dimmed, and a pick of one shows no panel + /// and says why it can't run, as the row's description does. + #[test] + fn a_dimmed_asset_export_command_does_not_open_its_panel() { + let ids = ["assets.export", "assets.remove", "assets.rename", "assets.settings.set", "assets.export3D", "assets.set3DFormat"]; + for id in ids { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let why = unavailable(&app, id, id); + assert!(why.is_some(), "{id} is dimmed with no document open"); + app.ui.status.clear(); + run_pick(&mut app, id); + assert!(!crate::panel_docking::showing(&app.ui, crate::panels::asset_export::ID), "{id}: {}", app.ui.status); + assert_eq!(Some(app.ui.status.clone()), why, "{id}"); + } + } + /// The open dialog's kind and fields, the active document's undo depth and the status line. type Outcome = (Option<(String, serde_json::Map)>, Option, String); From 3056ebe9f9b88603179e8db20c89e476d09164b3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 13:34:55 -0800 Subject: [PATCH 39/69] i18n: Inflate's refusal of graphics on a side is translated The refusal "Inflate maps graphics onto its front and back, not onto a side" gets an @msg row in each of the 24 complete-message catalogs, next to the Revolve row, so three_d_refusals_are_translated_in_every_complete_catalog passes. --- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 24 files changed, 24 insertions(+) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 604bbb9028..bd34511544 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6755,6 +6755,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` ha de ser una matriu @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió, Revolució i Infla @msg Revolve maps graphics onto its side: map them onto the front Revoluciona aplica els gràfics al seu lateral: aplica’ls a la cara davantera +@msg Inflate maps graphics onto its front and back, not onto a side Infla aplica els gràfics a la cara davantera i a la posterior, no a un lateral @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on l’objecte {_1}: la cara posterior d’Infla només admet gràfics amb Tots dos costats i Tapa activats @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Els gràfics són massa complexos per a aquesta superfície: simplifica la il·lustració dels símbols o redueix Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admet com a màxim {MAX_GRAPHICS} gràfics diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 941b4da68a..538575924b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6550,6 +6550,7 @@ mark-style Japanese Japonské @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musí být pole @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafika se mapuje na typy objektu Rovina, Vysunutí, Rotační těleso a Nafouknutí @msg Revolve maps graphics onto its side: map them onto the front Rotační těleso mapuje grafiku na svůj bok: umístěte ji na přední stranu +@msg Inflate maps graphics onto its front and back, not onto a side Nafouknutí mapuje grafiku na přední a zadní stranu, ne na bok @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objekt {_1}: zadní strana Nafouknutí přijímá grafiku jen se zapnutými volbami Obě strany a Uzávěr @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafika je pro tento povrch příliš složitá: zjednodušte kresbu symbolů nebo snižte Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` přijímá nejvýše {MAX_GRAPHICS} grafik diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 789dcc430f..9f03515356 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -438,6 +438,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` skal være et array @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafik kortlægges på objekttyperne Plan, Ekstrudér, Omdrej og Pust op @msg Revolve maps graphics onto its side: map them onto the front Omdrej kortlægger grafik på siden: kortlæg den på forsiden +@msg Inflate maps graphics onto its front and back, not onto a side Pust op kortlægger grafik på forsiden og bagsiden, ikke på en side @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objektet {_1}: bagsiden af Pust op tager kun imod grafik, når Begge sider og Kappe er slået til @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikken er for kompleks til denne overflade: forenkl symbolernes grafik, eller reducér Segmenter @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tager højst {MAX_GRAPHICS} grafikelementer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index b0d5cff68c..7ff48b2d14 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -6118,6 +6118,7 @@ lighting Light Licht @msg `{GRAPHICS}` must be an array `{GRAPHICS}` muss ein Array sein @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiken werden auf die Objekttypen Ebene, Extrudieren, Kreiseln und Aufblasen abgebildet @msg Revolve maps graphics onto its side: map them onto the front Kreiseln bildet Grafiken auf seiner Mantelfläche ab: Bilden Sie sie auf der Vorderseite ab +@msg Inflate maps graphics onto its front and back, not onto a side Aufblasen bildet Grafiken auf der Vorder- und Rückseite ab, nicht auf einer Seitenfläche @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on Objekt {_1}: Die Rückseite von „Aufblasen“ nimmt Grafiken nur mit aktivierten Optionen „Beidseitig“ und „Deckflächen“ auf @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Die Grafiken sind für diese Oberfläche zu komplex: Vereinfachen Sie das Bildmaterial der Symbole oder verringern Sie Segmente @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` nimmt höchstens {MAX_GRAPHICS} Grafiken auf diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 0166d82d30..e97c2cee65 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5938,6 +5938,7 @@ variable-list-end {0}, {1} {0} και {1} @msg `{GRAPHICS}` must be an array το `{GRAPHICS}` πρέπει να είναι πίνακας @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση, Περιστροφή γύρω από άξονα και Φούσκωμα @msg Revolve maps graphics onto its side: map them onto the front Η Περιστροφή γύρω από άξονα αντιστοιχίζει τα γραφικά στην πλευρική της επιφάνεια: αντιστοιχίστε τα στην μπροστινή όψη +@msg Inflate maps graphics onto its front and back, not onto a side Το Φούσκωμα αντιστοιχίζει τα γραφικά στην μπροστινή και την πίσω όψη, όχι σε πλευρική επιφάνεια @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on το αντικείμενο {_1}: η πίσω όψη του Φουσκώματος δέχεται γραφικά μόνο με ενεργά τα Και οι δύο πλευρές και Κλείσιμο άκρου @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Τα γραφικά είναι πολύ σύνθετα για αυτή την επιφάνεια: απλοποιήστε το σχέδιο των συμβόλων ή μειώστε τα Τμήματα @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics το `{GRAPHICS}` δέχεται το πολύ {MAX_GRAPHICS} γραφικά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d52a76a65d..62578b6492 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6523,6 +6523,7 @@ mark-style Japanese Japonesas @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión, Revolución e Inflar Graphics map onto the Plane, Extrude, Revolve and Inflate object types. Los gráficos se asignan a los tipos de objeto Plano, Extrusión, Revolución e Inflar. @msg Revolve maps graphics onto its side: map them onto the front Revolución asigna los gráficos a su lateral: asígnelos a la cara frontal +@msg Inflate maps graphics onto its front and back, not onto a side Inflar asigna los gráficos a la cara frontal y a la posterior, no a un lateral @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on el objeto {_1}: la cara posterior de Inflar admite gráficos solo con Ambos lados y Tapa activados @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Los gráficos son demasiado complejos para esta superficie: simplifique la ilustración de los símbolos o reduzca Segmentos @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` admite como máximo {MAX_GRAPHICS} gráficos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index c04fbd953c..395ba3d006 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6455,6 +6455,7 @@ mark-style Japanese Japanilainen @msg `{GRAPHICS}` must be an array `{GRAPHICS}` on oltava taulukko @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiikat sijoitetaan objektityypeille Taso, Pursota, Pyöräytä ja Täytä ilmalla @msg Revolve maps graphics onto its side: map them onto the front Pyöräytä sijoittaa grafiikat kylkeensä: sijoita ne etupuolelle +@msg Inflate maps graphics onto its front and back, not onto a side Täytä ilmalla sijoittaa grafiikat etu- ja takapuolelle, ei kylkeen @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objekti {_1}: Täytä ilmalla -tehosteen takapuoli ottaa grafiikoita vain, kun Molemmat puolet ja Pääty ovat käytössä @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiikat ovat liian monimutkaisia tälle pinnalle: yksinkertaista symbolien kuvitusta tai pienennä Segmentit-arvoa @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` hyväksyy enintään {MAX_GRAPHICS} grafiikkaa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 01e15553dd..1dad86223b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6118,6 +6118,7 @@ lighting Light Lumière @msg `{GRAPHICS}` must be an array `{GRAPHICS}` doit être un tableau @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Les graphiques s’appliquent aux types d’objet Plan, Extrusion, Révolution et Gonfler @msg Revolve maps graphics onto its side: map them onto the front Révolution applique les graphiques sur sa face latérale : appliquez-les sur la face avant +@msg Inflate maps graphics onto its front and back, not onto a side Gonfler applique les graphiques sur la face avant et l’arrière, pas sur une face latérale @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objet {_1} : l’arrière de Gonfler n’accepte des graphiques qu’avec Deux côtés et Fermeture activés @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Les graphiques sont trop complexes pour cette surface : simplifiez l’illustration des symboles ou réduisez Segments @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accepte au plus {MAX_GRAPHICS} graphiques diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 36bfd90eb2..9d26d3b333 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8647,6 +8647,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` एक ऐरे होना चाहिए @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types ग्राफ़िक्स समतल, एक्सट्रूड, रिवॉल्व और फुलाएँ ऑब्जेक्ट प्रकारों पर लगते हैं @msg Revolve maps graphics onto its side: map them onto the front रिवॉल्व ग्राफ़िक्स को अपनी बगल वाली सतह पर लगाता है: उन्हें सामने वाले फ़ेस पर लगाएँ +@msg Inflate maps graphics onto its front and back, not onto a side फुलाएँ ग्राफ़िक्स को सामने और पिछले फ़ेस पर लगाता है, बगल वाली सतह पर नहीं @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on ऑब्जेक्ट {_1}: फुलाएँ का पिछला फ़ेस ग्राफ़िक्स तभी लेता है जब दोनों तरफ़ और कैप चालू हों @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments ग्राफ़िक्स इस सतह के लिए बहुत जटिल हैं: सिंबल्स के आर्ट को सरल बनाएँ या सेगमेंट कम करें @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` अधिकतम {MAX_GRAPHICS} ग्राफ़िक्स लेता है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 798ca1697d..61d314847b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6534,6 +6534,7 @@ variable-list-end {0}, {1} {0} és {1} @msg `{GRAPHICS}` must be an array a `{GRAPHICS}` értéke tömb kell legyen @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types A grafikák a Sík, a Kihúzás, a Forgatás tengely körül és a Felfújás objektumtípusra kerülnek @msg Revolve maps graphics onto its side: map them onto the front A Forgatás tengely körül a grafikákat a palástjára helyezi: az elülső oldalra helyezze őket +@msg Inflate maps graphics onto its front and back, not onto a side A Felfújás a grafikákat az elülső és a hátoldalra helyezi, nem az oldalára @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on {_1} objektum: a Felfújás hátoldala csak a Mindkét oldal és a Zárólap bekapcsolásával fogad grafikát @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments A grafikák túl összetettek ehhez a felülethez: egyszerűsítse a szimbólumok rajzát, vagy csökkentse a Szakaszok értékét @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics a `{GRAPHICS}` legfeljebb {MAX_GRAPHICS} grafikát fogad diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1483c97f4a..698bc5d21c 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -6165,6 +6165,7 @@ lighting Light Luce @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve essere un array @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Le grafiche si applicano ai tipi di oggetto Piano, Estrusione, Rivoluzione e Gonfia @msg Revolve maps graphics onto its side: map them onto the front Rivoluzione applica le grafiche sul suo lato: applicatele sulla faccia anteriore +@msg Inflate maps graphics onto its front and back, not onto a side Gonfia applica le grafiche sulla faccia anteriore e sul retro, non su un lato @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on oggetto {_1}: il retro di Gonfia accetta grafiche solo con Entrambi i lati e Chiusura attivi @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Le grafiche sono troppo complesse per questa superficie: semplificate il disegno dei simboli o riducete Segmenti @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` accetta al massimo {MAX_GRAPHICS} grafiche diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index d4abe69ee5..35f58aa08f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -6215,6 +6215,7 @@ lighting Light ライト @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types グラフィックはオブジェクトの種類が平面、押し出し、回転体、膨張のときにマッピングされます Graphics map onto the Plane, Extrude, Revolve and Inflate object types. グラフィックはオブジェクトの種類が平面、押し出し、回転体、膨張のときにマッピングされます。 @msg Revolve maps graphics onto its side: map them onto the front 回転体はグラフィックを側面にマッピングします。前面にマッピングしてください +@msg Inflate maps graphics onto its front and back, not onto a side 膨張はグラフィックを前面と背面にマッピングします。側面にはマッピングできません @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on オブジェクト {_1}: 「膨張」の背面にグラフィックをマッピングするには「両面」と「キャップ」をオンにしてください @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments グラフィックがこのサーフェスには複雑すぎます。シンボルのアートを単純化するか、分割数を減らしてください @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` に指定できるグラフィックは {MAX_GRAPHICS} 個までです diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d03d46435f..f747fddad7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7902,6 +7902,7 @@ font-technology Variable ცვლადი @msg `{GRAPHICS}` must be an array `{GRAPHICS}` უნდა იყოს მასივი @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“, „ბრუნვა“ და „გაბერვა“ @msg Revolve maps graphics onto its side: map them onto the front ბრუნვა გრაფიკას თავის გვერდით ზედაპირზე ათავსებს: განათავსეთ ისინი წინა მხარეზე +@msg Inflate maps graphics onto its front and back, not onto a side გაბერვა გრაფიკას წინა და უკანა მხარეზე ათავსებს და არა გვერდით ზედაპირზე @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on ობიექტი {_1}: გაბერვის უკანა მხარე გრაფიკას იღებს მხოლოდ ჩართული „ორივე მხარე“ და „თავსახური“ პარამეტრებით @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments გრაფიკა ზედმეტად რთულია ამ ზედაპირისთვის: გაამარტივეთ სიმბოლოების ნახატი ან შეამცირეთ სეგმენტები @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` იღებს მაქსიმუმ {MAX_GRAPHICS} გრაფიკას diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 363de4c969..637a06d4c3 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -6135,6 +6135,7 @@ lighting Light 광원 @msg `{GRAPHICS}` must be an array `{GRAPHICS}`은(는) 배열이어야 합니다 @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 그래픽은 평면, 돌출, 회전체, 부풀리기 개체 유형에 매핑됩니다 @msg Revolve maps graphics onto its side: map them onto the front 회전체는 그래픽을 옆면에 매핑합니다. 앞면에 매핑하십시오 +@msg Inflate maps graphics onto its front and back, not onto a side 부풀리기는 그래픽을 앞면과 뒷면에 매핑하며 옆면에는 매핑하지 않습니다 @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on 개체 {_1}: 부풀리기의 뒷면에 그래픽을 매핑하려면 양면과 캡을 켜세요 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 그래픽이 이 표면에 비해 너무 복잡합니다. 심볼의 아트를 단순화하거나 세그먼트를 줄이십시오 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}`에는 그래픽을 최대 {MAX_GRAPHICS}개까지 넣을 수 있습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b13e066e49..68377c6b2d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -8306,6 +8306,7 @@ mark-style Japanese Japans @msg Graphics map onto planar faces: use the Extrude or Plane object type Illustraties worden op platte vlakken geplaatst: gebruik het objecttype Extruderen of Vlak @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Illustraties worden op de objecttypen Vlak, Extruderen, Draaien en Opblazen geplaatst @msg Revolve maps graphics onto its side: map them onto the front Draaien plaatst illustraties op de zijkant: plaats ze op de voorkant +@msg Inflate maps graphics onto its front and back, not onto a side Opblazen plaatst illustraties op de voorkant en de achterkant, niet op een zijkant @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on object {_1}: de achterkant van Opblazen neemt alleen afbeeldingen aan met Beide zijden en Dop ingeschakeld @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments De illustraties zijn te complex voor dit oppervlak: vereenvoudig de illustraties van de symbolen of verlaag Segmenten @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` neemt maximaal {MAX_GRAPHICS} illustraties op diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 4d5c25d727..97f6a8151e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6374,6 +6374,7 @@ mark-style Japanese Japońskie @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musi być tablicą @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiki są nakładane na obiekty typu Płaszczyzna, Wyciągnięcie, Obrót i Nadmuchanie @msg Revolve maps graphics onto its side: map them onto the front Obrót nakłada grafiki na swoją powierzchnię boczną: umieść je na przedniej stronie +@msg Inflate maps graphics onto its front and back, not onto a side Nadmuchanie nakłada grafiki na przednią i tylną stronę, a nie na powierzchnię boczną @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on obiekt {_1}: tył Nadmuchania przyjmuje grafiki tylko przy włączonych opcjach Obie strony i Zakończenie @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiki są zbyt złożone dla tej powierzchni: uprość kompozycje symboli lub zmniejsz Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` przyjmuje najwyżej {MAX_GRAPHICS} grafik diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4aba908498..fe75a942a8 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6500,6 +6500,7 @@ mark-style Japanese Japonesas @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve ser uma matriz @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Os gráficos são mapeados nos tipos de objeto Plano, Extrusão, Revolver e Inflar @msg Revolve maps graphics onto its side: map them onto the front Revolver mapeia os gráficos na sua lateral: mapeie-os na face frontal +@msg Inflate maps graphics onto its front and back, not onto a side Inflar mapeia os gráficos na face frontal e no verso, não em uma lateral @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objeto {_1}: o verso de Inflar recebe gráficos apenas com Ambos os Lados e Tampa ativados @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Os gráficos são complexos demais para esta superfície: simplifique a arte dos símbolos ou reduza Segmentos @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` aceita no máximo {MAX_GRAPHICS} gráficos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2e236f1827..79219217e3 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6162,6 +6162,7 @@ lighting Light Свет @msg `{GRAPHICS}` must be an array `{GRAPHICS}` должен быть массивом @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графика наносится на объекты типов «Плоскость», «Выдавливание», «Вращение» и «Надувание» @msg Revolve maps graphics onto its side: map them onto the front «Вращение» наносит графику на свою боковую поверхность: размещайте её на передней стороне +@msg Inflate maps graphics onto its front and back, not onto a side «Надувание» наносит графику на переднюю и заднюю стороны, а не на боковую поверхность @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on объект {_1}: задняя сторона «Надувания» принимает графику только при включённых параметрах «С обеих сторон» и «Торцы» @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графика слишком сложна для этой поверхности: упростите иллюстрации символов или уменьшите «Сегменты» @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` принимает не более {MAX_GRAPHICS} графических элементов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 0a0ebced8f..d4d8354258 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6036,6 +6036,7 @@ lighting Light Ljus @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafik placeras på objekttyperna Plan, Extrudera, Rotera runt axel och Blås upp Graphics map onto the Plane, Extrude, Revolve and Inflate object types. Grafik placeras på objekttyperna Plan, Extrudera, Rotera runt axel och Blås upp. @msg Revolve maps graphics onto its side: map them onto the front Rotera runt axel placerar grafik på sin mantelyta: placera den på framsidan +@msg Inflate maps graphics onto its front and back, not onto a side Blås upp placerar grafik på framsidan och baksidan, inte på en sida @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on objekt {_1}: baksidan av Blås upp tar emot grafik bara när Båda sidor och Lock är på @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiken är för komplex för den här ytan: förenkla symbolernas teckning eller minska Segment @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` tar högst {MAX_GRAPHICS} grafiker diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d5e33ac203..a059b476eb 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5860,6 +5860,7 @@ lighting Light Işık @msg `{GRAPHICS}` must be an array `{GRAPHICS}` bir dizi olmalıdır @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafikler Düzlem, Ekstrüzyon, Eksen Etrafında Döndür ve Şişir nesne türlerine eşlenir @msg Revolve maps graphics onto its side: map them onto the front Eksen Etrafında Döndür grafikleri yan yüzeyine eşler: onları ön yüze eşle +@msg Inflate maps graphics onto its front and back, not onto a side Şişir grafikleri ön ve arka yüze eşler, yan yüze eşlemez @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on nesne {_1}: Şişir efektinin arka yüzü yalnızca Her iki taraf ve Kapak açıkken grafik alır @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafikler bu yüzey için çok karmaşık: sembollerin resmini basitleştir veya Segmentler değerini azalt @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` en fazla {MAX_GRAPHICS} grafik alır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index bfc0e4bb75..229f71a8de 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -6145,6 +6145,7 @@ lighting Light Світло @msg `{GRAPHICS}` must be an array `{GRAPHICS}` має бути масивом @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графіка наноситься на об’єкти типів «Площина», «Видавлювання», «Обертання» та «Надування» @msg Revolve maps graphics onto its side: map them onto the front «Обертання» наносить графіку на свою бічну поверхню: розміщуйте її на передній стороні +@msg Inflate maps graphics onto its front and back, not onto a side «Надування» наносить графіку на передній і задній боки, а не на бічну поверхню @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on об’єкт {_1}: задній бік «Надування» приймає графіку лише з увімкненими параметрами «З обох боків» і «Торці» @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Графіка надто складна для цієї поверхні: спростіть ілюстрації символів або зменште «Сегменти» @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` приймає не більше {MAX_GRAPHICS} графічних елементів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5b84157a6c..3e08dddb09 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5958,6 +5958,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` phải là một mảng @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Đồ họa được đặt lên các loại đối tượng Mặt phẳng, Kéo dài, Xoay tròn và Phình @msg Revolve maps graphics onto its side: map them onto the front Xoay tròn đặt đồ họa lên mặt bên của nó: hãy đặt chúng lên mặt trước +@msg Inflate maps graphics onto its front and back, not onto a side Phình đặt đồ họa lên mặt trước và mặt sau, không đặt lên mặt bên @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on đối tượng {_1}: mặt sau của Phình chỉ nhận đồ họa khi bật Cả hai mặt và Nắp @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Đồ họa quá phức tạp cho bề mặt này: hãy đơn giản hóa hình vẽ của các ký hiệu hoặc giảm Đoạn @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` nhận tối đa {MAX_GRAPHICS} đồ họa diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index d28e8a698f..24ebfbae21 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6416,6 +6416,7 @@ lighting Light 光源 @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 图形映射到平面、突出、回转和膨胀对象类型上 Graphics map onto the Plane, Extrude, Revolve and Inflate object types. 图形映射到平面、突出、回转和膨胀对象类型上。 @msg Revolve maps graphics onto its side: map them onto the front 回转将图形映射到其侧面:请将图形映射到正面 +@msg Inflate maps graphics onto its front and back, not onto a side 膨胀将图形映射到正面和背面,不映射到侧面 @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on 对象 {_1}:只有打开“双面”和“封口”后,膨胀的背面才能贴图 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 图形对此表面过于复杂:请简化符号的图稿或减少分段数 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` 最多接受 {MAX_GRAPHICS} 个图形 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9627f43344..4f8cea925c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -6264,6 +6264,7 @@ lighting Light 光源 @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 圖形會對應到「平面」、「突出」、「迴轉」與「膨脹」物件類型 Graphics map onto the Plane, Extrude, Revolve and Inflate object types. 圖形會對應到「平面」、「突出」、「迴轉」與「膨脹」物件類型。 @msg Revolve maps graphics onto its side: map them onto the front 迴轉會將圖形對應到其側面:請將圖形對應到正面 +@msg Inflate maps graphics onto its front and back, not onto a side 膨脹會將圖形對應到正面和背面,不會對應到側面 @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on 物件 {_1}:只有開啟「雙面」和「封口」後,膨脹的背面才能對應圖形 @msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments 圖形對此表面過於複雜:請簡化符號的圖稿或減少分段數 @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` 最多接受 {MAX_GRAPHICS} 個圖形 From 591480d33ba2f575fc583378b7732cc5fb23c04d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 14:08:12 -0800 Subject: [PATCH 40/69] Command Palette: Enter runs the query typed in its frame, and Paste is dimmed with no document - Text typed into the search field in the frame that presses Enter changed the query after the results were listed, so Enter ran the old list's highlighted result (on an empty search, the last pick). Enter now runs the first result of the query as typed. - `menus::why_off` treated Paste as enabled while the system clipboard read as pasteable, also with no document open, until the next clipboard check. The override now needs an open document, and the engine's reason shows. - `a_result_that_cannot_run_now_is_dimmed_and_says_why` looks up the row's color by the name the row draws (without its menu path). `paste_is_dimmed_only_while_nothing_can_be_pasted` finds the Paste row by its full screen-reader label. `screen_readers_hear_the_kind_and_home` checks the first line of the field's description, since Round Corners can't run with no document and its reason goes on a second line. --- crates/ui-egui/src/menus/state.rs | 5 ++- crates/ui-egui/src/palette.rs | 68 ++++++++++++++++++++++++++----- 2 files changed, 60 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 52dda32983..de8920443b 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -226,8 +226,9 @@ pub(crate) fn why_off(app: &VectorcraftApp, id: &str) -> Option> if let Some(c) = vectorcraft_engine::find_command(id) { return match (c.enabled)(&app.session) { Ok(()) => None, - // The system clipboard's contents can be pasted with an empty internal clipboard. - Err(_) if app.system_paste && id.starts_with("edit.paste") => None, + // The system clipboard's contents can be pasted into an open document with an empty + // internal clipboard. + Err(_) if app.system_paste && app.session.active().is_some() && id.starts_with("edit.paste") => None, Err(why) => Some(Some(why)), }; } diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 4645a86c02..41e999db98 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1566,12 +1566,20 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); }); - if !list_open - && !history_focused - && ui.input(|i| i.key_pressed(egui::Key::Enter)) - && let Some(e) = matches.get(sel) - { - run = Some(e.id.clone()); + if !list_open && !history_focused && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + // Text typed in the frame that pressed Enter changed the query after the results + // were listed: Enter runs the first result of the new query. + let typed = app.ui.palette_query.to_lowercase(); + let picked = if typed == q { + matches.get(sel).copied() + } else if typed.trim().is_empty() { + recent.first().copied() + } else { + matching(&entries, &typed, &app.ui.recent_commands, &app.ui.command_uses).first().copied() + }; + if let Some(e) = picked { + run = Some(e.id.clone()); + } } }); }); @@ -2458,6 +2466,25 @@ mod tests { assert_eq!(open.app.ui.recent_commands, ["paint.swap", "object.group"]); } + /// Text typed into an empty search in the frame that presses Enter runs the first result of the + /// new query, not the last pick the empty search listed. + #[test] + fn enter_with_text_typed_in_its_frame_runs_the_new_querys_first_result() { + let mut open = Open::new("", WINDOW); + open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + open.app.ui.recent_commands = vec!["paint.swap".into()]; + open.app.ui.palette_open = true; + open.frame(vec![]); + open.frame(vec![]); + let entries = entries(&open.ctx, Lang::EN); + let first = super::matching(&entries, "select all", &open.app.ui.recent_commands, &open.app.ui.command_uses)[0].id.clone(); + assert_ne!(first, "paint.swap"); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + open.frame(vec![egui::Event::Text("select all".into()), enter]); + assert!(!open.app.ui.palette_open, "the palette closes"); + assert_eq!(open.app.ui.recent_commands.first(), Some(&first), "{}", open.app.ui.status); + } + /// The palette opens again with its first row highlighted, even when it shows the same rows. #[test] fn the_palette_opens_again_with_its_first_row_highlighted() { @@ -3558,7 +3585,8 @@ mod tests { assert_eq!(said, "Effect, Round Corners…, Effect › Stylize"); let row = rows(&nodes).into_iter().find(|r| r.0 == said).expect("its row is drawn"); assert!((row.3 - row.2 - f64::from(ROW_HEIGHT)).abs() < 0.01, "{row:?}"); - assert!(field_description(&nodes).ends_with(&said), "{}", field_description(&nodes)); + // With no document, Round Corners can't run now, and the reason goes on a second line. + assert!(field_place(&nodes).ends_with(&said), "{}", field_description(&nodes)); let open = Open::new("group selection", WINDOW); assert_eq!(open.said("tool:groupSelection"), "Tool, Group Selection Tool, Toolbar, in the Direct Selection Tool group"); let mut open = Open::new("layers", WINDOW); @@ -3657,7 +3685,8 @@ mod tests { assert!(ungroup.is_disabled(), "{ungroup:?}"); assert_eq!(ungroup.description(), Some(why.as_str())); let t = Tokens::get(&open.ctx); - assert_eq!(open.color_of(&entry.shown), Some(t.text_disabled), "the name is drawn dimmed"); + // The row draws the name without the menu path its home shows. + assert_eq!(open.color_of(label_of(entry)), Some(t.text_disabled), "the name is drawn dimmed"); let footer_says = |nodes: &[egui::accesskit::Node]| labels(nodes).contains(&why); assert!(footer_says(&nodes), "{:?}", labels(&nodes)); // The arrow keys leave screen readers on the search field, so its description says why too. @@ -3669,7 +3698,7 @@ mod tests { let nodes = open.frame(vec![]); let ungroup = row_named(&nodes, &name); assert!(!ungroup.is_disabled() && ungroup.description().is_none(), "{ungroup:?}"); - assert_eq!(open.color_of(&entry.shown), Some(t.text)); + assert_eq!(open.color_of(label_of(entry)), Some(t.text)); assert!(!footer_says(&nodes), "{:?}", labels(&nodes)); assert_eq!(field_description(&nodes), place); // Whether a result can run never moves it. @@ -3859,13 +3888,30 @@ mod tests { fn paste_is_dimmed_only_while_nothing_can_be_pasted() { let mut open = open_on("paste", vectorcraft_testkit::fixtures::Fixture::Multi.session()); open.app.system_paste = false; + let name = open.said("edit.paste"); let nodes = open.frame(vec![]); - let paste = row_named(&nodes, "Edit › Paste"); + let paste = row_named(&nodes, &name); assert!(paste.is_disabled(), "{paste:?}"); assert_eq!(paste.description(), Some("command `Edit › Paste` is not available right now: clipboard is empty")); open.app.system_paste = true; let nodes = open.frame(vec![]); - assert!(!row_named(&nodes, "Edit › Paste").is_disabled()); + assert!(!row_named(&nodes, &name).is_disabled()); + } + + /// With no document open, Paste is dimmed with the engine's reason, though the system + /// clipboard still reads as pasteable until its next check. + #[test] + fn paste_is_dimmed_with_no_document_open() { + let mut open = open_on("paste", vectorcraft_engine::Session::new()); + open.app.system_paste = true; + let name = open.said("edit.paste"); + let nodes = open.frame(vec![]); + let paste = row_named(&nodes, &name); + assert!(paste.is_disabled(), "{paste:?}"); + let reason = (vectorcraft_engine::find_command("edit.paste").unwrap().enabled)(&open.app.session).unwrap_err(); + let why = format!("command `Edit › Paste` is not available right now: {reason}"); + assert_eq!(paste.description(), Some(why.as_str())); + assert!(!menus::enabled(&open.app, "edit.paste")); } /// A tool can always be chosen; a panel can't be shown in Presentation Mode, and says so. From 51da82254161e449474da1de36c070672cebe19c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 14:42:09 -0800 Subject: [PATCH 41/69] Brushes: Filigree Arrow's shaft runs into its head with no gap The shaft ended at x = 84 while the head's inner edge starts at about x = 84.5 at the shaft's edges and x = 85 on its center line, so a straight stroke drew a gap between them. The shaft now ends at x = 86, overlapping the head without moving the tip. --- crates/engine/src/cmd/brushlib.rs | 3 ++- crates/engine/src/tests/brushlib.rs | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 8f72e64676..7eb1af3dba 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -529,7 +529,8 @@ fn ornamental() -> BrushLibrary { black(polygon(&[(60.0, 3.0), (66.0, 5.0), (72.0, -1.0), (67.0, -2.0)])), ]); let arrow = group(vec![ - black(shapes::rectangle(Rect::new(4.0, -0.7, 84.0, 0.7))), + // The shaft runs into the head's notch at x = 85 so the two overlap. + black(shapes::rectangle(Rect::new(4.0, -0.7, 86.0, 0.7))), black(polygon(&[(80.0, -6.5), (100.0, 0.0), (80.0, 6.5), (85.0, 0.0)])), ring(Point::new(7.0, 0.0), 4.0, 1.7), black(polygon(&[(25.0, -0.4), (31.0, -4.4), (37.0, -2.0), (31.0, 0.8)])), diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index aecce4717a..9b57a22bb0 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -334,6 +334,26 @@ fn ornamental_brushes_draw_flourishes_and_survive_a_saved_library() { assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } +/// Filigree Arrow's shaft runs into its head with no gap, so a straight stroke draws one arrow. +#[test] +fn the_filigree_arrow_shaft_meets_its_head() { + let s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Ornamental").unwrap(); + let BrushKind::Art(art) = &lib.brush("Filigree Arrow").unwrap().kind else { panic!("Filigree Arrow is not an art brush") }; + let mut parts = vec![]; + art.art.walk(&mut |c| { + if c.path_data().is_some() { + parts.push(c.contains_fn()); + } + }); + for y in [-0.6, 0.0, 0.6] { + for i in 0..=930 { + let p = vectorcraft_geom::Point::new(4.05 + 0.1 * f64::from(i), y); + assert!(parts.iter().any(|inside| inside(p)), "gap at {p:?}"); + } + } +} + #[test] fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() { let mut s = session(); From 0ee9ffcd4519cfb63dd306a1dcdd60a722626587 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 15:38:51 -0800 Subject: [PATCH 42/69] Tests: "vectorize" finds the image trace commands after the labels that hold "trace" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The search ranks a result whose label holds a word of the query's group above one that holds it only in its menu path. Edit › Tracing Presets… is a third label with a form of "trace", next to Batch Trace Folder… and the Image Trace panel, so the Object › Image Trace commands now come fourth for "vectorize". The test checks that "vectorize" finds them and that only results whose label holds a form of "trace" rank above them, in place of a fixed place in the first three. --- crates/ui-egui/src/palette/search.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index 1e4f794a8f..aed70389d0 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -1380,7 +1380,12 @@ mod tests { assert_eq!(first("outline text"), "type.createOutlines"); assert!(within("flip", "object.reflect", 3), "{:?}", ranked(&c, "flip")); assert!(within("combine", "object.pathfinder.unite", 3), "{:?}", ranked(&c, "combine")); - assert!(ranked(&c, "vectorize").iter().take(3).any(|id| id.starts_with("imageTrace.")), "{:?}", ranked(&c, "vectorize")); + // "vectorize" finds the image trace commands, and only results whose label holds a form of + // "trace" rank above them. + let vectorize = ranked(&c, "vectorize"); + let traced = |id: &String| c.list.iter().any(|e| &e.id == id && split_name(&e.shown).0.to_lowercase().contains("trac")); + let traces = vectorize.iter().position(|id| id.starts_with("imageTrace.")); + assert!(traces.is_some_and(|p| vectorize.get(..p).is_some_and(|above| above.iter().all(traced))), "{vectorize:?}"); assert_eq!(first("colour"), "panel:color", "{:?}", ranked(&c, "colour")); // A word that only starts other labels is in a group, and its labels follow the direct match. assert_eq!(first("unite"), "object.pathfinder.unite"); From 5e9d4356fe277060f2d2bb2cde84499be03260a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 15:49:47 -0800 Subject: [PATCH 43/69] Rerun CI From b66e43f0486a7f12ff8fc3fccf249b2d6b38704d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:06:24 -0800 Subject: [PATCH 44/69] Shapes: Circle tool options pass the tool's own option check The Circle tool now answers Tool::check_option with the values check_options takes, so tool.setOption and the option check that runs on every tool accept the options the tool reports. - With Third Point by Dragging off, a click in reach of both placed points is on the nearer one (or the one it snapped to). - A press on the second point previews the circle on the two points that its release draws, and a press on the first point previews none. - With Anchors at Standard Positions off, the preview is the path with an anchor at each point, which the release draws. - A move of less than 2 screen points keeps the second or third point where it was pressed. - circle_with_anchors_at gives the two ends of a diameter four anchors also where rounding of the midpoint puts the second point more than half a turn from the first. - The canvas-edge test checks for an outline whether dashed or solid. - docs/mcp.md says that only anchors: "standard" draws a live ellipse. --- crates/geom/src/shapes.rs | 26 +++++++++- crates/tools/src/circle.rs | 54 ++++++++++++++++----- crates/tools/src/circle/tests.rs | 82 +++++++++++++++++++++++++++++++- docs/mcp.md | 5 +- 4 files changed, 150 insertions(+), 17 deletions(-) diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index d194fcac4e..419c2b8ddf 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -371,8 +371,9 @@ pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> { /// circle, as [`circle_through_points`] gives it) plus as many more as split each arc between two /// of them into equal parts of at most a quarter turn. The path starts at the first point and runs /// as [`ellipse`] does (left, top, right on the page); each curve's handles are 4/3·tan(θ/4) of -/// the radius along the tangents at its ends (θ, its turn). A point given twice is one anchor; -/// with no points it starts at the left, as [`ellipse`] does. +/// the radius along the tangents at its ends (θ, its turn). Two points with `center` at their +/// midpoint give four anchors. A point given twice is one anchor; with no points it starts at the +/// left, as [`ellipse`] does. pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> PathData { let quarter = PI / 2.0; let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); @@ -381,6 +382,13 @@ pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> P let mut placed: Vec<(f64, Point)> = points.iter().map(|p| ((angle(*p) - start).rem_euclid(TAU), *p)).collect(); placed.sort_by(|a, b| a.0.total_cmp(&b.0)); placed.dedup_by(|a, b| a.1 == b.1); + // Two points with the center at their midpoint are the ends of a diameter: the second is half a + // turn from the first, also where rounding moves the angle from the center off it. + if let [(_, a), (turn, b)] = placed.as_mut_slice() + && a.midpoint(*b) == center + { + *turn = PI; + } if placed.is_empty() { placed.push((0.0, Point::new(center.x - radius, center.y))); } @@ -861,6 +869,20 @@ mod tests { } } + /// The two ends of a diameter give four anchors, also where the midpoint rounds off it: at + /// x = 10⁶, steps of 2⁻³³ put the second point more than half a turn from the first, seen from + /// the rounded center. + #[test] + fn a_diameter_gives_four_anchors_where_its_midpoint_rounds() { + let u = 2f64.powi(-33); + let (a, b) = (Point::new(1_000_000.0, 0.0), Point::new(1_000_000.0 + 9.0 * u, 8.0 * u)); + let (center, radius) = circle_through_points(&[a, b]).expect("a circle"); + let path = circle_with_anchors_at(center, radius, &[a, b]); + let sub = &path.subpaths[0]; + assert_eq!(sub.anchors.len(), 4, "{sub:?}"); + assert_eq!((sub.anchors[0].p, sub.anchors[2].p), (a, b)); + } + /// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta /// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular /// bisector; a point 10⁻¹² off it does not. diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index fb19af46e0..9e08f79d49 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -205,8 +205,16 @@ impl CircleTool { fn points(&self) -> Vec { let mut out: Vec = self.first.into_iter().collect(); if let Some((b, _)) = self.second { - out.push(b); - out.extend(self.pointer); + match self.press { + // Let go where it was pressed, a press on the first point draws nothing and one on + // the second point draws the circle on the two. + Some(Press::Third { on_first: true, dragged: false, .. }) => {} + Some(Press::Third { on_second: true, dragged: false, .. }) => out.push(b), + _ => { + out.push(b); + out.extend(self.pointer); + } + } return out; } match self.press { @@ -302,9 +310,16 @@ impl Tool for CircleTool { PointerKind::Down => { if let (Some(a), Some((b, clicked))) = (self.first, self.second) { let at = self.snap.press(cx, ev.pos, &[], None); - let on = |q: Point| at == q || ev.pos.distance(q) <= cx.tol(REACH_PX); - let on_second = on(b) || ev.pos.distance(clicked) <= cx.tol(REACH_PX); - self.press = Some(Press::Third { at, from: ev.pos, on_first: on(a), on_second, dragged: false }); + let reach = cx.tol(REACH_PX); + let to_second = ev.pos.distance(b).min(ev.pos.distance(clicked)); + let (mut on_first, mut on_second) = (at == a || ev.pos.distance(a) <= reach, at == b || to_second <= reach); + // A press in reach of both points is on the one it snapped to, otherwise on the + // nearer one. + if on_first && on_second { + let first = if (at == a) != (at == b) { at == a } else { ev.pos.distance(a) < to_second }; + (on_first, on_second) = (first, !first); + } + self.press = Some(Press::Third { at, from: ev.pos, on_first, on_second, dragged: false }); self.pointer = Some(at); return vec![]; } @@ -332,17 +347,22 @@ impl Tool for CircleTool { match &mut self.press { // With `dragThird` off, the second point follows the pointer as it does before // the press. + // The point stays where it was pressed until the press is a drag. Some(Press::Second { at, snapped, from, on_first: false, dragged }) if !drag_third => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); - let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift)); - *snapped = self.snap.drag(cx, ev.pos, leave.as_ref()); - *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods)); - self.pointer = Some(*at); + if *dragged { + let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift)); + *snapped = self.snap.drag(cx, ev.pos, leave.as_ref()); + *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods)); + self.pointer = Some(*at); + } } Some(Press::Third { at, from, dragged, .. }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); - *at = self.snap.drag(cx, ev.pos, None); - self.pointer = Some(*at); + if *dragged { + *at = self.snap.drag(cx, ev.pos, None); + self.pointer = Some(*at); + } } Some(Press::First { at, from, dragged }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); @@ -443,7 +463,12 @@ impl Tool for CircleTool { let points = self.points(); let color = crate::draw2::FEEDBACK; if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) { - let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); + // The path the release draws: with `standardAnchors` off, the one with an anchor at each point. + let path = if self.options.standard_anchors { + shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath() + } else { + shapes::circle_with_anchors_at(c, r, &points).to_bezpath() + }; // The canvas draws a dashed outline dash by dash along its whole length: a circle longer // than DASHED_PX on screen is drawn solid instead. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); @@ -489,6 +514,11 @@ impl Tool for CircleTool { }) } + /// Takes the values [`check_options`] takes. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + check_options(&Map::from_iter([(key.to_string(), value.clone())])) + } + /// Sets one option; a value the option does not take leaves it as it was. Switching /// `dragThird` drops the points placed so far. fn set_option(&mut self, key: &str, value: &Value) { diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index 40be85c4e7..e526f044a5 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -162,6 +162,25 @@ fn anchors_at_the_points_asks_for_them() { assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]); } +/// With `standardAnchors` off, the tool shows the path with an anchor at each point, the one its +/// release draws. +#[test] +fn anchors_at_the_points_show_the_path_they_draw() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (310.0, 340.0), Mods::default())); + let points = [Point::new(300.0, 300.0), Point::new(380.0, 300.0), Point::new(310.0, 340.0)]; + let (c, r) = circle_of(&points).expect("a circle"); + let want = shapes::circle_with_anchors_at(c, r, &points).to_bezpath(); + let o = t.overlays(&cx); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { path, .. } if *path == want)), "{o:?}"); +} + /// With `standardAnchors` off, a circle within 1 pt of the canvas edge whose path with anchors at /// the points curves past that edge is not shown and not drawn; with standard anchors it is. #[test] @@ -180,10 +199,67 @@ fn anchors_at_the_points_keep_the_path_on_the_canvas() { click(&mut t, &cx, points[0]); t.pointer(&cx, &ev(PointerKind::Down, points[1], Mods::default())); t.pointer(&cx, &ev(PointerKind::Drag, points[2], Mods::default())); - assert_eq!(preview(&t.overlays(&cx)), None); + // No outline at all: at this size the tool would draw it solid, not dashed. + let o = t.overlays(&cx); + assert!(!o.iter().any(|o| matches!(o, Overlay::Path { .. })), "{o:?}"); assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, points[2], Mods::default())), vec![]); } +/// With `dragThird` off, a click in reach of both placed points is on the nearer one: nearer the +/// first point it places nothing, nearer the second it draws the circle on the two. +#[test] +fn with_third_point_by_dragging_off_a_click_near_both_points_takes_the_nearer() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(click(&mut t, &cx, (104.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (101.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (103.0, 100.0)), circle(&[(100.0, 100.0), (104.0, 100.0)])); +} + +/// With `dragThird` off, a press on the second point shows the circle on the two points, which its +/// release draws, and a press on the first point shows none. +#[test] +fn with_third_point_by_dragging_off_a_press_shows_the_circle_its_release_draws() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + click(&mut t, &cx, (200.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (101.0, 101.0), Mods::default())); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.0, 101.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(PointerKind::Down, (202.0, 101.0), Mods::default())); + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(100.0, 50.0, 200.0, 150.0)), "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (202.0, 101.0), Mods::default())), circle(&[(100.0, 100.0), (200.0, 100.0)])); +} + +/// With `dragThird` off, a press that moves less than 2 screen points keeps the point where it was +/// pressed, for the second point and for the third. +#[test] +fn with_third_point_by_dragging_off_a_short_move_keeps_the_pressed_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(down, (200.0, 100.0), Mods::default())); + t.pointer(&cx, &ev(drag, (201.0, 100.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (200.0, 100.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(down, (150.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(drag, (151.0, 200.0), Mods::default())); + let three = circle(&[(100.0, 100.0), (200.0, 100.0), (150.0, 200.0)]); + assert_eq!(t.pointer(&cx, &ev(up, (150.0, 200.0), Mods::default())), three); +} + /// With `dragThird` off, a second click places the second point and a third click draws the circle /// through the three; a click on the second point again (as a double-click there does) draws the /// circle on the two; a second point let go on the first places nothing; a drag from the first @@ -300,6 +376,9 @@ fn an_alt_click_places_the_second_point_where_it_is_shown() { fn check_options_takes_only_the_values_the_options_take() { let ok = json!({"center": false, "radii": true, "diameter": false, "color": "gray", "standardAnchors": false, "dragThird": false}); assert_eq!(check_options(ok.as_object().unwrap()), Ok(())); + // The tool's own check, which `tool.setOption` also runs, takes the same values. + let tool = CircleTool::default(); + assert_eq!(tool.check_options(ok.as_object().unwrap()), Ok(())); for (bad, error) in [ (json!({"center": 1}), "`center` must be true or false"), (json!({"dragThird": null}), "`dragThird` must be true or false"), @@ -307,6 +386,7 @@ fn check_options_takes_only_the_values_the_options_take() { (json!({"colour": "red"}), "unknown Circle tool option `colour`"), ] { assert_eq!(check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}"); + assert_eq!(tool.check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}"); } } diff --git a/docs/mcp.md b/docs/mcp.md index 63a0215986..445c52ec3d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6582,8 +6582,9 @@ slider back to the Auto-Smooth level. ## Circle through two or three points -`shape.circleThroughPoints {points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]]}` draws the circle whose edge passes -through the points, as a live ellipse with the current paint, and selects it. Two points are the ends of a diameter. +`shape.circleThroughPoints {points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]], anchors?}` draws the circle whose +edge passes through the points, with the current paint, and selects it: a live ellipse with the default +`anchors: "standard"`, and a plain path with `anchors: "points"`. Two points are the ends of a diameter. Without `points`, it uses the two or three selected anchor points, from one path or several: anchor points selected with Direct Selection, or all the anchor points of a path selected whole, such as a triangle. The ends of selected segments do not count. The result is `{id, cx, cy, radius}`, and one undo removes the circle. The circle is not pixel-aligned, From 30ead6b0ca1110f5411e0624d5a495fc9ce403cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:41:08 -0800 Subject: [PATCH 45/69] Tests: "vectorize" checks label words for trace and a place in the first five The check for the results above the image trace commands matched any label containing the letters "trac", so labels such as Highlight Tracking or Subtract passed it. It now splits the label into words with the search's own word rules and accepts a word that is "trace" or stems to it (Tracing, Traced, Traces). The first image trace command must also be in the first five results. --- crates/ui-egui/src/palette/search.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index aed70389d0..71c2a7fd3b 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -1380,12 +1380,16 @@ mod tests { assert_eq!(first("outline text"), "type.createOutlines"); assert!(within("flip", "object.reflect", 3), "{:?}", ranked(&c, "flip")); assert!(within("combine", "object.pathfinder.unite", 3), "{:?}", ranked(&c, "combine")); - // "vectorize" finds the image trace commands, and only results whose label holds a form of - // "trace" rank above them. + // "vectorize" lists an image trace command in the first five, and only results whose label + // holds a word that is "trace" or stems to it rank above it. let vectorize = ranked(&c, "vectorize"); - let traced = |id: &String| c.list.iter().any(|e| &e.id == id && split_name(&e.shown).0.to_lowercase().contains("trac")); + let trace_word = |w: &str| { + let w = w.to_lowercase(); + w == "trace" || stems(&w).iter().any(|s| s == "trace") + }; + let traced = |id: &String| c.list.iter().any(|e| &e.id == id && words(split_name(&e.shown).0).any(trace_word)); let traces = vectorize.iter().position(|id| id.starts_with("imageTrace.")); - assert!(traces.is_some_and(|p| vectorize.get(..p).is_some_and(|above| above.iter().all(traced))), "{vectorize:?}"); + assert!(traces.is_some_and(|p| p < 5 && vectorize.get(..p).is_some_and(|above| above.iter().all(traced))), "{vectorize:?}"); assert_eq!(first("colour"), "panel:color", "{:?}", ranked(&c, "colour")); // A word that only starts other labels is in a group, and its labels follow the direct match. assert_eq!(first("unite"), "object.pathfinder.unite"); From 4137b8e50a2e1440f18f68f593588912a2779cb8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 14:27:35 -0800 Subject: [PATCH 46/69] Graphs: keep pasted graph edits, redraw graphs in pasted symbols and masks - A paste redraws a graph with the document's design of the same name only when that design's art differs or uses a resource the paste renamed or merged, so an unrelated rename no longer redraws every pasted graph. - Graphs in the art of symbols the paste added, and graphs in opacity-mask art, are drawn again with the document's design as well. - Adding or deleting a graph design also redraws the graphs in symbols' art and in opacity-mask art that use it. A dynamic symbol's instances drop their changes to graph parts that the redraw replaced. - Applying a library design to a graph that was moved or resized keeps its new place in Graph Column and Graph Marker. - swatch.library.load refuses inline data and dataBase64 larger than 256 MB before copying or decoding them. - A document with graph designs and no swatches of its own loads as a library with no swatches. Its designs keep the document's swatches and graphic styles that share a name with a new document's defaults. - graph.column, graph.marker and graph.design match a library's name in any case, as the swatch library commands do. --- crates/engine/src/cmd/clipboard/resources.rs | 55 ++- crates/engine/src/cmd/edit.rs | 4 +- crates/engine/src/cmd/graph.rs | 2 +- crates/engine/src/cmd/graph/columns.rs | 6 +- crates/engine/src/cmd/graph/designs.rs | 107 ++++-- crates/engine/src/cmd/graph/edit.rs | 36 +- crates/engine/src/cmd/graph/markers.rs | 6 +- crates/engine/src/cmd/graph/tests.rs | 332 +++++++++++++++++++ crates/engine/src/cmd/swatchlib.rs | 16 +- crates/engine/src/cmd/symboledit.rs | 13 + 10 files changed, 529 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index e0def02934..de626e514b 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1048,6 +1048,11 @@ pub(crate) struct Imported { /// and that would draw them otherwise than the art they were pasted with: the document keeps /// its own, and the pasted graphs are drawn again with it. pub kept_designs: BTreeSet, + /// The names of the symbols added to the document, whose art may hold graphs that draw with + /// [`Self::kept_designs`]. + pub added_symbols: BTreeSet, + /// The global and spot colors that took the document's color (merged). + merged_swatches: BTreeSet, } impl Imported { @@ -1114,7 +1119,12 @@ impl Clipboard { /// `d` keeps its own design. pub(super) fn used(&self, d: &Document) -> Used { let designs: Vec = self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)).cloned().collect(); - let defs = Defs { + Used::of(&self.defs(&designs), &self.nodes) + } + + /// The clipboard's definitions, with graph designs `designs`. + fn defs<'a>(&'a self, designs: &'a [GraphDesign]) -> Defs<'a> { + Defs { swatches: self.swatches.iter().collect(), symbols: &self.symbols, patterns: &self.patterns, @@ -1122,10 +1132,9 @@ impl Clipboard { char_styles: &self.char_styles, para_styles: &self.para_styles, brushes: Brushes::Ready(&self.brushes), - graph_designs: &designs, + graph_designs: designs, index: DefIndex::default(), - }; - Used::of(&defs, &self.nodes) + } } /// The used global and spot colours whose name `d` gives another one: (pasted, document). @@ -1317,6 +1326,7 @@ impl Clipboard { for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) { out.relink.node(Arc::make_mut(&mut s.art)); } + out.added_symbols = added_symbols.into_iter().collect(); for p in d.patterns.iter_mut().filter(|p| added_patterns.contains(&p.name)) { for a in &mut p.art { out.relink.node(Arc::make_mut(a)); @@ -1438,6 +1448,7 @@ impl Clipboard { for w in &bases { let p = if conflicts.contains(&w.name) && choices.of(&w.name) == SwatchChoice::Merge { out.merged += 1; + out.merged_swatches.insert(w.name.clone()); Placed::Existing } else { add_swatch(d, w, same_doc) @@ -1495,15 +1506,25 @@ impl Clipboard { // Every name the pasted graphs draw with whose design in the document would draw them // otherwise: another design of that name, one the clipboard holds no design for (deleted // and made again), or, from another document, the same art when a resource came in renamed - // or a swatch took the document's color (the art may draw it). - let moved = !same_doc && (!out.relink.renames.is_empty() || out.merged > 0); + // or a swatch took the document's color, that the design's art uses. (An SVG filter effect + // carries its definition, so a filter that draws otherwise makes the art differ.) + let defs = self.defs(&self.graph_designs); + let moved = |n: &str| { + if same_doc || (out.relink.renames.is_empty() && out.merged_swatches.is_empty()) { + return false; + } + let uses = designs_used(&defs, &[n.to_string()]); + out.relink.renames.iter().any(|(r, names)| names.keys().any(|from| uses.has(*r, from))) + || out.merged_swatches.iter().any(|w| uses.has(Res::Swatch, w)) + }; let differs = |n: &str| { let ours = d.graph_designs.iter().find(|x| x.name == n); let theirs = self.graph_designs.iter().find(|g| g.name == n); - ours.is_some_and(|x| moved || theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art)) + ours.is_some_and(|x| theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art) || moved(n)) }; let named = used.names.get(&Res::GraphDesign).into_iter().flatten(); - out.kept_designs.extend(named.filter(|n| differs(n)).cloned()); + let kept: Vec = named.filter(|n| differs(n)).cloned().collect(); + out.kept_designs.extend(kept); for g in self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)) { if d.graph_designs.iter().any(|x| x.name == g.name) { out.placed(Res::GraphDesign, &g.name, &Placed::Existing); @@ -1582,6 +1603,24 @@ pub(crate) fn graph_design_library(src: &Document) -> Option { let used = designs_used(&Defs::of(src, &library), &names); let clip = Clipboard::with_used(src, &used, &library, vec![]); let mut d = clip.to_document(); + // A new document's default swatches and graphic styles give way to the source's of the same + // name or id, so a design draws with the source's. + let defaults = d.swatches.len().saturating_sub(clip.swatches.len()); + let mut i = 0; + d.swatches.retain(|s| { + i += 1; + i > defaults || !clip.swatches.iter().any(|c| c.name == s.name) + }); + // The swatch groups are all a new document's. + for g in d.swatch_groups.iter_mut() { + g.swatches.retain(|s| !clip.swatches.iter().any(|c| c.name == s.name)); + } + let defaults = d.graphic_styles.len().saturating_sub(clip.graphic_styles.len()); + let mut i = 0; + d.graphic_styles.retain(|g| { + i += 1; + i > defaults || !clip.graphic_styles.iter().any(|c| (c.id != 0 && c.id == g.id) || c.name == g.name) + }); // The symbols keep their Symbol Options, which the document keeps by name. for (name, options) in &clip.symbol_options { options.give(&mut d, name); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index e025b64e2c..b707a8367a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1619,9 +1619,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho for id in &new_ids { super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default()); } - // A pasted graph whose design the document has under the same name draws with the document's. + // A pasted graph whose design the document has under the same name draws with the document's, + // in the pasted objects and in the art of the symbols the paste added. if !imported.kept_designs.is_empty() { super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?; + super::graph::redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs); } sel.set(new_ids.iter().copied()); // Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 2d48b6339a..13c34deb28 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -41,7 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; -pub(crate) use designs::redraw_with_designs; +pub(crate) use designs::{redraw_symbols_with_designs, redraw_with_designs}; pub use edit::{GraphTypeSubject, graph_type_subject}; pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed}; pub use generate::calculated_axes; diff --git a/crates/engine/src/cmd/graph/columns.rs b/crates/engine/src/cmd/graph/columns.rs index 4e56338849..6c87143618 100644 --- a/crates/engine/src/cmd/graph/columns.rs +++ b/crates/engine/src/cmd/graph/columns.rs @@ -1,5 +1,5 @@ use super::data::fmt_value; -use super::designs::{bring_in, design_names, from_library, libraries_json}; +use super::designs::{bring_in_for, design_names, from_library, libraries_json}; use super::edit::{regenerate, spec_of, target}; use super::generate::generate_with; use super::markers::{design_frame, fit_affine}; @@ -493,7 +493,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { // Drawn once on a copy of the document, to refuse designs past the budget before the edit. let mut probe = (*s.doc()?.doc).clone(); if let Some((lib, name)) = &library { - bring_in(&mut probe, lib, std::slice::from_ref(name))?; + bring_in_for(&mut probe, lib, name, id, &mut spec)?; } let looks = column_designs(&probe, &spec); if generate_with(&mut probe, &spec, &looks).is_none() { @@ -501,7 +501,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { } s.edit("Graph Column", |d, sel| { if let Some((lib, name)) = &library { - bring_in(d, lib, std::slice::from_ref(name))?; + bring_in_for(d, lib, name, id, &mut spec)?; } regenerate(d, id, spec)?; if !reselect.is_empty() { diff --git a/crates/engine/src/cmd/graph/designs.rs b/crates/engine/src/cmd/graph/designs.rs index 4d272d7bc3..1b7d89a8c5 100644 --- a/crates/engine/src/cmd/graph/designs.rs +++ b/crates/engine/src/cmd/graph/designs.rs @@ -1,5 +1,5 @@ -use super::edit::regenerate; -use super::{Arc, Document, GraphDesign, GraphSpec, Result, Session, Value, bad, json, ok, str_param}; +use super::edit::{regenerate, regenerate_detached}; +use super::{Arc, Document, GraphDesign, GraphSpec, Node, Result, Session, Value, bad, json, ok, str_param}; use crate::cmd::clipboard::resources::import_graph_designs; use crate::cmd::swatchlib::{concealed_library_id, shown_library_id}; @@ -9,7 +9,8 @@ pub(super) fn design_names(d: &Document) -> Vec { } /// The library param `library` names: a document Other Library… loaded (`swatch.library.load`) -/// that holds graph designs, by its id, the id a reply showed for it, or its name. `None` without +/// that holds graph designs, by its id, the id a reply showed for it, or its name (in any case, as +/// swatch library names are matched). `None` without /// `library`. fn library_param(s: &Session, p: &Value, cmd: &str) -> Result>> { let key = match p.get("library") { @@ -24,7 +25,7 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result Re Ok(()) } +/// [`bring_in`] library design `name` for graph `id`, whose new spec is `spec`: when that redraws +/// the graph, `spec` takes the rectangle the redraw gave it, so a graph moved or resized since it +/// was last drawn stays where it is. +pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: super::NodeId, spec: &mut GraphSpec) -> Result<()> { + bring_in(d, lib, &[name.to_string()])?; + if let Some(g) = d.node(id).and_then(|n| n.extras().graph.as_deref()) { + spec.rect = g.rect; + } + Ok(()) +} + /// Whether graph `g` draws a series with design `name`, as its marker or its columns. fn draws_with(g: &GraphSpec, name: &str) -> bool { g.series_markers.iter().flatten().any(|m| m == name) || g.series_columns.iter().flatten().any(|c| c.design == name) } -/// Regenerate the graphs whose series use design `name` (it was added or removed). +/// Regenerate the graphs whose series use design `name` (it was added or removed), in the layers, +/// in opacity-mask art and in symbols' art. fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> { - let mut ids = vec![]; + let names = std::collections::BTreeSet::from([name.to_string()]); + let (mut ids, mut masked) = (vec![], vec![]); d.walk(|n| { if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, name)) { ids.push(n.id); } + if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, &names)) { + masked.push(n.id); + } }); for id in ids { if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) { regenerate(d, id, spec)?; } } + // The graphs in objects' opacity-mask art. + for id in masked { + let Some(mut art) = d.node(id).and_then(|n| n.extras().mask.as_deref()).map(|m| (*m.art).clone()) else { continue }; + redraw_in(d, &mut art, &names); + if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) { + mask.art = Arc::new(art); + } + } + // And the graphs in symbols' art, which instances draw. + let symbols: std::collections::BTreeSet = d.symbols.iter().map(|s| s.name.clone()).collect(); + redraw_symbols_with_designs(d, &symbols, &names); Ok(()) } /// Draw the graphs in the subtrees of `ids` again that draw a series with one of the designs /// `names`: pasted graphs, after the paste kept the document's own designs of those names. pub(crate) fn redraw_with_designs(d: &mut Document, ids: &[super::NodeId], names: &std::collections::BTreeSet) -> Result<()> { - let mut graphs = vec![]; for id in ids { - if let Some(n) = d.node(*id) { - n.walk(&mut |m| { - if m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) { - graphs.push(m.id); - } - }); - } - } - for id in graphs { - if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) { - regenerate(d, id, spec)?; - } + let Some(mut n) = d.node(*id).filter(|n| holds(n, names)).cloned() else { continue }; + redraw_in(d, &mut n, names); + *d.node_mut(*id).ok_or(super::EngineError::NoNode(*id))? = n; } Ok(()) } +/// Draw the graphs in the art of symbols `symbols` again that draw a series with one of the +/// designs `names`: graphs of the symbols a paste added, after the paste kept the document's own +/// designs of those names. +pub(crate) fn redraw_symbols_with_designs( + d: &mut Document, + symbols: &std::collections::BTreeSet, + names: &std::collections::BTreeSet, +) { + for i in 0..d.symbols.len() { + let Some(s) = d.symbols.get(i).filter(|s| symbols.contains(&s.name) && holds(&s.art, names)) else { continue }; + let old = s.art.clone(); + let mut art = (*old).clone(); + redraw_in(d, &mut art, names); + let Some(s) = d.symbols.get_mut(i) else { continue }; + s.art = Arc::new(art); + // Instances' changes to parts the redraw replaced are dropped. + let name = s.name.clone(); + crate::cmd::symboledit::follow_art_change(d, &name, &old); + } +} + +/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series +/// with one of the designs `names`. +fn holds(n: &Node, names: &std::collections::BTreeSet) -> bool { + let mut found = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + found |= m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))); + }); + found +} + +/// Redraw the graphs of `n`'s subtree, the art of opacity masks included, that draw a series with +/// one of the designs `names`. +fn redraw_in(d: &mut Document, n: &mut Node, names: &std::collections::BTreeSet) { + if let Some(mut art) = n.extras().mask.as_deref().filter(|m| holds(&m.art, names)).map(|m| (*m.art).clone()) { + redraw_in(d, &mut art, names); + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + mask.art = Arc::new(art); + } + } + if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) { + regenerate_detached(d, n); + return; + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| holds(c, names)) { + redraw_in(d, Arc::make_mut(c), names); + } + } +} + /// The designs no graph's series draw with (Select Unused). fn unused_designs(d: &Document) -> Vec { let mut used = std::collections::HashSet::new(); diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index 728eff6427..e5ce1e7ed0 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -109,6 +109,33 @@ pub(crate) fn edit_graph_art(n: &mut Node, edit: impl FnOnce(&mut Node)) { /// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them). pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> { let n = d.node(id).ok_or(EngineError::NoNode(id))?; + carry_moves(n, &mut spec); + let children = generate(d, &spec); + spec.placed = children_bounds(&children); + spec.placed_art = art_bounds(&children); + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + if let Some(ch) = n.children_mut() { + *ch = children; + } + n.extras_mut().graph = Some(Box::new(spec)); + Ok(()) +} + +/// [`regenerate`] graph `n` from its own spec, where `n` is outside `d`'s layers (in a symbol's art). +pub(super) fn regenerate_detached(d: &mut Document, n: &mut Node) { + let Some(mut spec) = n.extras().graph.as_deref().cloned() else { return }; + carry_moves(n, &mut spec); + let children = generate(d, &spec); + spec.placed = children_bounds(&children); + spec.placed_art = art_bounds(&children); + if let Some(ch) = n.children_mut() { + *ch = children; + } + n.extras_mut().graph = Some(Box::new(spec)); +} + +/// Adjust `spec`'s plot rect for any move or scale of graph `n` since its last generation. +fn carry_moves(n: &Node, spec: &mut GraphSpec) { if let Some((placed, now)) = measured(n) && placed.width() > 1e-9 && placed.height() > 1e-9 @@ -119,15 +146,6 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R * Affine::translate(-placed.origin().to_vec2()); spec.rect = a.transform_rect_bbox(spec.rect); } - let children = generate(d, &spec); - spec.placed = children_bounds(&children); - spec.placed_art = art_bounds(&children); - let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; - if let Some(ch) = n.children_mut() { - *ch = children; - } - n.extras_mut().graph = Some(Box::new(spec)); - Ok(()) } pub(super) fn create(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/graph/markers.rs b/crates/engine/src/cmd/graph/markers.rs index 7045fee638..7b8a14d496 100644 --- a/crates/engine/src/cmd/graph/markers.rs +++ b/crates/engine/src/cmd/graph/markers.rs @@ -1,4 +1,4 @@ -use super::designs::{bring_in, design_names, from_library, libraries_json}; +use super::designs::{bring_in_for, design_names, from_library, libraries_json}; use super::edit::{regenerate, spec_of, target}; use super::series::{picked_series, reselect_series}; use super::{Affine, Arc, Document, GraphSpec, Node, NodeKind, Rect, Result, Session, Value, bad, json}; @@ -93,7 +93,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { let cost = match &library { Some((lib, name)) => { let mut probe = (*s.doc()?.doc).clone(); - bring_in(&mut probe, lib, std::slice::from_ref(name))?; + bring_in_for(&mut probe, lib, name, id, &mut spec)?; marker_cost(&spec, &marker_designs(&probe, &spec)) } None => marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)), @@ -103,7 +103,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { } s.edit("Graph Marker", |d, sel| { if let Some((lib, name)) = &library { - bring_in(d, lib, std::slice::from_ref(name))?; + bring_in_for(d, lib, name, id, &mut spec)?; } regenerate(d, id, spec)?; if !reselect.is_empty() { diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 45ce34a157..c1230301bb 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -5538,6 +5538,31 @@ fn designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied() { } } +#[test] +fn a_library_design_applied_to_a_moved_graph_that_names_it_keeps_the_graph_in_place() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A library's name works in any case, as swatch library names do. + assert_eq!(s.execute("graph.design", &json!({"library": "COINS"})).unwrap(), json!({"designs": ["Coin"]})); + for (kind, cmd) in [("line", "graph.marker"), ("column", "graph.column")] { + // The graph names design "Coin", which the document no longer has, and is moved after. + save_design(&mut s, "Coin"); + let id = graph(&mut s, kind); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute(cmd, &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let rect = spec(&s, id).rect; + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap(); + s.execute(cmd, &json!({"id": id.0, "design": "Coin", "library": lib})).unwrap(); + let now = spec(&s, id).rect; + assert!((now.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (now.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{cmd}: {now:?}"); + assert!((now.width() - rect.width()).abs() < 1e-6 && (now.height() - rect.height()).abs() < 1e-6, "{cmd}: {now:?}"); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + } +} + #[test] fn a_design_the_document_has_under_the_same_name_stays_as_it_is() { let mut s = Session::new(); @@ -5659,6 +5684,234 @@ fn a_pasted_graph_naming_a_deleted_design_draws_with_the_documents_design_of_tha assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); } +#[test] +fn a_pasted_graph_keeps_its_art_when_only_a_resource_its_design_does_not_use_comes_in_renamed() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff0000", "global": true})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [r]})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + // An edit of the graph's art that drawing the graph again would not keep. + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + // A copy of the document holds the same design; its "Ink" is another color, so the pasted + // rectangle's swatch takes the document's color, or with "add" comes in renamed. + let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc)); + s.execute("select.set", &json!({"ids": [id.0, r]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap(); + s.execute("swatch.edit", &json!({"name": "Ink", "color": "#0000ff"})).unwrap(); + for conflict in ["merge", "add"] { + let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap(); + assert!(r["merged"] == 1 || r["renamed"].as_array().is_some_and(|a| !a.is_empty()), "{conflict}: {r}"); + let st = s.doc().unwrap(); + let d = &st.doc; + let pasted = st.selection.objects.iter().copied().find(|i| d.node(*i).is_some_and(|n| n.extras().graph.is_some())).unwrap(); + let names: Vec> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect(); + assert_eq!(names[0].as_deref(), Some("Mine"), "{conflict}: not drawn again: {names:?}"); + } +} + +#[test] +fn a_pasted_graph_is_drawn_again_when_its_designs_svg_filter_comes_in_under_another_name() { + const SHIFT: &str = r#""#; + const SHIFT_MORE: &str = r#""#; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("svgFilter.apply", &json!({"name": "Shift", "ids": [r]})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Coin"})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + // A copy of the document holds the same design, but its "Shift" filter draws otherwise, so the + // pasted graph's filter keeps its own definition under another name. + let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc)); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": SHIFT_MORE, "replace": "Shift"})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let pasted = st.selection.objects.to_vec()[0]; + let names: Vec> = series(st.doc.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect(); + assert_ne!(names[0].as_deref(), Some("Mine"), "drawn again with the document's design: {names:?}"); +} + +#[test] +fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_that_name() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [instance]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document whose "Coin" is a rectangle and an ellipse: the symbol's graph draws with it. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns: Vec = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); +} + +#[test] +fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A graph that names "Coin", which the document no longer has, kept as a symbol's art. + save_design(&mut s, "Coin"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let d = &s.doc().unwrap().doc; + let art = &d.symbols.iter().find(|x| x.name == "Chart").unwrap().art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design"); +} + +#[test] +fn a_design_brought_in_from_a_library_redraws_a_graph_in_an_opacity_mask() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let mut graphs = vec![]; + vectorcraft_doc::swatches::walk_with_masks(s.doc().unwrap().doc.node(NodeId(r)).unwrap(), &mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design"); +} + +#[test] +fn an_instance_drops_its_changes_to_graph_parts_a_design_change_redraws() { + use vectorcraft_doc::symbol_overrides::SymbolOverride; + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap(); + let instance = NodeId(instance); + // A change to the graph itself, and one to a part of it that drawing it again replaces. + let changes = vec![ + SymbolOverride { path: vec![], opacity: Some(0.5), ..Default::default() }, + SymbolOverride { path: vec![0], opacity: Some(0.25), ..Default::default() }, + ]; + s.edit("Change", |d, _| { + if let Some(n) = d.node_mut(instance) { + n.extras_mut().symbol_overrides = changes; + } + Ok(()) + }) + .unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let kept = s.doc().unwrap().doc.node(instance).unwrap().extras().symbol_overrides.clone(); + assert_eq!(kept.iter().map(|o| o.path.clone()).collect::>(), [Vec::::new()], "{kept:?}"); +} + +#[test] +fn a_graph_in_an_opacity_mask_draws_with_the_documents_design_when_pasted() { + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let mask_graph = |n: &vectorcraft_doc::Node| { + let mut graphs = vec![]; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + graphs.into_iter().next().expect("the masked graph") + }; + // In a symbol's art and among the pasted objects. + for in_symbol in [true, false] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let copied = if in_symbol { s.execute("symbol.new", &json!({"name": "Masked", "ids": [r]})).unwrap()["id"].as_u64().unwrap() } else { r }; + s.execute("select.set", &json!({"ids": [copied]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let g = if in_symbol { + mask_graph(&st.doc.symbols.iter().find(|x| x.name == "Masked").expect("the symbol came in").art) + } else { + mask_graph(st.doc.node(st.selection.objects.to_vec()[0]).unwrap()) + }; + let columns: Vec = series(&g, 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "in a symbol: {in_symbol}"); + } +} + #[test] fn a_graph_pasted_back_after_its_design_was_made_again_draws_with_the_new_design() { let mut s = Session::new(); @@ -5711,6 +5964,85 @@ fn a_swatch_library_file_over_the_size_limit_is_refused_before_it_is_read() { assert!(e.contains("larger than 256 MB"), "{e}"); } +#[test] +fn a_document_with_graph_designs_and_no_swatches_loads_for_its_designs() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut src, "Pill"); + let mut d = (*src.doc().unwrap().doc).clone(); + d.swatches.clear(); + d.swatch_groups.clear(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Pills.vectorcraft"}); + let mut s = Session::new(); + let r = s.execute("swatch.library.load", &p).unwrap(); + assert_eq!((r["count"].clone(), r["graphDesigns"].clone()), (json!(0), json!(1))); + // Without graph designs it has nothing to offer. + d.graph_designs.clear(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Bare.vectorcraft"}); + let e = s.execute("swatch.library.load", &p).unwrap_err().to_string(); + assert!(e.contains("has no swatches of its own"), "{e}"); +} + +#[test] +fn a_design_library_keeps_the_sources_color_for_a_default_swatch_name() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A default swatch the source made global and gave another color, used by a design. + let name = src.doc().unwrap().doc.swatches.iter().find(|w| !w.name.starts_with('[')).unwrap().name.clone(); + let mine = Paint::solid(vectorcraft_color::Color::rgb(0.1, 0.7, 0.3)); + let (n, p) = (name.clone(), mine.clone()); + src.edit("Change", move |d, _| { + if let Some(w) = d.swatches.iter_mut().find(|w| w.name == n) { + w.paint = p; + w.global = true; + } + Ok(()) + }) + .unwrap(); + let r = src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + src.execute("paint.setFill", &json!({"swatch": name, "ids": [r]})).unwrap(); + src.execute("select.set", &json!({"ids": [r]})).unwrap(); + src.execute("graph.design", &json!({"new": "Green"})).unwrap(); + let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap(); + let named: Vec<_> = lib.swatches.iter().filter(|w| w.name == name).collect(); + assert_eq!(named.len(), 1, "one swatch named {name}"); + assert_eq!(named[0].paint, mine); + // And one named like a swatch in a default group. + let grouped = src.doc().unwrap().doc.swatch_groups.iter().flat_map(|g| g.swatches.iter()).next().unwrap().name.clone(); + let (n, p) = (grouped.clone(), mine.clone()); + src.edit("Change", move |d, _| { + if let Some(w) = d.swatch_groups.iter_mut().flat_map(|g| g.swatches.iter_mut()).find(|w| w.name == n) { + w.paint = p; + w.global = true; + } + Ok(()) + }) + .unwrap(); + let r = src.execute("shape.rectangle", &json!({"x": 650, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + src.execute("paint.setFill", &json!({"swatch": grouped, "ids": [r]})).unwrap(); + src.execute("select.set", &json!({"ids": [r]})).unwrap(); + src.execute("graph.design", &json!({"new": "Grouped"})).unwrap(); + let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap(); + let all: Vec<_> = lib.swatches.iter().chain(lib.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter(|w| w.name == grouped).collect(); + assert_eq!(all.len(), 1, "one swatch named {grouped}"); +} + +#[test] +fn inline_swatch_library_data_over_the_size_limit_is_refused_before_it_is_read() { + let max = crate::cmd::place::document::MAX_FILE; + let mut s = Session::new(); + // Text one byte over the limit, and base64 that decodes to one byte over it. + let chars = (max + 1) * 4 / 3 + 1; + // Each input is made in turn, so only one is held at a time. + for key in ["data", "dataBase64"] { + let value = if key == "data" { "a".repeat(max + 1) } else { "A".repeat(chars) }; + let mut p = serde_json::Map::new(); + p.insert(key.into(), serde_json::Value::String(value)); + let e = s.execute("swatch.library.load", &serde_json::Value::Object(p)).unwrap_err().to_string(); + assert!(e.contains("larger than 256 MB"), "{key}: {e}"); + } +} + #[test] fn a_library_design_brings_its_symbols_with_their_symbol_options() { // The source design is an instance of symbol "Corner" with 9-slice scaling, a top-left diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 7884ca6905..b16f743367 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -818,11 +818,19 @@ fn save(s: &mut Session, p: &Value) -> Result { fn load(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.load"; - // The size is checked before the file is read. + // The size is checked before the file is read, copied or decoded. let max = super::place::document::MAX_FILE; - if let Some(path) = text_param(p, "path", C)? - && super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64) - { + let too_big = match text_param(p, "path", C)? { + Some(path) => super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64), + None => match text_param(p, "data", C)? { + Some(text) => text.len() > max, + // Base64 holds 3 bytes in every 4 characters (padding and white space hold none). + None => { + text_param(p, "dataBase64", C)?.is_some_and(|b| b.bytes().filter(|c| *c != b'=' && !c.is_ascii_whitespace()).count() * 3 / 4 > max) + } + }, + }; + if too_big { return Err(bad(C, format!("the file is larger than {} MB", max >> 20))); } let mut designs = None; diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index a413631bb3..3b5d7cdf48 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -424,6 +424,19 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec) { + let Some(new) = d.symbols.iter().find(|s| s.name == name).map(|s| s.art.clone()) else { return }; + let parts = |art: &Arc| match (&art.kind, art.children()) { + (NodeKind::Group { .. }, Some(ch)) => (ch.to_vec(), true), + _ => (vec![art.clone()], false), + }; + let (old, new) = (parts(old), parts(&new)); + follow_objects(d, name, (&old.0, old.1), (&new.0, new.1)); +} + /// Each instance's appearance changes to objects of symbol `name`'s art follow those objects /// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes the art /// still draws ([`fit_parts`]). That covers the instances on the layers and in the art of the From 1bb3becb2733e6f5162895857b5b316e0977fd87 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 19:00:16 -0800 Subject: [PATCH 47/69] MCP: the UI command catalog lists Circle Tool Options crates/mcp/src/ui_catalog.rs is regenerated from ui_commands.rs, so the tool.options entry describes the circleOptions dialog as the desktop table does. --- crates/mcp/src/ui_catalog.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 88f60fd6c8..3d85a7f3b1 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1078,7 +1078,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", From 40f1201f1eeeffa2682e3558c28ed072155d610c Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Thu, 19 Nov 2026 15:36:23 +0500 Subject: [PATCH 48/69] View: Trim View hides the guides and the grid while it is on (#8363) Trim View only clipped the art to the artboards: ruler guides, paths made into guides and the grid still drew across the pasteboard. Public forum threads describe Trim View hiding them, with Show Guides and Show Grid unavailable until it is off. ViewFlags::guides_shown() and grid_shown() now say whether they draw, and the canvas, the tiled panes, the art raster, hit testing and the tools' snapping read them. Show/Hide Guides and Show/Hide Grid are greyed out while Trim View is on (menu bar, canvas context menu, Properties) and refuse to run; the stored choices are kept, so they come back as they were. A selected guide path is deselected when Trim View hides it, as Hide Guides does. The rulers stay. Fixes #8363 --- crates/ui-egui/src/app/view.rs | 2 +- crates/ui-egui/src/canvas.rs | 8 ++-- crates/ui-egui/src/canvas/outline.rs | 2 +- crates/ui-egui/src/canvas/panes.rs | 4 +- crates/ui-egui/src/canvas/tests.rs | 54 +++++++++++++++++++++++++ crates/ui-egui/src/menus/context.rs | 7 ++-- crates/ui-egui/src/menus/run.rs | 45 ++++++++++++++------- crates/ui-egui/src/menus/state.rs | 3 ++ crates/ui-egui/src/menus/tests.rs | 40 ++++++++++++++++++ crates/ui-egui/src/panels/properties.rs | 7 +++- crates/ui-egui/src/state.rs | 13 ++++++ docs/roadmap.md | 5 ++- docs/target-app-parity.md | 4 +- docs/ui-parity.md | 4 +- 14 files changed, 166 insertions(+), 32 deletions(-) diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index a1c2af21ff..1e9d931a0a 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -122,7 +122,7 @@ impl VectorcraftApp { zoom: self.view().map_or(1.0, |v| v.screen_zoom(self.canvas_ui_zoom)), outline: self.outline_view(), smart_guides: self.ui.view.smart_guides, - guides: self.ui.view.guides, + guides: self.ui.view.guides_shown(), snap_to_grid: self.ui.view.snap_to_grid, pixel_preview: self.ui.view.pixel_preview, snap_to_pixel: self.ui.view.snap_to_pixel, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 921bb23c4e..1972ab9549 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -322,7 +322,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { paint_paper(app, st, ui, &painter, &xf, rect, (&t, app.outline_view())); // The grid behind the art (Guides & Grid › Grids In Back), else over it below. - let grid_look = (app.ui.view.grid && !presenting).then(|| LineLook::grid(&app.session.prefs)); + let grid_look = (app.ui.view.grid_shown() && !presenting).then(|| LineLook::grid(&app.session.prefs)); let grids_in_back = app.session.prefs.grids_in_back; if let Some(look) = grid_look.filter(|_| grids_in_back) { grid(&painter, &xf, doc.grid.spacing, doc.grid.subdivisions, look); @@ -410,7 +410,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { grid(&painter, &xf, 1.0, 1, LineLook { color: PIXEL_GRID, dots: false }); } artboard_outlines(app, ui, &painter, &xf, &t); - if app.ui.view.guides { + if app.ui.view.guides_shown() { guide_lines(app, &painter, &xf, rect, &t); } nine_slice_overlay(app, &painter, &xf); @@ -627,7 +627,7 @@ fn cache_key( outline: app.outline_view(), trim: app.ui.view.trim_view, templates: app.ui.view.templates, - guides: app.ui.view.guides, + guides: app.ui.view.guides_shown(), ppp, hidden: vec![], rot: v.rotation, @@ -827,7 +827,7 @@ fn frame_options( overprint_preview: vectorcraft_render::proof::overprint_preview_on(), trim: app.ui.view.trim_view, hide_templates: !app.ui.view.templates, - hide_guides: !app.ui.view.guides, + hide_guides: !app.ui.view.guides_shown(), tile_edge: vectorcraft_color::Color::from_hex(&app.session.prefs.pattern_tile_edge_color).map_or(opts.tile_edge, |c| { let [r, g, b, _] = c.to_rgba8(1.0); [r, g, b] diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 9d1794ab7d..c2ab7945be 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -188,7 +188,7 @@ pub(super) fn hit_with( path_only: prefs.object_selection_by_path_only, type_path_only: prefs.type_selection_by_path_only, scope: app.session.active().and_then(|st| st.isolation), - skip_guides: !app.ui.view.guides, + skip_guides: !app.ui.view.guides_shown(), ..Default::default() }; test(&app.session.active()?.doc, p, opt) diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index cef27dab18..63d89f2be2 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -554,7 +554,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo let xf = Xf::at(rect, &v, ui_zoom); let painter = ui.painter_at(rect); paint_paper(app, st, ui, &painter, &xf, rect, (&t, v.outline)); - let grid_look = app.ui.view.grid.then(|| LineLook::grid(&app.session.prefs)); + let grid_look = app.ui.view.grid_shown().then(|| LineLook::grid(&app.session.prefs)); let grids_in_back = app.session.prefs.grids_in_back; if let Some(look) = grid_look.filter(|_| grids_in_back) { grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look); @@ -587,7 +587,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo if shows_artboards(app) { artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(&t, v.outline)), |_| false); } - if app.ui.view.guides { + if app.ui.view.guides_shown() { guides_of(app, st, (&painter, &xf, &t), rect); } if app.ui.view.edges { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 35c9fd3737..fde4bf777f 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -15290,3 +15290,57 @@ fn auto_spell_check_is_a_toggle_of_the_canvas_lines() { assert_eq!(count(&mut app), 0, "off"); assert!(app.canvas.spelling.lines.is_empty(), "no node is kept"); } + +/// #8363: Trim View hides the ruler guides, the guide paths and the grid while it is on, and they +/// are neither snapped to nor picked, as hidden guides are; turned off, they come back as they +/// were. The rulers stay. +#[test] +fn trim_view_hides_the_guides_and_the_grid() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.canvas.worker_started = true; // render on this thread + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app.ui.view.grid, app.ui.view.guides, app.ui.view.rulers) = (true, true, true); + let (red, green) = (Color32::from_rgb(255, 0, 0), Color32::from_rgb(0, 255, 0)); + app.session.execute("prefs.set", &json!({"values": {"gridColor": "#ff0000", "guideColor": "#00ff00"}})).unwrap(); + let ctx = egui::Context::default(); + // → (a gridline, a ruler guide, guide paths in the art, guides snapped to and picked). + let drawn = |app: &mut VectorcraftApp| { + let s = shapes(app, &ctx); + let line = |c: Color32| s.iter().any(|s| matches!(s, Shape::LineSegment { stroke, .. } if stroke.color == c)); + let guide_paths = !app.canvas.shown.as_ref().unwrap().1.hide_guides; + (line(red), line(green), guide_paths, app.view_info().guides) + }; + assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: all of them"); + + app.run("view.trimView", json!({})).unwrap(); + assert_eq!(drawn(&mut app), (false, false, false, false), "Trim View on: none of them"); + assert!(app.ui.view.grid && app.ui.view.guides && app.ui.view.rulers, "the choices stay, and so do the rulers"); + + app.run("view.trimView", json!({})).unwrap(); + assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: back as they were"); + + // Hidden before, they stay hidden after. + app.run("view.guides", json!({})).unwrap(); + app.run("view.trimView", json!({})).unwrap(); + app.run("view.trimView", json!({})).unwrap(); + assert_eq!(drawn(&mut app), (true, false, false, false), "guides hidden before Trim View stay hidden"); +} + +/// #8363: a selected guide path is deselected when Trim View hides it, as Hide Guides does (#3219). +#[test] +fn trim_view_deselects_selected_guide_paths() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(id)]); + + app.run("view.trimView", json!({})).unwrap(); + + assert!(app.session.active().unwrap().selection.objects.is_empty()); +} diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index 7a4566ae27..a83f1f7113 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -268,8 +268,9 @@ fn isolatable(app: &VectorcraftApp, doc: &vectorcraft_doc::Document, n: &vectorc && doc.symbol_edit.as_ref().is_none_or(|e| doc.ancestry(target).is_some_and(|a| a.contains(&e.layer))) } -/// `items` without the commands that can't run now (Undo and Redo stay, greyed out), submenus -/// left empty, and separators that no longer separate anything. +/// `items` without the commands that can't run now (Undo and Redo stay, greyed out, and so do Show +/// Grid and Hide Guides while Trim View holds them off: #8363), submenus left empty, and separators +/// that no longer separate anything. fn prune(app: &VectorcraftApp, items: Vec) -> Vec { let mut out: Vec = Vec::with_capacity(items.len()); for it in items { @@ -278,7 +279,7 @@ fn prune(app: &VectorcraftApp, items: Vec) -> Vec { it => it, }; let keep = match &it { - Item::Cmd(_, id, _) => matches!(*id, "edit.undo" | "edit.redo") || enabled(app, id), + Item::Cmd(_, id, _) => matches!(*id, "edit.undo" | "edit.redo" | "view.guides" | "view.grid") || enabled(app, id), Item::Sub(_, children) => !children.is_empty(), Item::Sep => out.last().is_some_and(|l| !matches!(l, Item::Sep)), _ => true, diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 3be667cf8b..4b5358b09d 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -135,6 +135,26 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option> { let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); @@ -292,7 +312,12 @@ fn run_ui_part3(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.view.pixel_preview), - "view.trimView" => flag(&mut app.ui.view.trim_view), + // Trim View hides the guides while it is on (#8363), and hidden guides cannot stay selected. + "view.trimView" => { + let r = flag(&mut app.ui.view.trim_view); + deselect_hidden_guides(app); + r + } "view.cornerWidget" => flag(&mut app.ui.view.corner_widgets), // Hide/Show Shape Widgets: `on` sets the state, and without it the state flips. "view.shapeWidgets" => opt_bool(p, "on").map(|on| { @@ -403,22 +428,12 @@ fn run_ui_part4(app: &mut VectorcraftApp, id: &str, _p: &Value) -> Option flag(&mut app.ui.view.bounding_box), + // Trim View hides the guides and the grid while it is on, and their Show/Hide items wait + // until it is off (#8363). + "view.guides" | "view.grid" if app.ui.view.trim_view => Err(TRIM_VIEW_HIDES.into()), "view.guides" => { let r = flag(&mut app.ui.view.guides); - // Hidden ruler guides and guide paths cannot stay selected: their selection overlay - // would otherwise reveal geometry that Hide Guides just hid. - let hidden_selection = !app.ui.view.guides - && app.session.active().is_some_and(|d| { - !d.selection.guides.is_empty() - || d.selection - .objects - .iter() - .any(|id| matches!(d.doc.node(*id).map(|n| &n.kind), Some(vectorcraft_doc::NodeKind::Path { guide: true, .. }))) - }); - if hidden_selection { - // Deselecting a document that is open cannot fail. - let _ = app.run("select.none", json!({})); - } + deselect_hidden_guides(app); r } "view.smartGuides" => flag(&mut app.ui.view.smart_guides), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index b9503ccd06..7eaad9329b 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -338,6 +338,9 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "file.exportSelection" => app.session.active().is_some_and(|d| !d.selection.is_empty()), "css.copy" | "css.exportFile" => app.session.active().is_some(), "print.printerSetup" => app.services.print.as_ref().is_some_and(|s| s.has_setup()), + // Trim View hides the guides and the grid while it is on, so their Show/Hide items wait + // until it is off (#8363). + "view.guides" | "view.grid" => !app.ui.view.trim_view, "view.refreshMonitorProfile" => app.session.prefs.monitor_profile_display && app.display_profile.has_reader(), "plugin.dialog" => app.session.active().is_some(), "ui.perspectiveGridDialog" | "ui.savePerspectivePreset" => app.session.active().is_some(), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 37ae4cba23..fa94c19cd5 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1745,3 +1745,43 @@ fn selection_tools_toggle_propagates_a_failed_valid_choice() { } assert_eq!(failures, vec![Err(failure.to_string()), Err(failure.to_string())], "both failed valid choices must reach the command caller"); } + +/// #8363: while Trim View is on, View › Guides › Show/Hide Guides and View › Show/Hide Grid are +/// greyed out (in the menu bar, on their keys and in the canvas context menu, where they stay +/// listed), refuse to run and leave the choices they keep alone; turning it off brings them back. +#[test] +fn trim_view_greys_out_show_guides_and_show_grid() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.grid = true; + let listed = |app: &VectorcraftApp, id: &str| { + fn find(items: &[Item], id: &str) -> bool { + items.iter().any(|it| match it { + Item::Cmd(_, c, _) => *c == id, + Item::Sub(_, children) => find(children, id), + _ => false, + }) + } + find(&context_items(app), id) + }; + for id in ["view.guides", "view.grid"] { + assert!(enabled(&app, id), "{id} runs with Trim View off"); + assert!(listed(&app, id), "{id} is in the canvas context menu"); + } + + app.run("view.trimView", json!({})).unwrap(); + for id in ["view.guides", "view.grid"] { + assert!(!enabled(&app, id), "{id} is greyed out while Trim View is on"); + assert!(listed(&app, id), "{id} stays in the canvas context menu, greyed out"); + assert!(app.run(id, json!({})).is_err(), "{id} does not run while Trim View is on"); + } + assert!(app.ui.view.guides && app.ui.view.grid, "the choices stay as they were"); + assert_eq!((checked(&app, "view.grid", &Value::Null), dynamic_label(&app, "view.guides", "Show Guides").as_str()), (Some(true), "Hide Guides")); + + app.run("view.trimView", json!({})).unwrap(); + for id in ["view.guides", "view.grid"] { + assert!(enabled(&app, id), "{id} runs again with Trim View off"); + } + app.run("view.guides", json!({})).unwrap(); + assert!(!app.ui.view.guides); +} diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 52b74a5fb5..94b4edc638 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -767,7 +767,9 @@ fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::icon_button(ui, "ruler", tl!("Show Rulers (⌘R)"), v.rulers, 26.0).clicked() { app.run("view.rulers", json!({})).ok(); } - if widgets::icon_button(ui, "grid-3x3", tl!("Show Grid (⌘')"), v.grid, 26.0).clicked() { + // Trim View holds the grid and the guides off while it is on (#8363). + let shows = crate::menus::enabled(app, "view.grid"); + if widgets::icon_button_enabled(ui, "grid-3x3", tl!("Show Grid (⌘')"), v.grid, shows, 26.0).clicked() { app.run("view.grid", json!({})).ok(); } let transparency_grid = app.session.active().is_some_and(|d| d.transparency_grid); @@ -779,7 +781,8 @@ fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { section_header(ui, tl!("Guides")); ui.horizontal(|ui| { let v = app.ui.view.clone(); - if widgets::icon_button(ui, "layout-grid", tl!("Show Guides"), v.guides, 26.0).clicked() { + let shows = crate::menus::enabled(app, "view.guides"); + if widgets::icon_button_enabled(ui, "layout-grid", tl!("Show Guides"), v.guides, shows, 26.0).clicked() { app.run("view.guides", json!({})).ok(); } if widgets::icon_button(ui, "sparkles", tl!("Smart Guides (⌘U)"), v.smart_guides, 26.0).clicked() { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8b67b84f34..fbb04def01 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -340,6 +340,19 @@ impl Default for ViewFlags { } } +impl ViewFlags { + /// Whether the ruler guides and guide paths draw: View › Show Guides, unless Trim View hides + /// them while it is on (#8363). `guides` keeps the choice, so they come back as they were. + pub fn guides_shown(&self) -> bool { + self.guides && !self.trim_view + } + + /// Whether the grid draws: View › Show Grid, unless Trim View hides it while it is on (#8363). + pub fn grid_shown(&self) -> bool { + self.grid && !self.trim_view + } +} + /// An open modal dialog. `fields` are string-valued so agents can set them uniformly. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Dialog { diff --git a/docs/roadmap.md b/docs/roadmap.md index 45df43932f..bdf1afae8e 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -187,7 +187,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, thirteen generated libraries including Tech Circuit, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | +| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | | M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | @@ -232,6 +232,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | M11: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid (#8363). Scores and estimates unchanged | | 2026-11-18 | minor | M10/G5: Media Controls joins Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons as a seventh built-in symbol library (Play, Pause, Stop, Skip Next, Shuffle, Repeat; original procedural vector symbols generated in code, no default 9-slice); G5 estimate decremented to 2–12 h, milestone estimates unchanged | | 2026-11-18 | minor | M7/G4: Retype phase 1 (#4934): `type.retype` turns outlined text that exactly matches an available font back into point text. Scores and estimates unchanged | | 2026-11-18 | minor | M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f4c76fcbbd..813bc61bad 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -626,6 +626,7 @@ since 2026-10-01. - **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged. - **Guide row highlight (#7344):** `guide_row_highlight_stays_selected_without_hover` in `crates/ui-egui/src/panels/layers/tests.rs` checks selected guide background after the pointer leaves, with unselected guide and ordinary row controls. Guide selection, dragging and deletion are unchanged. Scores and estimates unchanged. +- **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. @@ -3079,6 +3080,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Guides, grids, smart guides, snapping, rulers: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out their Show/Hide items (#8363). Scores and estimates unchanged. | | 2026-11-18 | minor | Layers panel: context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show) with one-step undo; regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | Type advanced: Retype phase 1 (`type.retype`, #4934), exact matches of available fonts become point text again; evidence added; near matches, the ranked font list and images remain; score and hours unchanged | | 2026-11-18 | minor | Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 0c09bbb405..61439f71cc 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -295,6 +295,7 @@ tools, never checked side by side) isn't captured row by row. | Ruler origin: corner drag with preview, snapped as a drawn point is (Smart Guides, Snap to Point and the ruler guides, pixels, the grid), double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | | Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer; each row's own eye and lock; a row dropped on the trash deletes its guide; selected guide rows keep their highlight away from the pointer (#7344); a plain click on another row lets go of the guide | done | `guide.setLayer`; guides from older files go on a layer; `layer.setProps` on a guide's id hides or locks it alone; Object › Lock/Hide › Selection, Unlock All and Show All reach guides; `guide.remove {indexes}`; #7340 | | Objects made into guides: drawn in the guide colour and style of Preferences; Lock Guides locks them too (no select, move or delete), in groups as well: a marquee leaves them out, so it does not take their group, and they still move with their group; a dragged selection snaps to ruler guides with Smart Guides on, by the nearest point of the path when pressed on its stroke or beside its edge, so the path lands exactly on the guide | done | #1534 (#1543, #1583); #3701; #8538 | +| View › Trim View hides the ruler guides, the guide paths and the grid while it is on, and View › Guides › Show/Hide Guides and View › Show/Hide Grid are greyed out until it is off (#8363) | done | As public forum threads describe ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). The Show/Hide choices are kept and come back as they were; the items stay greyed in the canvas context menu and the Properties panel's buttons, and refuse to run from keys, the palette or MCP. Hidden guides are neither snapped to nor picked, as with Hide Guides, and a selected guide path is deselected. The rulers stay as they are. `menus::tests::trim_view_greys_out_show_guides_and_show_grid`, `canvas::tests::{trim_view_hides_the_guides_and_the_grid, trim_view_deselects_selected_guide_paths}` | | A selected ruler guide's X or Y in the Transform panel; typing a value moves it | not scored | #1659 (part of #1597); several guides move together; not in Properties or the Control bar. Not established by the documentation we could find: the help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) don't describe it, and the one public statement is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. Kept as a convenience pending the owner's decision; no parity claim | | Alt swaps a ruler guide's orientation while dragging | missing | Alt-drag copies the selected guides ([Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html)); `guide.move` `{copy: true}` | | Alt swaps a new ruler guide's orientation while dragging | done | Both rulers; preview, snapping and final placement follow the current modifier ([public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). | @@ -616,6 +617,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid until it is off; the choices come back as they were and the rulers stay (#8363). Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s (part of #5930, `file.cancelPlace`); indeterminate moving bar, Cancel (Esc) leaves the document unmodified without undo steps; scores and estimates unchanged. | | 2026-11-18 | minor | Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | From 9d2bbbc6b43f3c06de19db56abde491edee99731 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 06:18:09 -0800 Subject: [PATCH 49/69] Graphs: redraw graphs a paste or library adds a design for, reuse redrawn symbols - A paste that adds a design the document lacked draws the document's graphs that name it again, in the same undo step; the pasted graphs keep their art. - A library design brings along the designs its art uses, and the graphs that name any of them are drawn again. A design the document keeps brings none of the library design's resources. - Only a series that draws a design is redrawn for it: a marker counts while Mark Data Points is on or the legend has an entry for the series, and a column design counts for a column or bar series. - A symbol pasted a second time is the one the first paste added and drew again with the document's designs. - Renaming a design renames it in the graphs of symbols and opacity masks, and Select Unused counts those graphs. - swatch.library.load reads a file no further than the 256 MB limit. --- crates/engine/src/cmd/clipboard/resources.rs | 64 +++- crates/engine/src/cmd/edit.rs | 5 + crates/engine/src/cmd/graph.rs | 2 +- crates/engine/src/cmd/graph/designs.rs | 146 +++++++-- crates/engine/src/cmd/graph/tests.rs | 306 ++++++++++++++++++- crates/engine/src/cmd/swatchlib.rs | 57 +++- docs/mcp.md | 7 +- 7 files changed, 526 insertions(+), 61 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index de626e514b..ab99a0f1e4 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -762,6 +762,22 @@ fn same_art(r: &Relink, ours: &[Arc], theirs: &[Arc]) -> bool { ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b)) } +/// `n` with the ids of its objects, those of opacity-mask art included, all 0: art drawn again +/// compares equal to art drawn the same way, whatever ids each drawing gave it. +fn without_ids(n: &Node) -> Node { + let mut n = n.clone(); + n.id = vectorcraft_doc::NodeId(0); + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + mask.art = Arc::new(without_ids(&mask.art)); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + *c = Arc::new(without_ids(c)); + } + } + n +} + /// Is `ours` (a document brush) brush `theirs` (a pasted one) once the art of that is relinked by /// `r`? Graphic style links don't count, as in [`same_art`]. fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool { @@ -1051,6 +1067,8 @@ pub(crate) struct Imported { /// The names of the symbols added to the document, whose art may hold graphs that draw with /// [`Self::kept_designs`]. pub added_symbols: BTreeSet, + /// The names of the graph designs added to the document. + pub added_designs: BTreeSet, /// The global and spot colors that took the document's color (merged). merged_swatches: BTreeSet, } @@ -1275,11 +1293,18 @@ impl Clipboard { .collect(), None => HashMap::new(), }; + // A symbol whose graphs the paste draws again with the document's designs is + // also the document's one that holds its art drawn that way (an earlier paste + // added it). + let redrawn = (!fresh && d.symbols.iter().any(|s| copy_of(&def.name, &s.name))) + .then(|| self.redrawn_art(d, &def.art, &out.relink)) + .flatten(); let r = &out.relink; let p = place(&mut d.symbols, def, same_doc, |a, b| { !fresh && options.is_none_or(|o| theirs.get(&a.name) == Some(o)) - && same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)) + && (same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)) + || redrawn.as_ref().is_some_and(|art| without_ids(&a.art) == *art)) }); if let Some(name) = p.new_name(&def.name) { if let Some(o) = options { @@ -1499,6 +1524,27 @@ impl Clipboard { } } + /// Symbol art `art` relinked by `relink` with its graphs drawn again with the designs `d` holds + /// under a name whose design the clipboard lacks or holds with other art, as a paste that adds + /// the symbol draws it, its ids left out ([`without_ids`]). `None` when no graph of it draws + /// with such a design. + fn redrawn_art(&self, d: &mut Document, art: &Arc, relink: &Relink) -> Option { + let theirs = |n: &str| self.graph_designs.iter().find(|g| g.name == n); + let differs: BTreeSet = d + .graph_designs + .iter() + .filter(|x| theirs(&x.name).is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art)) + .map(|x| x.name.clone()) + .collect(); + if differs.is_empty() || !crate::cmd::graph::holds_designs(art, &differs) { + return None; + } + let mut n = (**art).clone(); + relink.node(&mut n); + crate::cmd::graph::redraw_detached(d, &mut n, &differs); + Some(without_ids(&n)) + } + /// Graph designs: the document's design of a name stays as it is and the pasted graphs draw /// with it ([`Imported::kept_designs`]); a design the document lacks is added under its name, its art following the /// resources placed above, with fresh ids. Called once every other resource is placed. @@ -1538,6 +1584,7 @@ impl Clipboard { let art = d.reid(&art); d.graph_designs.push(GraphDesign { name: g.name.clone(), art: Arc::new(art) }); out.placed(Res::GraphDesign, &g.name, &Placed::Added); + out.added_designs.insert(g.name.clone()); } Ok(()) } @@ -1632,15 +1679,16 @@ pub(crate) fn graph_design_library(src: &Document) -> Option { /// Add graph designs `names` of `src` to `d`, with the swatches, patterns, symbols, styles, /// brushes and images their art uses, placed as Paste places them ([`Clipboard::import_into`]; a /// global or spot color whose name `d` gives another color is `d`'s). A design `d` has under the -/// same name stays as it is. → each name, and whether its design was added. An error, with `d` -/// unchanged, when `d` would hold more than [`GraphDesign::MAX`] designs. -pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result> { +/// same name stays as it is, and the art of `src`'s design of that name is not followed. → the +/// names of the designs added: those of `names` `d` lacked, and those their art uses. An error, +/// with `d` unchanged, when `d` would hold more than [`GraphDesign::MAX`] designs. +pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result> { let library = OnceCell::new(); - let used = designs_used(&Defs::of(src, &library), names); + let held = |n: &str| d.graph_designs.iter().any(|x| x.name == n); + let followed: Vec = src.graph_designs.iter().filter(|g| names.contains(&g.name) || !held(&g.name)).cloned().collect(); + let used = designs_used(&Defs { graph_designs: &followed, ..Defs::of(src, &library) }, names); let clip = Clipboard::with_used(src, &used, &library, vec![]); - let before: HashSet = d.graph_designs.iter().map(|g| g.name.clone()).collect(); - clip.import_used(d, &used, &SwatchChoices::default(), false)?; - Ok(names.iter().map(|n| (n.clone(), !before.contains(n))).collect()) + Ok(clip.import_used(d, &used, &SwatchChoices::default(), false)?.added_designs) } /// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index b707a8367a..259bcc48a8 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1625,6 +1625,11 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?; super::graph::redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs); } + // The graphs already in the document that draw with a design the paste added are drawn + // again with it; the pasted ones already draw with it. + if !imported.added_designs.is_empty() { + super::graph::refresh_graphs(d, &imported.added_designs, &new_ids, &imported.added_symbols)?; + } sel.set(new_ids.iter().copied()); // Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a // paste of guides alone keeps them where they were, but onto another artboard or every diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index 13c34deb28..06fb062e50 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -41,7 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; -pub(crate) use designs::{redraw_symbols_with_designs, redraw_with_designs}; +pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs}; pub use edit::{GraphTypeSubject, graph_type_subject}; pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed}; pub use generate::calculated_axes; diff --git a/crates/engine/src/cmd/graph/designs.rs b/crates/engine/src/cmd/graph/designs.rs index 1b7d89a8c5..d0807df3f1 100644 --- a/crates/engine/src/cmd/graph/designs.rs +++ b/crates/engine/src/cmd/graph/designs.rs @@ -1,5 +1,7 @@ use super::edit::{regenerate, regenerate_detached}; -use super::{Arc, Document, GraphDesign, GraphSpec, Node, Result, Session, Value, bad, json, ok, str_param}; +use std::collections::BTreeSet; + +use super::{Arc, Document, GraphDesign, GraphKind, GraphSpec, Node, Result, Session, Value, bad, json, ok, str_param}; use crate::cmd::clipboard::resources::import_graph_designs; use crate::cmd::swatchlib::{concealed_library_id, shown_library_id}; @@ -57,12 +59,11 @@ pub(super) fn from_library(s: &Session, p: &Value, cmd: &str) -> Result Result<()> { - for (name, added) in import_graph_designs(lib, d, names)? { - if added { - refresh_graphs_using(d, &name)?; - } + let added = import_graph_designs(lib, d, names)?; + if !added.is_empty() { + refresh_graphs(d, &added, &[], &BTreeSet::new())?; } Ok(()) } @@ -78,21 +79,58 @@ pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: sup Ok(()) } -/// Whether graph `g` draws a series with design `name`, as its marker or its columns. +/// Whether graph `g` draws a series with design `name`: as the marker of a series drawn with +/// markers (every series of a scatter or radar graph, and line series) while Mark Data Points is +/// on or the legend has an entry for the series, or as the columns of a series drawn as columns or +/// bars. fn draws_with(g: &GraphSpec, name: &str) -> bool { + let scatter = g.kind == GraphKind::Scatter; + let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES); + // The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank + // (a scatter graph's entries are its pairs of series, labeled by the first of each pair). + let in_legend = |s: usize| { + let entries = if scatter { nser.div_ceil(2) } else { nser }; + let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str); + g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label) + }; + let shown = |s: usize| g.mark_points || in_legend(s); + let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line); + let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar); + g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s)) + || g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s)) +} + +/// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or +/// not the series draws with it. +fn names_design(g: &GraphSpec, name: &str) -> bool { g.series_markers.iter().flatten().any(|m| m == name) || g.series_columns.iter().flatten().any(|c| c.design == name) } /// Regenerate the graphs whose series use design `name` (it was added or removed), in the layers, /// in opacity-mask art and in symbols' art. fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> { - let names = std::collections::BTreeSet::from([name.to_string()]); + refresh_graphs(d, &BTreeSet::from([name.to_string()]), &[], &BTreeSet::new()) +} + +/// Regenerate the graphs that draw a series with one of the designs `names`, in the layers, in +/// opacity-mask art and in symbols' art, except those in the subtrees of `skip` and in the art of +/// symbols `skip_symbols`. +pub(crate) fn refresh_graphs(d: &mut Document, names: &BTreeSet, skip: &[super::NodeId], skip_symbols: &BTreeSet) -> Result<()> { + let mut skipped = std::collections::HashSet::new(); + for n in skip.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |m| { + skipped.insert(m.id); + }); + } let (mut ids, mut masked) = (vec![], vec![]); d.walk(|n| { - if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, name)) { + if skipped.contains(&n.id) { + return; + } + if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) { ids.push(n.id); } - if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, &names)) { + if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, names)) { masked.push(n.id); } }); @@ -104,17 +142,31 @@ fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> { // The graphs in objects' opacity-mask art. for id in masked { let Some(mut art) = d.node(id).and_then(|n| n.extras().mask.as_deref()).map(|m| (*m.art).clone()) else { continue }; - redraw_in(d, &mut art, &names); + redraw_in(d, &mut art, names); if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) { mask.art = Arc::new(art); } } // And the graphs in symbols' art, which instances draw. - let symbols: std::collections::BTreeSet = d.symbols.iter().map(|s| s.name.clone()).collect(); - redraw_symbols_with_designs(d, &symbols, &names); + let symbols: BTreeSet = d.symbols.iter().map(|s| s.name.clone()).filter(|s| !skip_symbols.contains(s)).collect(); + redraw_symbols_with_designs(d, &symbols, names); Ok(()) } +/// [`redraw_in`] for the clipboard: graph art `n`, outside the document, drawn again with `d`'s +/// designs `names`. +pub(crate) fn redraw_detached(d: &mut Document, n: &mut Node, names: &BTreeSet) { + if holds(n, names) { + redraw_in(d, n, names); + } +} + +/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series +/// with one of the designs `names`. +pub(crate) fn holds_designs(n: &Node, names: &BTreeSet) -> bool { + holds(n, names) +} + /// Draw the graphs in the subtrees of `ids` again that draw a series with one of the designs /// `names`: pasted graphs, after the paste kept the document's own designs of those names. pub(crate) fn redraw_with_designs(d: &mut Document, ids: &[super::NodeId], names: &std::collections::BTreeSet) -> Result<()> { @@ -177,18 +229,57 @@ fn redraw_in(d: &mut Document, n: &mut Node, names: &std::collections::BTreeSet< } } -/// The designs no graph's series draw with (Select Unused). +/// The designs no graph's series draw with (Select Unused): graphs in the layers, in opacity-mask +/// art and in symbols' art count. fn unused_designs(d: &Document) -> Vec { let mut used = std::collections::HashSet::new(); - d.walk(|n| { + let mut note = |n: &Node| { if let Some(g) = n.extras().graph.as_deref() { used.extend(g.series_markers.iter().flatten().cloned()); used.extend(g.series_columns.iter().flatten().map(|c| c.design.clone())); } - }); + }; + for art in d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)) { + vectorcraft_doc::swatches::walk_with_masks(art, &mut note); + } d.graph_designs.iter().map(|x| x.name.clone()).filter(|n| !used.contains(n)).collect() } +/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that names design +/// `name` for a series ([`names_design`]). +fn names_in(n: &Node, name: &str) -> bool { + let mut found = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + found |= m.extras().graph.as_deref().is_some_and(|g| names_design(g, name)); + }); + found +} + +/// Graph `g`'s series that name design `old` name `new` instead. +fn rename_series(g: &mut GraphSpec, old: &str, new: &str) { + for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) { + *m = new.to_string(); + } + for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) { + c.design = new.to_string(); + } +} + +/// [`rename_series`] for the graphs of `n`'s subtree, the art of opacity masks included. +fn rename_in(n: &mut Node, old: &str, new: &str) { + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()).filter(|m| names_in(&m.art, old)) { + rename_in(Arc::make_mut(&mut mask.art), old, new); + } + if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) { + rename_series(g, old, new); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| names_in(c, old)) { + rename_in(Arc::make_mut(c), old, new); + } + } +} + /// Design names from param `key`: one name or a list of names. fn names_param(p: &Value, key: &str, cmd: &str) -> Result>> { match p.get(key) { @@ -255,22 +346,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result { if let Some(x) = d.graph_designs.iter_mut().find(|x| x.name == old) { x.name = new.clone(); } - let mut graphs = vec![]; + let (mut graphs, mut masked) = (vec![], vec![]); d.walk(|n| { - if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, &old)) { + if n.extras().graph.as_deref().is_some_and(|g| names_design(g, &old)) { graphs.push(n.id); } + if n.extras().mask.as_deref().is_some_and(|m| names_in(&m.art, &old)) { + masked.push(n.id); + } }); for id in graphs { if let Some(g) = d.node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) { - for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) { - *m = new.clone(); - } - for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) { - c.design = new.clone(); - } + rename_series(g, &old, &new); } } + // The graphs in opacity-mask art and in symbols' art follow too, their art as it is. + for id in masked { + if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) { + rename_in(Arc::make_mut(&mut mask.art), &old, &new); + } + } + for s in d.symbols.iter_mut().filter(|s| names_in(&s.art, &old)) { + rename_in(Arc::make_mut(&mut s.art), &old, &new); + } Ok(()) })?; return Ok(json!({ "name": to })); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index c1230301bb..a254f71ccc 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -5713,7 +5713,9 @@ fn a_pasted_graph_keeps_its_art_when_only_a_resource_its_design_does_not_use_com s.execute("swatch.edit", &json!({"name": "Ink", "color": "#0000ff"})).unwrap(); for conflict in ["merge", "add"] { let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap(); - assert!(r["merged"] == 1 || r["renamed"].as_array().is_some_and(|a| !a.is_empty()), "{conflict}: {r}"); + let ink_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Ink")); + let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) }; + assert_eq!((r["merged"].clone(), ink_renamed), expected, "{conflict}: {r}"); let st = s.doc().unwrap(); let d = &st.doc; let pasted = st.selection.objects.iter().copied().find(|i| d.node(*i).is_some_and(|n| n.extras().graph.is_some())).unwrap(); @@ -5937,6 +5939,276 @@ fn a_graph_pasted_back_after_its_design_was_made_again_draws_with_the_new_design assert_eq!(columns, [2, 2, 2, 2], "drawn with the design the document has now"); } +/// The graphs in `n`'s subtree, those in opacity-mask art included. +fn graphs_in(n: &vectorcraft_doc::Node) -> Vec { + let mut graphs = vec![]; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + graphs +} + +/// Load a saved document holding [`save_coin_design`]'s "Coin" and design "Chart", an instance of +/// symbol "Plot" whose column graph names "Coin" as its columns (`columns`) or only as a marker +/// its columns do not draw, as a swatch library → its id. +fn load_chart_library(s: &mut Session, columns: bool) -> String { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut src); + let id = graph(&mut src, "column"); + src.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + src.execute(if columns { "graph.column" } else { "graph.marker" }, &json!({"design": "Coin"})).unwrap(); + let instance = src.execute("symbol.new", &json!({"name": "Plot", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap(); + src.execute("select.set", &json!({"ids": [instance]})).unwrap(); + src.execute("graph.design", &json!({"new": "Chart"})).unwrap(); + let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Charts.vectorcraft"}); + s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string() +} + +#[test] +fn a_library_design_brings_none_of_the_resources_of_a_design_the_document_keeps() { + let mut s = Session::new(); + let lib = load_chart_library(&mut s, false); + // The document keeps its own "Coin": nothing the library's "Coin" uses comes in. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.symbols.iter().any(|x| x.name == "Plot"), "the design's symbol came in"); + assert!(d.swatch("Gold").is_none()); + // A document without one takes the design and its swatch. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.iter().any(|x| x.name == "Coin") && d.swatch("Gold").is_some()); +} + +#[test] +fn a_design_a_library_design_brings_along_redraws_the_graphs_that_name_it() { + let mut s = Session::new(); + let lib = load_chart_library(&mut s, true); + // A graph that names "Coin", which the document no longer has. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let r = s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap(); + assert_eq!(r, json!({"added": ["Chart"], "existing": []})); + let d = &s.doc().unwrap().doc; + assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "drawn with the library's Coin"); +} + +#[test] +fn a_paste_that_adds_a_design_redraws_the_documents_graphs_that_name_it_and_not_the_pasted_ones() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + // An edit of the copied graph's art that drawing it again would not keep. + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document whose graph names "Coin", which it no longer has. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let own = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [own.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + assert!(paints_with_swatch(series(st.doc.node(own).unwrap(), 0), "Gold"), "drawn with the pasted Coin"); + let pasted = st.selection.objects.to_vec()[0]; + let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone(); + assert_eq!(first.as_deref(), Some("Mine"), "the pasted graph is not drawn again"); +} + +#[test] +fn a_paste_that_adds_a_marker_design_a_graph_does_not_show_leaves_that_graph_as_it_is() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A line graph whose series name "Coin", which the document no longer has, as a marker that + // Mark Data Points does not show, with no legend or with a legend that has no entry for them. + for (legend, csv) in [(false, ",2024,2025\nQ1,3,2\nQ2,5,4"), (true, ",,\nQ1,3,2\nQ2,5,4")] { + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let p = json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv}); + let own = NodeId(s.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [own.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.setType", &json!({"id": own.0, "markPoints": false, "legend": legend})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let mark = series(s.doc().unwrap().doc.node(own).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.iter().any(|x| x.name == "Coin"), "legend {legend}: the paste added Coin"); + let first = series(d.node(own).unwrap(), 0).children().unwrap()[0].name.clone(); + assert_eq!(first.as_deref(), Some("Mine"), "legend {legend}: not drawn again"); + } +} + +#[test] +fn a_symbol_pasted_twice_with_a_graph_the_document_draws_again_is_added_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [instance]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document whose "Coin" is other art: the first paste draws the symbol's graph with it. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + // The paths of each column of the symbol's graph: 2 for the document's Coin, 1 for the copied one. + let columns = |s: &Session| { + let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art.clone(); + let graph = graphs_in(&art).remove(0); + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + series(&graph, 0).children().unwrap().iter().map(|n| paths(n)).collect::>() + }; + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(columns(&s), [2, 2, 2, 2], "the first paste draws with the document's Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect(); + assert_eq!(names, ["Chart"]); + assert_eq!(columns(&s), [2, 2, 2, 2], "drawn with the document's Coin"); +} + +#[test] +fn a_symbol_pasted_twice_whose_designs_swatch_takes_the_documents_color_is_added_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + // A copy of the document holds the same "Coin"; its "Gold" is another color. + let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc)); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [instance]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + for conflict in ["merge", "add"] { + s.execute("document.open", &json!({"name": format!("{conflict}.vectorcraft"), "dataBase64": saved})).unwrap(); + s.execute("swatch.edit", &json!({"name": "Gold", "color": "#0000ff"})).unwrap(); + let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap(); + let gold_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Gold")); + let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) }; + assert_eq!((r["merged"].clone(), gold_renamed), expected, "{conflict}: {r}"); + s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap(); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect(); + assert_eq!(names, ["Chart"], "{conflict}"); + } +} + +#[test] +fn a_pasted_graph_that_only_names_a_kept_design_as_an_undrawn_marker_keeps_its_art() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + // A column graph whose series name "Coin" as a marker, which columns do not draw. + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin"})).unwrap(); + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let pasted = st.selection.objects.to_vec()[0]; + let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone(); + assert_eq!(first.as_deref(), Some("Mine"), "not drawn again"); +} + +#[test] +fn renaming_a_design_renames_it_in_the_graphs_of_symbols_and_opacity_masks() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let in_symbol = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [in_symbol.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [in_symbol.0]})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let masked = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [masked.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let before = graphs_in(&s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art); + s.execute("graph.design", &json!({"rename": "Coin", "to": "Medal"})).unwrap(); + let d = &s.doc().unwrap().doc; + let symbol = graphs_in(&d.symbols.iter().find(|x| x.name == "Chart").unwrap().art); + let mask = graphs_in(d.node(NodeId(r)).unwrap()); + for (where_, g) in [("symbol", &symbol[0]), ("mask", &mask[0])] { + let designs: Vec = g.extras().graph.as_deref().unwrap().series_columns.iter().flatten().map(|c| c.design.clone()).collect(); + assert!(!designs.is_empty() && designs.iter().all(|n| n == "Medal"), "{where_}: {designs:?}"); + } + assert_eq!(symbol[0].children(), before[0].children(), "the symbol's graph keeps its art"); +} + +#[test] +fn a_design_only_a_graph_in_a_symbol_or_a_mask_draws_with_is_not_unused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + save_design(&mut s, "Pill"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let masked = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [masked.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Pill"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + assert_eq!(s.execute("graph.design", &json!({})).unwrap()["unused"], json!([])); +} + #[test] fn a_library_copied_to_user_defined_keeps_its_graph_designs_under_the_loaded_id() { let dir = vectorcraft_testkit::TempDir::new("graph-design-library-user"); @@ -6029,18 +6301,28 @@ fn a_design_library_keeps_the_sources_color_for_a_default_swatch_name() { #[test] fn inline_swatch_library_data_over_the_size_limit_is_refused_before_it_is_read() { - let max = crate::cmd::place::document::MAX_FILE; + // With a limit of 3 bytes: text and base64 of 3 bytes pass, and of 4 bytes are refused. + let too_big = |p: serde_json::Value| crate::cmd::swatchlib::library_too_big(&p, "swatch.library.load", 3).unwrap(); + assert!(!too_big(json!({"data": "abc"}))); + assert!(too_big(json!({"data": "abcd"}))); + let b64 = |n: usize| vectorcraft_format::base64_encode(&vec![7u8; n]); + assert!(!too_big(json!({"dataBase64": b64(3)}))); + assert!(too_big(json!({"dataBase64": b64(4)}))); +} + +#[test] +fn a_swatch_library_file_is_read_no_further_than_the_size_limit() { + let dir = vectorcraft_testkit::TempDir::new("graph-design-library-bound"); + let path = dir.join("grown.gpl"); + std::fs::write(&path, [b'a'; 9]).unwrap(); let mut s = Session::new(); - // Text one byte over the limit, and base64 that decodes to one byte over it. - let chars = (max + 1) * 4 / 3 + 1; - // Each input is made in turn, so only one is held at a time. - for key in ["data", "dataBase64"] { - let value = if key == "data" { "a".repeat(max + 1) } else { "A".repeat(chars) }; - let mut p = serde_json::Map::new(); - p.insert(key.into(), serde_json::Value::String(value)); - let e = s.execute("swatch.library.load", &serde_json::Value::Object(p)).unwrap_err().to_string(); - assert!(e.contains("larger than 256 MB"), "{key}: {e}"); - } + let p = json!({"path": path}); + let parsed = |_: &[u8], _: &str| Err(crate::EngineError::Other("parsed".into())); + // A file that grew past the limit after the size check is refused when it is read. + let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(8), parsed).unwrap_err().to_string(); + assert!(e.contains("larger than"), "{e}"); + let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(9), parsed).unwrap_err().to_string(); + assert!(e.contains("parsed"), "{e}"); } #[test] diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index b16f743367..e4d89b9c13 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -17,7 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches}; use vectorcraft_doc::pattern::pattern_paint; -use super::fileio::{create_dir, extension, read_file, write_file, write_new_file}; +use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file}; use super::menucmds::squash; use super::package::free_name; use super::patternlib; @@ -393,12 +393,32 @@ impl Libraries { /// or a file with the same extension and bytes as one there, is that User Defined library; /// others are listed as loaded until the app quits. pub(crate) fn load(&mut self, p: &Value, cmd: &str, parse: impl FnOnce(&[u8], &str) -> Result) -> Result<(LibraryInfo, Arc)> { + self.load_within(p, cmd, None, parse) + } + + /// [`Self::load`], with a file at `path` read up to `max` bytes and refused when it is longer. + pub(crate) fn load_within( + &mut self, + p: &Value, + cmd: &str, + max: Option, + parse: impl FnOnce(&[u8], &str) -> Result, + ) -> Result<(LibraryInfo, Arc)> { let path = text_param(p, "path", cmd)?; let data = text_param(p, "data", cmd)?; let data_base64 = text_param(p, "dataBase64", cmd)?; let name = text_param(p, "name", cmd)?; let bytes = match (path, data, data_base64) { - (Some(path), ..) => read_file(path)?, + (Some(path), ..) => match max { + Some(max) => { + let bytes = read_file_head(path, max.saturating_add(1))?; + if bytes.len() > max { + return Err(bad(cmd, too_big_message(max))); + } + bytes + } + None => read_file(path)?, + }, (None, Some(text), _) => text.as_bytes().to_vec(), (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(cmd, "bad dataBase64"))?, _ => return Err(bad(cmd, "give `path`, `data` or `dataBase64`")), @@ -816,27 +836,38 @@ fn save(s: &mut Session, p: &Value) -> Result { Ok(out) } -fn load(s: &mut Session, p: &Value) -> Result { - const C: &str = "swatch.library.load"; - // The size is checked before the file is read, copied or decoded. - let max = super::place::document::MAX_FILE; - let too_big = match text_param(p, "path", C)? { +/// The error for a library file larger than `max` bytes. +fn too_big_message(max: usize) -> String { + format!("the file is larger than {} MB", max >> 20) +} + +/// Whether the library `p` gives (`path`, `data` or `dataBase64`) is larger than `max` bytes, +/// checked before the file is read, copied or decoded. +pub(crate) fn library_too_big(p: &Value, cmd: &str, max: usize) -> Result { + Ok(match text_param(p, "path", cmd)? { Some(path) => super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64), - None => match text_param(p, "data", C)? { + None => match text_param(p, "data", cmd)? { Some(text) => text.len() > max, // Base64 holds 3 bytes in every 4 characters (padding and white space hold none). None => { - text_param(p, "dataBase64", C)?.is_some_and(|b| b.bytes().filter(|c| *c != b'=' && !c.is_ascii_whitespace()).count() * 3 / 4 > max) + text_param(p, "dataBase64", cmd)?.is_some_and(|b| b.bytes().filter(|c| *c != b'=' && !c.is_ascii_whitespace()).count() * 3 / 4 > max) } }, - }; - if too_big { - return Err(bad(C, format!("the file is larger than {} MB", max >> 20))); + }) +} + +fn load(s: &mut Session, p: &Value) -> Result { + const C: &str = "swatch.library.load"; + let max = super::place::document::MAX_FILE; + if library_too_big(p, C, max)? { + return Err(bad(C, too_big_message(max))); } let mut designs = None; // The document a library with pattern swatches was read from, which holds their patterns. let mut patterns = None; - let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| { + // The file is read no further than the limit, so a file that grew since it was checked is + // refused too. + let (info, lib) = s.swatch_libraries.load_within(p, C, Some(max), |bytes, file| { // A library file, or a document whose swatches become the library and whose graph // designs the Graph Column and Graph Marker dialogs offer. if palette_io::sniff_bytes(bytes) { diff --git a/docs/mcp.md b/docs/mcp.md index e59eecb22b..6ab12c046e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5409,10 +5409,11 @@ Defined copy made with `swatch.library.copyToUser` holds the swatches alone, so swatches, patterns, symbols, styles, brushes and images its art uses, in the same undo step as the graph change. `graph.design {library, add: name | [names]}` copies designs without applying them and returns `{added, existing}`, and `graph.design {library}` lists the library's designs. A design the document already has under the same name stays as it -is. With no `design`, `graph.column`, `graph.marker` and `graph.design` list the loaded libraries that hold designs as -`libraries: [{library, name, designs}]`. Copying a graph and pasting it into another document brings the designs its series +is. `graph.column` and `graph.marker` with no `design`, and `graph.design {}`, list the loaded libraries that hold +designs as `libraries: [{library, name, designs}]`. Copying a graph and pasting it into another document brings the designs its series draw with in the same way; a pasted graph is drawn again with the document's design of that name when that design -would draw it otherwise. +would draw it otherwise. The graphs already in the document that draw with a design the copy or paste adds, one a copied +design's art uses included, are drawn again with it. `swatch.library.copyToUser {library}` copies a loaded library into the user library folder of the desktop app (a library file as it is; a document's swatches or a library loaded from `data` or `dataBase64` as `.vcswatches`; a library with pattern swatches is refused) under a name no file there has, and lists it as User From d1f2a8a3c2be0c3d2b0faecaa1d2ab7b1435bc6f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 06:31:22 -0800 Subject: [PATCH 50/69] Clipboard: a pasted design the document keeps adds no filter names The SVG filters in the art of a graph design the document already has are left out when the paste picks names for the filters it brings, since that art is not pasted. --- crates/engine/src/cmd/clipboard/resources.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index ab99a0f1e4..f221248f74 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1392,7 +1392,8 @@ impl Clipboard { for a in self.brushes.iter().flat_map(Brush::art) { node_filters(a, &mut found); } - for g in &self.graph_designs { + // A design the document has under the same name stays its own, so its art here is not pasted. + for g in self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)) { node_filters(&g.art, &mut found); } for g in &self.graphic_styles { From fb7d601feacf99f55e7841e857b539b95d6f261e Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Thu, 19 Nov 2026 19:42:22 +0500 Subject: [PATCH 51/69] View: no guide from the rulers while Trim View is on (#8363) Trim View hides the guides, so a guide dragged or double-clicked out of a ruler while it is on was made but could not be seen, and the drag turned the stored Show Guides choice on. Now neither makes a guide: no preview line, no undo step, the stored choice is left alone, and the status line says why. A drag already going when Trim View turns on ends as a release off the canvas does. --- crates/engine/src/tooling.rs | 6 +++ crates/ui-egui/src/canvas/grid.rs | 22 ++++++++- crates/ui-egui/src/canvas/tests.rs | 77 ++++++++++++++++++++++++++++++ crates/ui-egui/src/menus.rs | 1 + crates/ui-egui/src/menus/run.rs | 2 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 4 +- docs/ui-parity.md | 4 +- 8 files changed, 110 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 5f36c5a98e..cef810afa5 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -839,6 +839,12 @@ impl Session { self.ruler_origin = None; } + /// A guide is being dragged out of a ruler ([`Session::ruler_guide`]): its first event came + /// and its release has not. + pub fn ruler_guide_dragging(&self) -> bool { + self.ruler_guide.is_some() + } + /// Time passed while the pointer button is held (`dt` seconds; see [`Tool::tick`]): the /// desktop app ticks every frame of a press, agents with `holdMs` on a pointer event. pub fn tool_tick(&mut self, dt: f64, view: ViewInfo) -> Result> { diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 5d533f7eaf..422e91811c 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -222,7 +222,14 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c if resp.clicked_by(egui::PointerButton::Primary) { ui.data_mut(|d| d.insert_temp(last_click, now)); } - if resp.double_clicked_by(egui::PointerButton::Primary) + // Trim View hides the guides (#8363): a guide made now could not be seen, so none is. + let trim_view = app.ui.view.trim_view; + let refuse = |app: &mut VectorcraftApp| app.status(crate::menus::TRIM_VIEW_HIDES.to_string()); + if trim_view && first_here && resp.double_clicked_by(egui::PointerButton::Primary) { + refuse(app); + } + if !trim_view + && resp.double_clicked_by(egui::PointerButton::Primary) && first_here && let Some(p) = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())) { @@ -253,8 +260,19 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c } else { continue; }; + if trim_view { + if resp.drag_started() { + refuse(app); + } + // No guide is dragged out, so none previews. One already dragged when Trim View + // turned on ends as a release off the canvas does: no guide, no undo step. + if !app.session.ruler_guide_dragging() { + continue; + } + } + let kind = if trim_view { PointerKind::Up } else { kind }; let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())); - let on_canvas = p.is_some_and(|p| canvas.contains(p)); + let on_canvas = !trim_view && p.is_some_and(|p| canvas.contains(p)); if on_canvas { // The new guide shows even if guides were hidden. app.ui.view.guides = true; diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index fde4bf777f..3a39185a11 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -15344,3 +15344,80 @@ fn trim_view_deselects_selected_guide_paths() { assert!(app.session.active().unwrap().selection.objects.is_empty()); } + +/// #8363: Trim View hides the guides, so a guide dragged or double-clicked out of a ruler while it +/// is on would be made but never seen. None is: no preview line, no guide, no undo step, the +/// stored Show/Hide Guides choice is left alone, and the status line says why. A drag already +/// going when Trim View turns on ends as a release off the canvas does. +#[test] +fn trim_view_makes_no_guide_from_the_rulers() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.guides = false; + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + app.ui.view.trim_view = true; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let from = pos2(rect.center().x, rect.top() - RULER / 2.0); + let at = pos2(rect.center().x, rect.top() + 120.0); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let across = |s: &Shape| { + matches!(s, Shape::LineSegment { points, .. } + if (points[0].y - at.y).abs() <= 2.0 && points[0].y == points[1].y && (points[1].x - points[0].x).abs() >= rect.width() - 0.5) + }; + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().len(); + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = steps(&app); + + // A drag: nothing previews and nothing is made. + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews"); + assert!(!app.session.ruler_guide_dragging()); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(count(&app), 0, "no guide from a drag"); + assert!(!app.ui.view.guides, "the stored choice is left alone"); + assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES); + + // A double-click: nothing either. + app.ui.status.clear(); + let click = |app: &mut VectorcraftApp| { + frame(app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(app, &ctx, vec![button(from, true)]); + frame(app, &ctx, vec![button(from, false)]); + }; + click(&mut app); + click(&mut app); + assert_eq!(count(&app), 0, "no guide from a double-click"); + assert!(!app.ui.view.guides); + assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES); + assert_eq!(steps(&app), before, "no undo step"); + + // Trim View turned on during a drag: the drag ends without a guide. + app.ui.view.trim_view = false; + let from2 = pos2(rect.center().x + 30.0, rect.top() - RULER / 2.0); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from2)]); + frame(&mut app, &ctx, vec![button(from2, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(app.session.ruler_guide_dragging(), "the drag started with Trim View off"); + app.ui.view.trim_view = true; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x + 5.0, at.y))]); + assert!(!app.session.ruler_guide_dragging(), "ended"); + assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews"); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(count(&app), 0, "no guide from the drag Trim View interrupted"); + assert_eq!(steps(&app), before, "no undo step"); + + // With Trim View off again, a drag makes a guide as before. + app.ui.view.trim_view = false; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(count(&app), 1); + assert!(app.ui.view.guides, "the new guide shows"); +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 781b6a9f63..92617f90ca 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -49,6 +49,7 @@ mod invoke; mod keyboard; mod labels; mod run; +pub(crate) use run::TRIM_VIEW_HIDES; mod slots; mod state; mod submenus; diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 4b5358b09d..71d384f5cf 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -136,7 +136,7 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option