From 9685ef571150b267ec68de3e3e43b7313cd2c40c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 04:33:18 -0800 Subject: [PATCH 1/6] =?UTF-8?q?Image=20Trace:=20Edit=20>=20Tracing=20Prese?= =?UTF-8?q?ts=E2=80=A6=20manages,=20imports=20and=20exports=20tracing=20pr?= =?UTF-8?q?esets?= 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 2/6] 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 60fe72537d04a0b44cc0834766c6b9fea16272fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 21:37:28 -0800 Subject: [PATCH 3/6] 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 cb1689c3a82012f1eee7866f33547c8f504ead42 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:14:15 -0800 Subject: [PATCH 4/6] 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 5c858d24e25db9ce1d6050086c7d6bdf4f1bf0c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 21:20:52 -0800 Subject: [PATCH 5/6] 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 6/6] 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}"); +}