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> = app.session.documents().iter().map(|d| d.path.clone()).collect(); assert_eq!(paths, [Some("/art/a.svg".to_string()), None]); assert_eq!(app.session.active().map(|d| d.uid), Some(uids[0])); @@ -717,57 +446,30 @@ fn save_as_saves_the_document_that_asked() { /// nothing is written, no other document is saved, and the status says why. #[test] fn an_answer_for_a_closed_document_is_dropped() { - 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(); app.run("document.activate", json!({"index": 0})).unwrap(); assert!(app.run("file.saveAs", json!({})).is_err()); app.session.execute("file.close", &json!({"index": 0})).unwrap(); app.sync_views(); - shown.answer(&["/art/a.svg"]); - poll(&mut app); - assert_eq!(app.ui.status, CLOSED); - assert!(written.borrow().is_empty()); - assert_eq!(dialog_kind(&app), None, "no SVG Options"); + picker.answer_saved("/art/a.svg", None); + settle(&mut app); + assert_eq!(app.ui.status, file_asks::CLOSED); + assert!(picker.written().is_empty()); + assert!(find(&app, "svgOptions").is_none(), "no SVG Options"); assert_eq!(app.session.documents().iter().map(|d| d.path.clone()).collect::>(), [None]); assert!(!app.file_dialog_open()); } -/// A button whose action asks for an open dialog and, once that answers, a save dialog shows both -/// off the UI thread, then finishes with both paths. -#[test] -fn a_buttons_second_dialog_shows_off_the_ui_thread_too() { - let (mut app, shown, _) = app(); - let (from, done) = (Rc::new(RefCell::new(None::)), Rc::new(RefCell::new(vec![]))); - let (f, d) = (from.clone(), done.clone()); - picks::button(&mut app, move |app| { - if f.borrow().is_none() { - let picked = picks::open(app, &FilePick::default()); - *f.borrow_mut() = picked; - } - let Some(source) = f.borrow().clone() else { return }; - if let Some(to) = picks::save(app, &FilePick::named("copy.svg")) { - d.borrow_mut().push((source, to)); - } - }); - assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(_)])); - shown.answer(&["/art/in.svg"]); - poll(&mut app); - assert_eq!(from.borrow().as_deref(), Some("/art/in.svg")); - assert_eq!(shown.requests(), [PickRequest::Save(FilePick::named("copy.svg"))]); - assert!(app.file_dialog_open() && done.borrow().is_empty()); - shown.answer(&["/art/out.svg"]); - poll(&mut app); - assert_eq!(*done.borrow(), [("/art/in.svg".to_string(), "/art/out.svg".to_string())]); - assert!(!app.file_dialog_open()); -} - -/// While a dialog's sheet is on the window (macOS) nothing quits or closes: Quit, Close and Close +/// While a pick's sheet is on the window (macOS) nothing quits or closes: Quit, Close and Close /// All say a file dialog is open and close nothing; once it answers or is cancelled they work /// again. #[test] fn nothing_closes_or_quits_while_a_sheet_is_open() { - let (mut app, shown, _) = app(); + let mut app = app(); + let picker = scripted(&mut app).sheets(true); app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); app.run("file.new", json!({"width": 200, "height": 160})).unwrap(); assert!(!app.file_dialog_open() && !app.file_sheet_open()); @@ -775,16 +477,16 @@ fn nothing_closes_or_quits_while_a_sheet_is_open() { assert!(app.file_dialog_open() && app.file_sheet_open()); let refused = |app: &mut VectorcraftApp| { for (id, p) in [("app.quit", json!({})), ("file.close", json!({})), ("file.close", json!({"index": 0})), ("file.closeAll", json!({}))] { - assert_eq!(app.run(id, p.clone()), Err(picks::busy().to_string()), "{id} {p}"); + assert_eq!(app.run(id, p.clone()), Err(file_asks::BUSY.to_string()), "{id} {p}"); } assert_eq!(app.session.documents().len(), 2); assert_ne!(app.ui.status, "quit"); - assert_eq!(dialog_kind(app), None, "no Save Changes either"); + assert!(open_dialogs(app).is_empty(), "no Save Changes either"); }; refused(&mut app); // Answered: the file opens, and documents close again. - shown.answer(&["/art/c.svg"]); - poll(&mut app); + picker.answer(&["/art/c.svg"]); + settle(&mut app); assert!(!app.file_dialog_open()); assert_eq!(app.session.documents().len(), 3); app.run("file.close", json!({})).unwrap(); @@ -792,39 +494,41 @@ fn nothing_closes_or_quits_while_a_sheet_is_open() { // Cancelled: the same. assert!(app.run("file.saveAs", json!({})).is_err()); refused(&mut app); - shown.answer(&[]); - poll(&mut app); + picker.cancel(); + settle(&mut app); assert!(!app.file_dialog_open()); app.run("file.closeAll", json!({})).unwrap(); assert!(app.session.documents().is_empty()); assert!(app.run("file.open", json!({})).is_err()); assert!(app.run("app.quit", json!({})).is_err()); - shown.answer(&[]); - poll(&mut app); + picker.cancel(); + settle(&mut app); app.run("app.quit", json!({})).unwrap(); assert_eq!(app.ui.status, "quit"); } -/// A view Window › New Window opened does not close while a dialog's sheet is on the window either. +/// A view Window › New Window opened does not close while a pick's sheet is on the window either. #[test] fn no_view_closes_while_a_sheet_is_open() { - let (mut app, shown, _) = app(); + let mut app = app(); + let picker = scripted(&mut app).sheets(true); app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); app.run("window.newWindow", json!({})).unwrap(); assert!(app.run("file.open", json!({})).is_err()); - assert_eq!(app.run("file.close", json!({})), Err(picks::busy().to_string())); + assert_eq!(app.run("file.close", json!({})), Err(file_asks::BUSY.to_string())); assert_eq!(crate::doc_windows::windows(&app), [(0, 1), (0, 2)]); - shown.answer(&[]); - poll(&mut app); + picker.cancel(); + settle(&mut app); app.run("file.close", json!({})).unwrap(); assert_eq!(crate::doc_windows::windows(&app), [(0, 1)]); } -/// On Linux the dialog is a window of its own, not a sheet: Close and Quit go on while it is open, +/// On Linux the picker is a window of its own, not a sheet: Close and Quit go on while it is open, /// and its answer for the document closed meanwhile is dropped, nothing written. #[test] fn on_linux_documents_close_while_a_dialog_is_open() { - let (mut app, shown, written) = with_dialogs(false); + let mut app = app(); + let picker = scripted(&mut app).sheets(false); app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); app.run("file.new", json!({"width": 200, "height": 160})).unwrap(); app.run("document.activate", json!({"index": 0})).unwrap(); @@ -832,11 +536,11 @@ fn on_linux_documents_close_while_a_dialog_is_open() { assert!(app.file_dialog_open() && !app.file_sheet_open()); app.run("file.close", json!({})).unwrap(); assert_eq!(app.session.documents().len(), 1); - shown.answer(&["/art/a.svg"]); - poll(&mut app); - assert_eq!(app.ui.status, CLOSED); - assert!(written.borrow().is_empty()); - assert_eq!(dialog_kind(&app), None); + picker.answer_saved("/art/a.svg", None); + settle(&mut app); + assert_eq!(app.ui.status, file_asks::CLOSED); + assert!(picker.written().is_empty()); + assert!(find(&app, "svgOptions").is_none()); // Quit goes on too. assert!(app.run("file.open", json!({})).is_err()); assert!(app.file_dialog_open()); @@ -845,73 +549,27 @@ fn on_linux_documents_close_while_a_dialog_is_open() { } /// File › Open acts on no document: its answer opens the file even when the document active at -/// the time closed meanwhile (Linux). +/// the time closed meanwhile. #[test] fn an_open_answer_goes_on_after_the_active_document_closes() { - let (mut app, shown, _) = with_dialogs(false); + let mut app = app(); + let picker = scripted(&mut app).sheets(false); app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); assert!(app.run("file.open", json!({})).is_err()); app.run("file.close", json!({})).unwrap(); assert!(app.session.documents().is_empty()); - shown.answer(&["/art/b.svg"]); - poll(&mut app); + picker.answer(&["/art/b.svg"]); + settle(&mut app); assert_eq!(app.session.documents().iter().map(|d| d.path.clone()).collect::>(), [Some("/art/b.svg".to_string())]); - assert_ne!(app.ui.status, CLOSED); + assert_ne!(app.ui.status, file_asks::CLOSED); } -/// Import Shortcut Set… acts on no document either: its answer opens the set picked in Import -/// Shortcut Set even when the document active at the time closed meanwhile (Linux). -#[test] -fn an_import_shortcut_set_answer_goes_on_after_the_active_document_closes() { - let (mut app, shown, _) = with_dialogs(false); - let dir = std::env::temp_dir().join(format!("vc-picks-kys-{}", 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.run("file.new", json!({"width": 100, "height": 80})).unwrap(); - assert!(app.run("ui.shortcutImportDialog", json!({})).is_err()); - app.run("file.close", json!({})).unwrap(); - assert!(app.session.documents().is_empty()); - shown.answer(&[&path]); - poll(&mut app); - assert_eq!(dialog_kind(&app), Some(crate::dialogs::shortcut_import::KIND), "{}", app.ui.status); - assert_ne!(app.ui.status, CLOSED); - let _ = std::fs::remove_dir_all(dir); -} - -/// Locate Library… acts on no document either: its answer shows the picked file's library in the -/// missing library's panel even when the document active at the time closed meanwhile (Linux). -#[test] -fn a_locate_library_answer_goes_on_after_the_active_document_closes() { - let (mut app, shown, _) = with_dialogs(false); - let dir = std::env::temp_dir().join(format!("vc-picks-locate-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let (gone, found) = (dir.join("Gone.gpl"), dir.join("Found.gpl")); - std::fs::write(&found, "GIMP Palette\nName: Found\n#\n255 0 0\tRed\n").unwrap(); - let id = format!("loaded/{}", gone.to_string_lossy()); - let path = Some(gone.to_string_lossy().into_owned()); - let missing = library_panel::LibraryPanel { kind: "swatches".into(), id: id.clone(), path, view: None, hide_find: false, persistent: true }; - app.ui.library_panels.push(missing); - let panel = library_panel::panel_id("swatches", &id); - app.run("window.panel", json!({"panel": panel})).unwrap(); - app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); - assert!(app.run("ui.libraryPanel.locate", json!({"panel": panel})).is_err()); - app.run("file.close", json!({})).unwrap(); - assert!(app.session.documents().is_empty()); - shown.answer(&[&found.to_string_lossy()]); - poll(&mut app); - let located = library_panel::panel_id("swatches", &format!("loaded/{}", found.to_string_lossy())); - assert!(library_panel::is_open(&app.ui, &located) && !library_panel::is_open(&app.ui, &panel), "{}", app.ui.status); - assert_ne!(app.ui.status, CLOSED); - let _ = std::fs::remove_dir_all(dir); -} - -/// Save Changes' Save, answered by its Save dialog, saves and closes the document it asked about, -/// even when an earlier document closed meanwhile (Linux), then asks about the next one. +/// Save Changes' Save, answered by its Save panel, saves and closes the document it asked about, +/// even when an earlier document closed meanwhile, then asks about the next one. #[test] fn save_changes_answers_for_its_own_document() { - let (mut app, shown, written) = with_dialogs(false); + let mut app = app(); + let picker = scripted(&mut app).sheets(false); let modified = |app: &mut VectorcraftApp| app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); // X clean, A modified and untitled, C modified with a file. app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); @@ -922,24 +580,23 @@ fn save_changes_answers_for_its_own_document() { app.session.active_mut().unwrap().path = Some("/art/c.vectorcraft".into()); let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); app.run("file.closeAll", json!({})).unwrap(); - assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["uid"].clone()), Some(json!(uids[1])), "asks about A"); - // Save: A's Save dialog shows, and X closes meanwhile. - assert!(crate::dialogs::confirm(&mut app).is_err()); - assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)])); + // Save: A's Save panel shows, and X closes meanwhile. + answer_dialog(&mut app, top(&app), &[], true); + assert_eq!(picker.requests().iter().map(|r| r.kind).collect::>(), [PickKind::Save]); app.run("file.close", json!({"index": 0})).unwrap(); - shown.answer(&["/art/a.vectorcraft"]); - poll(&mut app); - assert_eq!(*written.borrow(), ["/art/a.vectorcraft"], "{}", app.ui.status); + picker.answer_saved("/art/a.vectorcraft", None); + settle(&mut app); + assert_eq!(picker.written(), ["/art/a.vectorcraft"], "{}", app.ui.status); assert_eq!(app.session.documents().iter().map(|d| d.uid).collect::>(), [uids[2]], "A closed, C untouched"); - let d = app.ui.dialog.as_ref().expect("Save Changes asks about C next"); - assert_eq!((d.kind.as_str(), &d.fields["uid"]), (crate::unsaved::KIND, &json!(uids[2]))); + assert!(!open_dialogs(&app).is_empty(), "Save Changes asks about C next"); } -/// Closing a modified background tab whose Save opens a Save dialog: once the dialog answers, -/// the document closes and the document that was in front before the question is in front again. +/// Closing a modified background tab whose Save opens a Save panel: once the panel answers, the +/// document closes and the document that was in front before the question is in front again. #[test] fn save_changes_answered_by_a_save_dialog_keeps_the_front_document() { - let (mut app, shown, written) = with_dialogs(false); + let mut app = app(); + let picker = scripted(&mut app).sheets(false); // A clean and in front, B modified and untitled, C clean. app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); @@ -948,52 +605,15 @@ fn save_changes_answered_by_a_save_dialog_keeps_the_front_document() { app.session.set_active(0); let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); app.run("file.close", json!({"index": 1})).unwrap(); - assert!(crate::dialogs::confirm(&mut app).is_err()); - assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)])); - shown.answer(&["/art/b.vectorcraft"]); - poll(&mut app); - assert_eq!(*written.borrow(), ["/art/b.vectorcraft"], "{}", app.ui.status); + answer_dialog(&mut app, top(&app), &[], true); + assert_eq!(picker.requests().iter().map(|r| r.kind).collect::>(), [PickKind::Save]); + picker.answer_saved("/art/b.vectorcraft", None); + settle(&mut app); + assert_eq!(picker.written(), ["/art/b.vectorcraft"], "{}", app.ui.status); assert_eq!(app.session.documents().iter().map(|d| d.uid).collect::>(), [uids[0], uids[2]]); assert_eq!(app.session.active().map(|d| d.uid), Some(uids[0]), "A is in front again"); } -/// A dialog asked for while another is open is refused, and the status bar says so rather than -/// "cancelled". -#[test] -fn a_refused_dialog_says_why() { - let (mut app, shown, _) = app(); - assert!(app.run("file.open", json!({})).is_err()); - poll(&mut app); - assert!(app.ui.status.is_empty(), "{}", app.ui.status); - crate::menus::invoke(&mut app, "file.open", json!({})); - assert_eq!(shown.requests().len(), 1); - poll(&mut app); - assert_eq!(app.ui.status, picks::busy()); - shown.answer(&[]); - poll(&mut app); - // The next dialog's own "cancelled" is cleared as before. - crate::menus::invoke(&mut app, "file.open", json!({})); - poll(&mut app); - assert!(app.ui.status.is_empty(), "{}", app.ui.status); -} - -/// After a panic inside what asks (a bug the frame's guard catches and recovers from), no entry is -/// left behind: the next command's answer runs that command, not the one that panicked. -#[test] -fn a_panic_inside_an_entry_leaves_none_behind() { - let (mut app, shown, written) = app(); - app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); - let r = vectorcraft_engine::guard::catch_panic(|| picks::button(&mut app, |_| panic!("a bug"))); - assert!(r.is_err()); - app.picks.recover(); - assert!(app.picks.is_entry_free()); - assert!(app.run("file.open", json!({})).is_err()); - shown.answer(&["/art/b.svg"]); - poll(&mut app); - assert_eq!(app.session.documents().len(), 2, "File › Open ran again"); - assert!(written.borrow().is_empty()); -} - /// One whole frame of the app (its logic and its window); `close` presses the window's close /// button. fn app_frame(ctx: &egui::Context, app: &mut VectorcraftApp, close: bool) -> Vec { @@ -1009,255 +629,67 @@ fn app_frame(ctx: &egui::Context, app: &mut VectorcraftApp, close: bool) -> Vec< out.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.commands.clone()).unwrap_or_default() } -/// The window's close button doesn't close the window while a dialog's sheet is on it: the status +/// The window's close button doesn't close the window while a pick's sheet is on it: the status /// says a file dialog is open. On Linux, and once the sheet answers, it closes. #[test] fn the_window_stays_open_while_a_sheet_is_on_it() { for sheets in [true, false] { - let (mut app, shown, _) = with_dialogs(sheets); - let ctx = egui::Context::default(); + let mut app = app(); + let picker = scripted(&mut app).sheets(sheets); + let ctx = app.ui_ctx.clone().unwrap(); app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); app_frame(&ctx, &mut app, false); assert!(app.run("file.open", json!({})).is_err()); let commands = app_frame(&ctx, &mut app, true); assert_eq!(commands.contains(&egui::ViewportCommand::CancelClose), sheets, "sheets: {sheets}"); - assert_eq!(app.ui.status == picks::busy(), sheets, "sheets: {sheets}: {}", app.ui.status); + assert_eq!(app.ui.status == file_asks::BUSY, sheets, "sheets: {sheets}: {}", app.ui.status); assert_eq!(app.session.documents().len(), 1); - shown.answer(&[]); + picker.cancel(); app_frame(&ctx, &mut app, false); assert!(!app_frame(&ctx, &mut app, true).contains(&egui::ViewportCommand::CancelClose), "sheets: {sheets}"); } } -/// `ui.inspect`'s `fileDialog` is the kind of dialog open (open, save, place, folder), null once it -/// answers. +/// `ui.inspect`'s `fileDialog` is the kind of pick that is up (open, save, place, folder), null once +/// it answers. #[test] fn inspect_tells_the_file_dialog_open() { - let (mut app, shown, _) = app(); - let ctx = egui::Context::default(); + let mut app = app(); + let picker = scripted(&mut app); + let ctx = app.ui_ctx.clone().unwrap(); let shows = |app: &VectorcraftApp| crate::control::inspect(app, &ctx)["fileDialog"].clone(); app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); assert_eq!(shows(&app), Value::Null); - /// What asks for a kind of dialog. + /// What asks for a kind of pick. type Ask = fn(&mut VectorcraftApp); let asks: [(&str, Ask); 4] = [ ("open", |app| assert!(app.run("file.open", json!({})).is_err())), ("save", |app| assert!(app.run("file.saveAs", json!({})).is_err())), ("place", |app| assert!(app.run("file.place", json!({})).is_err())), ("folder", |app| { - let mut d = Dialog::new("exportForScreens", json!({"folder": ""})); - app.ui.dialog = Some(d.clone()); - picks::folder_field(app, &mut d, "folder"); + let id = browse_dialog(app); + browse_folder(app, id); }), ]; for (kind, ask) in asks { ask(&mut app); assert!(app.file_dialog_open(), "{kind}"); assert_eq!(shows(&app), json!(kind)); - shown.answer(&[]); - poll(&mut app); + picker.cancel(); + settle(&mut app); assert!(!app.file_dialog_open(), "{kind}"); assert_eq!(shows(&app), Value::Null, "{kind}"); } } -// ------------------------------------------------------------------------ nothing asks in line - -/// `src` with comments and the insides of string and char literals blanked: only code is left. -fn code_only(src: &str) -> String { - let b: Vec = src.chars().collect(); - let ident = |i: usize| i < b.len() && (b[i].is_alphanumeric() || b[i] == '_'); - let mut out = String::with_capacity(src.len()); - let mut i = 0; - while let Some(&c) = b.get(i) { - let next = b.get(i + 1).copied(); - if c == '/' && next == Some('/') { - while i < b.len() && b[i] != '\n' { - i += 1; - } - } else if c == '/' && next == Some('*') { - let mut depth = 0; - while i < b.len() { - if b[i] == '/' && b.get(i + 1) == Some(&'*') { - depth += 1; - i += 2; - } else if b[i] == '*' && b.get(i + 1) == Some(&'/') { - depth -= 1; - i += 2; - if depth == 0 { - break; - } - } else { - i += 1; - } - } - out.push(' '); - } else if c == 'r' && (i == 0 || !ident(i - 1) || (b[i - 1] == 'b' && (i < 2 || !ident(i - 2)))) && matches!(next, Some('"' | '#')) { - // A raw string r"…", r#"…"# (or a raw identifier r#name, kept). - let hashes = b[i + 1..].iter().take_while(|&&c| c == '#').count(); - if b.get(i + 1 + hashes) != Some(&'"') { - out.push(c); - i += 1; - continue; - } - let close: Vec = std::iter::once('"').chain(std::iter::repeat_n('#', hashes)).collect(); - i += 2 + hashes; - while i < b.len() && !b[i..].starts_with(&close) { - i += 1; - } - i += close.len(); - out.push_str("\"\""); - } else if c == '"' { - i += 1; - while i < b.len() && b[i] != '"' { - i += if b[i] == '\\' { 2 } else { 1 }; - } - i += 1; - out.push_str("\"\""); - } else if c == '\'' && next == Some('\\') { - // An escaped char literal. - i += 2; - while i < b.len() && b[i] != '\'' { - i += 1; - } - i += 1; - out.push_str("' '"); - } else if c == '\'' && b.get(i + 2) == Some(&'\'') { - i += 3; - out.push_str("' '"); - } else { - // A lifetime's quote, or code. - out.push(c); - i += 1; - } - } - out -} - -/// `code` (from [`code_only`]) without its `#[cfg(test)]` items: test modules and their -/// declarations, test helpers. -fn without_tests(code: &str) -> String { - let mut out = String::new(); - let mut rest = code; - while let Some(at) = rest.find("#[cfg(test)]") { - out.push_str(&rest[..at]); - let item = &rest[at..]; - // The item ends at its first `;` outside braces, or with the braces it opens. - let mut depth = 0usize; - let mut end = item.len(); - for (k, ch) in item.char_indices() { - match ch { - '{' => depth += 1, - '}' => { - depth = depth.saturating_sub(1); - if depth == 0 { - end = k + 1; - break; - } - } - ';' if depth == 0 => { - end = k + 1; - break; - } - _ => {} - } - } - rest = &item[end..]; - } - out.push_str(rest); - out -} - -/// The calls in `code` (from [`code_only`]) of the host's in-line dialogs: [`Services`]' -/// `pick_open`, `pick_save`, `pick_folder`, `pick_folder_at`, `pick_open_multi` and -/// `pick_open_files` used other than to ask whether the host has them (`.is_some()`, `.is_none()`). -fn in_line_dialogs(code: &str) -> Vec { - let mut found = vec![]; - for name in ["pick_open", "pick_save", "pick_folder", "pick_folder_at", "pick_open_multi", "pick_open_files"] { - let field = format!(".{name}"); - let mut rest = code; - while let Some(at) = rest.find(&field) { - rest = &rest[at + field.len()..]; - // Another field whose name starts with this one's (`pick_open_multi`). - if rest.starts_with(|c: char| c.is_alphanumeric() || c == '_') { - continue; - } - // What follows, over line breaks. - let next: String = rest.chars().filter(|c| !c.is_whitespace()).take(40).collect(); - if !next.starts_with(".is_some()") && !next.starts_with(".is_none()") { - found.push(format!("{field}{next}")); - } - } - } - found -} - -/// Nothing but `picks` shows the host's file dialogs: everything else asks through it, which shows -/// them off the UI thread when what asks runs as an entry (#867). Asking whether the host has one -/// is fine. -#[test] -fn only_picks_shows_the_hosts_dialogs() { - // The scan finds the in-line call Load Profile… made, split over lines, and not presence checks - // or comments. - let before = r#"if widgets::flat_button(ui, tl!("Load Profile…"), 110.0).clicked() - && let Some(path) = app - .services - .pick_open - .as_mut() - .and_then(|f| f(&crate::FilePick { filters: vec![FilePick::filter("ICC Profiles", &["icc", "icm"])], ..Default::default() })) - {"#; - assert_eq!(in_line_dialogs(&code_only(before)).len(), 1); - assert_eq!(in_line_dialogs(&code_only("let s = &mut app.services; let p = (s.pick_save.as_mut()?)(&pick);")).len(), 1); - assert_eq!(in_line_dialogs(&code_only("let Some(f) = &mut s.pick_open else { return };")).len(), 1); - let fine = "let paths = if app.services.pick_open_multi.is_some() { 1 } else { 2 }; // app.services.pick_open.as_mut()\n\ - let t = \"services.pick_folder.take()\"; let c = '\"'; let u = s.pick_folder.is_none();"; - assert_eq!(in_line_dialogs(&code_only(fine)), Vec::::new()); - assert_eq!( - without_tests(&code_only("fn a() {}\n#[cfg(test)]\nmod tests;\n#[cfg(test)]\nmod t { fn b() { x.pick_open.take(); } }\nfn c() {}")), - "fn a() {}\n\n\nfn c() {}" - ); - - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); - // Each source file's code without its tests, by its path under `src`. - let mut scanned = BTreeMap::new(); - let mut stack = vec![dir.clone()]; - while let Some(d) = stack.pop() { - for entry in std::fs::read_dir(&d).into_iter().flatten().flatten() { - let path = entry.path(); - let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string(); - if path.is_dir() { - if name != "tests" { - stack.push(path); - } - } else if name.ends_with(".rs") && !name.starts_with("tests") && name != "picks.rs" { - let key = path.strip_prefix(&dir).unwrap().to_string_lossy().replace('\\', "/"); - scanned.insert(key, without_tests(&code_only(&std::fs::read_to_string(&path).unwrap()))); - } - } - } - // Code after a test item is still read: lib.rs declares its test modules first, and the - // shortcut editor's mirror macro has a test-only block. - for (file, code) in [ - ("app/files.rs", "fnfile_dialog_open"), - ("shortcut_editor.rs", "fnimport_into_dialog"), - ("ui_fonts.rs", "fnpainted_text"), - ("place.rs", ".pick_open_multi.is_some()"), - ("panels/separations.rs", "picks::open("), - ] { - let flat: String = scanned.get(file).unwrap_or_else(|| panic!("{file} not read")).chars().filter(|c| !c.is_whitespace()).collect(); - assert!(flat.contains(code), "{file} lost `{code}`"); - } - let found: Vec = scanned.iter().flat_map(|(file, code)| in_line_dialogs(code).into_iter().map(move |c| format!("{file}: {c}"))).collect(); - assert!(found.is_empty(), "file dialogs shown in line, not through `picks`: {found:#?}"); -} - -/// #2200: Missing Fonts › Find in Folder… (a sheet on macOS) on a folder the search refuses, a -/// home folder's Library where font tools leave fonts to test: the dialog says why. Without it -/// the dialog reads as before the folder was picked, only with "Not found" under each font, and -/// the reason is in the status bar alone. +/// Find Fonts' folder button: when the folder picked is one the search refuses (other apps' or the +/// system's folders, such as the home folder's Library where font tools leave fonts to test), the +/// dialog says why. Without it the dialog reads as before the folder was picked, only with "Not +/// found" under each font, and the reason is in the status bar alone. #[test] fn missing_fonts_says_why_the_folder_picked_wasnt_searched() { - let (mut app, shown, _) = app(); + let mut app = app(); + let picker = scripted(&mut app); app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); app.services.write = None; let root = std::fs::canonicalize(vectorcraft_testkit::temp_dir("missing-fonts-refused")).unwrap(); @@ -1267,27 +699,28 @@ fn missing_fonts_says_why_the_folder_picked_wasnt_searched() { app.run("document.save", json!({"path": doc.to_string_lossy()})).unwrap(); app.session.execute("file.close", &json!({})).unwrap(); crate::io::open_path(&mut app, &doc.to_string_lossy()).unwrap(); - assert_eq!(dialog_kind(&app), Some("missingFonts")); + let missing = find(&app, "missingFonts").expect("Missing Fonts"); // The test's folder is the home folder: its Library holds other apps' folders. app.session.search_rules = Some(vectorcraft_engine::cmd::findfiles::Rules { home: Some(root.clone()), ..Default::default() }); let fonts = root.join("Library").join("Application Support").join("Font Tool").join("Export"); std::fs::create_dir_all(&fonts).unwrap(); std::fs::write(fonts.join("Findme.otf"), vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap(); click(&mut app, "Find in Folder…", dialogs); - assert_eq!(shown.requests(), [PickRequest::Folder]); - shown.answer(&[&fonts.to_string_lossy()]); - let ctx = egui::Context::default(); + assert_eq!(picker.requests().iter().map(|r| r.kind).collect::>(), [PickKind::Folder]); + picker.answer(&[&fonts.to_string_lossy()]); + let ctx = app.ui_ctx.clone().unwrap(); + let state = |app: &VectorcraftApp| fields_of(app, missing).map(|f| f["state"].clone()); let until = std::time::Instant::now() + std::time::Duration::from_secs(10); loop { app_frame(&ctx, &mut app, false); - let searching = app.ui.dialog.as_ref().is_some_and(|d| d.str("state") == "searching"); - if !searching || std::time::Instant::now() > until { + if state(&app) != Some(json!("searching")) || std::time::Instant::now() > until { break; } std::thread::sleep(std::time::Duration::from_millis(5)); } - assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("state")).as_deref(), Some("failed")); - let text = crate::tests_labels::painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + // PLAN: assumed Missing Fonts' `state` field and the line's text carry over (files-w11). + assert_eq!(state(&app), Some(json!("failed"))); + let text = frame(&ctx, &mut app, vec![], &dialogs).into_iter().map(|(t, _)| t).collect::>().join("\n"); assert!(text.contains("VectorCraft doesn't search other apps' or the system's folders"), "{text}"); assert!(!text.contains("Not found"), "the folder wasn't searched: {text}"); }