diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs
index 5d96a14fa6..f0b66f8d30 100644
--- a/crates/ui-egui/src/tests/picks.rs
+++ b/crates/ui-egui/src/tests/picks.rs
@@ -1,97 +1,169 @@
-//! File dialogs shown off the UI thread (Linux, #592) or as sheets on the window (macOS, #867):
-//! what asked runs again with the answer, on the document it asked for; while a sheet is open
-//! nothing closes or quits; and nothing outside `picks` shows a dialog in line.
+//! File picks through the framework's file service: what asked runs again with the answer, on the
+//! document it asked for; while a pick's sheet is open nothing closes or quits.
use std::cell::RefCell;
-use std::collections::BTreeMap;
+use std::path::PathBuf;
use std::rc::Rc;
-use std::sync::mpsc::{Sender, channel};
+use std::sync::Arc;
+// PLAN: assumed ui-egui depends on craft-host, craft-ui-panels and craft-ui (hub-w1/hub-w2 add them).
+use craft::host::{Host, PickKind, Picked, ScriptedFiles};
+use craft_ui::contract::Bind;
+use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
+use craft_ui::runtime::requests::{PathKind, PathRequest};
+use craft_ui_panels::dialog::{DialogId, OpenDialog};
use egui::{Pos2, Rect, vec2};
use serde_json::{Value, json};
use vectorcraft_engine::Session;
-use crate::panels::graphic_styles::GraphicStyleLibraries;
-use crate::panels::library_panel::{self, library_menu};
-use crate::panels::swatches::SwatchLibraries;
-use crate::picks::{self, PickRequest};
-use crate::state::Dialog;
-use crate::{FilePick, Services, VectorcraftApp};
+use crate::picks::PickRequest;
+use crate::{Services, VectorcraftApp, file_asks};
const SVG: &[u8] = br#""#;
-/// What the status bar says when an answer comes for a document no longer open.
-const CLOSED: &str = "The document was closed while its file dialog was open";
+/// The scripted file service of one test: picks stay open until the test answers them.
+pub(crate) struct Picker {
+ files: Arc,
+ ctx: egui::Context,
+ written: Rc>>,
+}
-/// A dialog asked for, and where its answer goes.
-type Asked = (PickRequest, Sender>);
-
-/// The dialogs showing.
-#[derive(Clone, Default)]
-pub(crate) struct Shown(Rc>>);
-
-impl Shown {
- pub(crate) fn requests(&self) -> Vec {
- self.0.borrow().iter().map(|(r, _)| r.clone()).collect()
+impl Picker {
+ /// The requests of every pick asked so far.
+ pub(crate) fn requests(&self) -> Vec {
+ self.files.requests()
}
- /// The last dialog shown answers `paths`.
+ /// The newest open pick answers `paths`.
pub(crate) fn answer(&self, paths: &[&str]) {
- let (_, tx) = self.0.borrow_mut().pop().expect("a dialog is showing");
- tx.send(paths.iter().map(|p| p.to_string()).collect()).unwrap();
+ self.files.answer(Picked::Paths(paths.iter().map(PathBuf::from).collect()));
+ }
+ /// The newest open Save pick answers `path`, with the index of the file type picked in the panel.
+ pub(crate) fn answer_saved(&self, path: &str, file_type: Option) {
+ self.files.answer(Picked::Saved { path: PathBuf::from(path), file_type });
+ }
+ /// The newest open pick is cancelled.
+ pub(crate) fn cancel(&self) {
+ self.files.answer(Picked::Cancelled);
+ }
+ /// Picks report whether they are sheets on the window; call before the first ask, because the
+ /// service is replaced.
+ pub(crate) fn sheets(self, on: bool) -> Picker {
+ let files = Arc::new(ScriptedFiles::held().sheets(on));
+ install(&self.ctx, files.clone());
+ Picker { files, ctx: self.ctx, written: self.written }
+ }
+ /// The paths files were written to.
+ pub(crate) fn written(&self) -> Vec {
+ self.written.borrow().clone()
}
}
-/// The paths files were written to.
-pub(crate) type Written = Rc>>;
+fn install(ctx: &egui::Context, files: Arc) {
+ // PLAN: assumed the app's context carries a Host (hub-w1).
+ let host = Host::try_of_ctx(ctx).expect("the app's context carries its host");
+ host.with_files(files).install(ctx);
+}
-/// Give `services` dialogs shown off the UI thread (none in line: those fail the test), a reader of
-/// [`SVG`] at any path and a writer that lists the paths written.
-pub(crate) fn off_the_ui_thread(services: &mut Services) -> (Shown, Written) {
- let (shown, written) = (Shown::default(), Written::default());
- let (s, w) = (shown.clone(), written.clone());
- let in_line = |_: &FilePick| -> Option { panic!("no dialog on the UI thread") };
- services.pick_open = Some(Box::new(in_line));
- services.pick_save = Some(Box::new(in_line));
- services.pick_open_multi = Some(Box::new(|| panic!("no dialog on the UI thread")));
- services.pick_open_files = Some(Box::new(|_: &FilePick| panic!("no dialog on the UI thread")));
- services.pick_folder = Some(Box::new(|| panic!("no dialog on the UI thread")));
- services.read = Some(Box::new(|_: &str| Ok(SVG.to_vec())));
- services.write = Some(Box::new(move |path: &str, _: &[u8]| {
+/// Give `app` a scripted file service, a reader of [`SVG`] at any path and a writer that lists the
+/// paths written.
+// PLAN: fl.A20 names neither `written()` nor the reader and writer; files-w7's sheet requires both.
+pub(crate) fn scripted(app: &mut VectorcraftApp) -> Picker {
+ let ctx = app.ui_ctx.get_or_insert_with(egui::Context::default).clone();
+ let files = Arc::new(ScriptedFiles::held());
+ install(&ctx, files.clone());
+ let written = Rc::new(RefCell::new(Vec::new()));
+ let w = written.clone();
+ app.services.read = Some(Box::new(|_: &str| Ok(SVG.to_vec())));
+ app.services.write = Some(Box::new(move |path: &str, _: &[u8]| {
w.borrow_mut().push(path.to_string());
Ok(())
}));
- services.start_pick = Some(Box::new(move |request: PickRequest| {
- let (tx, rx) = channel();
- s.0.borrow_mut().push((request, tx));
- Some(rx)
- }));
- (shown, written)
+ Picker { files, ctx, written }
}
-/// A desktop app whose dialogs show off the UI thread, as sheets on the window when `sheets`
-/// (macOS) or as windows of their own (Linux).
-fn with_dialogs(sheets: bool) -> (VectorcraftApp, Shown, Written) {
- let mut services = Services { dialogs_are_sheets: sheets, ..Default::default() };
- let (shown, written) = off_the_ui_thread(&mut services);
- (VectorcraftApp::new(Session::new(), services), shown, written)
+/// Run what the frame runs for the picks: their continuations, then the saves.
+pub(crate) fn poll(app: &mut VectorcraftApp, ctx: &egui::Context) {
+ file_asks::poll(app);
+ crate::io::save::pump(app, ctx);
}
-/// The macOS app: its dialogs are sheets.
-fn app() -> (VectorcraftApp, Shown, Written) {
- with_dialogs(true)
+/// The dialogs the window has open, in opening order (the top one last).
+pub(crate) fn open_dialogs(app: &VectorcraftApp) -> Vec {
+ app.dialogs().map(|d| d.with(|h| h.open_dialogs())).unwrap_or_default()
}
-fn poll(app: &mut VectorcraftApp) {
- picks::poll(app, &egui::Context::default());
+/// Sets `fields` of dialog `id` as a person editing them would, presses OK when `ok`, and runs the
+/// app's pump over the answer.
+pub(crate) fn answer_dialog(app: &mut VectorcraftApp, id: DialogId, fields: &[(&str, Value)], ok: bool) {
+ let ctx = app.ui_ctx.clone().expect("a window context");
+ let host = app.dialogs().expect("the window's dialog host");
+ host.with(|h| {
+ for (field, value) in fields {
+ h.set_json_field(&ctx, id, field, value.clone()).unwrap_or_else(|e| panic!("{field}: {e}"));
+ }
+ if ok {
+ assert!(h.confirm_by_id(&ctx, id), "OK was refused");
+ }
+ });
+ crate::dialogs::host::pump(app, &ctx);
}
-fn dialog_kind(app: &VectorcraftApp) -> Option<&str> {
- app.ui.dialog.as_ref().map(|d| d.kind.as_str())
+fn app() -> VectorcraftApp {
+ VectorcraftApp::new(Session::new(), Services::default())
+}
+
+fn settle(app: &mut VectorcraftApp) {
+ let ctx = app.ui_ctx.clone().unwrap_or_default();
+ poll(app, &ctx);
+}
+
+/// The id of the open dialog with `key`.
+// PLAN: assumed the hosted dialogs' keys equal the old dialog kinds (`svgOptions`, `missingFonts`).
+fn find(app: &VectorcraftApp, key: &str) -> Option {
+ open_dialogs(app).iter().find(|d| d.key.as_deref() == Some(key)).map(|d| d.id)
+}
+
+fn top(app: &VectorcraftApp) -> DialogId {
+ open_dialogs(app).last().map(|d| d.id).expect("a dialog is open")
+}
+
+fn fields_of(app: &VectorcraftApp, id: DialogId) -> Option {
+ open_dialogs(app).into_iter().find(|d| d.id == id).and_then(|d| d.fields)
+}
+
+/// One pass of the app's `poll` as a frame → the URLs the frame asked egui to open.
+fn opened_urls(app: &mut VectorcraftApp) -> Vec {
+ let ctx = app.ui_ctx.clone().unwrap_or_default();
+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 900.0))), ..Default::default() };
+ let out = ctx.run_ui(raw, |ui| poll(app, ui.ctx()));
+ out.platform_output
+ .commands
+ .iter()
+ .filter_map(|c| match c {
+ egui::OutputCommand::OpenUrl(open) => Some(open.url.clone()),
+ _ => None,
+ })
+ .collect()
+}
+
+/// A hosted dialog with one folder row, open on the window's host.
+fn browse_dialog(app: &mut VectorcraftApp) -> DialogId {
+ let ctx = app.ui_ctx.clone().expect("a window context");
+ let params = vec![Param::new("folder", "Folder", ParamKind::text("")).browse(PathKind::Folder)];
+ let dialog = HostedParamDialog::new(&ctx, "browseTest", DialogFields::from_pairs([("folder", "")]), move |fields| {
+ ParamDialog::new("browseTest", "Browse test", params.clone()).values(Bind::bound(fields))
+ });
+ app.dialogs().expect("the window's dialog host").with(|h| h.open(dialog))
+}
+
+/// Asks for a folder on behalf of dialog `id`'s `folder` row.
+fn browse_folder(app: &mut VectorcraftApp, id: DialogId) {
+ file_asks::browse(app, id, PathRequest::new("folder", PathKind::Folder), PickRequest::folder("export"), file_asks::answer_path);
}
// ------------------------------------------------------------------------- driven like a person
-/// Room for a dialog, a panel or a menu (the libraries menu lists every library).
+/// Room for a dialog, a panel or a menu.
const SCREEN: (f32, f32) = (1600.0, 6000.0);
/// One frame of `draw` with `events` → its texts and where they were drawn.
@@ -128,7 +200,7 @@ fn at(texts: &[(String, Rect)], label: &str) -> Pos2 {
/// Draw `draw` until it settles, then click its text `label`.
fn click(app: &mut VectorcraftApp, label: &str, draw: impl Fn(&mut VectorcraftApp, &mut egui::Ui)) {
- let ctx = egui::Context::default();
+ let ctx = app.ui_ctx.clone().unwrap_or_default();
crate::theme::install_fonts(&ctx);
frame(&ctx, app, vec![], &draw);
frame(&ctx, app, vec![], &draw);
@@ -137,78 +209,61 @@ fn click(app: &mut VectorcraftApp, label: &str, draw: impl Fn(&mut VectorcraftAp
frame(&ctx, app, vec![egui::Event::PointerMoved(pos), button(true), button(false)], &draw);
}
-/// The open dialog, drawn as the app draws it.
+/// The open dialogs, drawn as the shell draws them, then the app's pump over their answers.
fn dialogs(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
- crate::dialogs::show(app, ui.ctx());
-}
-
-/// The active document written to `Poster.vectorcraft` in a folder of its own named after `tag`
-/// → (the folder, the file).
-fn saved_document(app: &mut VectorcraftApp, tag: &str) -> (std::path::PathBuf, String) {
- let b64 = app.run("document.serialize", json!({})).unwrap()["dataBase64"].as_str().unwrap().to_string();
- let dir = std::env::temp_dir().join(format!("vc-picks-{tag}-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let file = dir.join("Poster.vectorcraft");
- std::fs::write(&file, vectorcraft_format::base64_decode(&b64).unwrap()).unwrap();
- (dir, file.to_string_lossy().into_owned())
+ if let Some(host) = app.dialogs() {
+ host.with(|h| h.run(ui));
+ }
+ crate::dialogs::host::pump(app, ui.ctx());
}
// ------------------------------------------------------------------------------------- the tests
+/// A command asks for a file and goes on with the answer; cancelled, nothing happens.
#[test]
-fn file_open_starts_in_the_last_opened_files_folder() {
- let (mut app, shown, _) = app();
- let dir = std::env::temp_dir().join(format!("vc-open-dialog-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let path = dir.join("poster.svg").to_string_lossy().into_owned();
- crate::io::note_recent(&mut app, &path);
- assert!(app.run("file.open", json!({})).is_err());
- poll(&mut app);
- let folder = dir.to_string_lossy().into_owned();
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(p)] if p.folder == Some(folder)));
- shown.answer(&[]);
- poll(&mut app);
- let _ = std::fs::remove_dir_all(&dir);
-}
-
-#[test]
-fn file_open_opens_what_its_dialog_picks_when_it_answers() {
- let (mut app, shown, _) = app();
- // The dialog shows; File › Open gives up for now, without a "cancelled".
- assert!(app.run("file.open", json!({})).is_err());
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(p)] if p.folder.is_none()));
- poll(&mut app);
- assert!(app.session.documents().is_empty() && app.ui.status.is_empty(), "{}", app.ui.status);
- // Another dialog waits for this one.
- assert!(app.run("file.open", json!({})).is_err());
- assert_eq!(shown.requests().len(), 1);
- assert!(app.ui.status.contains("file dialog is open"), "{}", app.ui.status);
- shown.answer(&["/art/a.svg"]);
- poll(&mut app);
- assert_eq!(app.session.documents().len(), 1);
- assert_eq!(app.session.active().and_then(|d| d.path.clone()).as_deref(), Some("/art/a.svg"));
- // Cancelled: nothing happens, and dialogs show again.
- assert!(app.run("file.open", json!({})).is_err());
- shown.answer(&[]);
- poll(&mut app);
- assert_eq!(app.session.documents().len(), 1);
- assert!(app.run("file.open", json!({})).is_err());
- assert_eq!(shown.requests().len(), 1);
-}
-
-#[test]
-fn save_as_goes_on_with_the_path_picked() {
- let (mut app, shown, written) = app();
- app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
- app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap();
- assert!(app.run("file.saveAs", json!({})).is_err());
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)]));
- shown.answer(&["/art/poster.svg"]);
- poll(&mut app);
- // SVG Options asks next, and its OK writes the file there.
- assert_eq!(dialog_kind(&app), Some("svgOptions"));
- crate::dialogs::confirm(&mut app).unwrap();
- assert_eq!(*written.borrow(), ["/art/poster.svg"]);
+fn a_command_asks_for_a_file_and_goes_on_with_the_answer() {
+ type Answer = fn(&Picker);
+ type Then = fn(&mut VectorcraftApp, &Picker);
+ // PLAN: `ui.findLinksInFolder` needs a linked image and a folder search; the find-links tests cover it.
+ let rows: [(&str, PickKind, Answer, Then); 3] = [
+ ("file.open", PickKind::Open, |p| p.answer(&["/art/a.svg"]), |app, _| {
+ assert_eq!(app.session.documents().len(), 2);
+ assert_eq!(app.session.active().and_then(|d| d.path.clone()).as_deref(), Some("/art/a.svg"));
+ }),
+ ("file.saveAs", PickKind::Save, |p| p.answer_saved("/art/poster.svg", None), |app, p| {
+ // SVG Options asks next, and its OK writes the file there.
+ let options = find(app, "svgOptions").expect("SVG Options");
+ answer_dialog(app, options, &[], true);
+ assert_eq!(p.written(), ["/art/poster.svg"]);
+ }),
+ ("file.place", PickKind::Open, |p| p.answer(&["/art/p.svg"]), |app, _| {
+ assert!(!open_dialogs(app).is_empty(), "the place dialog opens: {}", app.ui.status);
+ }),
+ ];
+ for (command, kind, answer, then) in rows {
+ let mut a = app();
+ let picker = scripted(&mut a);
+ a.run("file.new", json!({"width": 100, "height": 80})).unwrap();
+ a.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap();
+ assert!(a.run(command, json!({})).is_err(), "{command} waits for its pick");
+ assert_eq!(picker.requests().iter().map(|r| r.kind).collect::>(), [kind], "{command}");
+ settle(&mut a);
+ assert!(a.file_dialog_open(), "{command}");
+ answer(&picker);
+ settle(&mut a);
+ assert!(!a.file_dialog_open(), "{command}");
+ then(&mut a, &picker);
+ }
+ for (command, ..) in rows {
+ let mut a = app();
+ let picker = scripted(&mut a);
+ a.run("file.new", json!({"width": 100, "height": 80})).unwrap();
+ assert!(a.run(command, json!({})).is_err());
+ picker.cancel();
+ settle(&mut a);
+ assert!(!a.file_dialog_open(), "{command}");
+ assert!(a.session.documents().len() == 1 && open_dialogs(&a).is_empty() && picker.written().is_empty(), "{command}: {}", a.ui.status);
+ }
}
/// Save as PDF with View PDF after Saving, asked for by automation without a path: the save panel
@@ -216,12 +271,8 @@ fn save_as_goes_on_with_the_path_picked() {
/// when a person picked the file. The person's own Save as PDF opens it.
#[test]
fn a_pdf_automation_asked_for_is_not_opened_when_its_save_panel_answers() {
- let opened = Rc::new(RefCell::new(Vec::::new()));
- let u = opened.clone();
- let mut services =
- Services { dialogs_are_sheets: true, open_url: Some(Box::new(move |p: &str| u.borrow_mut().push(p.to_string()))), ..Default::default() };
- let (shown, written) = off_the_ui_thread(&mut services);
- let mut app = VectorcraftApp::new(Session::new(), services);
+ let mut app = app();
+ let picker = scripted(&mut app).sheets(true);
app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap();
let view = json!({"viewAfterSaving": true});
@@ -229,347 +280,119 @@ fn a_pdf_automation_asked_for_is_not_opened_when_its_save_panel_answers() {
app.ui.answering_control = true;
let _ = app.run("file.export.pdf", view.clone());
app.ui.answering_control = false;
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)]));
- shown.answer(&["/art/automated.pdf"]);
- poll(&mut app);
- assert_eq!(*written.borrow(), ["/art/automated.pdf"]);
- assert!(opened.borrow().is_empty(), "{:?}", opened.borrow());
+ assert_eq!(picker.requests().iter().map(|r| r.kind).collect::>(), [PickKind::Save]);
+ picker.answer_saved("/art/automated.pdf", None);
+ let urls = opened_urls(&mut app);
+ assert_eq!(picker.written(), ["/art/automated.pdf"]);
+ assert!(urls.is_empty(), "{urls:?}");
let _ = app.run("file.export.pdf", view);
- shown.answer(&["/art/mine.pdf"]);
- poll(&mut app);
- assert_eq!(*written.borrow(), ["/art/automated.pdf", "/art/mine.pdf"]);
- assert_eq!(opened.borrow().len(), 1, "{:?}", opened.borrow());
- assert!(opened.borrow()[0].ends_with("/art/mine.pdf"), "{:?}", opened.borrow());
+ picker.answer_saved("/art/mine.pdf", None);
+ let urls = opened_urls(&mut app);
+ assert_eq!(picker.written(), ["/art/automated.pdf", "/art/mine.pdf"]);
+ assert!(matches!(urls.as_slice(), [url] if url.ends_with("/art/mine.pdf")), "{urls:?}");
}
+/// A Browse row's answer fills the open dialog's field; an answer after the dialog closed does nothing.
#[test]
fn a_dialogs_folder_button_fills_its_field_when_the_picker_answers() {
- let (mut app, shown, _) = app();
- let mut d = Dialog::new("exportForScreens", json!({"folder": ""}));
- app.ui.dialog = Some(d.clone());
- picks::folder_field(&mut app, &mut d, "folder");
- assert_eq!(shown.requests(), [PickRequest::Folder]);
- shown.answer(&["/out"]);
- poll(&mut app);
- assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("folder")).as_deref(), Some("/out"));
+ let mut app = app();
+ let picker = scripted(&mut app);
+ let id = browse_dialog(&mut app);
+ browse_folder(&mut app, id);
+ assert_eq!(picker.requests().iter().map(|r| r.kind).collect::>(), [PickKind::Folder]);
+ picker.answer(&["/out"]);
+ settle(&mut app);
+ assert_eq!(fields_of(&app, id).map(|f| f["folder"].clone()), Some(json!("/out")));
+
+ browse_folder(&mut app, id);
+ let ctx = app.ui_ctx.clone().unwrap();
+ app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id));
+ picker.answer(&["/late"]);
+ settle(&mut app);
+ assert!(open_dialogs(&app).is_empty(), "the answer reopened nothing");
}
-/// Separations Preview › Load Profile… asks off the UI thread, and the profile picked is loaded
-/// when the dialog answers (here a missing file, whose error names it).
-#[test]
-fn load_profile_asks_off_the_ui_thread() {
- let (mut app, shown, _) = app();
- app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
- click(&mut app, "Load Profile…", crate::panels::separations::show);
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(p)] if p.filters.iter().any(|(_, e)| e.iter().any(|e| e == "icc"))));
- poll(&mut app);
- assert!(app.ui.status.is_empty(), "{}", app.ui.status);
- shown.answer(&["/no/such/profile.icc"]);
- poll(&mut app);
- assert!(app.ui.status.contains("/no/such/profile.icc"), "color.loadProfile ran on the path: {}", app.ui.status);
-}
-
-/// The Variables panel menu's Import Data Sets… and Export Data Sets… ask off the UI thread: the
-/// data sets in the file picked are loaded, and the header and the data set's row are written to
-/// the path the dialog answers.
-#[test]
-fn variables_panel_data_sets_ask_off_the_ui_thread() {
- let (mut app, shown, _) = app();
- app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
- let dir = vectorcraft_testkit::temp_dir("picks-data-sets");
- if let Err(e) = std::fs::remove_dir_all(&dir) {
- assert_eq!(e.kind(), std::io::ErrorKind::NotFound, "cannot empty {}: {e}", dir.display());
- }
- std::fs::create_dir_all(&dir).unwrap();
- let (csv, out) = (dir.join("sets.csv"), dir.join("out.csv"));
- std::fs::write(&csv, "Name\ny\n").unwrap();
- let sets = |app: &VectorcraftApp| app.session.doc().unwrap().doc.variables.datasets.iter().map(|d| d.name.clone()).collect::>();
-
- click(&mut app, "Import Data Sets…", crate::panels::variables::menu);
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(_)]));
- shown.answer(&[&csv.to_string_lossy()]);
- poll(&mut app);
- assert_eq!(sets(&app), ["Data Set 1"], "{}", app.ui.status);
-
- click(&mut app, "Export Data Sets…", crate::panels::variables::menu);
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)]));
- shown.answer(&[&out.to_string_lossy()]);
- poll(&mut app);
- assert_eq!(std::fs::read_to_string(&out).ok().as_deref(), Some("Name\ny\n"), "{}", app.ui.status);
- let _ = std::fs::remove_dir_all(dir);
-}
-
-/// The Swatches libraries menu's Other Library… asks off the UI thread; the file picked (another
-/// document) loads as a library and opens in the library panel.
-#[test]
-fn other_swatch_library_asks_off_the_ui_thread() {
- let (mut app, shown, _) = app();
- app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
- app.run("swatch.new", json!({"name": "Signal", "color": "#ff3300"})).unwrap();
- let (dir, file) = saved_document(&mut app, "swatches");
- click(&mut app, "Other Library…", library_menu::);
- assert!(matches!(
- shown.requests().as_slice(),
- [PickRequest::Open(p)] if p.filters.first().is_some_and(|(label, exts)| label == "Swatch libraries" && exts.iter().any(|e| e == "ase"))
- ));
- poll(&mut app);
- assert!(library_panel::last_open(&app.ui).is_none() && app.ui.status.is_empty(), "{}", app.ui.status);
- shown.answer(&[&file]);
- poll(&mut app);
- let open = library_panel::last_open(&app.ui).cloned().unwrap_or_else(|| panic!("no library open: {}", app.ui.status));
- assert_eq!(open.kind, "swatches");
- let (_, lib) = vectorcraft_engine::cmd::swatchlib::library(&app.session, &open.id).unwrap();
- assert!(lib.swatch("Signal").is_some(), "{}", open.id);
- let _ = std::fs::remove_dir_all(dir);
-}
-
-/// The Graphic Styles libraries menu's Other Library… asks off the UI thread; the file picked
-/// (another document) loads as a library and opens in the library panel.
-#[test]
-fn other_graphic_style_library_asks_off_the_ui_thread() {
- let (mut app, shown, _) = app();
- app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
- let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone();
- app.run("graphicStyle.new", json!({"name": "Poster Look", "id": id})).unwrap();
- let (dir, file) = saved_document(&mut app, "styles");
- click(&mut app, "Other Library…", library_menu::);
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(_)]));
- shown.answer(&[&file]);
- poll(&mut app);
- let open = library_panel::last_open(&app.ui).cloned().unwrap_or_else(|| panic!("no library open: {}", app.ui.status));
- assert_eq!(open.kind, "graphicStyles");
- let (_, lib) = vectorcraft_engine::cmd::stylelib::library(&app.session, &open.id).unwrap();
- assert!(lib.style("Poster Look").is_some(), "{}", open.id);
- let _ = std::fs::remove_dir_all(dir);
-}
-
-/// The Variables panel menu's Load Variable Library… asks off the UI thread: the library picked
-/// loads when the dialog answers.
-#[test]
-fn load_variable_library_asks_off_the_ui_thread() {
- let (mut app, shown, _) = app();
- app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
- let dir = std::env::temp_dir().join(format!("vc-picks-variables-{}", std::process::id()));
- std::fs::create_dir_all(&dir).unwrap();
- let library = dir.join("library.xml");
- let xml = r#"
-
x
"#;
- std::fs::write(&library, xml).unwrap();
- let sets = |app: &VectorcraftApp| app.session.doc().unwrap().doc.variables.datasets.iter().map(|d| d.name.clone()).collect::>();
-
- click(&mut app, "Load Variable Library…", crate::panels::variables::menu);
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(_)]));
- assert!(sets(&app).is_empty(), "nothing loads before the dialog answers");
- shown.answer(&[&library.to_string_lossy()]);
- poll(&mut app);
- assert_eq!(sets(&app), ["A"], "{}", app.ui.status);
- let _ = std::fs::remove_dir_all(dir);
-}
-
-/// The Variables panel menu's Save Variable Library… is enabled once the document has a variable,
-/// of any kind, and then asks off the UI thread: the library is written to the path the dialog
-/// answers, and Load Variable Library reads back its visibility and text variables.
-#[test]
-fn save_variable_library_asks_off_the_ui_thread() {
- let (mut app, shown, _) = app();
- app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
- // Without a variable the item is disabled and asks for no file.
- click(&mut app, "Save Variable Library…", crate::panels::variables::menu);
- assert!(shown.requests().is_empty(), "{:?}", shown.requests());
- app.run("variable.define", json!({"name": "Shown", "kind": "visibility"})).unwrap();
- app.run("variable.define", json!({"name": "Name", "kind": "text"})).unwrap();
- app.run("dataset.new", json!({"name": "A", "values": {"Name": "x", "Shown": true}})).unwrap();
- let dir = vectorcraft_testkit::temp_dir("picks-save-variable-library");
- if let Err(e) = std::fs::remove_dir_all(&dir) {
- assert_eq!(e.kind(), std::io::ErrorKind::NotFound, "cannot empty {}: {e}", dir.display());
- }
- std::fs::create_dir_all(&dir).unwrap();
- let library = dir.join("library.xml");
-
- click(&mut app, "Save Variable Library…", crate::panels::variables::menu);
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(p)] if p.name == "variables.xml"));
- assert!(!library.exists(), "nothing is written before the dialog answers");
- shown.answer(&[&library.to_string_lossy()]);
- poll(&mut app);
- let xml = std::fs::read_to_string(&library).unwrap_or_else(|e| panic!("{e}: {}", app.ui.status));
- let loaded = app.run("variable.loadLibrary", json!({"xml": xml})).unwrap();
- assert_eq!((loaded["variables"].clone(), loaded["names"].clone()), (json!(["Shown", "Name"]), json!(["A"])));
- let values = &app.session.doc().unwrap().doc.variables.datasets[0].values;
- assert_eq!(values.get("Shown"), Some(&vectorcraft_doc::DataValue::Visible(true)));
- let _ = std::fs::remove_dir_all(dir);
-}
-
-/// The Keyboard Shortcuts dialog's Import… and Export… ask off the UI thread: the set imported
-/// replaces the dialog's working set (kept on OK), Export… writes it where the dialog answers, and
-/// an answer once the dialog is closed does nothing.
-#[test]
-fn keyboard_shortcuts_import_and_export_ask_off_the_ui_thread() {
- let (mut app, shown, written) = app();
- let set = crate::shortcut_editor::export_json("Custom", &crate::keymap::overrides_from(&[("view.grid", "Ctrl+Alt+G")]));
- let (_, want) = crate::shortcut_editor::import_json(&set).unwrap();
- let bytes = serde_json::to_vec(&set).unwrap();
- app.services.read = Some(Box::new(move |_: &str| Ok(bytes.clone())));
- app.run("edit.keyboardShortcuts", json!({})).unwrap();
- click(&mut app, "Import…", dialogs);
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(_)]));
- shown.answer(&["/keys/mine.json"]);
- poll(&mut app);
- let d = app.ui.dialog.as_ref().expect("the dialog stays open");
- assert_eq!((d.kind.as_str(), &d.fields["overrides"]), ("shortcuts", &serde_json::to_value(&want).unwrap()));
- assert!(d.str("__message").starts_with("Imported"), "{}", d.str("__message"));
- assert!(app.ui.shortcut_overrides.is_empty(), "kept only on OK");
- click(&mut app, "Export…", dialogs);
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)]));
- shown.answer(&["/keys/out.json"]);
- poll(&mut app);
- assert_eq!(*written.borrow(), ["/keys/out.json"]);
- // Closed before the dialog answers: nothing is written, and the status says why.
- click(&mut app, "Export…", dialogs);
- app.ui.dialog = None;
- shown.answer(&["/keys/late.json"]);
- poll(&mut app);
- assert_eq!(*written.borrow(), ["/keys/out.json"]);
- assert_eq!(app.ui.status, picks::dialog_gone());
- // The command waits for its dialog too: no data in place of the file.
- assert_eq!(app.run("shortcuts.export", json!({})), Err("cancelled".to_string()));
- shown.answer(&["/keys/command.json"]);
- poll(&mut app);
- assert_eq!(*written.borrow(), ["/keys/out.json", "/keys/command.json"]);
-}
-
-/// The Keyboard Shortcuts dialog's Export Text… asks off the UI thread for a `.txt` file and writes
-/// the dialog's working set, as edited so far, as text where the dialog answers.
+/// Export Text writes the working set as text where its save panel answers.
#[test]
fn keyboard_shortcuts_export_text_writes_the_working_set_as_text() {
- let (mut app, shown, _) = app();
+ let mut app = app();
+ let picker = scripted(&mut app);
let texts: Rc>> = Default::default();
let t = texts.clone();
app.services.write = Some(Box::new(move |path: &str, b: &[u8]| {
t.borrow_mut().push((path.to_string(), String::from_utf8_lossy(b).into_owned()));
Ok(())
}));
- let ov = crate::keymap::overrides_from(&[("view.grid", "Ctrl+Alt+G")]);
- let revision = crate::menus::plugin_revision();
- app.run("edit.keyboardShortcuts", json!({})).unwrap();
- let d = app.ui.dialog.as_mut().expect("Keyboard Shortcuts");
- d.fields.insert("overrides".into(), crate::keymap::stored::to_value(&ov));
- d.fields.insert("set".into(), json!("Custom"));
- click(&mut app, "Export Text…", dialogs);
- match shown.requests().as_slice() {
- [PickRequest::Save(pick)] => {
- assert_eq!(pick.filters, FilePick::filters([("Text", &["txt"][..]), ("Shortcut sheet", &["pdf"][..]), ("CSV", &["csv"][..])]))
- }
- other => panic!("{other:?}"),
- }
- shown.answer(&["/keys/list.txt"]);
- poll(&mut app);
+ // PLAN: the working set is the active set's defaults here; shortcuts-w6's `Overrides` setter is not named.
+ let _ = app.run("shortcuts.exportText", json!({}));
+ let requests = picker.requests();
+ let [request] = requests.as_slice() else { panic!("{requests:?}") };
+ assert_eq!(request.kind, PickKind::Save);
+ assert_eq!(request.filters.iter().map(|f| f.extensions.join(",")).collect::>(), ["txt", "pdf", "csv"]);
+ picker.answer_saved("/keys/list.txt", Some(0));
+ settle(&mut app);
let texts = texts.borrow();
let [(path, text)] = texts.as_slice() else { panic!("{texts:?}") };
assert_eq!(path, "/keys/list.txt");
- // Another test installing or removing a plug-in meanwhile changes the Effect menu's rows.
- if crate::menus::plugin_revision() == revision {
- assert_eq!(*text, crate::shortcut_editor::export_text("Custom", &ov));
- }
- assert!(text.starts_with("Keyboard Shortcuts\nSet: Custom\n"), "{text}");
- assert!(text.contains(&format!("\t{}\n", crate::menus::pretty_shortcut("Ctrl+Alt+G"))), "{text}");
- assert!(app.ui.shortcut_overrides.is_empty(), "the working set is kept only on OK");
- assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "the dialog stays open");
+ assert!(text.starts_with("Keyboard Shortcuts\n"), "{text}");
+ assert!(text.contains(&format!("\t{}\n", crate::menus::pretty_shortcut("Ctrl+S"))), "{text}");
}
-/// The file type picked in Export Text…'s save dialog picks the file: the PDF sheet or the CSV file
-/// for a name typed with `.pdf` or `.csv`, and for a type the dialog reports with a name typed
-/// without an extension, that type's file under the name with its extension.
+/// The file type picked in Export Text's save panel picks the file: a name typed with `.pdf` or
+/// `.csv` is that file, and a name typed without an extension gets the picked type's extension.
#[test]
fn keyboard_shortcuts_export_text_writes_the_format_picked_in_its_save_dialog() {
- for (answer, path, start) in [
- (&["/keys/list.pdf"][..], "/keys/list.pdf", &b"%PDF-"[..]),
- (&["/keys/list.csv"][..], "/keys/list.csv", &b"\xef\xbb\xbfGroup,Command,Shortcut\r\n"[..]),
- (&["/keys/table", "csv"][..], "/keys/table.csv", &b"\xef\xbb\xbfGroup,Command,Shortcut\r\n"[..]),
- (&["/keys/sheet", "pdf"][..], "/keys/sheet.pdf", &b"%PDF-"[..]),
- (&["/keys/plain", "txt"][..], "/keys/plain.txt", &b"Keyboard Shortcuts\n"[..]),
+ let csv = &b"\xef\xbb\xbfGroup,Command,Shortcut\r\n"[..];
+ for (answer, file_type, path, start) in [
+ ("/keys/list.pdf", None, "/keys/list.pdf", &b"%PDF-"[..]),
+ ("/keys/list.csv", None, "/keys/list.csv", csv),
+ ("/keys/table", Some(2), "/keys/table.csv", csv),
+ ("/keys/sheet", Some(1), "/keys/sheet.pdf", &b"%PDF-"[..]),
+ ("/keys/plain", Some(0), "/keys/plain.txt", &b"Keyboard Shortcuts\n"[..]),
] {
- let (mut app, shown, _) = app();
- type Files = Rc)>>>;
- let files: Files = Default::default();
+ let mut app = app();
+ let picker = scripted(&mut app);
+ let files: Rc)>>> = Default::default();
let f = files.clone();
app.services.write = Some(Box::new(move |path: &str, b: &[u8]| {
f.borrow_mut().push((path.to_string(), b.to_vec()));
Ok(())
}));
- app.run("edit.keyboardShortcuts", json!({})).unwrap();
- click(&mut app, "Export Text…", dialogs);
- shown.answer(answer);
- poll(&mut app);
+ let _ = app.run("shortcuts.exportText", json!({}));
+ picker.answer_saved(answer, file_type);
+ settle(&mut app);
let files = files.borrow();
- let [(written, bytes)] = files.as_slice() else { panic!("{files:?}") };
+ let [(written, bytes)] = files.as_slice() else { panic!("{answer}: {files:?}") };
assert_eq!(written, path);
assert!(bytes.starts_with(start), "{path}: {:?}", String::from_utf8_lossy(&bytes[..bytes.len().min(40)]));
}
}
-/// `shortcuts.exportText` with a `format` and no `path` gives the name its save dialog answers
-/// that format's extension, though the dialog reports no file type.
-#[test]
-fn export_text_with_a_format_gives_the_answered_name_its_extension() {
- let (mut app, shown, _) = app();
- let written: Rc>> = Default::default();
- let w = written.clone();
- app.services.write = Some(Box::new(move |path: &str, _: &[u8]| {
- w.borrow_mut().push(path.to_string());
- Ok(())
- }));
- let _ = app.run("shortcuts.exportText", json!({"format": "sheet"}));
- shown.answer(&["/keys/sheet"]);
- poll(&mut app);
- assert_eq!(*written.borrow(), ["/keys/sheet.pdf"]);
-}
-
-/// A name that Export Text… gives the picked type's extension names a file the save dialog did
-/// not check: when one is there, a question asks before replacing it and nothing is written
-/// meanwhile.
-#[test]
-fn keyboard_shortcuts_export_text_asks_before_replacing_a_file_its_extension_names() {
- let (mut app, shown, _) = app();
- let written: Rc>> = Default::default();
- let w = written.clone();
- app.services.write = Some(Box::new(move |path: &str, _: &[u8]| {
- w.borrow_mut().push(path.to_string());
- Ok(())
- }));
- app.services.exists = Some(std::sync::Arc::new(|p: &str| p == "/keys/list.pdf"));
- app.run("edit.keyboardShortcuts", json!({})).unwrap();
- click(&mut app, "Export Text…", dialogs);
- shown.answer(&["/keys/list.txt", "pdf"]);
- poll(&mut app);
- assert!(written.borrow().is_empty(), "{:?}", written.borrow());
- let d = app.ui.dialog.as_ref().expect("a question");
- assert_eq!(d.str("path"), "/keys/list.pdf");
-}
-
-/// Keyboard Shortcuts' Import… opens a shortcut set another app saved as text (`.kys`) in Import
-/// Shortcut Set over the dialog when its file dialog answers, and the dialog's working set stays in
-/// Keyboard Shortcuts, which Cancel shows again.
+/// Keyboard Shortcuts' Import opens a shortcut set another app saved as text (`.kys`) in a review
+/// over the dialog when its file dialog answers; Cancel shows Keyboard Shortcuts again.
#[test]
fn keyboard_shortcuts_import_opens_a_text_set_over_the_dialog() {
- let (mut app, shown, _) = app();
+ let mut app = app();
+ let picker = scripted(&mut app);
let dir = std::env::temp_dir().join(format!("vc-picks-kys-import-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let set = dir.join("Mine.kys");
std::fs::write(&set, "/Menus {\n /Acme\\ Undo { /Modifiers 11 /Key 902 }\n}\n").unwrap();
- let path = set.to_string_lossy().into_owned();
+ app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string())));
app.run("edit.keyboardShortcuts", json!({})).unwrap();
- click(&mut app, "Import…", dialogs);
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(_)]));
- shown.answer(&[&path]);
- poll(&mut app);
- let d = app.ui.dialog.as_ref().unwrap_or_else(|| panic!("no dialog: {}", app.ui.status));
- assert_eq!(d.kind.as_str(), crate::dialogs::shortcut_import::KIND, "{}", app.ui.status);
- for field in ["overrides", "set", "__message"] {
- assert!(!d.fields.contains_key(field), "Keyboard Shortcuts' `{field}` stays in Keyboard Shortcuts");
- }
- crate::dialogs::cancel(&mut app);
- assert_eq!(dialog_kind(&app), Some("shortcuts"));
+ let shortcuts = top(&app);
+ assert_eq!(app.run("shortcuts.import", json!({})), Err("cancelled".to_string()));
+ picker.answer(&[&set.to_string_lossy()]);
+ settle(&mut app);
+ // PLAN: assumed the review is a dialog of its own over Keyboard Shortcuts (shortcuts-w8).
+ let open = open_dialogs(&app);
+ assert_eq!(open.len(), 2, "{}", app.ui.status);
+ assert_eq!(open[0].id, shortcuts);
+ let ctx = app.ui_ctx.clone().unwrap();
+ let review = top(&app);
+ app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, review));
+ assert_eq!(top(&app), shortcuts);
let _ = std::fs::remove_dir_all(dir);
}
@@ -577,8 +400,9 @@ fn keyboard_shortcuts_import_opens_a_text_set_over_the_dialog() {
/// dialog, read and write nothing, and give an error naming `path`; a null `path` still asks.
#[test]
fn keyboard_shortcuts_commands_reject_a_path_that_is_not_a_string() {
- let (mut app, shown, written) = app();
- let read: Written = Default::default();
+ let mut app = app();
+ let picker = scripted(&mut app);
+ let read: Rc>> = Default::default();
let r = read.clone();
app.services.read = Some(Box::new(move |path: &str| {
r.borrow_mut().push(path.to_string());
@@ -587,127 +411,32 @@ fn keyboard_shortcuts_commands_reject_a_path_that_is_not_a_string() {
for path in [json!(5), json!(true), json!({"file": "/keys/a.json"}), json!(["/keys/a.json"])] {
for id in ["shortcuts.export", "shortcuts.import"] {
assert_eq!(app.run(id, json!({ "path": path })), Err("`path` must be a string".to_string()), "{id} {path}");
- assert!(shown.requests().is_empty(), "{id} {path}: {:?}", shown.requests());
+ assert!(picker.requests().is_empty(), "{id} {path}: {:?}", picker.requests());
}
}
- assert!(written.borrow().is_empty() && read.borrow().is_empty());
- assert!(app.ui.shortcut_overrides.is_empty());
+ assert!(picker.written().is_empty() && read.borrow().is_empty());
assert_eq!(app.run("shortcuts.export", json!({"path": null})), Err("cancelled".to_string()));
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)]));
-}
-
-/// A dialog's folder button answered after the dialog closed fills nothing, and the status says
-/// why.
-#[test]
-fn a_folder_for_a_closed_dialog_is_dropped() {
- let (mut app, shown, _) = app();
- let mut d = Dialog::new("exportForScreens", json!({"folder": ""}));
- app.ui.dialog = Some(d.clone());
- picks::folder_field(&mut app, &mut d, "folder");
- app.ui.dialog = None;
- shown.answer(&["/out"]);
- poll(&mut app);
- assert_eq!(dialog_kind(&app), None);
- assert_eq!(app.ui.status, picks::dialog_gone());
-}
-
-/// Export… in the PDF, Print, Transparency Flattener and Perspective Grid Presets dialogs asks off
-/// the UI thread and writes the selected preset where the dialog answers; the dialog stays open.
-#[test]
-fn preset_dialogs_export_asks_off_the_ui_thread() {
- use vectorcraft_engine::cmd::{flatten, pdfcmds, perspgrid, printpresets};
- let cases = [
- ("pdf.preset.save", json!({"name": "Mine"}), "ui.pdfPresetsDialog", pdfcmds::PRESET_FORMAT),
- ("print.presets.save", json!({"name": "Mine", "settings": {"copies": 2}}), "ui.printPresetsDialog", printpresets::PRESET_FORMAT),
- ("flattener.presets.save", json!({"name": "Mine", "balance": 20}), "ui.flattenerPresetsDialog", flatten::PRESET_FORMAT),
- ("perspective.presets.save", json!({"name": "Mine"}), "ui.perspectivePresetsDialog", perspgrid::PRESET_FORMAT),
- ];
- for (save, params, open, ext) in cases {
- let (mut app, shown, written) = app();
- app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
- app.run(save, params).unwrap();
- app.run(open, json!({"selected": "Mine"})).unwrap();
- let kind = dialog_kind(&app).unwrap().to_string();
- click(&mut app, "Export…", dialogs);
- assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)]), "{open}: {:?}", shown.requests());
- assert!(written.borrow().is_empty(), "{open}");
- let path = format!("/presets/mine.{ext}");
- shown.answer(&[&path]);
- poll(&mut app);
- assert_eq!(*written.borrow(), [path], "{open}: {}", app.ui.status);
- assert_eq!(dialog_kind(&app), Some(kind.as_str()), "{open}");
- }
-}
-
-/// A sheet's answer that names a file that is there once given its extension asks before replacing
-/// it, with no "cancelled" in the status bar, and the question's OK writes it without another sheet.
-#[test]
-fn a_sheets_answer_given_its_extension_asks_before_replacing() {
- let (mut app, shown, written) = app();
- app.services.exists = Some(std::sync::Arc::new(|p: &str| p == "/art/card.vectorcraft"));
- app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
- assert!(app.run("file.save", json!({})).is_err());
- shown.answer(&["/art/card"]);
- poll(&mut app);
- assert_eq!(dialog_kind(&app), Some(crate::dialogs::confirm::REPLACE));
- assert!(written.borrow().is_empty());
- poll(&mut app);
- assert_eq!(app.ui.status, "");
- crate::dialogs::confirm(&mut app).unwrap();
- assert_eq!(*written.borrow(), ["/art/card.vectorcraft"]);
- assert!(shown.requests().is_empty(), "{:?}", shown.requests());
-}
-
-/// Export… in a presets dialog whose save dialog shows in line (Windows): a name that is there
-/// once given its extension asks over the presets dialog; Cancel shows it again and writes
-/// nothing, and OK writes the preset and shows it again.
-#[test]
-fn a_preset_dialogs_export_asks_before_replacing_over_it() {
- let written = Written::default();
- let w = written.clone();
- let services = Services {
- pick_save: Some(Box::new(|_: &FilePick| Some("/presets/mine".to_string()))),
- write: Some(Box::new(move |path: &str, _: &[u8]| {
- w.borrow_mut().push(path.to_string());
- Ok(())
- })),
- exists: Some(std::sync::Arc::new(|_: &str| true)),
- ..Default::default()
- };
- let mut app = VectorcraftApp::new(Session::new(), services);
- app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
- app.run("pdf.preset.save", json!({"name": "Mine"})).unwrap();
- app.run("ui.pdfPresetsDialog", json!({"selected": "Mine"})).unwrap();
- let kind = dialog_kind(&app).unwrap().to_string();
- click(&mut app, "Export…", dialogs);
- assert_eq!(dialog_kind(&app), Some(crate::dialogs::confirm::REPLACE));
- crate::dialogs::cancel(&mut app);
- assert_eq!(dialog_kind(&app), Some(kind.as_str()));
- assert!(written.borrow().is_empty());
- click(&mut app, "Export…", dialogs);
- crate::dialogs::confirm(&mut app).unwrap();
- let path = format!("/presets/mine.{}", vectorcraft_engine::cmd::pdfcmds::PRESET_FORMAT);
- assert_eq!(*written.borrow(), [path], "{}", app.ui.status);
- assert_eq!(dialog_kind(&app), Some(kind.as_str()));
+ assert_eq!(picker.requests().iter().map(|r| r.kind).collect::>(), [PickKind::Save]);
}
/// Save As answers on the document that asked for it: the one made active meanwhile isn't saved,
/// and the one that asked is active again.
#[test]
fn save_as_saves_the_document_that_asked() {
- let (mut app, shown, written) = app();
+ let mut app = app();
+ let picker = scripted(&mut app);
app.run("file.new", json!({"width": 100, "height": 80})).unwrap();
app.run("file.new", json!({"width": 200, "height": 160})).unwrap();
let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect();
app.run("document.activate", json!({"index": 0})).unwrap();
assert!(app.run("file.saveAs", json!({})).is_err());
app.run("document.activate", json!({"index": 1})).unwrap();
- shown.answer(&["/art/a.svg"]);
- poll(&mut app);
+ picker.answer_saved("/art/a.svg", None);
+ settle(&mut app);
assert_eq!(app.session.active().map(|d| d.uid), Some(uids[0]));
- assert_eq!(dialog_kind(&app), Some("svgOptions"));
- crate::dialogs::confirm(&mut app).unwrap();
- assert_eq!(*written.borrow(), ["/art/a.svg"]);
+ let options = find(&app, "svgOptions").expect("SVG Options");
+ answer_dialog(&mut app, options, &[], true);
+ assert_eq!(picker.written(), ["/art/a.svg"]);
let paths: Vec