diff --git a/crates/ui-egui/src/dialogs/find_links.rs b/crates/ui-egui/src/dialogs/find_links.rs index 3f9bd56c57..d717d02f9e 100644 --- a/crates/ui-egui/src/dialogs/find_links.rs +++ b/crates/ui-egui/src/dialogs/find_links.rs @@ -6,7 +6,7 @@ //! (the size and hash saved with the link). Relink relinks each choice (`links.relink`, one undo //! step each); with Copy into the document's folder (a saved document), an image's file is copied //! there first, never replacing a file, and a placed document is relinked where its file is. Opened -//! from Find in Folder… in Linked File Not Found (dialog `missingLinks`), the files left without a +//! from Find in Folder… in Linked File Not Found ([`super::missing_links`]), the files left without a //! choice and those that fail to relink go back to that dialog; opened from the Links panel's Find //! in Folder… (`ui.findLinksInFolder`), they stay as they are. //! @@ -14,62 +14,303 @@ //! of the images whose file was modified, offered for update afterwards), `notes` (from //! `missingLinks`: the open's notes, shown with the line about the modified files), `back` (the //! files left without a choice and those that fail to relink go back to dialog `missingLinks`), `state` -//! (empty, `searching`, `done`, `stopped` or `failed`), `search` (the search's `id`), `folder`, +//! (empty, `searching`, `done`, `stopped` or `failed`), `search` (the search's id), `folder`, //! `found` (`links.findFiles`'s `links`, with the files found), `searched`, `skipped`, //! `unreadable`, `stopped`, `error`, `picks` (the file chosen for each row of `missing`, or null), //! `touched` (the rows whose file was chosen in the dialog: new search results leave their pick as //! it is), `copy` and `searchFolder` (set it and confirm to search that folder). +//! +//! The dialog keeps those fields as its state ([`Fields`]) and files what needs the app (starting, +//! stopping and following the search) as a [`Request`]; [`pump`] does it each frame, since the +//! dialog has no app to run commands on. use std::time::Duration; -use serde_json::{Value, json}; +use craft::host::{PickKind, PickRequest}; +use craft::theme::TypeRole; +use craft::ui::buttons::Button; +use craft::ui::choice::{Checkbox, Radio, RadioGroup}; +use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use craft::ui::display::{Badge, Elide, Shade, Spinner, Text}; +use craft::ui::layout_components::{Row, Stack}; +use craft::ui::patterns::form_dialogs::FormDialog; +use serde_json::{Map, Value, json}; -use super::DialogSpec; -use crate::picks::PickRequest; -use crate::state::Dialog; -use crate::theme::{self, Tokens}; -use crate::{VectorcraftApp, widgets}; +use super::missing_links::{Asked, LinkAsk, flag_field, ids, label, show_notes_again, text_field}; +use crate::VectorcraftApp; +use crate::file_asks::{self, Owner}; /// The dialog kind of Find Linked Files. pub const KIND: &str = "findLinks"; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("Find Linked Files").into(), - body, - confirm, - ok: Some("Relink"), - min_width: 440.0, - max_width: Some(560.0), - inputs: |_| &["searchFolder"], - ..DialogSpec::FORM -}; +/// How often the dialog follows a running search, and a picker it waits for. +const POLL: Duration = Duration::from_millis(100); + +/// The dialog's state: the fields in the module's header. +type Fields = Map; /// The rows of field `key` of `d` (`missing`, `modified`, `picks`…). -fn rows(d: &Dialog, key: &str) -> Vec { - d.fields.get(key).and_then(Value::as_array).cloned().unwrap_or_default() +fn rows(d: &Fields, key: &str) -> Vec { + d.get(key).and_then(Value::as_array).cloned().unwrap_or_default() } -/// The ids in `rows` (`[{ids}]`). -fn ids(rows: &[Value]) -> Vec { - rows.iter().flat_map(|r| r["ids"].as_array().cloned().unwrap_or_default()).collect() +/// The string field `key` of `d`; empty when it has none. +fn text<'a>(d: &'a Fields, key: &str) -> &'a str { + d.get(key).and_then(Value::as_str).unwrap_or_default() } -/// A Find Linked Files dialog for the `missing` files of the active document. -fn dialog(app: &VectorcraftApp, missing: Vec, modified: Vec, back: bool) -> Result { +/// The boolean field `key` of `d`. +fn flag(d: &Fields, key: &str) -> bool { + d.get(key).and_then(Value::as_bool).unwrap_or(false) +} + +/// The open's notes the dialog keeps (field `notes`). +fn notes(d: &Fields) -> Vec { + d.get("notes").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect() +} + +/// What the dialog asks of the app on the next frame ([`pump`]). +enum Request { + /// Look for the files in this folder. + Search(String), + /// Stop the running search. + Stop, +} + +/// What the form edits: the file chosen for each row, the rows chosen in the dialog and Copy. +#[derive(Clone, Default, PartialEq)] +struct Edit { + picks: Vec, + touched: Vec, + copy: bool, +} + +/// Find Linked Files: the missing files, the files found for each and the one chosen. +pub(crate) struct FindLinksDialog { + fields: Fields, + request: Option, + search_folder: String, + asked: Asked<()>, + can_pick: bool, + /// The folder of the document, when it was saved: where Copy copies to. + copy_folder: Option, +} + +impl FindLinksDialog { + /// The dialog over `fields` ([`dialog`]). + fn new(app: &VectorcraftApp, fields: Fields) -> Self { + FindLinksDialog { + copy_folder: document_folder(app, &fields), + fields, + request: None, + search_folder: String::new(), + asked: Asked::default(), + can_pick: file_asks::can(app, PickKind::Folder), + } + } + + /// The id of the search the dialog started. + fn search(&self) -> Option { + self.fields.get("search").and_then(Value::as_u64) + } +} + +impl StackDialog for FindLinksDialog { + type Result = Fields; + + fn id(&self) -> DialogId { + dialog_id(KIND) + } + + fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { + let ctx = ui.ctx().clone(); + if let Some((picked, ())) = self.asked.answer(&ctx) + && let Some(folder) = picked.first_path() + { + self.request = Some(Request::Search(folder.to_string_lossy().into_owned())); + } + if self.asked.pending() || self.request.is_some() { + ctx.request_repaint_after(POLL); + } + let state = text(&self.fields, "state").to_string(); + let searching = state == "searching"; + let (missing, found) = (rows(&self.fields, "missing"), rows(&self.fields, "found")); + let progress = super::missing_fonts::progress(&Value::Object(self.fields.clone())); + let mut edit = Edit { picks: rows(&self.fields, "picks"), touched: rows(&self.fields, "touched"), copy: flag(&self.fields, "copy") }; + edit.picks.resize(missing.len(), Value::Null); + let (can_pick, copy_folder) = (self.can_pick, self.copy_folder.clone()); + let (mut pick, mut stop) = (false, false); + let shown = FormDialog::new(label(tl!("Find Linked Files")), Bind::bound(&mut edit)).ok_label(label(tl!("Relink"))).show(ui, |ui, _, edit| { + Text::new(label(tl!("Choose the file to relink each linked file to. Files with the size and contents saved with the link come first."))) + .shade(Shade::Muted) + .show(ui); + Stack::new().scroll(Scroll::vertical()).show(ui, |ui, _| { + for (i, row) in missing.iter().enumerate() { + let (name, path) = (row["name"].as_str().unwrap_or_default(), row["path"].as_str().unwrap_or_default()); + Text::new(label(name)).role(TypeRole::BodyStrong).show(ui); + Text::new(label(path)).shade(Shade::Muted).elide(Elide::Path).tooltip(path.to_string()).show(ui); + let files = files_for(&found, row); + let current = files.iter().position(|f| edit.picks.get(i) == Some(&f["path"])); + let mut chosen = current; + RadioGroup::new(label(name), Bind::bound(&mut chosen)).show(ui, |ui, _| { + for (at, f) in files.iter().enumerate() { + let file = f["path"].as_str().unwrap_or_default(); + let p = std::path::Path::new(file); + let file_name = p.file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned()); + Row::new().show(ui, |ui, _| { + Radio::new(Some(at)).label(label(&file_name)).show(ui); + match f["match"].as_str() { + Some("same") => Badge::new(label(tl!("Same file"))).show(ui), + Some("size") => Badge::new(label(tl!("Same size"))).show(ui), + _ => return, + }; + }); + let folder = p.parent().map_or_else(String::new, |f| f.to_string_lossy().into_owned()); + Text::new(label(&folder)).shade(Shade::Muted).elide(Elide::Path).tooltip(file.to_string()).show(ui); + } + if !files.is_empty() { + Radio::new(None::).label(label(tl!("Don't Relink"))).show(ui); + } + }); + if chosen != current + && let Some(slot) = edit.picks.get_mut(i) + { + *slot = chosen.and_then(|at| files.get(at)).map_or(Value::Null, |f| f["path"].clone()); + if !edit.touched.contains(&json!(i)) { + edit.touched.push(json!(i)); + } + } + // A failed search (a folder it refuses) didn't look: `progress` says why. + if files.is_empty() && !state.is_empty() && state != "failed" { + let line = if searching { tl!("Searching…") } else { tl!("Not found") }; + Text::new(label(line)).shade(Shade::Muted).show(ui); + } + } + }); + Row::new().show(ui, |ui, _| { + if can_pick && Button::new(label(tl!("Find in Folder…"))).enabled(!searching).show(ui).clicked() { + pick = true; + } + if searching { + stop = Button::new(label(tl!("Stop"))).show(ui).clicked(); + Spinner::new().show(ui); + } + }); + for line in &progress { + Text::new(line.clone()).shade(Shade::Muted).show(ui); + } + if let Some(folder) = ©_folder { + Checkbox::new(Bind::bound(&mut edit.copy)).label(label(tl!("Copy into the document's folder"))).tooltip(folder.clone()).show(ui); + } + true + }); + self.fields.insert("picks".into(), json!(edit.picks)); + self.fields.insert("touched".into(), json!(edit.touched)); + self.fields.insert("copy".into(), json!(edit.copy)); + if pick { + self.asked.file(&ctx, PickRequest::folder("links"), ()); + } + if stop { + self.request = Some(Request::Stop); + } + match (shown.accepted, shown.closed) { + (Some(_), _) => Some(DialogResult::Ok(self.fields.clone())), + (None, Some(_)) => { + self.asked.forget(&ctx); + Some(DialogResult::Cancel) + } + (None, None) => None, + } + } + + fn confirm(&mut self, _: &egui::Context) -> Option { + if !self.search_folder.is_empty() { + self.request = Some(Request::Search(std::mem::take(&mut self.search_folder))); + return None; + } + Some(self.fields.clone()) + } + + fn cancelled(&mut self, ctx: &egui::Context) { + self.asked.forget(ctx); + } + + fn json_fields(&self) -> Option { + Some(Value::Object(self.fields.clone())) + } + + fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> { + match field { + "searchFolder" => self.search_folder = text_field(field, &value)?, + "copy" => { + let copy = flag_field(field, &value)?; + self.fields.insert("copy".into(), json!(copy)); + } + "picks" => self.set_picks(&value)?, + _ => return Err(format!("unknown field `{field}`")), + } + ctx.request_repaint(); + Ok(()) + } +} + +impl FindLinksDialog { + /// Sets the file chosen for each row (`picks`, one path or null per row) as the user choosing + /// them would: a row whose file changes is one the next search results leave as it is. + fn set_picks(&mut self, value: &Value) -> Result<(), String> { + let rows_given = value.as_array().ok_or_else(|| format!("field `picks` takes a list, got {value}"))?; + let missing = rows(&self.fields, "missing").len(); + if rows_given.len() != missing || rows_given.iter().any(|p| !p.is_null() && !p.is_string()) { + return Err(format!("field `picks` takes {missing} paths or nulls, got {value}")); + } + let before = rows(&self.fields, "picks"); + let mut touched = rows(&self.fields, "touched"); + for (i, pick) in rows_given.iter().enumerate() { + if before.get(i) != Some(pick) && !touched.contains(&json!(i)) { + touched.push(json!(i)); + } + } + self.fields.insert("picks".into(), json!(rows_given)); + self.fields.insert("touched".into(), json!(touched)); + Ok(()) + } +} + +/// The fields of a Find Linked Files dialog for the `missing` files of the active document. +fn dialog(app: &VectorcraftApp, missing: Vec, modified: Vec, back: bool) -> Result { let uid = app.session.active().map(|d| d.uid).ok_or("no document open")?; let picks = vec![Value::Null; missing.len()]; - let fields = - json!({ "document": uid, "missing": missing, "modified": modified, "back": back, "state": "", "picks": picks, "touched": [], "copy": false }); - Ok(Dialog::new(KIND, fields)) + let fields = json!({ "document": uid, "missing": missing, "modified": modified, "back": back, "state": "", "picks": picks, "touched": [], "copy": false }); + match fields { + Value::Object(fields) => Ok(fields), + _ => Err("the dialog has no fields".into()), + } } -/// Linked File Not Found's Find in Folder… (`d`, the `missingLinks` dialog): `d` becomes Find -/// Linked Files, searching `folder` for every file `d` still asks about. -pub(super) fn from_missing_links(app: &mut VectorcraftApp, d: &mut Dialog, folder: &str) -> Result<(), String> { - let mut find = dialog(app, rows(d, "missing"), rows(d, "modified"), true)?; - find.fields.insert("notes".into(), json!(super::missing_links::notes(d))); +/// Shows the dialog over `fields`. +fn open(app: &mut VectorcraftApp, fields: Fields) -> Result<(), String> { + let dialog = FindLinksDialog::new(app, fields); + let dialogs = app.dialogs().ok_or("no window to show the dialog in")?; + dialogs.with(|h| h.open(dialog)); + Ok(()) +} + +/// Linked File Not Found's Find in Folder…: Find Linked Files opens, searching `folder` for every +/// file still asked about (`missing`). The files left without a choice and those that fail to +/// relink go back to Linked File Not Found, with `modified` and the open's `notes`. +pub(super) fn from_missing_links( + app: &mut VectorcraftApp, + missing: Vec, + modified: Vec, + notes: Vec, + folder: &str, +) -> Result<(), String> { + let mut find = dialog(app, missing.clone(), modified.clone(), true)?; + find.insert("notes".into(), json!(notes)); start_search(app, &mut find, folder)?; - *d = find; + open(app, find)?; + app.link_asks = Some(LinkAsk { missing, modified, notes, back: true }); Ok(()) } @@ -86,11 +327,9 @@ fn selected_linked(app: &VectorcraftApp) -> Vec { st.selection.objects.iter().filter(|id| linked(id)).map(|id| json!(id.0)).collect() } -/// `ui.findLinksInFolder` (the Links panel's Find in Folder…): ask for a folder (or take `folder`), -/// then open Find Linked Files searching it for the files of linked objects `ids` (default: the -/// selected linked images and placed documents, else the files that are missing). -pub(crate) fn find_in_folder_command(app: &mut VectorcraftApp, folder: Option, ids: Option>) -> Result { - let ids = ids.filter(|ids| !ids.is_empty()).or_else(|| Some(selected_linked(app)).filter(|ids| !ids.is_empty())); +/// The linked files of objects `ids` (all of them when given, else the files that are missing) as +/// the rows the dialog looks for. Nothing to look for is an error. +fn linked_files(app: &mut VectorcraftApp, ids: Option<&[Value]>) -> Result, String> { let all = ids.is_some(); let r = app.session.execute("links.check", &json!({ "ids": ids })).map_err(|e| e.to_string())?; let missing: Vec = r["links"] @@ -100,17 +339,35 @@ pub(crate) fn find_in_folder_command(app: &mut VectorcraftApp, folder: Option f, - None => crate::picks::folder(app).ok_or("cancelled")?, - }; + Ok(missing) +} + +/// `ui.findLinksInFolder` (the Links panel's Find in Folder…): ask for a folder (or take `folder`), +/// then open Find Linked Files searching it for the files of linked objects `ids` (default: the +/// selected linked images and placed documents, else the files that are missing). +pub(crate) fn find_in_folder_command(app: &mut VectorcraftApp, folder: Option, ids: Option>) -> Result { + let ids = ids.filter(|ids| !ids.is_empty()).or_else(|| Some(selected_linked(app)).filter(|ids| !ids.is_empty())); + // Nothing to look for: no folder is asked for. + linked_files(app, ids.as_deref())?; + match folder { + Some(folder) => find_in(app, ids, &folder), + // PLAN: assumed `file_asks::Owner::Document` and `ask(app, request, owner, then) -> Value` (fl.A3, files-w5). + None => Ok(file_asks::ask(app, PickRequest::folder("links"), Owner::Document, move |app, picked| { + let folder = picked.first_path().ok_or("cancelled")?; + find_in(app, ids, &folder.to_string_lossy()) + })), + } +} + +/// Opens Find Linked Files searching `folder` for the files of `ids`. +fn find_in(app: &mut VectorcraftApp, ids: Option>, folder: &str) -> Result { + let missing = linked_files(app, ids.as_deref())?; let mut d = dialog(app, missing, vec![], false)?; - start_search(app, &mut d, &folder)?; - app.ui.dialog = Some(d); + start_search(app, &mut d, folder)?; + open(app, d)?; Ok(Value::Null) } @@ -123,8 +380,8 @@ fn is_image(app: &VectorcraftApp, id: &Value) -> bool { } /// Make the dialog's document the active one: it may be another tab's. -fn activate(app: &mut VectorcraftApp, d: &Dialog) -> Result<(), String> { - let uid = d.fields.get("document").and_then(Value::as_u64); +fn activate(app: &mut VectorcraftApp, d: &Fields) -> Result<(), String> { + let uid = d.get("document").and_then(Value::as_u64); if app.session.active().map(|st| st.uid) == uid { return Ok(()); } @@ -134,16 +391,16 @@ fn activate(app: &mut VectorcraftApp, d: &Dialog) -> Result<(), String> { /// Start looking in `folder` for the files of the dialog's rows; what an earlier search found, and /// the files chosen from it, are dropped. -fn start_search(app: &mut VectorcraftApp, d: &mut Dialog, folder: &str) -> Result<(), String> { +fn start_search(app: &mut VectorcraftApp, d: &mut Fields, folder: &str) -> Result<(), String> { activate(app, d)?; let r = app.run("links.findFiles", json!({ "folder": folder, "ids": ids(&rows(d, "missing")) }))?; for k in ["found", "searched", "skipped", "unreadable", "stopped", "error"] { - d.fields.remove(k); + d.remove(k); } - d.fields.insert("picks".into(), json!(vec![Value::Null; rows(d, "missing").len()])); - d.fields.insert("touched".into(), json!([])); - d.fields.insert("search".into(), r["id"].clone()); - d.fields.insert("folder".into(), json!(folder)); + d.insert("picks".into(), json!(vec![Value::Null; rows(d, "missing").len()])); + d.insert("touched".into(), json!([])); + d.insert("search".into(), r["id"].clone()); + d.insert("folder".into(), json!(folder)); update(d, &r); app.ui.links_search = r["id"].as_u64(); Ok(()) @@ -169,7 +426,7 @@ fn first_pick(files: &[Value]) -> Option<&Value> { /// A search's answer `r` into the dialog. A row whose file wasn't chosen in the dialog takes the /// file chosen at the start ([`first_pick`]). -fn update(d: &mut Dialog, r: &Value) { +fn update(d: &mut Fields, r: &Value) { let missing = rows(d, "missing"); let touched = rows(d, "touched"); let mut picks = rows(d, "picks"); @@ -180,23 +437,23 @@ fn update(d: &mut Dialog, r: &Value) { *pick = first_pick(files_for(found, row)).cloned().unwrap_or(Value::Null); } } - d.fields.insert("picks".into(), json!(picks)); - d.fields.insert("found".into(), r["links"].clone()); + d.insert("picks".into(), json!(picks)); + d.insert("found".into(), r["links"].clone()); for k in ["state", "searched", "skipped", "unreadable", "stopped", "error"] { match r.get(k) { - Some(v) => d.fields.insert(k.into(), v.clone()), - None => d.fields.remove(k), + Some(v) => d.insert(k.into(), v.clone()), + None => d.remove(k), }; } } /// While searching: the search's progress into the dialog. A search started elsewhere since /// stopped this one. -fn follow(app: &mut VectorcraftApp, d: &mut Dialog) { +fn follow(app: &mut VectorcraftApp, d: &mut Fields) { // Polled through `session.execute`. let Ok(r) = app.session.execute("links.findFiles", &json!({})) else { return }; - if d.fields.get("search") != Some(&r["id"]) { - d.fields.insert("state".into(), json!("stopped")); + if d.get("search") != Some(&r["id"]) { + d.insert("state".into(), json!("stopped")); return; } update(d, &r); @@ -208,7 +465,7 @@ fn follow(app: &mut VectorcraftApp, d: &mut Dialog) { /// Stop the search the dialog started once the dialog is gone (closed, or another in its place). pub(super) fn stop_when_closed(app: &mut VectorcraftApp) { let Some(id) = app.ui.links_search else { return }; - let open = app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND && d.fields.get("search").and_then(Value::as_u64) == Some(id)); + let open = app.dialogs().is_some_and(|d| d.with(|h| h.get::().is_some_and(|d| d.search() == Some(id)))); if !open { app.ui.links_search = None; vectorcraft_engine::cmd::linkfiles::stop(&mut app.session, id); @@ -216,141 +473,66 @@ pub(super) fn stop_when_closed(app: &mut VectorcraftApp) { } /// The folder of the dialog's document, when it was saved. -fn document_folder(app: &VectorcraftApp, d: &Dialog) -> Option { - let uid = d.fields.get("document").and_then(Value::as_u64)?; +fn document_folder(app: &VectorcraftApp, d: &Fields) -> Option { + let uid = d.get("document").and_then(Value::as_u64)?; let path = app.session.documents().iter().find(|doc| doc.uid == uid)?.path.clone()?; std::path::Path::new(&path).parent().map(|p| p.to_string_lossy().into_owned()) } -/// A button of the dialog's. -enum Act { - Pick, - Stop, -} - -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let t = Tokens::get(ui.ctx()); - if d.str("state") == "searching" { - follow(app, d); - ui.ctx().request_repaint_after(Duration::from_millis(100)); - } - let state = d.str("state"); - let searching = state == "searching"; - widgets::dim_label(ui, tl!("Choose the file to relink each linked file to. Files with the size and contents saved with the link come first.")); - ui.add_space(8.0); - let missing = rows(d, "missing"); - let found = rows(d, "found"); - let mut picks = rows(d, "picks"); - picks.resize(missing.len(), Value::Null); - let mut touched = rows(d, "touched"); - widgets::list_box(ui, |ui| { - egui::ScrollArea::vertical().max_height(280.0).show(ui, |ui| { - ui.set_width(ui.available_width()); - for (i, (row, pick)) in missing.iter().zip(picks.iter_mut()).enumerate() { - ui.horizontal(|ui| { - ui.add_space(6.0); - ui.vertical(|ui| { - ui.add_space(3.0); - ui.label(egui::RichText::new(row["name"].as_str().unwrap_or_default()).font(theme::semibold(12.0)).color(t.text_strong)); - let path = row["path"].as_str().unwrap_or_default(); - ui.add(egui::Label::new(egui::RichText::new(path).size(11.0).color(t.text_dim)).truncate()).on_hover_text(path); - let files = files_for(&found, row); - let mut chose = None; - for f in files { - let file = f["path"].as_str().unwrap_or_default(); - let p = std::path::Path::new(file); - ui.horizontal(|ui| { - let name = p.file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned()); - if widgets::radio(ui, &name, *pick == f["path"], true) { - chose = Some(f["path"].clone()); - } - let tag = match f["match"].as_str() { - Some("same") => tl!("Same file"), - Some("size") => tl!("Same size"), - _ => "", - }; - if !tag.is_empty() { - ui.label(egui::RichText::new(tag).size(11.0).color(t.accent)); - } - }); - let folder = p.parent().map_or_else(String::new, |f| f.to_string_lossy().into_owned()); - ui.add(egui::Label::new(egui::RichText::new(folder).size(11.0).color(t.text_dim)).truncate()).on_hover_text(file); - } - if !files.is_empty() && widgets::radio(ui, tl!("Don't Relink"), pick.is_null(), true) { - chose = Some(Value::Null); - } - if let Some(c) = chose { - *pick = c; - if !touched.contains(&json!(i)) { - touched.push(json!(i)); - } - } - // A failed search (a folder it refuses) didn't look: `progress` says why. - if files.is_empty() && !state.is_empty() && state != "failed" { - widgets::dim_label(ui, if searching { tl!("Searching…") } else { tl!("Not found") }); - } - ui.add_space(3.0); - }); - }); +/// Each frame: stops a search whose dialog is gone, takes the answer of the dialog that closed +/// (Cancel shows the open's notes again when Linked File Not Found opened it; Relink relinks), and +/// does what the open dialog asked of the app: start or stop its search, and follow it while it runs. +pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { + stop_when_closed(app); + let Some(dialogs) = app.dialogs() else { return }; + if let Some(result) = dialogs.with(|h| h.take::()) { + let ask = app.link_asks.take_if(|ask| ask.back); + match (result.ok(), ask) { + (Some(fields), _) => { + if let Err(e) = relink(app, &fields) { + app.status(e); + } } - }); - }); - d.fields.insert("picks".into(), json!(picks)); - d.fields.insert("touched".into(), json!(touched)); - ui.add_space(10.0); - let mut act = None; - ui.horizontal(|ui| { - if crate::picks::can(app, &PickRequest::Folder) && ui.add_enabled(!searching, egui::Button::new(tl!("Find in Folder…"))).clicked() { - act = Some(Act::Pick); - } - if searching { - if ui.button(tl!("Stop")).clicked() { - act = Some(Act::Stop); - } - ui.add(egui::Spinner::new().size(12.0).color(t.accent)); - } - }); - super::missing_fonts::progress(ui, d); - if let Some(folder) = document_folder(app, d) { - ui.add_space(8.0); - let copy = d.bool("copy"); - if widgets::check_tip(ui, tl!("Copy into the document's folder"), copy, true, &folder) { - d.fields.insert("copy".into(), json!(!copy)); + (None, Some(ask)) => show_notes_again(app, &ask), + (None, None) => {} } + return; } - let r = match act { - Some(Act::Pick) => crate::picks::in_dialog(app, d, |app, d| match crate::picks::folder(app) { - Some(folder) => start_search(app, d, &folder), - None => Ok(()), - }), - Some(Act::Stop) => app.run("links.findFiles", json!({ "stop": true })).map(|_| follow(app, d)), - None => Ok(()), + let Some((mut fields, request)) = dialogs.with(|h| h.get_mut::().map(|d| (d.fields.clone(), d.request.take()))) else { + return; }; - if let Err(e) = r { + if request.is_none() && text(&fields, "state") != "searching" { + return; + } + let before = fields.clone(); + let done = match request { + Some(Request::Search(folder)) => start_search(app, &mut fields, &folder), + Some(Request::Stop) => app.run("links.findFiles", json!({ "stop": true })).map(|_| follow(app, &mut fields)), + None => { + follow(app, &mut fields); + Ok(()) + } + }; + if let Err(e) = done { app.status(e); } - false + if text(&fields, "state") == "searching" { + ctx.request_repaint_after(POLL); + } + if fields != before { + dialogs.with(|h| { + if let Some(d) = h.get_mut::() { + d.fields = fields; + } + }); + } } -/// With `searchFolder` (agents): search that folder, and stay open. Otherwise Relink: each row's -/// file, one `links.relink` each (copied into the document's folder with `copy`). The status line -/// names the first file that fails to relink, and the other files still relink. From Linked File -/// Not Found, the rows left without a file and the rows that failed to relink go back to it, then -/// the modified files are offered for update. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let folder = d.str("searchFolder"); - if !folder.is_empty() { - let mut d = d.clone(); - d.fields.remove("searchFolder"); - // The folder is searched once: a search that doesn't start leaves the dialog without it. - if let Some(open) = app.ui.dialog.as_mut().filter(|open| open.kind == KIND) { - open.fields.remove("searchFolder"); - } - start_search(app, &mut d, &folder)?; - let state = d.fields.get("state").cloned().unwrap_or(Value::Null); - app.ui.dialog = Some(d); - return Ok(json!({ "state": state })); - } +/// Relink: each row's file, one `links.relink` each (copied into the document's folder with +/// `copy`). The status line names the first file that fails to relink, and the other files still +/// relink. From Linked File Not Found, the rows left without a file and the rows that failed to +/// relink go back to it, then the modified files are offered for update. +fn relink(app: &mut VectorcraftApp, d: &Fields) -> Result { activate(app, d)?; let picks = rows(d, "picks"); let (mut relinked, mut failed, mut rest) = (vec![], vec![], vec![]); @@ -361,7 +543,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { }; let mut params = json!({ "ids": row["ids"], "path": path }); // A placed document is relinked where its file is. - if d.bool("copy") && row["ids"].as_array().is_some_and(|ids| ids.iter().all(|id| is_image(app, id))) { + if flag(d, "copy") && row["ids"].as_array().is_some_and(|ids| ids.iter().all(|id| is_image(app, id))) { params["copy"] = json!(true); } match app.run("links.relink", params) { @@ -372,7 +554,6 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } } } - app.ui.dialog = None; let n = relinked.len(); match failed.first() { Some(f) => { @@ -387,8 +568,8 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { None if n > 0 => app.status(crate::panels::links::relinked_status(n)), None => {} } - if d.bool("back") { - super::missing_links::ask_next(app, rest, rows(d, "modified"), super::missing_links::notes(d)); + if flag(d, "back") { + super::missing_links::ask_next(app, rest, rows(d, "modified"), notes(d)); } Ok(json!({ "relinked": relinked, "failed": failed })) } diff --git a/crates/ui-egui/src/dialogs/find_links/tests.rs b/crates/ui-egui/src/dialogs/find_links/tests.rs index c582154173..0459e0a723 100644 --- a/crates/ui-egui/src/dialogs/find_links/tests.rs +++ b/crates/ui-egui/src/dialogs/find_links/tests.rs @@ -1,15 +1,11 @@ use std::path::{Path, PathBuf}; use std::time::Instant; -use vectorcraft_engine::Session; use vectorcraft_engine::cmd::findfiles::Rules; +use super::super::missing_links::{MissingLinksDialog, drive}; use super::*; -fn frame(app: &mut VectorcraftApp) -> String { - crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) -} - /// A fresh temporary folder (canonical, as a search reports it). fn folder(tag: &str) -> PathBuf { let dir = vectorcraft_testkit::temp_dir(&format!("find-links-{tag}")); @@ -18,12 +14,11 @@ fn folder(tag: &str) -> PathBuf { vectorcraft_engine::cmd::findfiles::plain(std::fs::canonicalize(&dir).unwrap()) } -/// An app that reads files, shows a folder picker and whose searches may go anywhere in `root`, +/// An app that reads files, with a window dialog host, and whose searches may go anywhere in `root`, /// on two threads. fn app_for(root: &Path) -> VectorcraftApp { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = drive::app(); app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); - app.services.pick_folder = Some(Box::new(|| None)); app.session.search_rules = Some(Rules { user_content: vec![root.to_path_buf()], ..Rules::default() }); app.session.search_threads = Some(2); app @@ -106,23 +101,37 @@ fn opened_without(app: &mut VectorcraftApp, root: &Path, names: &[&str]) -> Vec< /// search's default `maxSeconds` of 60, which would end a search that does not end by itself. const WAIT: Duration = Duration::from_secs(30); -/// Draw the dialog until its search ends ([`WAIT`] at most). +/// The fields of the open Find Linked Files dialog. +fn found(app: &VectorcraftApp) -> Value { + drive::fields::(app) +} + +/// Pump frames until the dialog's search ends ([`WAIT`] at most). fn searched(app: &mut VectorcraftApp) { let until = Instant::now() + WAIT; - while app.ui.dialog.as_ref().is_some_and(|d| d.str("state") == "searching") && Instant::now() < until { - frame(app); + while found(app)["state"] == "searching" && Instant::now() < until { + drive::pump(app); std::thread::sleep(Duration::from_millis(5)); } } -fn kind(app: &VectorcraftApp) -> Option<&str> { - app.ui.dialog.as_ref().map(|d| d.kind.as_str()) +/// The pick of the row named `name` in the dialog's `fields`. +fn pick(fields: &Value, name: &str) -> Value { + let i = fields["missing"].as_array().unwrap().iter().position(|r| r["name"] == name).unwrap(); + fields["picks"][i].clone() } -/// The pick of the row named `name`. -fn pick<'a>(d: &'a Dialog, name: &str) -> &'a Value { - let i = d.fields["missing"].as_array().unwrap().iter().position(|r| r["name"] == name).unwrap(); - &d.fields["picks"][i] +/// The folder the open dialog copies into, when it offers Copy. +fn copy_folder(app: &VectorcraftApp) -> Option { + app.dialogs().and_then(|d| d.with(|h| h.get::().map(|d| d.copy_folder.clone()))).expect("the dialog is open") +} + +/// The Find Linked Files state `v` as the dialog keeps it. +fn state(v: Value) -> Fields { + match v { + Value::Object(fields) => fields, + other => panic!("fields are an object, got {other}"), + } } /// Find in Folder… in Linked File Not Found: each missing file's same file is chosen, and Relink @@ -132,27 +141,20 @@ fn find_in_folder_relinks_the_missing_files_to_the_files_found() { let root = folder("relink"); let mut app = app_for(&root); let bytes = opened_without(&mut app, &root, &["a.png", "b.png"]); - assert_eq!(kind(&app), Some(super::super::missing_links::KIND)); - assert!(frame(&mut app).contains("Find in Folder…")); + assert!(drive::is_open::(&app)); let (a, b) = (at(&root, "found/sub/a.png"), at(&root, "found/b.png")); write(&a, &bytes[0]); write(&b, &bytes[1]); write(&at(&root, "found/other/b.png"), b"another file"); // What Find in Folder… does with the folder picked. - app.ui.dialog.as_mut().unwrap().fields.insert("searchFolder".into(), json!(root.join("found"))); - let r = super::super::confirm(&mut app).unwrap(); - assert!(matches!(r["state"].as_str(), Some("searching" | "done")), "{r}"); - assert_eq!(kind(&app), Some(KIND)); + drive::answer::(&mut app, &[("searchFolder", json!(root.join("found")))], true); + assert!(drive::is_open::(&app) && !drive::is_open::(&app)); + assert!(matches!(found(&app)["state"].as_str(), Some("searching" | "done")), "{}", found(&app)); searched(&mut app); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.str("state"), pick(d, "a.png"), pick(d, "b.png")), ("done".to_string(), &json!(a), &json!(b))); - let text = frame(&mut app); - for label in ["Find Linked Files", "a.png", "b.png", "Same file", "Don't Relink", "Find in Folder…", "Copy into the document's folder", "Relink"] - { - assert!(text.contains(label), "{label} in {text}"); - } - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + let f = found(&app); + assert_eq!((&f["state"], pick(&f, "a.png"), pick(&f, "b.png")), (&json!("done"), json!(a), json!(b))); + drive::answer::(&mut app, &[], true); + assert!(!drive::is_open::(&app)); assert_eq!(app.ui.status, "Relinked 2 images"); assert_eq!(app.run("links.check", json!({})).unwrap()["missing"], 0); } @@ -167,24 +169,22 @@ fn files_not_relinked_go_back_to_linked_file_not_found() { let bytes = opened_without(&mut app, &root, &["a.png", "b.png", "c.png"]); write(&at(&root, "found/a.png"), &bytes[0]); write(&at(&root, "found/b.png"), b"not an image"); - let missing_links = app.ui.dialog.as_mut().unwrap(); - missing_links.fields.insert("notes".into(), json!(["a note"])); - missing_links.fields.insert("searchFolder".into(), json!(root.join("found"))); - super::super::confirm(&mut app).unwrap(); + // The open's notes are the ones the questions keep. + app.link_asks.as_mut().unwrap().notes = vec!["a note".to_string()]; + drive::answer::(&mut app, &[("searchFolder", json!(root.join("found")))], true); searched(&mut app); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!(d.fields["notes"], json!(["a note"])); + let f = found(&app); + assert_eq!(f["notes"], json!(["a note"])); // b.png's only file is chosen, c.png has none. - assert_eq!((pick(d, "b.png"), pick(d, "c.png")), (&json!(at(&root, "found/b.png")), &Value::Null)); - assert!(frame(&mut app).contains("Not found")); - super::super::confirm(&mut app).unwrap(); + assert_eq!((pick(&f, "b.png"), pick(&f, "c.png")), (json!(at(&root, "found/b.png")), Value::Null)); + drive::answer::(&mut app, &[], true); assert!(app.ui.status.starts_with("Relinked 1 image; b.png couldn't be relinked: "), "{}", app.ui.status); - let d = app.ui.dialog.as_ref().expect("Linked File Not Found again"); - let names: Vec<&str> = d.fields["missing"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap()).collect(); - assert_eq!((d.kind.as_str(), names.len()), (super::super::missing_links::KIND, 2)); + let m = drive::fields::(&app); + let names: Vec<&str> = m["missing"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap()).collect(); + assert_eq!(names.len(), 2); assert!(names.contains(&"b.png") && names.contains(&"c.png"), "{names:?}"); - assert_eq!(d.fields["notes"], json!(["a note"])); - super::super::cancel(&mut app); + assert_eq!(m["notes"], json!(["a note"])); + drive::answer::(&mut app, &[], false); assert_eq!(app.run("links.check", json!({})).unwrap()["missing"], 2); let opened = crate::io::opened_with_notes(1, "a note"); assert_eq!((&app.ui.status, &app.ui.status_notes), (&opened, &Some((opened.clone(), vec!["a note".to_string()])))); @@ -198,28 +198,32 @@ fn the_last_find_in_folder_answer_keeps_the_open_notes() { let root = folder("notes"); let mut app = app_for(&root); let bytes = opened_without(&mut app, &root, &["a.png"]); - let found = at(&root, "found/a.png"); - write(&found, &bytes[0]); - let missing = rows(app.ui.dialog.as_ref().unwrap(), "missing"); + let place = at(&root, "found/a.png"); + write(&place, &bytes[0]); + let missing = drive::fields::(&app)["missing"].as_array().cloned().unwrap(); let notes = vec!["a note".to_string(), "another note".to_string()]; let opened = crate::io::opened_with_notes(2, "a note"); - let find = |app: &mut VectorcraftApp, back: bool| { - let mut d = dialog(app, missing.clone(), vec![], back).unwrap(); - d.fields.insert("notes".into(), json!(notes)); - d.fields.insert("picks".into(), json!([found])); - app.ui.dialog = Some(d); + drive::answer::(&mut app, &[], false); + let search = root.join("found").to_string_lossy().into_owned(); + + // From the Links panel: Cancel leaves the message. + app.run("ui.findLinksInFolder", json!({ "folder": search })).unwrap(); + app.status("Something else"); + drive::answer::(&mut app, &[], false); + assert_eq!(app.ui.status, "Something else"); + + // From Linked File Not Found. + let from_missing = |app: &mut VectorcraftApp| { + from_missing_links(app, missing.clone(), vec![], notes.clone(), &search).unwrap(); app.status("Something else"); }; - find(&mut app, false); - super::super::cancel(&mut app); - assert_eq!(app.ui.status, "Something else"); - find(&mut app, true); - super::super::cancel(&mut app); - assert!(app.ui.dialog.is_none()); + from_missing(&mut app); + drive::answer::(&mut app, &[], false); + assert!(!drive::is_open::(&app)); assert_eq!((&app.ui.status, &app.ui.status_notes), (&opened, &Some((opened.clone(), notes.clone()))), "Cancel"); - find(&mut app, true); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + from_missing(&mut app); + drive::answer::(&mut app, &[("picks", json!([place]))], true); + assert!(!drive::is_open::(&app) && !drive::is_open::(&app)); assert_eq!(app.run("links.check", json!({})).unwrap()["missing"], 0); assert_eq!((&app.ui.status, &app.ui.status_notes), (&opened, &Some((opened.clone(), notes.clone()))), "Relink"); } @@ -229,7 +233,7 @@ fn the_last_find_in_folder_answer_keeps_the_open_notes() { #[test] fn a_file_is_chosen_only_when_the_choice_is_clear() { let row = |p: &str| json!({"name": "a.png", "path": p, "ids": [1]}); - let mut d = Dialog::new(KIND, json!({"missing": [row("/x/a.png"), row("/y/a.png"), row("/z/a.png")], "picks": [], "touched": []})); + let mut d = state(json!({"missing": [row("/x/a.png"), row("/y/a.png"), row("/z/a.png")], "picks": [], "touched": []})); let file = |p: &str, m: &str| json!({"path": p, "match": m}); let answer = |y: Vec| { json!({"state": "searching", "links": [ @@ -239,13 +243,13 @@ fn a_file_is_chosen_only_when_the_choice_is_clear() { ]}) }; update(&mut d, &answer(vec![file("/f/a.png", "name")])); - assert_eq!(d.fields["picks"], json!(["/f/a.png", "/f/a.png", null])); + assert_eq!(d["picks"], json!(["/f/a.png", "/f/a.png", null])); // Don't Relink chosen for the first row: the next answer leaves it, and the second row has // two files now. - d.fields.insert("picks".into(), json!([null, "/f/a.png", null])); - d.fields.insert("touched".into(), json!([0])); + d.insert("picks".into(), json!([null, "/f/a.png", null])); + d.insert("touched".into(), json!([0])); update(&mut d, &answer(vec![file("/f/a.png", "name"), file("/g/a.png", "name")])); - assert_eq!(d.fields["picks"], json!([null, null, null])); + assert_eq!(d["picks"], json!([null, null, null])); } /// A search of another folder starts the choices over: a file chosen from the last folder's @@ -255,23 +259,20 @@ fn another_folder_starts_the_choices_over() { let root = folder("again"); let mut app = app_for(&root); opened_without(&mut app, &root, &["a.png"]); - super::super::cancel(&mut app); + drive::answer::(&mut app, &[], false); // Two files of the name and neither the same file: the search reads both folders. write(&at(&root, "one/a.png"), b"one file"); write(&at(&root, "one/x/a.png"), b"another file"); std::fs::create_dir_all(root.join("two")).unwrap(); app.run("ui.findLinksInFolder", json!({"folder": root.join("one")})).unwrap(); searched(&mut app); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["found"][0]["files"].as_array().map(Vec::len), Some(2)); + assert_eq!(found(&app)["found"][0]["files"].as_array().map(Vec::len), Some(2)); // The second file chosen, then another folder searched, which has no file of the name. - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("picks".into(), json!([at(&root, "one/x/a.png")])); - d.fields.insert("touched".into(), json!([0])); - d.fields.insert("searchFolder".into(), json!(root.join("two"))); - super::super::confirm(&mut app).unwrap(); + let fields = [("picks", json!([at(&root, "one/x/a.png")])), ("searchFolder", json!(root.join("two")))]; + drive::answer::(&mut app, &fields, true); searched(&mut app); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((pick(d, "a.png"), &d.fields["touched"]), (&Value::Null, &json!([]))); + let f = found(&app); + assert_eq!((pick(&f, "a.png"), &f["touched"]), (Value::Null, &json!([]))); } #[test] @@ -286,12 +287,12 @@ fn cancel_closes_the_dialog_and_stops_its_search() { let mut app = app_for(&root); app.session.search_threads = Some(1); opened_without(&mut app, &root, &["a.png"]); - super::super::cancel(&mut app); + drive::answer::(&mut app, &[], false); app.run("ui.findLinksInFolder", json!({"folder": root.join("tree")})).unwrap(); let id = app.ui.links_search.expect("the dialog's search"); - assert_eq!((kind(&app), app.ui.dialog.as_ref().unwrap().bool("back")), (Some(KIND), false)); - super::super::cancel(&mut app); - assert!(app.ui.dialog.is_none() && app.ui.links_search.is_none()); + assert_eq!((drive::is_open::(&app), &found(&app)["back"]), (true, &json!(false))); + drive::answer::(&mut app, &[], false); + assert!(!drive::is_open::(&app) && app.ui.links_search.is_none()); // Stopped by the close, unless the walker finished the folders first. let r = app.session.execute("links.findFiles", &json!({})).unwrap(); assert_eq!(r["id"].as_u64(), Some(id), "{r}"); @@ -307,14 +308,13 @@ fn copy_into_the_documents_folder_copies_before_relinking() { let root = folder("copy"); let mut app = app_for(&root); let bytes = opened_without(&mut app, &root, &["a.png"]); - super::super::cancel(&mut app); + drive::answer::(&mut app, &[], false); write(&at(&root, "found/a.png"), &bytes[0]); app.run("ui.findLinksInFolder", json!({"folder": root.join("found")})).unwrap(); searched(&mut app); - assert!(frame(&mut app).contains("Copy into the document's folder")); - app.ui.dialog.as_mut().unwrap().fields.insert("copy".into(), json!(true)); - let r = super::super::confirm(&mut app).unwrap(); - assert_eq!((r["relinked"].as_array().unwrap().len(), app.ui.dialog.is_none()), (1, true), "{r}"); + assert_eq!(copy_folder(&app), Some(at(&root, "doc").to_string_lossy().into_owned())); + drive::answer::(&mut app, &[("copy", json!(true))], true); + assert!(!drive::is_open::(&app)); let copy = at(&root, "doc/a.png"); assert_eq!(std::fs::read(©).unwrap(), bytes[0]); let c = app.run("links.check", json!({})).unwrap(); @@ -325,7 +325,7 @@ fn copy_into_the_documents_folder_copies_before_relinking() { app.run("select.set", json!({"ids": [id]})).unwrap(); app.run("ui.findLinksInFolder", json!({"folder": root.join("found")})).unwrap(); searched(&mut app); - assert!(!frame(&mut app).contains("Copy into the document's folder")); + assert_eq!(copy_folder(&app), None); } /// Copy into the document's folder copies the file of an image in a symbol's art too, picked in the @@ -347,9 +347,8 @@ fn copy_takes_an_image_in_a_symbol_into_the_documents_folder() { let row = list["links"].as_array().unwrap().iter().find(|r| r["owner"]["kind"] == "symbol").cloned().expect("the symbol's image"); app.run("ui.findLinksInFolder", json!({"folder": root.join("found"), "ids": [row["id"]]})).unwrap(); searched(&mut app); - app.ui.dialog.as_mut().unwrap().fields.insert("copy".into(), json!(true)); - let r = super::super::confirm(&mut app).unwrap(); - assert_eq!((r["relinked"].as_array().map(Vec::len), &r["failed"]), (Some(1), &json!([])), "{r}"); + drive::answer::(&mut app, &[("copy", json!(true))], true); + assert!(!drive::is_open::(&app)); let copy = at(&root, "doc/a.png"); assert_eq!(std::fs::read(©).unwrap(), png(3)); let list = app.run("links.list", json!({})).unwrap(); @@ -367,8 +366,8 @@ fn copy_leaves_placed_documents_where_they_are() { let badge = at(&root, "orig/badge.vectorcraft"); std::fs::create_dir_all(badge.parent().unwrap()).unwrap(); app.run("document.save", json!({"path": badge})).unwrap(); - let found = at(&root, "found/badge.vectorcraft"); - write(&found, &std::fs::read(&badge).unwrap()); + let place = at(&root, "found/badge.vectorcraft"); + write(&place, &std::fs::read(&badge).unwrap()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); app.run("file.place", json!({"path": badge, "link": true})).unwrap(); let doc = at(&root, "doc/doc.vectorcraft"); @@ -377,69 +376,35 @@ fn copy_leaves_placed_documents_where_they_are() { std::fs::remove_dir_all(root.join("orig")).unwrap(); app.run("file.close", json!({})).unwrap(); crate::io::open_path(&mut app, &doc.to_string_lossy()).unwrap(); - super::super::cancel(&mut app); + drive::answer::(&mut app, &[], false); app.run("ui.findLinksInFolder", json!({"folder": root.join("found")})).unwrap(); searched(&mut app); - app.ui.dialog.as_mut().unwrap().fields.insert("copy".into(), json!(true)); - let r = super::super::confirm(&mut app).unwrap(); - assert_eq!((r["relinked"].as_array().unwrap().len(), &r["failed"]), (1, &json!([])), "{r}"); + drive::answer::(&mut app, &[("copy", json!(true))], true); + assert!(!drive::is_open::(&app)); assert!(!at(&root, "doc/badge.vectorcraft").exists()); - assert_eq!(app.run("links.check", json!({})).unwrap()["links"][0]["path"], json!(found)); + assert_eq!(app.run("links.check", json!({})).unwrap()["links"][0]["path"], json!(place)); } /// The Links panel's Find in Folder… (`ui.findLinksInFolder`): the selected linked files, else -/// the missing ones, in a folder the user picks. +/// the missing ones, in a folder. #[test] fn the_links_panel_looks_for_the_selected_or_the_missing_files() { let root = folder("panel"); let mut app = app_for(&root); - app.services.pick_folder = None; app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - assert!(!crate::menus::enabled(&app, "ui.findLinksInFolder"), "no folder picker (the web)"); let picked = root.join("found").to_string_lossy().into_owned(); - let answer = picked.clone(); - app.services.pick_folder = Some(Box::new(move || Some(answer.clone()))); - assert!(crate::menus::enabled(&app, "ui.findLinksInFolder")); // Nothing to look for: no folder is asked for. - assert_eq!(app.run("ui.findLinksInFolder", json!({})).err().as_deref(), Some("No linked files to look for")); + assert_eq!(app.run("ui.findLinksInFolder", json!({"folder": picked})).err().as_deref(), Some("No linked files to look for")); + assert!(!drive::is_open::(&app)); let here = at(&root, "found/here.png"); write(&here, &png(1)); let id = app.run("file.place", json!({"path": here})).unwrap()["ids"][0].clone(); app.run("select.set", json!({"ids": [id]})).unwrap(); - let menu = crate::tests_labels::painted_text(&mut app, crate::panels::links::menu); - assert!(menu.contains("Find in Folder…"), "{menu}"); - app.run("ui.findLinksInFolder", json!({})).unwrap(); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.kind.as_str(), d.fields["missing"][0]["name"].as_str(), d.str("folder")), (KIND, Some("here.png"), picked)); - // here.png isn't missing: the dialog asks about linked files. - assert!(frame(&mut app).contains("Choose the file to relink each linked file to.")); + app.run("ui.findLinksInFolder", json!({"folder": picked})).unwrap(); + let f = found(&app); + assert_eq!((f["missing"][0]["name"].as_str(), f["folder"].as_str()), (Some("here.png"), Some(picked.as_str()))); searched(&mut app); - assert_eq!(pick(app.ui.dialog.as_ref().unwrap(), "here.png"), &json!(here)); -} - -/// The Links panel's Find in Folder… asks for the folder off the UI thread (#867): Find Linked -/// Files opens on the folder when the folder picker answers. -#[test] -fn find_in_folder_asks_for_the_folder_off_the_ui_thread() { - let root = folder("later"); - let mut app = app_for(&root); - let (shown, _) = crate::tests_picks::off_the_ui_thread(&mut app.services); - app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); - app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let here = at(&root, "found/here.png"); - write(&here, &png(1)); - let id = app.run("file.place", json!({"path": here})).unwrap()["ids"][0].clone(); - app.run("select.set", json!({"ids": [id]})).unwrap(); - // Nothing opens until the picker answers. - assert!(app.run("ui.findLinksInFolder", json!({})).is_err()); - assert_eq!((shown.requests(), kind(&app)), (vec![PickRequest::Folder], None)); - let found = root.join("found").to_string_lossy().into_owned(); - shown.answer(&[found.as_str()]); - crate::picks::poll(&mut app, &egui::Context::default()); - let d = app.ui.dialog.as_ref().expect("Find Linked Files"); - assert_eq!((d.kind.as_str(), d.str("folder")), (KIND, found)); - searched(&mut app); - assert_eq!(pick(app.ui.dialog.as_ref().unwrap(), "here.png"), &json!(here)); + assert_eq!(pick(&found(&app), "here.png"), json!(here)); } /// A row whose path `links.check` left out (its file is outside the read roots) still shows the diff --git a/crates/ui-egui/src/dialogs/missing_links.rs b/crates/ui-egui/src/dialogs/missing_links.rs index 702db0c14f..a31c550d46 100644 --- a/crates/ui-egui/src/dialogs/missing_links.rs +++ b/crates/ui-egui/src/dialogs/missing_links.rs @@ -9,36 +9,280 @@ //! //! Fields: `missing` (`[{name, path, ids}]`, the one asked about first), `modified` (the ids of //! images whose file was modified), `notes` (the open's notes, shown again after the last question -//! or Cancel), `applyToAll`, `path` (the replacement file; picked when empty), `discard` -//! (Ignore) and `searchFolder` (set it and confirm for Find in Folder… on that folder). +//! or Cancel), `applyToAll`, `path` (the replacement file; picked when empty), `choice` (`ignore` +//! for Ignore) and `searchFolder` (set it and confirm for Find in Folder… on that folder). +//! +//! The dialog answers through [`pump`], which relinks and asks about the next file. What the +//! questions about one open still need after a dialog closed (the open's notes, the modified +//! files) is kept in [`LinkAsk`] on the app: Cancel, Escape and the close box carry no answer. +use std::time::Duration; + +// PLAN: crates/ui-egui/Cargo.toml names craft-ui, not the `craft` facade these paths use; the manifest owner adds `craft` with the host, theme and ui features. +use craft::host::{Host, PickId, PickKind, PickRequest, Picked}; +use craft::theme::TypeRole; +use craft::ui::buttons::Button; +use craft::ui::choice::Checkbox; +use craft::ui::contract::{Bind, Props as _, Show as _}; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use craft::ui::display::{Elide, Shade, Text}; +use craft::ui::patterns::form_dialogs::FormDialog; +use craft::ui::runtime::env::Label; +use craft::ui::sections::{DialogRole, FooterButton}; use serde_json::{Value, json}; -use super::DialogSpec; -use crate::state::Dialog; -use crate::theme::{self, Tokens}; -use crate::{VectorcraftApp, widgets}; +use crate::{VectorcraftApp, file_asks}; /// The dialog kind of a missing linked file. pub const KIND: &str = "missingLinks"; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |_| tl!("Linked File Not Found").into(), - body, - confirm, - ok: Some("Replace…"), - discard: Some("Ignore"), - min_width: 380.0, - max_width: Some(460.0), - inputs: |_| &["searchFolder"], - ..DialogSpec::FORM -}; +/// How often a dialog waiting for a picker looks for its answer. +const POLL: Duration = Duration::from_millis(100); + +/// The footer index of the accepting button (Replace…) and of Ignore, the first extra button. +const ACCEPT: usize = 0; +const IGNORE: usize = 2; + +/// `text` as a label of the dialog: the interface language's wording of it. +pub(super) fn label(text: &str) -> Label { + Label::from(text.to_string()) +} /// The ids in `rows` (`[{ids}]`). -fn ids(rows: &[Value]) -> Vec { +pub(super) fn ids(rows: &[Value]) -> Vec { rows.iter().flat_map(|r| r["ids"].as_array().cloned().unwrap_or_default()).collect() } +/// A string field's `value`, for `set_json_field`. +pub(super) fn text_field(field: &str, value: &Value) -> Result { + value.as_str().map(str::to_owned).ok_or_else(|| format!("field `{field}` takes a string, got {value}")) +} + +/// A boolean field's `value`, for `set_json_field`. +pub(super) fn flag_field(field: &str, value: &Value) -> Result { + value.as_bool().ok_or_else(|| format!("field `{field}` takes true or false, got {value}")) +} + +/// A picker a dialog filed with the host and waits for; `W` says what the answer is for. +pub(super) struct Asked(Option<(PickId, W)>); + +impl Default for Asked { + fn default() -> Self { + Asked(None) + } +} + +impl Asked { + /// Whether a picker is open or waiting. + pub(super) fn pending(&self) -> bool { + self.0.is_some() + } + + /// Files `request` for `what`, unless a picker is already waiting. + pub(super) fn file(&mut self, ctx: &egui::Context, request: PickRequest, what: W) { + if self.0.is_none() + && let Some(host) = Host::try_of_ctx(ctx) + { + self.0 = Some((host.files().pick(request), what)); + } + } + + /// The answer of the waiting picker, once it came, with what it was for. + pub(super) fn answer(&mut self, ctx: &egui::Context) -> Option<(Picked, W)> { + let (id, what) = self.0?; + let picked = Host::try_of_ctx(ctx)?.files().take_answer(id)?; + self.0 = None; + Some((picked, what)) + } + + /// Drops the waiting picker: its answer is not wanted. + pub(super) fn forget(&mut self, ctx: &egui::Context) { + if let (Some((id, _)), Some(host)) = (self.0.take(), Host::try_of_ctx(ctx)) { + host.files().forget(id); + } + } +} + +/// What the questions about one open's linked files keep between their dialogs: the files still +/// asked about, the modified images to offer for update afterwards and the open's notes. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct LinkAsk { + /// The missing files still asked about (`[{name, path, ids}]`), the next one first. + pub(crate) missing: Vec, + /// The ids of the images whose file was modified. + pub(crate) modified: Vec, + /// The open's notes, shown in the status bar again after the last question. + pub(crate) notes: Vec, + /// Whether Find Linked Files, opened from Find in Folder… here, is the open question: its Cancel + /// shows the notes again, as this dialog's does. + pub(crate) back: bool, +} + +/// What the user answered about the first missing file. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum MissingLinksAnswer { + /// Replace it with the file at `path`; with `apply_to_all` the others by name in its folder. + Replace { + /// The replacement file. + path: String, + /// Whether the other missing files are looked for beside it. + apply_to_all: bool, + }, + /// Keep the preview; with `apply_to_all` for the other missing files too. + Ignore { + /// Whether the other missing files are ignored too. + apply_to_all: bool, + }, + /// Look for every missing file in this folder ([`super::find_links`]). + FindInFolder(String), +} + +/// What a waiting picker answers for. +#[derive(Clone, Copy)] +enum Wanted { + /// The file that replaces the missing one. + File, + /// The folder Find in Folder… searches. + Folder, +} + +/// What the form edits. +#[derive(Clone, Default, PartialEq)] +struct Edit { + apply_to_all: bool, + path: String, +} + +/// Linked File Not Found: the first of the missing files, with Replace…, Ignore and Find in Folder…. +pub(crate) struct MissingLinksDialog { + ask: LinkAsk, + edit: Edit, + ignore: bool, + search_folder: String, + asked: Asked, + can_pick: bool, +} + +impl MissingLinksDialog { + /// The dialog over `ask`; Find in Folder… shows when the app can ask for a folder. + fn new(app: &VectorcraftApp, ask: LinkAsk) -> Self { + MissingLinksDialog { + ask, + edit: Edit::default(), + ignore: false, + search_folder: String::new(), + asked: Asked::default(), + can_pick: file_asks::can(app, PickKind::Folder), + } + } + + /// Replace…: the answer when a file is given, else files the picker for one and waits. + fn accept(&mut self, ctx: &egui::Context) -> Option { + if self.edit.path.is_empty() { + let request = vectorcraft_engine::cmd::fileio::place_filters().fold(PickRequest::open("links"), |r, (name, exts)| r.filter(name, exts)); + self.asked.file(ctx, request, Wanted::File); + return None; + } + Some(MissingLinksAnswer::Replace { path: self.edit.path.clone(), apply_to_all: self.edit.apply_to_all }) + } +} + +impl StackDialog for MissingLinksDialog { + type Result = MissingLinksAnswer; + + fn id(&self) -> DialogId { + dialog_id(KIND) + } + + fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option> { + let ctx = ui.ctx().clone(); + if let Some((picked, wanted)) = self.asked.answer(&ctx) + && let Some(path) = picked.first_path() + { + let path = path.to_string_lossy().into_owned(); + return Some(DialogResult::Ok(match wanted { + Wanted::File => MissingLinksAnswer::Replace { path, apply_to_all: self.edit.apply_to_all }, + Wanted::Folder => MissingLinksAnswer::FindInFolder(path), + })); + } + if self.asked.pending() { + ctx.request_repaint_after(POLL); + } + let Some(current) = self.ask.missing.first() else { return Some(DialogResult::Cancel) }; + let rest = self.ask.missing.len() - 1; + let (name, path) = (current["name"].as_str().unwrap_or_default(), current["path"].as_str().unwrap_or_default()); + let (can_pick, mut find) = (self.can_pick, false); + let shown = FormDialog::new(label(tl!("Linked File Not Found")), Bind::bound(&mut self.edit)) + .ok_label(label(tl!("Replace…"))) + .accept_stays_open(true) + .extra_buttons([FooterButton::new(label(tl!("Ignore")), DialogRole::Other)]) + .show(ui, |ui, _, edit| { + Text::new(label(name)).role(TypeRole::BodyStrong).show(ui); + Text::new(label(path)).shade(Shade::Muted).elide(Elide::Path).tooltip(path.to_string()).show(ui); + Text::new(label(tl!("Replace it with another file, or ignore it: its images keep showing the preview saved with the document."))) + .shade(Shade::Muted) + .show(ui); + if can_pick && Button::new(label(tl!("Find in Folder…"))).show(ui).clicked() { + find = true; + } + if rest > 0 { + let all = crate::i18n::tn(rest as u64, "Apply to All ({n} more missing)", "Apply to All ({n} more missing)"); + Checkbox::new(Bind::bound(&mut edit.apply_to_all)).label(label(&all)).show(ui); + } + true + }); + if find { + self.asked.file(&ctx, PickRequest::folder("links"), Wanted::Folder); + } + if shown.picked == Some(IGNORE) { + return Some(DialogResult::Ok(MissingLinksAnswer::Ignore { apply_to_all: self.edit.apply_to_all })); + } + if shown.picked == Some(ACCEPT) || shown.accepted.is_some() { + return self.accept(&ctx).map(DialogResult::Ok); + } + if shown.closed.is_some() { + self.asked.forget(&ctx); + return Some(DialogResult::Cancel); + } + None + } + + fn confirm(&mut self, ctx: &egui::Context) -> Option { + if !self.search_folder.is_empty() { + return Some(MissingLinksAnswer::FindInFolder(std::mem::take(&mut self.search_folder))); + } + if self.ignore { + return Some(MissingLinksAnswer::Ignore { apply_to_all: self.edit.apply_to_all }); + } + self.accept(ctx) + } + + fn cancelled(&mut self, ctx: &egui::Context) { + self.asked.forget(ctx); + } + + fn json_fields(&self) -> Option { + let LinkAsk { missing, modified, notes, .. } = &self.ask; + Some(json!({ "missing": missing, "modified": modified, "notes": notes, "applyToAll": self.edit.apply_to_all, "path": self.edit.path })) + } + + fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> { + match field { + "applyToAll" => self.edit.apply_to_all = flag_field(field, &value)?, + "path" => self.edit.path = text_field(field, &value)?, + "searchFolder" => self.search_folder = text_field(field, &value)?, + "choice" => match value.as_str() { + Some("ignore") => self.ignore = true, + Some("replace") => self.ignore = false, + _ => return Err(format!("field `choice` takes `replace` or `ignore`, got {value}")), + }, + _ => return Err(format!("unknown field `{field}`")), + } + ctx.request_repaint(); + Ok(()) + } +} + /// After a document opened (`document.open`'s result `r`): ask about its missing linked files, /// then about its modified ones, then about the fonts it opened without /// ([`super::missing_fonts`]). The web reads no linked files, so missing ones just show their @@ -69,7 +313,7 @@ fn after_open_for(app: &mut VectorcraftApp, r: &Value, mut notes: Vec, w None }; crate::io::show_opened(app, notice, notes); - super::settle(app); + // PLAN: the registry's `super::settle(app)` that ended this function is the frame pump's now (fl.A9). } /// The status bar's line for `n` linked files the web can't read. @@ -106,27 +350,23 @@ fn questions_for(app: &VectorcraftApp, r: &Value, web: bool) -> (Vec, Ve (lines, missing, modified) } +/// Opens the dialog about the first of `missing`, keeping what the questions after it need +/// ([`LinkAsk`]). A window that isn't up has nothing to show a question in. fn open(app: &mut VectorcraftApp, missing: Vec, modified: Vec, notes: &[String]) { - let fields = json!({ "missing": missing, "modified": modified, "notes": notes, "applyToAll": false, "path": "" }); - app.ui.dialog = Some(Dialog::new(KIND, fields)); + let ask = LinkAsk { missing, modified, notes: notes.to_vec(), back: false }; + let Some(dialogs) = app.dialogs() else { return }; + let dialog = MissingLinksDialog::new(app, ask.clone()); + app.link_asks = Some(ask); + dialogs.with(|h| h.open(dialog)); } -/// The open's notes a dialog `d` of the missing linked files keeps (field `notes`). -pub(super) fn notes(d: &Dialog) -> Vec { - let notes = d.fields.get("notes").and_then(Value::as_array).into_iter().flatten(); - notes.filter_map(Value::as_str).map(str::to_string).collect() -} - -/// Cancel of the dialog `d`: when it is this dialog, or the Find Linked Files dialog its Find in -/// Folder… opened, the rest of the questions are not asked and the status bar shows the open's -/// notes again ([`crate::io::show_opened`]), after the line about the modified files when Update -/// Links doesn't ask about them. -pub(super) fn cancelled(app: &mut VectorcraftApp, d: &Dialog) { - if d.kind == KIND || (d.kind == super::find_links::KIND && d.bool("back")) { - let modified = d.fields.get("modified").and_then(Value::as_array).map_or(0, Vec::len); - let notice = (modified > 0 && app.session.prefs.update_links != "askWhenModified").then(|| changed_on_disk_status(modified)); - crate::io::show_opened(app, notice, notes(d)); - } +/// The status bar shows the open's notes again, after the line about the modified files when +/// Update Links doesn't ask about them ([`crate::io::show_opened`]): the rest of the questions are +/// not asked. +pub(super) fn show_notes_again(app: &mut VectorcraftApp, ask: &LinkAsk) { + let modified = ask.modified.len(); + let notice = (modified > 0 && app.session.prefs.update_links != "askWhenModified").then(|| changed_on_disk_status(modified)); + crate::io::show_opened(app, notice, ask.notes.clone()); } /// Ask about the missing files `rest`, one at a time, then offer the modified ones `modified` for @@ -135,7 +375,7 @@ pub(super) fn cancelled(app: &mut VectorcraftApp, d: &Dialog) { /// them whatever message the answers showed. pub(crate) fn ask_next(app: &mut VectorcraftApp, rest: Vec, modified: Vec, notes: Vec) { if rest.is_empty() { - app.ui.dialog = None; + app.link_asks = None; let notice = ask_update(app, modified); crate::io::show_opened(app, notice, notes); } else { @@ -189,108 +429,118 @@ pub(crate) fn changed_on_disk_status(n: usize) -> String { ) } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let t = Tokens::get(ui.ctx()); - let missing = d.fields.get("missing").and_then(Value::as_array).map_or(&[][..], Vec::as_slice); - let Some(current) = missing.first() else { return true }; - let rest = missing.len() - 1; - let name = current["name"].as_str().unwrap_or_default(); - widgets::list_box(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.add_space(6.0); - ui.vertical(|ui| { - ui.add_space(3.0); - ui.label(egui::RichText::new(name).font(theme::semibold(12.0)).color(t.text_strong)); - let path = current["path"].as_str().unwrap_or_default(); - ui.add(egui::Label::new(egui::RichText::new(path).size(11.5).color(t.text_dim)).truncate()).on_hover_text(path); - ui.add_space(3.0); - }); - }); - }); - ui.add_space(8.0); - widgets::dim_label(ui, tl!("Replace it with another file, or ignore it: its images keep showing the preview saved with the document.")); - if crate::picks::can(app, &crate::picks::PickRequest::Folder) { - ui.add_space(8.0); - if ui.button(tl!("Find in Folder…")).clicked() { - let r = crate::picks::in_dialog(app, d, |app, d| match crate::picks::folder(app) { - Some(folder) => super::find_links::from_missing_links(app, d, &folder), - None => Ok(()), - }); - if let Err(e) = r { - app.status(e); - } +/// Takes the answer of the dialog that closed: Cancel shows the open's notes again; Replace relinks +/// the first file, Ignore keeps its preview, and either asks about the next. Find in Folder… opens +/// Find Linked Files over the files still asked about ([`super::find_links::from_missing_links`]). +/// A step that fails says why in the status bar and asks about the same files again. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + let Some(dialogs) = app.dialogs() else { return }; + let Some(result) = dialogs.with(|h| h.take::()) else { return }; + let ask = app.link_asks.take().unwrap_or_default(); + let Some(answer) = result.ok() else { return show_notes_again(app, &ask) }; + let LinkAsk { missing, modified, notes, .. } = ask; + let done = match answer { + MissingLinksAnswer::FindInFolder(folder) => { + super::find_links::from_missing_links(app, missing.clone(), modified.clone(), notes.clone(), &folder).map(|()| None) + } + answer => apply(app, &missing, answer).map(Some), + }; + match done { + Ok(Some(rest)) => ask_next(app, rest, modified, notes), + Ok(None) => {} + Err(e) => { + app.status(e); + open(app, missing, modified, ¬es); } } - if rest > 0 { - ui.add_space(10.0); - let all = d.bool("applyToAll"); - let label = crate::i18n::tn(rest as u64, "Apply to All ({n} more missing)", "Apply to All ({n} more missing)"); - if widgets::check(ui, &label, all, true) { - d.fields.insert("applyToAll".into(), json!(!all)); - } - } - false } -/// Replace (with `path`, else a picked file) or Ignore (`discard`) the first missing file, then -/// ask about the next. With `searchFolder`: Find in Folder… on that folder. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let folder = d.str("searchFolder"); - if !folder.is_empty() { - let mut d = d.clone(); - // The folder is searched once: a search that doesn't start leaves the dialog without it. - if let Some(open) = app.ui.dialog.as_mut().filter(|open| open.kind == KIND) { - open.fields.remove("searchFolder"); - } - super::find_links::from_missing_links(app, &mut d, &folder)?; - let state = d.fields.get("state").cloned().unwrap_or(Value::Null); - app.ui.dialog = Some(d); - return Ok(json!({ "state": state })); - } - let missing = d.fields.get("missing").and_then(Value::as_array).cloned().unwrap_or_default(); - let modified = d.fields.get("modified").and_then(Value::as_array).cloned().unwrap_or_default(); - let all = d.bool("applyToAll"); - let Some((current, rest)) = missing.split_first() else { - app.ui.dialog = None; - return Ok(Value::Null); - }; +/// Replace (with `path`) or Ignore the first of `missing` → the files still to ask about. Apply to +/// All: the others by name in the same folder; any not there are asked about. +fn apply(app: &mut VectorcraftApp, missing: &[Value], answer: MissingLinksAnswer) -> Result, String> { + let Some((current, rest)) = missing.split_first() else { return Ok(vec![]) }; let mut rest = rest.to_vec(); - let mut out = Value::Null; - if d.bool("discard") { - if all { - rest.clear(); - } - } else { - let path = match d.str("path") { - p if !p.is_empty() => p, - _ => { - let pick = - crate::FilePick { filters: crate::FilePick::filters(vectorcraft_engine::cmd::fileio::place_filters()), ..Default::default() }; - crate::picks::open(app, &pick).ok_or("cancelled")? + match answer { + MissingLinksAnswer::Ignore { apply_to_all } => { + if apply_to_all { + rest.clear(); } - }; - out = app.run("links.relink", json!({ "ids": current["ids"], "path": path }))?; - // Apply to All: the others by name in the same folder; any not there are asked about. - let folder = std::path::Path::new(&path).parent().map(|p| p.to_string_lossy().into_owned()); - if let (true, false, Some(folder)) = (all, rest.is_empty(), folder) { - let r = app.run("links.relink", json!({ "ids": ids(&rest), "folder": folder }))?; - let done = r["relinked"].as_array().cloned().unwrap_or_default(); - rest.retain(|row| row["ids"].as_array().is_none_or(|ids| ids.iter().any(|id| !done.contains(id)))); } + MissingLinksAnswer::Replace { path, apply_to_all } => { + app.run("links.relink", json!({ "ids": current["ids"], "path": path }))?; + let folder = std::path::Path::new(&path).parent().map(|p| p.to_string_lossy().into_owned()); + if let (true, false, Some(folder)) = (apply_to_all, rest.is_empty(), folder) { + let r = app.run("links.relink", json!({ "ids": ids(&rest), "folder": folder }))?; + let done = r["relinked"].as_array().cloned().unwrap_or_default(); + rest.retain(|row| row["ids"].as_array().is_none_or(|ids| ids.iter().any(|id| !done.contains(id)))); + } + } + // `pump` sends Find in Folder… elsewhere. + MissingLinksAnswer::FindInFolder(_) => {} + } + Ok(rest) +} + +/// What the tests of both link dialogs drive them with: the window's dialog host, as the shell +/// shows it, and the frame pump. +#[cfg(test)] +pub(super) mod drive { + use super::*; + + /// An app whose window has a dialog host. + pub(crate) fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.adopt_context(&crate::testing::ui_context()); + app + } + + /// Whether dialog `D` is open. + pub(crate) fn is_open(app: &VectorcraftApp) -> bool { + app.dialogs().is_some_and(|d| d.with(|h| h.is_open::())) + } + + /// The fields of the open dialog `D` (`Null` when it is not open). + pub(crate) fn fields(app: &VectorcraftApp) -> Value { + app.dialogs().and_then(|d| d.with(|h| h.get::().and_then(|d| d.json_fields()))).unwrap_or(Value::Null) + } + + /// One frame of the window's dialogs, which take the answers of the pickers they filed. + pub(crate) fn frame(app: &mut VectorcraftApp) { + let ctx = app.ui_ctx.clone().expect("the context the app adopted"); + let dialogs = app.dialogs().expect("a window dialog host"); + let _ = ctx.run(Default::default(), |ctx| { + egui::CentralPanel::default().show(ctx, |ui| dialogs.with(|h| h.run(ui))); + }); + } + + /// One frame's pump. + pub(crate) fn pump(app: &mut VectorcraftApp) { + let ctx = app.ui_ctx.clone().expect("the context the app adopted"); + crate::dialogs::host::pump(app, &ctx); + } + + /// Sets `fields` of the open dialog `D`, then confirms it (`ok`) or cancels it, then pumps. + pub(crate) fn answer(app: &mut VectorcraftApp, fields: &[(&str, Value)], ok: bool) { + let ctx = app.ui_ctx.clone().expect("the context the app adopted"); + let dialogs = app.dialogs().expect("a window dialog host"); + dialogs.with(|h| { + let Some(id) = h.get::().map(|d| d.id()) else { return }; + for (field, value) in fields { + h.set_json_field(&ctx, id, field, value.clone()).expect("a field the dialog takes"); + } + if ok { + h.confirm_by_id(&ctx, id); + } else { + h.cancel_by_id(&ctx, id); + } + }); + pump(app); } - ask_next(app, rest, modified, notes(d)); - Ok(out) } #[cfg(test)] mod tests { use super::*; - use vectorcraft_engine::Session; - - fn frame(app: &mut VectorcraftApp) -> String { - crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) - } fn png(rgb: [u8; 3]) -> Vec { let [r, g, b] = rgb; @@ -311,7 +561,7 @@ mod tests { let dir = std::env::temp_dir().join(format!("vectorcraft-missing-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = drive::app(); app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); for n in ["a.png", "b.png"] { @@ -330,30 +580,29 @@ mod tests { (app, dir, doc) } + /// The name of the file the open dialog asks about. + fn asked_name(app: &VectorcraftApp) -> Value { + drive::fields::(app)["missing"][0]["name"].clone() + } + + fn row(n: u64) -> Value { + json!({ "name": format!("{n}.png"), "path": format!("/gone/{n}.png"), "ids": [n] }) + } + + /// Replace relinks the first file and asks about the next; Ignore keeps its preview. #[test] fn opening_without_linked_files_asks_to_replace_or_ignore_each() { let (mut app, dir, _) = opened_without_links("each"); - let d = app.ui.dialog.as_ref().expect("the dialog"); - assert_eq!((d.kind.as_str(), d.fields["missing"].as_array().unwrap().len()), (KIND, 2)); - let text = frame(&mut app); - for label in ["Linked File Not Found", "a.png", "Apply to All (1 more missing)", "Replace…", "Ignore", "Cancel"] { - assert!(text.contains(label), "{label} in {text}"); - } + assert_eq!(drive::fields::(&app)["missing"].as_array().map(Vec::len), Some(2)); // Replace the first with a file given by path (the file picker otherwise). let blue = dir.join("new/blue.png"); std::fs::create_dir_all(blue.parent().unwrap()).unwrap(); std::fs::write(&blue, png([0, 0, 200])).unwrap(); - app.ui.dialog.as_mut().unwrap().fields.insert("path".into(), json!(blue.to_string_lossy())); - let r = super::super::confirm(&mut app).unwrap(); - assert_eq!(r["relinked"].as_array().unwrap().len(), 1); - let d = app.ui.dialog.as_ref().expect("asks about the next"); - assert_eq!(d.fields["missing"][0]["name"], "b.png"); - assert!(!d.fields.contains_key("discard")); - assert!(frame(&mut app).contains("b.png")); + drive::answer::(&mut app, &[("path", json!(blue.to_string_lossy()))], true); + assert_eq!(asked_name(&app), "b.png", "asks about the next"); // Ignore: done, the image keeps its preview. - app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + drive::answer::(&mut app, &[("choice", json!("ignore"))], true); + assert!(!drive::is_open::(&app)); let c = app.run("links.check", json!({})).unwrap(); let status: Vec<&str> = c["links"].as_array().unwrap().iter().map(|l| l["status"].as_str().unwrap()).collect(); assert_eq!((status, c["missing"].as_u64()), (vec!["ok", "missing"], Some(1))); @@ -365,7 +614,7 @@ mod tests { /// about. #[test] fn the_questions_about_linked_files_wait_or_become_lines() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = drive::app(); let r = json!({ "missingLinks": [{"name": "a.png", "path": "/x/a.png", "ids": [1]}], "modifiedLinks": [{"ids": [2]}, {"ids": [3]}] }); app.session.prefs.update_links = "askWhenModified".into(); assert_eq!(questions_for(&app, &r, false), (vec![], r["missingLinks"].as_array().unwrap().clone(), vec![json!(2), json!(3)])); @@ -374,25 +623,7 @@ mod tests { assert_eq!(questions_for(&app, &r, false), (vec![changed.clone()], r["missingLinks"].as_array().unwrap().clone(), vec![])); let unreadable = "1 linked file can't be read here: its preview shows".to_string(); assert_eq!(questions_for(&app, &r, true), (vec![unreadable, changed], vec![], vec![])); - assert!(app.ui.dialog.is_none(), "nothing is asked yet"); - } - - /// The question about modified linked files uses the form the language's plural rule picks for - /// the count. - #[test] - fn the_modified_links_question_uses_each_count_form() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let mut question = |code: &str, n: u64| { - crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); - ask_update(&mut app, (0..n).map(|id| json!(id)).collect()); - let detail = app.ui.dialog.take().map(|d| d.str("detail")); - crate::i18n::set_current(crate::i18n::Lang::EN); - detail.unwrap_or_default() - }; - assert_eq!(question("en", 1), "1 linked image changed since this document was saved. Show the new version?"); - assert_eq!(question("cs", 1), "Od uložení dokumentu se změnil 1 propojený obrázek. Zobrazit novou verzi?"); - assert_eq!(question("cs", 2), "Od uložení dokumentu se změnily 2 propojené obrázky. Zobrazit nové verze?"); - assert_eq!(question("cs", 5), "Od uložení dokumentu se změnilo 5 propojených obrázků. Zobrazit nové verze?"); + assert!(!drive::is_open::(&app), "nothing is asked yet"); } /// On the web, an open with two notes and two linked files it can't read: the status bar says @@ -400,7 +631,7 @@ mod tests { /// the line about the files is shown alone. #[test] fn an_open_with_unreadable_links_keeps_import_notes_reachable() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = drive::app(); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let missing = json!([{ "name": "a.png", "path": "/gone/a.png", "ids": [1] }, { "name": "b.png", "path": "/gone/b.png", "ids": [2] }]); let notes = vec!["a note".to_string(), "another note".to_string()]; @@ -409,7 +640,7 @@ mod tests { let notice = "2 linked files can't be read here: their previews show"; assert_eq!(app.ui.status, crate::io::opened_after_notice(notice, 2, "a note")); assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), notes))); - assert!(app.ui.dialog.is_none()); + assert!(!drive::is_open::(&app)); after_open_for(&mut app, &json!({ "missingLinks": missing }), vec![], true); assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (notice, &None)); } @@ -421,7 +652,7 @@ mod tests { /// unreadable files stays. #[test] fn a_web_open_with_unreadable_and_modified_links_keeps_both_lines() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = drive::app(); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); app.session.prefs.update_links = "manually".into(); let missing = json!([{ "name": "a.png", "path": "/gone/a.png", "ids": [1] }, { "name": "b.png", "path": "/gone/b.png", "ids": [2] }]); @@ -434,7 +665,7 @@ mod tests { let kept = [vec![changed.clone()], notes].concat(); assert_eq!(app.ui.status, crate::io::opened_after_notice(unreadable, 3, &changed)); assert_eq!(app.ui.status_notes, Some((app.ui.status.clone(), kept))); - assert!(app.ui.dialog.is_none()); + assert!(!drive::is_open::(&app)); after_open_for(&mut app, &r, vec![], true); assert_eq!(app.ui.status, crate::io::opened_after_notice(unreadable, 1, &changed)); @@ -446,8 +677,9 @@ mod tests { app.session.prefs.update_links = "askWhenModified".into(); after_open_for(&mut app, &r, vec![], true); - let d = app.ui.dialog.as_ref().expect("asks"); - assert_eq!((d.kind.as_str(), d.str("__command")), (super::super::confirm::KIND, "links.update".to_string())); + // PLAN: assumed `confirm::open_question(&VectorcraftApp) -> Option<(String, String, String)>` (message, detail, command; widgets-w10). + let (_, _, command) = super::super::confirm::open_question(&app).expect("asks"); + assert_eq!(command, "links.update"); assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (unreadable, &None)); } @@ -457,7 +689,7 @@ mod tests { /// line about files changed on disk while the document is open doesn't take them. #[test] fn modified_links_after_the_missing_ones_keep_the_open_notes() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = drive::app(); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); app.session.prefs.update_links = "manually".into(); let notes = vec!["a note".to_string(), "another note".to_string()]; @@ -466,12 +698,11 @@ mod tests { "modifiedLinks": [{ "ids": [2] }], }); let ignore = |app: &mut VectorcraftApp| { - app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); - super::super::confirm(app).unwrap(); - assert!(app.ui.dialog.is_none()); + drive::answer::(app, &[("choice", json!("ignore"))], true); + assert!(!drive::is_open::(app)); }; after_open_for(&mut app, &links, notes.clone(), false); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + assert_eq!(drive::fields::(&app)["notes"], json!(notes)); assert_eq!(app.ui.status, crate::io::opened_with_notes(2, "a note")); app.status("Relinked 1 image"); ignore(&mut app); @@ -499,58 +730,54 @@ mod tests { /// as it is. #[test] fn the_last_missing_link_answer_keeps_the_open_notes() { - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = drive::app(); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let notes = vec!["a note".to_string(), "another note".to_string()]; let opened = crate::io::opened_with_notes(2, "a note"); - let row = |n: u64| json!({ "name": format!("{n}.png"), "path": format!("/gone/{n}.png"), "ids": [n] }); - let answer = |app: &mut VectorcraftApp, fields: &[(&str, bool)]| { + let answer = |app: &mut VectorcraftApp, fields: &[(&str, Value)]| { app.status("Something else"); - let d = app.ui.dialog.as_mut().unwrap(); - for (k, v) in fields { - d.fields.insert(k.to_string(), json!(v)); - } - super::super::confirm(app).unwrap(); + let fields: Vec<(&str, Value)> = [("choice", json!("ignore"))].into_iter().chain(fields.iter().cloned()).collect(); + drive::answer::(app, &fields, true); }; for prefs in ["manually", "askWhenModified"] { app.session.prefs.update_links = prefs.into(); after_open_for(&mut app, &json!({ "missingLinks": [row(1)] }), notes.clone(), false); - answer(&mut app, &[("discard", true)]); - assert!(app.ui.dialog.is_none()); + answer(&mut app, &[]); + assert!(!drive::is_open::(&app)); assert_eq!((&app.ui.status, &app.ui.status_notes), (&opened, &Some((opened.clone(), notes.clone()))), "Ignore, {prefs}"); after_open_for(&mut app, &json!({ "missingLinks": [row(1), row(2)] }), notes.clone(), false); - answer(&mut app, &[("discard", true), ("applyToAll", true)]); - assert!(app.ui.dialog.is_none()); + answer(&mut app, &[("applyToAll", json!(true))]); + assert!(!drive::is_open::(&app)); assert_eq!((&app.ui.status, &app.ui.status_notes), (&opened, &Some((opened.clone(), notes.clone()))), "Apply to All, {prefs}"); after_open_for(&mut app, &json!({ "missingLinks": [row(1), row(2)], "modifiedLinks": [{ "ids": [3] }] }), notes.clone(), false); app.status("Something else"); - super::super::cancel(&mut app); - assert!(app.ui.dialog.is_none(), "Cancel asks nothing more"); + drive::answer::(&mut app, &[], false); + assert!(!drive::is_open::(&app), "Cancel asks nothing more"); let cancelled = if prefs == "manually" { crate::io::opened_after_notice(&changed_on_disk_status(1), 2, "a note") } else { opened.clone() }; assert_eq!((&app.ui.status, &app.ui.status_notes), (&cancelled, &Some((cancelled.clone(), notes.clone()))), "Cancel, {prefs}"); } after_open_for(&mut app, &json!({ "missingLinks": [row(1)], "modifiedLinks": [{ "ids": [3] }] }), notes.clone(), false); - answer(&mut app, &[("discard", true)]); - let d = app.ui.dialog.as_ref().expect("asks"); - assert_eq!((d.kind.as_str(), d.str("__command")), (super::super::confirm::KIND, "links.update".to_string())); + answer(&mut app, &[]); + // PLAN: assumed `confirm::open_question(&VectorcraftApp) -> Option<(String, String, String)>` (widgets-w10). + let (_, _, command) = super::super::confirm::open_question(&app).expect("asks"); + assert_eq!(command, "links.update"); assert_eq!((&app.ui.status, &app.ui.status_notes), (&opened, &Some((opened.clone(), notes.clone())))); - app.ui.dialog = None; after_open_for(&mut app, &json!({ "missingLinks": [row(1)] }), vec![], false); - answer(&mut app, &[("discard", true)]); + answer(&mut app, &[]); assert_eq!(app.ui.status, "Something else"); after_open_for(&mut app, &json!({ "missingLinks": [row(1)] }), vec![], false); app.status("Something else"); - super::super::cancel(&mut app); + drive::answer::(&mut app, &[], false); assert_eq!(app.ui.status, "Something else"); app.session.prefs.update_links = "manually".into(); after_open_for(&mut app, &json!({ "missingLinks": [row(1)], "modifiedLinks": [{ "ids": [3] }] }), vec![], false); app.status("Something else"); - super::super::cancel(&mut app); + drive::answer::(&mut app, &[], false); assert_eq!(app.ui.status, changed_on_disk_status(1), "Cancel keeps the line about the modified files"); } @@ -567,21 +794,29 @@ mod tests { for n in ["a.png", "b.png"] { std::fs::write(found.join(n), png([0, 0, 200])).unwrap(); } - app.ui.dialog.as_mut().unwrap().fields.insert("notes".into(), json!(notes)); - app.ui.dialog.as_mut().unwrap().fields.insert("path".into(), json!(found.join("a.png").to_string_lossy())); - super::super::confirm(&mut app).unwrap(); - assert_eq!(app.ui.dialog.as_ref().expect("asks about the next").fields["missing"][0]["name"], "b.png"); + // The open's notes are the ones the question keeps. + app.link_asks.as_mut().unwrap().notes = notes.clone(); + drive::answer::(&mut app, &[("path", json!(found.join("a.png").to_string_lossy()))], true); + assert_eq!(asked_name(&app), "b.png", "asks about the next"); - app.services.pick_open = Some(Box::new(|_: &crate::FilePick| None)); + // PLAN: assumed `tests::picks::scripted(&mut VectorcraftApp) -> Picker` with `requests()`, `answer(&[&str])` and `cancel()` (fl.A20, files-w7). + let picker = crate::tests::picks::scripted(&mut app); app.status("Something else"); - assert_eq!(super::super::confirm(&mut app), Err("cancelled".to_string())); - assert_eq!(app.ui.dialog.as_ref().expect("still asks").fields["missing"][0]["name"], "b.png"); + // Replace… without a file files the picker; the dialog takes its answer in its next frame. + drive::answer::(&mut app, &[], true); + assert_eq!(picker.requests().len(), 1); + picker.cancel(); + drive::frame(&mut app); + drive::pump(&mut app); + assert!(drive::is_open::(&app), "a canceled picker leaves the question open"); + assert_eq!(asked_name(&app), "b.png"); assert_eq!(app.ui.status, "Something else"); - let b = found.join("b.png").to_string_lossy().into_owned(); - app.services.pick_open = Some(Box::new(move |_: &crate::FilePick| Some(b.clone()))); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none()); + drive::answer::(&mut app, &[], true); + picker.answer(&[&found.join("b.png").to_string_lossy()]); + drive::frame(&mut app); + drive::pump(&mut app); + assert!(!drive::is_open::(&app)); assert_eq!((&app.ui.status, &app.ui.status_notes), (&opened, &Some((opened.clone(), notes.clone()))), "picked"); let _ = std::fs::remove_dir_all(dir); @@ -591,13 +826,11 @@ mod tests { for n in ["a.png", "b.png"] { std::fs::write(found.join(n), png([0, 0, 200])).unwrap(); } - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("notes".into(), json!(notes)); - d.fields.insert("applyToAll".into(), json!(true)); - d.fields.insert("path".into(), json!(found.join("a.png").to_string_lossy())); + app.link_asks.as_mut().unwrap().notes = notes.clone(); app.status("Something else"); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none(), "both relinked"); + let fields = [("applyToAll", json!(true)), ("path", json!(found.join("a.png").to_string_lossy()))]; + drive::answer::(&mut app, &fields, true); + assert!(!drive::is_open::(&app), "both relinked"); assert_eq!((&app.ui.status, &app.ui.status_notes), (&opened, &Some((opened.clone(), notes.clone()))), "Apply to All"); let _ = std::fs::remove_dir_all(dir); } @@ -610,11 +843,9 @@ mod tests { for n in ["a.png", "b.png"] { std::fs::write(found.join(n), png([0, 0, 200])).unwrap(); } - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("applyToAll".into(), json!(true)); - d.fields.insert("path".into(), json!(found.join("a.png").to_string_lossy())); - super::super::confirm(&mut app).unwrap(); - assert!(app.ui.dialog.is_none(), "both relinked"); + let fields = [("applyToAll", json!(true)), ("path", json!(found.join("a.png").to_string_lossy()))]; + drive::answer::(&mut app, &fields, true); + assert!(!drive::is_open::(&app), "both relinked"); let c = app.run("links.check", json!({})).unwrap(); assert_eq!(c["missing"], 0, "{c}"); let _ = std::fs::remove_dir_all(dir); @@ -624,7 +855,7 @@ mod tests { fn modified_links_are_offered_for_update_when_the_preference_asks() { let dir = std::env::temp_dir().join(format!("vectorcraft-modified-ui-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut app = drive::app(); app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); let pic = dir.join("a.png"); @@ -648,9 +879,11 @@ mod tests { // Reopened: an open file would only come to the front (#3455). app.run("file.close", json!({})).unwrap(); crate::io::open_path(&mut app, &doc).unwrap(); - let d = app.ui.dialog.as_ref().expect("asks"); - assert_eq!((d.kind.as_str(), d.str("__command")), (super::super::confirm::KIND, "links.update".to_string())); - super::super::confirm(&mut app).unwrap(); + // PLAN: assumed `confirm::open_question(&VectorcraftApp) -> Option<(String, String, String)>` and + // `confirm::answer_question(&mut VectorcraftApp, bool)` (widgets-w10): OK runs the question's command. + let (_, _, command) = super::super::confirm::open_question(&app).expect("asks"); + assert_eq!(command, "links.update"); + super::super::confirm::answer_question(&mut app, true); assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 0); // Manually: no question. app.run("prefs.set", json!({"key": "updateLinks", "value": "manually"})).unwrap(); @@ -658,7 +891,7 @@ mod tests { mark_modified(4); app.session.execute("file.close", &json!({})).unwrap(); crate::io::open_path(&mut app, &doc).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(super::super::confirm::open_question(&app).is_none()); assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1); let _ = std::fs::remove_dir_all(dir); }