Merge pull request #9494 from dotCooCoo/fix/tracing-preset-import-opening

Keep Image Trace preset picker results with the manager that opened them
This commit is contained in:
BFlat authored and GitHub committed 2026-11-27 07:25:46 +07:00
commit 09cd0290c7
2 files changed
+108 -40

No files matched your search

+66 -40
View File
@@ -89,6 +89,8 @@ pub(crate) struct Manager {
data: RowsData,
/// What a button asked for, taken by [`pump`].
action: Option<Action>,
/// Identifies this opening when an Import picker finishes later.
import_owner: Arc<()>,
}
impl StackDialog for Manager {
@@ -180,8 +182,13 @@ impl StackDialog for Manager {
/// Open the presets manager on `selected` (default: the first preset, Default).
pub(crate) fn open(app: &mut VectorcraftApp, selected: Option<&str>) {
let manager =
Manager { list: image_trace::presets(app), selected: selected.unwrap_or("Default").to_string(), data: RowsData::of(app), action: None };
let manager = Manager {
list: image_trace::presets(app),
selected: selected.unwrap_or("Default").to_string(),
data: RowsData::of(app),
action: None,
import_owner: Arc::new(()),
};
match app.dialogs() {
Some(dialogs) => {
dialogs.with(|host| host.open(manager));
@@ -251,10 +258,11 @@ fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), Strin
select(app, next.as_deref().unwrap_or("Default"));
}
Action::Import => {
let Some(owner) = with_manager(app, |m| Arc::clone(&m.import_owner)) else { return Ok(()) };
let name = file_asks::filter_name(crate::i18n::current(), "Tracing presets");
let request = PickRequest::open("tracingPresets").filter(name, TRACE_PRESET_EXTS);
// The answer, or its failure, reaches the status bar from the continuation; nothing is pending here.
let _ = file_asks::ask(app, request, Owner::Free, picked);
let _ = file_asks::ask(app, request, Owner::Free, move |app, answer| picked(app, answer, ImportSource::Picker(owner)));
}
Action::Export => {
crate::io::save_command_output(app, "imageTrace.presets.export", TRACE_PRESET_FORMAT, json!({}), |_, _| Ok(Value::Null))?;
@@ -263,20 +271,37 @@ fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), Strin
Ok(())
}
/// The file Import… picked: a path on the desktop, the file's bytes on the web.
fn picked(app: &mut VectorcraftApp, picked: Picked) -> Result<Value, String> {
match picked {
Picked::Paths(paths) => {
if let Some(path) = paths.first() {
open_path(app, &path.to_string_lossy())?;
}
enum ImportSource {
FileOpen,
Picker(Arc<()>),
}
impl ImportSource {
fn matches(&self, manager: &Manager) -> bool {
match self {
Self::FileOpen => true,
Self::Picker(owner) => Arc::ptr_eq(owner, &manager.import_owner),
}
Picked::Contents(files) => {
if let Some((_, bytes)) = files.first() {
open_file(app, bytes)?;
}
fn select(&self, app: &VectorcraftApp, name: &str) {
let _ = with_manager(app, |manager| {
if self.matches(manager) {
manager.selected = name.to_string();
}
}
_ => {}
});
}
}
/// The file Import… picked, a path on the desktop or the file's bytes on the web.
fn picked(app: &mut VectorcraftApp, picked: Picked, source: ImportSource) -> Result<Value, String> {
let file = match picked {
Picked::Paths(paths) => paths.first().map(|path| file_contents(app, json!({ "path": path.to_string_lossy() }))).transpose()?,
Picked::Contents(files) => files.first().map(|(_, bytes)| checked_contents(bytes)).transpose()?,
_ => None,
};
if let Some(file) = file {
open_import(app, file, source)?;
}
Ok(Value::Null)
}
@@ -294,6 +319,7 @@ fn import_file(app: &mut VectorcraftApp, file: &Value) -> Result<(Value, Vec<Val
struct ReplaceFile {
file: Value,
first: Option<String>,
source: ImportSource,
}
/// The Replace question. Its own type, so the host keeps its answer apart from every other prompt's.
@@ -301,22 +327,23 @@ pub(crate) struct ReplacePresets(pub(crate) StandardPrompt);
crate::dialogs::confirm::wrapped_dialog!(ReplacePresets, StandardPrompt, REPLACE_KIND);
/// Asks whether the import of `file` replaces the saved presets `skipped` kept, over the manager
/// when it is open.
fn ask_replace(app: &VectorcraftApp, skipped: &[Value], file: Value) {
/// Asks whether the import of `file` replaces the saved presets `skipped` kept. It opens over the
/// manager if the import targets that opening.
fn ask_replace(app: &VectorcraftApp, skipped: &[Value], file: Value, source: ImportSource) {
let names: Vec<Label> = skipped.iter().filter_map(Value::as_str).map(|n| Label::from(n.to_string())).collect();
let first = skipped.first().and_then(Value::as_str).map(str::to_owned);
let prompt = StandardPrompt::custom(tl!("Replace the saved presets that have these names?"))
.lines(names)
.button(PromptChoice::Proceed, tl!("Replace"))
.button(PromptChoice::Cancel, tl!("Cancel"))
.tag(ReplaceFile { file, first });
.button(PromptChoice::Cancel, tl!("Cancel"));
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| {
if host.is_open::<Manager>() {
host.open_child(ReplacePresets(prompt), dialog_id(KIND));
let over_manager = host.get::<Manager>().is_some_and(|manager| source.matches(manager));
let prompt = ReplacePresets(prompt.tag(ReplaceFile { file, first, source }));
if over_manager {
host.open_child(prompt, dialog_id(KIND));
} else {
host.open(ReplacePresets(prompt));
host.open(prompt);
}
});
}
@@ -331,12 +358,12 @@ fn answer_replace(app: &mut VectorcraftApp) {
if answer.choice != PromptChoice::Proceed {
return;
}
let Some(ReplaceFile { mut file, first }) = answer.take_tag::<ReplaceFile>() else { return };
let Some(ReplaceFile { mut file, first, source }) = answer.take_tag::<ReplaceFile>() else { return };
file["replace"] = json!(true);
match app.run("imageTrace.presets.import", file) {
Ok(_) => {
if let Some(first) = first {
select(app, &first);
source.select(app, &first);
}
}
Err(e) => app.status(e),
@@ -363,37 +390,36 @@ fn file_contents(app: &VectorcraftApp, file: Value) -> Result<Value, String> {
(None, Some(read)) => read(path)?,
(None, None) => return Err("no file reader".into()),
};
checked_contents(&bytes)
}
fn checked_contents(bytes: &[u8]) -> Result<Value, String> {
if bytes.len() > TRACE_PRESET_MAX_BYTES {
return Err(too_big());
}
Ok(json!({ "dataBase64": vectorcraft_format::base64_encode(&bytes) }))
Ok(json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) }))
}
/// A tracing presets file opened (File › Open, a drop, or the file Import… picked): it imports as
/// Import… does, over the manager when it is open (which selects the first preset it added), and
/// asks whether to replace saved presets of the file's names.
/// Imports a tracing presets file opened through File › Open or a drop. The open manager selects
/// the first newly imported preset and hosts the question about duplicates.
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_import(app, checked_contents(bytes)?, ImportSource::FileOpen)
}
/// [`open_file`] for the tracing presets file at `path` (File › Open, a drop, Import…): the file is
/// read no further than one byte past the size limit.
/// [`open_file`] for the file at `path`. Reads at most one byte past the size limit.
pub(crate) fn open_path(app: &mut VectorcraftApp, path: &str) -> Result<(), String> {
let file = file_contents(app, json!({ "path": path }))?;
open_import(app, file)
open_import(app, file, ImportSource::FileOpen)
}
/// The import of a tracing presets file `file` (`{dataBase64}`), over the manager when it is open.
fn open_import(app: &mut VectorcraftApp, file: Value) -> Result<(), String> {
/// Imports the file into the saved presets and directs its dialog changes to the import's source.
fn open_import(app: &mut VectorcraftApp, file: Value, source: ImportSource) -> Result<(), String> {
let (imported, skipped) = import_file(app, &file)?;
if let Some(first) = imported.get(0).and_then(Value::as_str) {
select(app, first);
source.select(app, first);
}
if !skipped.is_empty() {
ask_replace(app, &skipped, file);
ask_replace(app, &skipped, file, source);
}
Ok(())
}
@@ -1,6 +1,7 @@
//! Edit → Tracing Presets: New… and Edit… through the preset editor, Delete, and the import with
//! the question about saved presets of the same names, all through the dialog host.
use craft::host::ScriptedFiles;
use craft::ui::dialog::dialog_id;
use craft::ui::patterns::form_dialogs::{FieldValue, HostedParamDialog};
use serde_json::{Value, json};
@@ -297,6 +298,47 @@ fn import_asks_before_replacing_saved_presets() {
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn delayed_import_keeps_the_reopened_tracing_preset_managers_selection() {
let (mut app, ctx) = windowed(Default::default());
let files = Arc::new(ScriptedFiles::held());
let host = app.host.with_files(files.clone());
host.clone().install(&ctx);
app.host = Arc::new(host);
app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap();
app.run("ui.tracingPresetsDialog", json!({})).unwrap();
press(&mut app, &ctx, Action::Import);
assert_eq!(files.open(), 1);
let dialogs = app.dialogs().unwrap();
assert!(dialogs.with(|host| host.cancel::<Manager>(&ctx)));
app.run("ui.tracingPresetsDialog", json!({"selected": "6 Colors"})).unwrap();
let contents =
br#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Poster", "params": {"noise": 40}}, {"name": "Ink", "params": {}}]}"#;
assert!(files.answer(Picked::Contents(vec![("picked.vctracepresets".into(), contents.to_vec())])).is_some());
crate::file_asks::poll(&mut app);
pass(&mut app, &ctx);
assert_eq!(saved_names(&app), ["Poster", "Ink"], "the requested import still adds new presets");
assert_eq!(selected(&app).as_deref(), Some("6 Colors"), "the reopened manager keeps its own selection");
let replace = dialog_id(REPLACE_KIND);
dialogs.with(|host| {
assert!(host.is_open::<ReplacePresets>());
assert_eq!(host.stack().parent(replace), None, "the duplicate question does not belong to the reopened manager");
host.set_json_field(&ctx, replace, "choice", json!("proceed")).unwrap();
assert!(host.confirm_by_id(&ctx, replace));
});
pass(&mut app, &ctx);
assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40, "Replace still updates the saved preset");
assert_eq!(selected(&app).as_deref(), Some("6 Colors"), "Replace leaves the reopened manager's selection alone");
press(&mut app, &ctx, Action::Import);
let current_pick = br#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Graphite", "params": {}}]}"#;
assert!(files.answer(Picked::Contents(vec![("current.vctracepresets".into(), current_pick.to_vec())])).is_some());
crate::file_asks::poll(&mut app);
pass(&mut app, &ctx);
assert_eq!(selected(&app).as_deref(), Some("Graphite"), "the current manager selects the preset it imported");
}
#[test]
fn a_file_with_a_fault_changes_nothing() {
let dir = std::env::temp_dir().join(format!("vc-tracing-presets-bad-{}", std::process::id()));