diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 756bf71255..8193248611 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -1,169 +1,160 @@ -//! A question answered with OK or Cancel; OK runs a command ([`ask`]). Used for confirmations such -//! as deleting swatches. -//! -//! Fields: `message` (the question, shown as the heading), `detail` (an optional line under it), -//! `__command` and `__params` (the command OK runs). Both texts are shown as given: callers -//! translate their template before filling in a name, so the name is never translated. +//! Questions and messages on the dialog host: a question answered with OK or Cancel, where OK runs +//! a command ([`ask`]); a message with a Close button ([`tell`]); the question whether a save or +//! export may replace files ([`ask_replace_files`]); the Type tool's missing-fonts question +//! ([`ask_missing_font_edit`]). Both texts are shown as given: callers translate their template +//! before filling in a name, so the name is never translated. +use craft_ui::panels::dialog::{Alert, DialogId, DialogResult, DialogStack, HeldOk, HostedAlert, PromptChoice, StackDialog, StandardPrompt, StartupStage, dialog_id}; +use egui::{Context, Ui}; use serde_json::{Value, json}; -use super::DialogSpec; use crate::VectorcraftApp; -use crate::state::Dialog; -use crate::theme::Tokens; -/// The dialog kind of a confirmation. +/// The key of a confirmation, and what the reply of a command that opened one says is pending. pub const KIND: &str = "confirm"; -pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |d| d.str("message"), - body: |_, ui, d| { - let detail = d.str("detail"); - if !detail.is_empty() { - ui.label(egui::RichText::new(detail).color(Tokens::get(ui.ctx()).text_dim)); +/// The key of a message with a Close button only ([`tell`]). +pub const MESSAGE: &str = "message"; + +/// What the reply of a save or export says is pending while the question about replacing files asks +/// ([`ask_replace_files`]). +pub const REPLACE_FILES: &str = "replaceFiles"; + +/// The key of the question a click or double-click asks before it edits type set in fonts that +/// aren't available ([`ask_missing_font_edit`]). +pub const MISSING_FONT_EDIT: &str = vectorcraft_tools::text::MISSING_FONT_EDIT; + +/// Writes the `StackDialog` impl of a wrapper around `$inner` that forwards everything to it and +/// answers `$key` as its id and key. `StandardPrompt` derives its id from the kind of question and +/// the host keeps results per type, so each family of questions is a type of its own: taking one +/// family's answer never takes another's. +macro_rules! wrapped_dialog { + ($wrapper:ident, $inner:ty, $key:expr) => { + impl StackDialog for $wrapper { + type Result = <$inner as StackDialog>::Result; + + fn id(&self) -> DialogId { + dialog_id($key) + } + + fn instance(&self) -> Option { + self.0.instance() + } + + fn key(&self) -> Option<&str> { + Some($key) + } + + fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option> { + self.0.show(ui, stack) + } + + fn confirm(&mut self, ctx: &Context) -> Option { + self.0.confirm(ctx) + } + + fn held_state(&self) -> Option { + self.0.held_state() + } + + fn json_fields(&self) -> Option { + self.0.json_fields() + } + + fn set_json_field(&mut self, ctx: &Context, field: &str, value: Value) -> Result<(), String> { + self.0.set_json_field(ctx, field, value) + } + + fn cancelled(&mut self, ctx: &Context) { + self.0.cancelled(ctx) + } + + fn preview_color(&mut self, key: &str, color: Option) { + self.0.preview_color(key, color) + } } - false - }, - confirm, - max_width: Some(420.0), - ..DialogSpec::FORM -}; + }; +} + +/// A confirmation: its tag is the command OK runs and that command's params. +pub(crate) struct Question(StandardPrompt); +wrapped_dialog!(Question, StandardPrompt, KIND); + +/// A message with a Close button. +pub(crate) struct Message(HostedAlert); +wrapped_dialog!(Message, HostedAlert, MESSAGE); + +/// The Type tool's question whether to edit type set in fonts that aren't available; its tag is the +/// tool's edit token. +pub(crate) struct MissingFontQuestion(StandardPrompt); +wrapped_dialog!(MissingFontQuestion, StandardPrompt, MISSING_FONT_EDIT); + +/// The tag of the question whether a save or export may replace files ([`ask_replace_files`]). +pub(crate) struct ReplaceFiles { + /// The uid of the document that asked. + pub(crate) doc: u64, + /// The files that are there and which the question names. + pub(crate) files: Vec, + /// The files an earlier OK allowed. + pub(crate) allowed: Vec, + /// The command OK runs again on that document. + pub(crate) command: String, + /// Its params. + pub(crate) params: Value, +} /// Ask `message` (with an optional `detail` line), both in the UI language; OK runs `command` /// with `params`. pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) { - let fields = json!({"message": message, "detail": detail, "__command": command, "__params": params}); - app.ui.dialog = Some(Dialog::new(KIND, fields)); + let Some(dialogs) = app.dialogs() else { + app.status(format!("{message} (no window to ask in)")); + return; + }; + let mut prompt = StandardPrompt::custom(message.to_string()); + if !detail.is_empty() { + prompt = prompt.paragraph(detail.to_string()); + } + let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag((command.to_string(), params)); + dialogs.with(|host| host.open(Question(prompt))); } -/// The dialog kind of a message with a Close button only ([`tell`]). -pub const MESSAGE: &str = "message"; - -pub(super) const MESSAGE_SPEC: DialogSpec = DialogSpec { ok: None, ..SPEC }; - -/// The dialog kind of the question whether to replace a file that a save panel's name names once -/// the app gave it an extension ([`ask_replace`]). Fields: `message`, `detail`, `path` (the file). -pub const REPLACE: &str = "replaceFile"; - -pub(super) const REPLACE_SPEC: DialogSpec = DialogSpec { confirm: |app, d| crate::picks::replace(app, &d.str("path")), ..SPEC }; - -/// Ask whether to replace the file at `path`, which the name `typed` in a save panel became when -/// the app gave it an extension, over the dialog open now (Cancel shows it again). OK runs -/// [`crate::picks::replace`]; the Enter that closed the save panel does not press it. -pub(crate) fn ask_replace(app: &mut VectorcraftApp, path: &str, typed: &str) { - let name = vectorcraft_engine::cmd::fileio::file_name(path); - let typed = vectorcraft_engine::cmd::fileio::file_name(typed); - let message = crate::i18n::fmt(tl!("“{name}” already exists. Replace it?"), &[("name", &name)]); - let detail = crate::i18n::fmt( - tl!("The name in the save panel was “{typed}”; VectorCraft added the file type's extension. Replacing the file overwrites its contents."), - &[("typed", &typed)], - ); - let under = app.ui.dialog.take().and_then(|d| serde_json::to_value(d).ok()); - let fields = json!({"message": message, "detail": detail, "path": path, super::PARENT: under, super::AFTER_PANEL: true}); - app.ui.dialog = Some(Dialog::new(REPLACE, fields)); +/// Tell the user `message` (with an optional `detail` line), both in the UI language, in a dialog +/// they close. While another dialog is open (the message comes from work in the background) it +/// waits its turn instead of replacing it: neither what the user was doing there nor the message +/// is lost. +pub fn tell(app: &mut VectorcraftApp, message: &str, detail: &str) { + let Some(dialogs) = app.dialogs() else { + return; + }; + if !app.told.admit(message, detail) { + return; + } + let alert = HostedAlert::new(Alert::new(message.to_string(), detail.to_string()).ok_label(tl!("Close"))); + dialogs.with(|host| host.enqueue(StartupStage::Warning, Message(alert))); } -/// The dialog kind of the question whether a save or export may replace the files it writes beside -/// the one picked in the save panel ([`ask_replace_files`]). Fields: `message`, `detail`, `files` -/// (their paths), `allowed` (files an earlier OK allowed), `doc` (the document's uid), `__command` -/// and `__params`. -pub const REPLACE_FILES: &str = "replaceFiles"; - -pub(super) const REPLACE_FILES_SPEC: DialogSpec = DialogSpec { confirm: replace_files, ..SPEC }; - /// Ask whether to replace `files`, files that are there beside the one a save or export of the /// document `doc` (its uid) writes, which the save panel did not ask about (a file per artboard, a /// linked image). OK runs `command` with `params` again on that document, now replacing those /// files and `allowed` (those an earlier OK allowed); Cancel writes nothing. pub(crate) fn ask_replace_files(app: &mut VectorcraftApp, doc: u64, files: &[String], allowed: &[String], command: &str, params: Value) { - let name = files.first().map(|f| vectorcraft_engine::cmd::fileio::file_name(f)).unwrap_or_default(); - let message = crate::i18n::fmt(tl!("“{name}” already exists. Replace it?"), &[("name", &name)]); - // Several: every one of them, by name. - let detail = match files { - [_, _, ..] => files.iter().map(|f| vectorcraft_engine::cmd::fileio::file_name(f)).collect::>().join("\n"), - _ => String::new(), + let Some(dialogs) = app.dialogs() else { + return; }; - let fields = - json!({"message": message, "detail": detail, "files": files, "allowed": allowed, "doc": doc, "__command": command, "__params": params}); - let d = Dialog::new(REPLACE_FILES, fields); + let name = |f: &String| vectorcraft_engine::cmd::fileio::file_name(f); + let first = files.first().map(name).unwrap_or_default(); + let prompt = StandardPrompt::replace_file(first, None).lines(files.iter().skip(1).map(|f| name(f).into())).tag(ReplaceFiles { + doc, + files: files.to_vec(), + allowed: allowed.to_vec(), + command: command.to_string(), + params, + }); // Asked when a Background Save or Export ends: a dialog open then stays, and this waits its turn // (however many messages wait: the save or export needs the answer). - match app.ui.dialog { - None => app.ui.dialog = Some(d), - Some(_) => app.ui.told.push(d), - } + dialogs.with(|host| host.enqueue(StartupStage::Warning, prompt)); } -/// OK on [`ask_replace_files`]: what asked runs again on its document, and the files the question -/// named are replaced; one it writes now that was not named is asked about again. The save or export -/// reads the allowance when it starts, before a background one hands its work to the worker. -fn replace_files(app: &mut VectorcraftApp, d: &Dialog) -> Result { - app.ui.dialog = None; - if !crate::picks::on_document(app, d.fields.get("doc").and_then(Value::as_u64)) { - return Ok(Value::Null); - } - let paths = |k: &str| d.fields.get(k).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string); - app.picks.replace_files_ok = paths("allowed").chain(paths("files")).collect(); - let r = confirm(app, d); - app.picks.replace_files_ok.clear(); - r -} - -/// The dialog kind of the question Reset Preferences asks over the Preferences dialog -/// ([`ask_reset_prefs`]). Fields: `message`, `detail`. -pub const RESET_PREFS: &str = "resetPreferences"; - -pub(super) const RESET_PREFS_SPEC: DialogSpec = DialogSpec { confirm: reset_prefs, ..SPEC }; - -/// Ask whether to reset the preferences, over the Preferences dialog open now. Cancel and Escape -/// show Preferences again as it was; OK shows it again with every preference at its default value -/// ([`crate::prefs_dialog::reset_fields`]). Nothing is applied until OK in Preferences. -pub(crate) fn ask_reset_prefs(app: &mut VectorcraftApp) { - let under = app.ui.dialog.take().and_then(|d| serde_json::to_value(d).ok()); - let message = tl!("Reset all preferences to their defaults?"); - let detail = tl!("The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences."); - let fields = json!({"message": message, "detail": detail, super::PARENT: under}); - app.ui.dialog = Some(Dialog::new(RESET_PREFS, fields)); -} - -/// OK on [`ask_reset_prefs`]: Preferences again, its fields at their defaults. -fn reset_prefs(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let mut prefs = super::parent(d).filter(|p| p.kind == "preferences").ok_or("the dialog it was opened over is no longer open")?; - crate::prefs_dialog::reset_fields(&mut prefs); - crate::original_editor::reset(app); - app.ui.dialog = Some(prefs); - Ok(Value::Null) -} - -/// The dialog kind of the question Reset Actions asks in the Actions panel menu -/// ([`ask_reset_actions`]). Fields: `message`, `detail`, `append` (set by Append). -pub const RESET_ACTIONS: &str = "resetActions"; - -pub(super) const RESET_ACTIONS_SPEC: DialogSpec = DialogSpec { confirm: reset_actions, alternate: Some(("Append", "append")), ..SPEC }; - -/// Ask whether to replace the Actions panel's sets with the built-in set. OK replaces them, Append -/// adds the built-in set after them ([`crate::panels::actions::reset`]), and Cancel or Escape -/// changes nothing. -pub(crate) fn ask_reset_actions(app: &mut VectorcraftApp) { - let message = tl!("Replace the current actions with the default set?"); - let detail = tl!("Append adds the default set after the current sets instead."); - app.ui.dialog = Some(Dialog::new(RESET_ACTIONS, json!({"message": message, "detail": detail, "append": false}))); -} - -/// OK or Append on [`ask_reset_actions`]: closes, then resets the action sets. -fn reset_actions(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let mode = if d.fields.get("append").and_then(Value::as_bool) == Some(true) { "append" } else { "replace" }; - app.ui.dialog = None; - app.run(crate::panels::actions::RESET, json!({ "mode": mode })) -} - -/// The dialog kind of the question a click or double-click asks before it edits type set in fonts -/// that aren't available as named ([`ask_missing_font_edit`]). Fields: `message`, `detail`, -/// `__token` (the Type tool's edit, which the answer names). -pub const MISSING_FONT_EDIT: &str = vectorcraft_tools::text::MISSING_FONT_EDIT; - -pub(super) const MISSING_FONT_EDIT_SPEC: DialogSpec = DialogSpec { confirm: edit_in_missing_fonts, ..SPEC }; - /// Ask whether to edit type whose story is drawn in fonts that aren't available, which the Type /// tool names in `p` (`token`, `missing` and `style`: "family style" names, `more`: how many more /// there are). The detail names each font (family and style, the family's own names, which are @@ -171,8 +162,13 @@ pub(super) const MISSING_FONT_EDIT_SPEC: DialogSpec = DialogSpec { confirm: edit /// While another dialog is open (a press sent with `ui.pointer` reaches the tool then), that dialog /// stays and the Type tool forgets the edit, as Cancel would. pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { - if app.ui.dialog.as_ref().is_some_and(|d| d.kind != MISSING_FONT_EDIT) { - app.session.set_tool_option("missingFontEdit", &json!({"token": p.get("token"), "ok": false})); + let token = p.get("token").cloned().unwrap_or(Value::Null); + let Some(dialogs) = app.dialogs() else { + answer_missing_font_edit(app, &token, false); + return; + }; + if app.any_dialog_open() && !dialogs.with(|host| host.is_open::()) { + answer_missing_font_edit(app, &token, false); return; } let names = |k: &str| p.get(k).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect::>(); @@ -182,54 +178,62 @@ pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { fonts.push("…".to_string()); } let detail = format!("{}\n{}", fonts.join(", "), tl!("These fonts aren't available. Their text shows in another font.")); - let message = tl!("Edit type set in fonts that aren't available?"); - let fields = json!({"message": message, "detail": detail, "__token": p.get("token")}); - app.ui.dialog = Some(Dialog::new(MISSING_FONT_EDIT, fields)); + let prompt = StandardPrompt::custom(tl!("Edit type set in fonts that aren't available?")) + .paragraph(detail) + .button(PromptChoice::Proceed, tl!("OK")) + .button(PromptChoice::Cancel, tl!("Cancel")) + .tag(token); + dialogs.with(|host| host.open(MissingFontQuestion(prompt))); } -/// OK on [`ask_missing_font_edit`]: closes, then the Type tool starts the edit. -fn edit_in_missing_fonts(app: &mut VectorcraftApp, d: &Dialog) -> Result { - app.ui.dialog = None; - answer_missing_font_edit(app, d, true); - Ok(Value::Null) -} - -/// Give the Type tool the answer to [`ask_missing_font_edit`]'s question `d`: with `ok` the edit -/// starts at once; without, the tool forgets it. -pub(super) fn answer_missing_font_edit(app: &mut VectorcraftApp, d: &Dialog, ok: bool) { - app.session.set_tool_option("missingFontEdit", &json!({"token": d.fields.get("__token"), "ok": ok})); +/// Give the Type tool the answer to [`ask_missing_font_edit`]'s question about the edit `token` +/// names: with `ok` the edit starts at once; without, the tool forgets it. +pub(crate) fn answer_missing_font_edit(app: &mut VectorcraftApp, token: &Value, ok: bool) { + app.session.set_tool_option("missingFontEdit", &json!({"token": token, "ok": ok})); if ok { let r = app.session.tool_poll(app.view_info(), false); crate::canvas::apply_requests(app, r); } } -/// Most messages kept for later while a dialog is open ([`tell`]). -const MAX_WAITING: usize = 16; - -/// Tell the user `message` (with an optional `detail` line), both in the UI language, in a dialog -/// they close. While another dialog is open (the message comes from work in the background) it -/// waits its turn instead of replacing it: neither what the user was doing there nor the message -/// is lost. -pub fn tell(app: &mut VectorcraftApp, message: &str, detail: &str) { - let d = Dialog::new(MESSAGE, json!({"message": message, "detail": detail})); - if app.ui.dialog.is_none() { - app.ui.dialog = Some(d); - } else if app.ui.told.len() < MAX_WAITING && !app.ui.dialog.iter().chain(&app.ui.told).any(|t| t.kind == MESSAGE && t.fields == d.fields) { - app.ui.told.push(d); +/// Each frame: runs the command of a confirmation answered OK, and forgets the messages the user +/// closed. The command runs after the host's lock is released and the question is closed, so a +/// dialog the command opens stays open. +pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) { + let Some(dialogs) = app.dialogs() else { + return; + }; + if let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::()) + && answer.choice == PromptChoice::Proceed + && let Some((command, params)) = answer.take_tag::<(String, Value)>() + && let Err(e) = app.run(&command, params) + { + app.status(e); + } + // The host opens queued messages in `enqueue` order, so the one closed is the oldest. + while dialogs.with(|host| host.take::()).is_some() { + app.told.pop_front(); } } -/// Show the next message that waited for a dialog to close (each frame). -pub(super) fn show_waiting(app: &mut VectorcraftApp) { - if app.ui.dialog.is_none() && !app.ui.told.is_empty() { - app.ui.dialog = Some(app.ui.told.remove(0)); - } +/// Each frame: the Type tool's answer to the missing-fonts question. OK starts the edit; Cancel +/// and every other way it closed make the tool forget it. +pub(crate) fn pump_missing_font(app: &mut VectorcraftApp, _ctx: &Context) { + let Some(dialogs) = app.dialogs() else { + return; + }; + let (ok, token) = match dialogs.with(|host| host.take::()) { + None => return, + Some(DialogResult::Ok(mut answer)) => (answer.choice == PromptChoice::Proceed, answer.take_tag::()), + // PLAN: a question the host cancelled carries no tag, so the tool's token is unknown here. + Some(_) => (false, None), + }; + answer_missing_font_edit(app, &token.unwrap_or(Value::Null), ok); } -/// Closes before running, so a dialog the command opens stays open. -fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { - let params = d.fields.get("__params").cloned().unwrap_or_else(|| json!({})); - app.ui.dialog = None; - app.run(&d.str("__command"), params) +/// The command and params of the confirmation open now, if one is. +#[cfg(test)] +// PLAN: the prompt exposes no message text, so the question's words cannot be read back. +pub(crate) fn open_question(app: &VectorcraftApp) -> Option<(String, Value)> { + app.dialogs()?.with(|host| host.get::().and_then(|q| q.0.tag_as::<(String, Value)>().cloned())) } diff --git a/crates/ui-egui/src/dialogs/tests_messages.rs b/crates/ui-egui/src/dialogs/tests_messages.rs new file mode 100644 index 0000000000..0c4f4658a9 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_messages.rs @@ -0,0 +1,84 @@ +//! Messages and questions on the dialog host: the queue of messages and the order a confirmed +//! command runs in. + +use serde_json::json; + +use super::confirm::{self, KIND, MESSAGE}; +use crate::VectorcraftApp; +use crate::tests_svg::app; + +/// Gives `app` a window to host dialogs in. +fn host(app: &mut VectorcraftApp) { + // PLAN: assumed `ui_ctx: Option` on the app (lib.rs:203). + let ctx = app.ui_ctx.get_or_insert_with(egui::Context::default).clone(); + crate::theme::install_fonts(&ctx); +} + +/// One frame of the host, then the pump. +fn pass(app: &mut VectorcraftApp) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + let Some(dialogs) = app.dialogs() else { return }; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))); + out.textures_delta.clear(); + super::host::pump(app, &ctx); +} + +/// The keys of the open dialogs. +fn keys(app: &VectorcraftApp) -> Vec> { + app.dialogs().map(|d| d.with(|host| host.open_dialogs().into_iter().map(|o| o.key).collect())).unwrap_or_default() +} + +/// Closes the top dialog: OK when `ok`, else Cancel; then a frame. +fn close_top(app: &mut VectorcraftApp, ok: bool) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| { + if let Some(id) = host.open_dialogs().last().map(|o| o.id) { + if ok { + host.confirm_by_id(&ctx, id); + } else { + host.cancel_by_id(&ctx, id); + } + } + }); + } + pass(app); +} + +#[test] +fn a_message_told_while_a_dialog_is_open_shows_after_it_once_per_text() { + let (mut app, _) = app("/tmp/doc.vectorcraft"); + host(&mut app); + confirm::ask(&mut app, "Question?", "", "shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5})); + pass(&mut app); + confirm::tell(&mut app, "First", ""); + confirm::tell(&mut app, "First", ""); + confirm::tell(&mut app, "Second", ""); + pass(&mut app); + assert_eq!(keys(&app), [Some(KIND.to_string())], "the messages wait behind the question"); + close_top(&mut app, false); + assert_eq!(keys(&app), [Some(MESSAGE.to_string())], "the first message shows"); + close_top(&mut app, false); + assert_eq!(keys(&app), [Some(MESSAGE.to_string())], "then the distinct one"); + close_top(&mut app, false); + assert!(keys(&app).is_empty(), "the duplicate never shows"); +} + +#[test] +fn a_question_closes_before_its_command_runs_and_cancel_runs_nothing() { + let (mut app, written) = app("/tmp/doc.vectorcraft"); + host(&mut app); + confirm::ask(&mut app, "Save as?", "", "file.saveAs", json!({})); + pass(&mut app); + assert_eq!(keys(&app), [Some(KIND.to_string())]); + close_top(&mut app, true); + let open = keys(&app); + assert_eq!(open.len(), 1, "only the dialog the command opened"); + assert_ne!(open[0].as_deref(), Some(KIND)); + close_top(&mut app, false); + confirm::ask(&mut app, "Save as?", "", "file.saveAs", json!({})); + pass(&mut app); + close_top(&mut app, false); + assert!(keys(&app).is_empty(), "Cancel runs nothing"); + assert!(written.borrow().is_empty()); +} diff --git a/crates/ui-egui/src/tests/nativeoptions.rs b/crates/ui-egui/src/tests/nativeoptions.rs index e97443eb36..283d27b089 100644 --- a/crates/ui-egui/src/tests/nativeoptions.rs +++ b/crates/ui-egui/src/tests/nativeoptions.rs @@ -2,21 +2,59 @@ //! Linked Files, Embed ICC Profiles, Create PDF-Compatible File, Use Compression and Preview; the //! web's Save As dialog shows them too. +use craft_ui::panels::dialog::{OpenDialog, StandardPrompt}; use serde_json::{Value, json}; +use crate::dialogs::confirm::{REPLACE_FILES, ReplaceFiles}; use crate::tests_svg::app; -use crate::{dialogs, theme}; +use crate::{VectorcraftApp, dialogs}; -/// One headless frame of the dialog layer. -fn frame(app: &mut crate::VectorcraftApp) { - let ctx = egui::Context::default(); - theme::install_fonts(&ctx); - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialogs::show(app, ui.ctx())); +/// Gives `app` a window to host dialogs in. +fn host(app: &mut VectorcraftApp) { + // PLAN: assumed `ui_ctx: Option` on the app (lib.rs:203). + let ctx = app.ui_ctx.get_or_insert_with(egui::Context::default).clone(); + crate::theme::install_fonts(&ctx); +} + +/// One frame of the host (which opens a queued question), then the pump. +fn pass(app: &mut VectorcraftApp) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + let Some(dialogs) = app.dialogs() else { return }; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))); out.textures_delta.clear(); + dialogs::host::pump(app, &ctx); +} + +/// The open dialogs, the top one last. +fn open_dialogs(app: &VectorcraftApp) -> Vec { + app.dialogs().map(|d| d.with(|host| host.open_dialogs())).unwrap_or_default() +} + +/// Sets `fields` on the top dialog and answers it: OK when `ok`, else Cancel. +fn answer(app: &mut VectorcraftApp, fields: &[(&str, Value)], ok: bool) { + pass(app); + let ctx = app.ui_ctx.clone().unwrap(); + app.dialogs().unwrap().with(|host| { + let id = host.open_dialogs().last().unwrap().id; + for (field, value) in fields { + host.set_json_field(&ctx, id, field, value.clone()).unwrap(); + } + if ok { + host.confirm_by_id(&ctx, id); + } else { + host.cancel_by_id(&ctx, id); + } + }); + pass(app); +} + +/// The files the replace question open now names. +fn replace_files(app: &VectorcraftApp) -> Option> { + app.dialogs()?.with(|host| host.get::().and_then(|p| p.tag_as::()).map(|r| r.files.clone())) } /// Add artboards B and C, a rectangle on each. -fn three_boards(app: &mut crate::VectorcraftApp) { +fn three_boards(app: &mut VectorcraftApp) { for (x, name) in [(200, "B"), (400, "C")] { app.run("artboard.new", json!({"x": x, "y": 0, "width": 100, "height": 80, "name": name})).unwrap(); app.run("shape.rectangle", json!({"x": x + 10, "y": 10, "width": 20, "height": 20})).unwrap(); @@ -26,41 +64,31 @@ fn three_boards(app: &mut crate::VectorcraftApp) { #[test] fn save_as_native_asks_for_its_options_and_writes_every_artboard() { let (mut app, written) = app("/tmp/doc.vectorcraft"); + host(&mut app); three_boards(&mut app); let r = app.run("file.saveAs", Value::Null).unwrap(); assert_eq!(r["pending"], "saveOptions"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!( - (d.str("format").as_str(), d.bool("separateArtboards"), d.bool("embedProfiles"), d.bool("pdfCompatible")), - ("vectorcraft", false, true, true) - ); + let open = open_dialogs(&app); + assert_eq!(open.len(), 1); + let f = open[0].fields.clone().unwrap(); + assert_eq!((&f["format"], &f["separateArtboards"], &f["embedProfiles"], &f["pdfCompatible"]), (&json!("vectorcraft"), &json!(false), &json!(true), &json!(true))); assert!(written.borrow().is_empty(), "nothing is written before OK"); - frame(&mut app); - assert!(app.ui.dialog.is_some(), "drawing keeps it open"); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("separateArtboards".into(), json!(true)); - d.fields.insert("all".into(), json!(false)); - d.fields.insert("range".into(), json!("9")); - frame(&mut app); - assert!(dialogs::confirm(&mut app).is_err(), "a bad range keeps the dialog open"); - assert!(app.ui.dialog.is_some()); - app.ui.dialog.as_mut().unwrap().fields.insert("range".into(), json!("2-3")); - let r = dialogs::confirm(&mut app).unwrap(); - let names: Vec = written.borrow().iter().map(|(p, _)| p.clone()).collect(); - assert_eq!(names, ["/tmp/doc.vectorcraft", "/tmp/doc-B.vectorcraft", "/tmp/doc-C.vectorcraft"], "{r}"); + answer(&mut app, &[("separateArtboards", json!(true)), ("all", json!(false)), ("range", json!("9"))], true); + assert_eq!(open_dialogs(&app).len(), 1, "a bad range keeps the dialog open"); + assert!(written.borrow().is_empty()); + answer(&mut app, &[("range", json!("2-3"))], true); + assert_eq!(names(&written), ["/tmp/doc.vectorcraft", "/tmp/doc-B.vectorcraft", "/tmp/doc-C.vectorcraft"]); let st = app.session.active().unwrap(); assert_eq!((st.path.as_deref(), st.is_dirty()), (Some("/tmp/doc.vectorcraft"), false)); // Save writes them again with the same options, without asking. app.run("shape.ellipse", json!({"x": 50, "y": 40, "width": 10, "height": 10})).unwrap(); app.run("file.save", Value::Null).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(open_dialogs(&app).is_empty()); assert_eq!(written.borrow().len(), 6); // All: every artboard. app.run("file.saveAs", Value::Null).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - assert!(d.bool("separateArtboards"), "the options as last saved"); - d.fields.insert("all".into(), json!(true)); - dialogs::confirm(&mut app).unwrap(); + assert_eq!(open_dialogs(&app)[0].fields.as_ref().unwrap()["separateArtboards"], json!(true), "the options as last saved"); + answer(&mut app, &[("all", json!(true))], true); assert_eq!(written.borrow().len(), 10); } @@ -75,44 +103,40 @@ fn names(written: &crate::tests_svg::Written) -> Vec { #[test] fn save_as_asks_before_replacing_an_artboard_file_that_is_there() { let (mut app, written) = app("/tmp/doc.vectorcraft"); + host(&mut app); three_boards(&mut app); let there = ["/tmp/doc-B.vectorcraft", "/tmp/doc-D.vectorcraft", "/tmp/doc-E.vectorcraft"]; app.services.exists = Some(std::sync::Arc::new(move |p: &str| there.contains(&p))); - let pick = |app: &mut crate::VectorcraftApp| { + let pick = |app: &mut VectorcraftApp| { app.run("file.saveAs", Value::Null).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("separateArtboards".into(), json!(true)); - d.fields.insert("all".into(), json!(true)); - dialogs::confirm(app).unwrap() + answer(app, &[("separateArtboards", json!(true)), ("all", json!(true))], true); }; - let r = pick(&mut app); - assert_eq!(r["pending"], dialogs::confirm::REPLACE_FILES, "{r}"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!((d.kind.as_str(), d.str("message").as_str()), (dialogs::confirm::REPLACE_FILES, "“doc-B.vectorcraft” already exists. Replace it?")); - assert_eq!(d.fields["files"], json!(["/tmp/doc-B.vectorcraft"])); + pick(&mut app); + assert_eq!(replace_files(&app), Some(vec!["/tmp/doc-B.vectorcraft".to_string()])); assert!(written.borrow().is_empty(), "nothing is written while it asks"); - dialogs::cancel(&mut app); + answer(&mut app, &[], false); assert!(written.borrow().is_empty(), "Cancel writes nothing"); assert!(app.session.active().unwrap().path.is_none()); pick(&mut app); - dialogs::confirm(&mut app).unwrap(); + answer(&mut app, &[], true); assert_eq!(names(&written), ["/tmp/doc.vectorcraft", "/tmp/doc-Artboard-1.vectorcraft", "/tmp/doc-B.vectorcraft", "/tmp/doc-C.vectorcraft"]); assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/tmp/doc.vectorcraft")); app.run("file.save", Value::Null).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(open_dialogs(&app).is_empty()); assert_eq!(written.borrow().len(), 8); // A new artboard's file is not one the last save wrote: Save asks about it alone. app.run("artboard.new", json!({"x": 600, "y": 0, "width": 100, "height": 80, "name": "D"})).unwrap(); let r = app.run("file.save", Value::Null).unwrap(); - assert_eq!(r["pending"], dialogs::confirm::REPLACE_FILES, "{r}"); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["files"], json!(["/tmp/doc-D.vectorcraft"])); + assert_eq!(r["pending"], REPLACE_FILES, "{r}"); + pass(&mut app); + assert_eq!(replace_files(&app), Some(vec!["/tmp/doc-D.vectorcraft".to_string()])); assert_eq!(written.borrow().len(), 8); // An artboard added while it asks writes a file the question did not name: OK asks about it. app.run("artboard.new", json!({"x": 800, "y": 0, "width": 100, "height": 80, "name": "E"})).unwrap(); - dialogs::confirm(&mut app).unwrap(); - assert_eq!(app.ui.dialog.as_ref().unwrap().fields["files"], json!(["/tmp/doc-E.vectorcraft"])); + answer(&mut app, &[], true); + assert_eq!(replace_files(&app), Some(vec!["/tmp/doc-E.vectorcraft".to_string()])); assert_eq!(written.borrow().len(), 8); - dialogs::confirm(&mut app).unwrap(); + answer(&mut app, &[], true); assert_eq!(written.borrow().len(), 14); assert!(!app.session.active().unwrap().is_dirty()); } @@ -121,13 +145,16 @@ fn save_as_asks_before_replacing_an_artboard_file_that_is_there() { #[test] fn the_question_waits_for_an_open_dialog() { let (mut app, _) = app("/tmp/doc.vectorcraft"); + host(&mut app); let uid = app.session.active().unwrap().uid; dialogs::confirm::tell(&mut app, "Open", ""); dialogs::confirm::ask_replace_files(&mut app, uid, &["/tmp/doc-B.vectorcraft".into()], &[], "file.save", json!({})); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("message")), Some("Open".to_string())); - dialogs::cancel(&mut app); - frame(&mut app); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::confirm::REPLACE_FILES)); + pass(&mut app); + let keys: Vec<_> = open_dialogs(&app).into_iter().map(|o| o.key).collect(); + assert_eq!(keys, [Some(dialogs::confirm::MESSAGE.to_string())]); + assert_eq!(replace_files(&app), None); + answer(&mut app, &[], false); + assert_eq!(replace_files(&app), Some(vec!["/tmp/doc-B.vectorcraft".to_string()])); } /// Export with a file per artboard asks the same way, naming every file that is there; OK writes @@ -135,23 +162,19 @@ fn the_question_waits_for_an_open_dialog() { #[test] fn export_asks_before_replacing_artboard_files_that_are_there() { let (mut app, written) = app("/tmp/art.png"); + host(&mut app); three_boards(&mut app); let there = ["/tmp/art-B.png", "/tmp/art-C.png"]; app.services.exists = Some(std::sync::Arc::new(move |p: &str| there.contains(&p))); let r = crate::io::export(&mut app, Some("png"), Some("/tmp/art.png".into()), &json!({"useArtboards": true})).unwrap(); - assert_eq!(r["pending"], dialogs::confirm::REPLACE_FILES, "{r}"); - let d = app.ui.dialog.as_ref().unwrap(); - assert_eq!( - (d.str("message").as_str(), d.str("detail").as_str(), d.str("__command").as_str()), - ("“art-B.png” already exists. Replace it?", "art-B.png\nart-C.png", "file.exportAs") - ); + assert_eq!(r["pending"], REPLACE_FILES, "{r}"); + pass(&mut app); + assert_eq!(replace_files(&app), Some(vec!["/tmp/art-B.png".to_string(), "/tmp/art-C.png".to_string()])); assert!(written.borrow().is_empty()); // Another document made active meanwhile: OK exports the one that asked. let uid = app.session.active().unwrap().uid; - let question = app.ui.dialog.take(); app.run("file.new", json!({"width": 50, "height": 50})).unwrap(); - app.ui.dialog = question; - dialogs::confirm(&mut app).unwrap(); + answer(&mut app, &[], true); assert_eq!(names(&written), ["/tmp/art-Artboard-1.png", "/tmp/art-B.png", "/tmp/art-C.png"]); assert_eq!(app.session.active().map(|d| d.uid), Some(uid)); } @@ -159,15 +182,13 @@ fn export_asks_before_replacing_artboard_files_that_are_there() { #[test] fn save_a_copy_and_save_dont_ask_and_options_reach_the_file() { let (mut app, written) = app("/tmp/plain.vectorcraft"); + host(&mut app); // Save of an untitled document goes straight to the file, as before. app.run("file.save", Value::Null).unwrap(); - assert!(app.ui.dialog.is_none()); + assert!(open_dialogs(&app).is_empty()); assert_eq!(written.borrow().len(), 1); app.run("file.saveAs", Value::Null).unwrap(); - let d = app.ui.dialog.as_mut().unwrap(); - d.fields.insert("pdfCompatible".into(), json!(true)); - d.fields.insert("compress".into(), json!(false)); - dialogs::confirm(&mut app).unwrap(); + answer(&mut app, &[("pdfCompatible", json!(true)), ("compress", json!(false))], true); let bytes = written.borrow()[1].1.clone(); assert!(vectorcraft_format::pdf_content(&bytes).is_some_and(|p| p.starts_with(b"%PDF"))); assert!(!vectorcraft_format::is_compressed(&bytes)); @@ -184,15 +205,15 @@ fn the_web_save_as_dialog_shows_the_native_options() { })), ..Default::default() }; - let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), services); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), services); + host(&mut app); app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); three_boards(&mut app); app.run("file.saveAs", Value::Null).unwrap(); - frame(&mut app); - let d = app.ui.dialog.as_mut().unwrap(); - assert!(d.bool("__pick") && d.fields.contains_key("separateArtboards")); - d.fields.insert("separateArtboards".into(), json!(true)); - dialogs::confirm(&mut app).unwrap(); + pass(&mut app); + let f = open_dialogs(&app)[0].fields.clone().unwrap(); + assert!(f.get("__pick").is_some() && f.get("separateArtboards").is_some()); + answer(&mut app, &[("separateArtboards", json!(true))], true); let names: Vec = written.borrow().iter().map(|(p, _)| p.clone()).collect(); assert_eq!(names, ["Untitled-1.vectorcraft", "Untitled-1-Artboard-1.vectorcraft", "Untitled-1-B.vectorcraft", "Untitled-1-C.vectorcraft"]); }