diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 9da06fd577..ab2d9f77a0 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -897,6 +897,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 739759afe6..fde7f7b24a 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -42,8 +42,10 @@ pub(crate) use live_paint::{isolated_live_paint, merge_drawn_in_isolation}; 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"; @@ -208,6 +210,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 203fd62338..d1f766bfdf 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -161,6 +161,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) { @@ -196,6 +199,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 dfab5336de..551c2187ad 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -8009,6 +8009,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 1e8b01efdd..47c1aed8ba 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1218,6 +1218,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 2531ca0a45..9d336fca08 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -149,6 +149,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; @@ -371,6 +372,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..52c075c09b --- /dev/null +++ b/crates/ui-egui/src/dialogs/tracing_presets.rs @@ -0,0 +1,519 @@ +//! 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"; + +/// 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, + 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(); + // 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, + 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. They scroll + // past the height of the preset list. + let mut params = preset.1.clone(); + 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)); + } + }); + }); + 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()); + } + 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)) { + 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!({})); + 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 +} + +/// 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..7176efbbc8 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs @@ -0,0 +1,441 @@ +//! 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); +} + +/// 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:?}"); + } +} + +/// 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}"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 9075d079df..f4fe2f5a27 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1775,6 +1775,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 6df8d411fa..5cd1319170 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1998,6 +1998,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 c20a4925e8..ba53e6fa05 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1186,6 +1186,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 3e055c469a..a72e36bd9c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2067,6 +2067,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 6ea94f6b7f..e3ba9936c8 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4614,6 +4614,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 43b0751066..999e59108e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1849,6 +1849,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 5fe3a1b13f..9eef7858e4 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1758,6 +1758,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 aafd9582a3..27d47e1a56 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1850,6 +1850,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 73079ac031..ac8718d41c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2038,6 +2038,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 7bddb26ab8..4c10aba589 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1840,6 +1840,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 cbf37f5dfc..ce5c1d5af5 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1349,6 +1349,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 cce666f627..3f0d5b606d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4917,6 +4917,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 3051f7b90a..71bad14be4 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1841,6 +1841,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 b550eda8be..50ce46f009 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1888,6 +1888,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 c3adcd9842..218d1f812c 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -386,6 +386,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 b18be5a00b..72fd0c2408 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4017,6 +4017,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 edfc25aabd..4a23324242 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -379,6 +379,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 572d4610ef..fe1d6da938 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2485,6 +2485,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 869fff2f53..df4cb2b068 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1985,6 +1985,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 c05e55789b..2b1cef132e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3942,6 +3942,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 21c2f5754d..bad85be78d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1874,6 +1874,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 e2c0e1de5a..3ca8a8e261 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1796,6 +1796,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 7788b3b8bb..6f75a861f2 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1674,6 +1674,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 6a4e129851..605d792a05 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1882,6 +1882,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 446d3a11f2..fd0b0168df 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4640,6 +4640,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 c55bd1cf73..555912d22b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1805,6 +1805,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 1da0102bb2..06212f33aa 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1853,6 +1853,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 11c02ca139..9c7da9e53e 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); @@ -108,6 +111,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"), ]; @@ -550,6 +554,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)?; diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index ff4eba30fb..aa4b565c07 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -154,6 +154,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 6fc3900dd0..43fa3c0e6c 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -889,6 +889,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.foldPreview" => crate::addons::packaging::preview::command(app, p), "ui.copyScriptConsole" => crate::panels::script_console::copy(app, p), diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 72daeffc0f..18f8e3e6a1 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -137,6 +137,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 342ab2e22c..b10c5336ff 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1219,6 +1219,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 28c9fe9a78..294d914988 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_node, 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))) @@ -310,7 +311,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) } @@ -454,7 +455,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 89ea4ced55..9d1c26f800 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", @@ -496,6 +496,7 @@ const MENU_DIALOG_COMMANDS: [&str; 40] = [ "ui.flattenerPresetsDialog", "ui.printPresetsDialog", "ui.pdfPresetsDialog", + "ui.tracingPresetsDialog", "ui.perspectivePresetsDialog", "ui.svgFilterDialog", ]; diff --git a/docs/mcp.md b/docs/mcp.md index e4831ac5ea..076ab5fd41 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4433,8 +4433,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?|id?}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?, color?, closeGaps?}` (Object › Live Paint › Gap Options). Make gives each covered face the fill rows that draw of @@ -7214,7 +7229,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 7310a41ac0..c5cec38d13 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1757,6 +1757,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, a trace started before File › Revert does not apply after it:** the reverted document keeps its tab, but a trace prepared before the revert no longer applies, even when the restored image, object and settings are the same. A background trace that finishes after the revert changes nothing and the status bar says the document was reverted; a result handed to `imageTrace.make` or `imageTrace.makeAndExpand` is dropped and the restored image is traced again, as one undo step. Reverting another document, or a revert that fails, does not affect the trace (VectorCraft's own rule). Tests: `a_trace_run_prepared_before_a_revert_does_not_apply_after_it` in `crates/engine`, `a_trace_started_before_a_revert_does_not_apply` in `crates/ui-egui`. Scores and hours unchanged. - **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)).